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
ronanguilloux/IsoCodes
src/IsoCodes/Luhn.php
Luhn.check
public static function check($luhn, $length, $unDecorate = true, $hyphens = []) { $luhn = $unDecorate ? self::unDecorate($luhn, $hyphens) : $luhn; if (strlen($luhn) != $length) { return false; } $expr = sprintf('/\\d{%d}/i', $length); if (!preg_match($expr, $luhn)) { return false; } if (0 === (int) $luhn) { return false; } $check = 0; for ($i = 0; $i < $length; $i += 2) { if ($length % 2 == 0) { $check += 3 * (int) substr($luhn, $i, 1); $check += (int) substr($luhn, $i + 1, 1); } else { $check += (int) substr($luhn, $i, 1); $check += 3 * (int) substr($luhn, $i + 1, 1); } } return $check % 10 == 0; }
php
public static function check($luhn, $length, $unDecorate = true, $hyphens = []) { $luhn = $unDecorate ? self::unDecorate($luhn, $hyphens) : $luhn; if (strlen($luhn) != $length) { return false; } $expr = sprintf('/\\d{%d}/i', $length); if (!preg_match($expr, $luhn)) { return false; } if (0 === (int) $luhn) { return false; } $check = 0; for ($i = 0; $i < $length; $i += 2) { if ($length % 2 == 0) { $check += 3 * (int) substr($luhn, $i, 1); $check += (int) substr($luhn, $i + 1, 1); } else { $check += (int) substr($luhn, $i, 1); $check += 3 * (int) substr($luhn, $i + 1, 1); } } return $check % 10 == 0; }
[ "public", "static", "function", "check", "(", "$", "luhn", ",", "$", "length", ",", "$", "unDecorate", "=", "true", ",", "$", "hyphens", "=", "[", "]", ")", "{", "$", "luhn", "=", "$", "unDecorate", "?", "self", "::", "unDecorate", "(", "$", "luhn"...
@param string $luhn @param int $length @param bool $unDecorate @param array $hyphens @return bool
[ "@param", "string", "$luhn", "@param", "int", "$length", "@param", "bool", "$unDecorate", "@param", "array", "$hyphens" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Luhn.php#L20-L46
ronanguilloux/IsoCodes
src/IsoCodes/Luhn.php
Luhn.unDecorate
public static function unDecorate($luhn, $hyphens = []) { $hyphensLength = count($hyphens); // removing hyphens for ($i = 0; $i < $hyphensLength; ++$i) { $luhn = str_replace($hyphens[$i], '', $luhn); } return $luhn; }
php
public static function unDecorate($luhn, $hyphens = []) { $hyphensLength = count($hyphens); // removing hyphens for ($i = 0; $i < $hyphensLength; ++$i) { $luhn = str_replace($hyphens[$i], '', $luhn); } return $luhn; }
[ "public", "static", "function", "unDecorate", "(", "$", "luhn", ",", "$", "hyphens", "=", "[", "]", ")", "{", "$", "hyphensLength", "=", "count", "(", "$", "hyphens", ")", ";", "// removing hyphens", "for", "(", "$", "i", "=", "0", ";", "$", "i", "...
@param string $luhn @param array $hyphens @return string
[ "@param", "string", "$luhn", "@param", "array", "$hyphens" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Luhn.php#L54-L63
ronanguilloux/IsoCodes
src/IsoCodes/PhoneNumber.php
PhoneNumber.validate
public static function validate($phoneNumber, $country = null) { $phoneNumber = trim($phoneNumber); if (empty($phoneNumber)) { return false; } $country = strtoupper($country); $phoneUtil = PhoneNumberUtil::getInstance(); try { $numberProto = $phoneUtil->parse($phoneNumber, $country); } catch (NumberParseException $e) { return false; } return $phoneUtil->isValidNumber($numberProto); }
php
public static function validate($phoneNumber, $country = null) { $phoneNumber = trim($phoneNumber); if (empty($phoneNumber)) { return false; } $country = strtoupper($country); $phoneUtil = PhoneNumberUtil::getInstance(); try { $numberProto = $phoneUtil->parse($phoneNumber, $country); } catch (NumberParseException $e) { return false; } return $phoneUtil->isValidNumber($numberProto); }
[ "public", "static", "function", "validate", "(", "$", "phoneNumber", ",", "$", "country", "=", "null", ")", "{", "$", "phoneNumber", "=", "trim", "(", "$", "phoneNumber", ")", ";", "if", "(", "empty", "(", "$", "phoneNumber", ")", ")", "{", "return", ...
@param string $phoneNumber @param string $country @return bool @throws \InvalidArgumentException
[ "@param", "string", "$phoneNumber", "@param", "string", "$country" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/PhoneNumber.php#L21-L36
ronanguilloux/IsoCodes
src/IsoCodes/Bban.php
Bban.validate
public static function validate($bban) { if (!extension_loaded('bcmath')) { throw new \RuntimeException(__METHOD__.' needs the bcmath extension.'); } if (mb_strlen($bban) !== 23) { return false; } $key = substr($bban, -2); $bank = substr($bban, 0, 5); $branch = substr($bban, 5, 5); $account = substr($bban, 10, 11); $account = strtr( $account, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '12345678912345678923456789' ); return 97 - bcmod(89 * $bank + 15 * $branch + 3 * $account, 97) === (int) $key; }
php
public static function validate($bban) { if (!extension_loaded('bcmath')) { throw new \RuntimeException(__METHOD__.' needs the bcmath extension.'); } if (mb_strlen($bban) !== 23) { return false; } $key = substr($bban, -2); $bank = substr($bban, 0, 5); $branch = substr($bban, 5, 5); $account = substr($bban, 10, 11); $account = strtr( $account, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '12345678912345678923456789' ); return 97 - bcmod(89 * $bank + 15 * $branch + 3 * $account, 97) === (int) $key; }
[ "public", "static", "function", "validate", "(", "$", "bban", ")", "{", "if", "(", "!", "extension_loaded", "(", "'bcmath'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "__METHOD__", ".", "' needs the bcmath extension.'", ")", ";", "}", "if...
Bban validator. @param string $bban @author petitchevalroux @licence originale http://creativecommons.org/licenses/by-sa/2.0/fr/ @link http://dev.petitchevalroux.net/php/valider-bban-php.359.html @link http://fr.wikipedia.org/wiki/Relev%C3%A9_d%27identit%C3%A9_bancaire @return bool
[ "Bban", "validator", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Bban.php#L23-L43
ronanguilloux/IsoCodes
src/IsoCodes/Grai.php
Grai.validate
public static function validate($grai) { if (strlen($grai) < 13) { return false; } $grai = self::unDecorate($grai); if (0 !== (int) $grai[0]) { return false; } $grai = substr($grai, 1, strlen($grai) - 1); if (strlen($grai) > 29) { return false; } $gtin13 = substr($grai, 0, 13); if (!ctype_alnum(substr($grai, 13, strlen($grai)))) { return false; } return parent::check($gtin13, 13); // optional serial component not to be checked }
php
public static function validate($grai) { if (strlen($grai) < 13) { return false; } $grai = self::unDecorate($grai); if (0 !== (int) $grai[0]) { return false; } $grai = substr($grai, 1, strlen($grai) - 1); if (strlen($grai) > 29) { return false; } $gtin13 = substr($grai, 0, 13); if (!ctype_alnum(substr($grai, 13, strlen($grai)))) { return false; } return parent::check($gtin13, 13); // optional serial component not to be checked }
[ "public", "static", "function", "validate", "(", "$", "grai", ")", "{", "if", "(", "strlen", "(", "$", "grai", ")", "<", "13", ")", "{", "return", "false", ";", "}", "$", "grai", "=", "self", "::", "unDecorate", "(", "$", "grai", ")", ";", "if", ...
@param mixed $grai @return bool
[ "@param", "mixed", "$grai" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Grai.php#L20-L39
ronanguilloux/IsoCodes
src/IsoCodes/Iban.php
Iban.validate
public static function validate($iban) { if (!extension_loaded('bcmath')) { throw new \RuntimeException(__METHOD__.' needs the bcmath extension.'); } // Per country validation rules static $rules = array( 'AL' => '[0-9]{8}[0-9A-Z]{16}', 'AD' => '[0-9]{8}[0-9A-Z]{12}', 'AT' => '[0-9]{16}', 'BE' => '[0-9]{12}', 'BA' => '[0-9]{16}', 'BG' => '[A-Z]{4}[0-9]{6}[0-9A-Z]{8}', 'HR' => '[0-9]{17}', 'CY' => '[0-9]{8}[0-9A-Z]{16}', 'CZ' => '[0-9]{20}', 'DK' => '[0-9]{14}', 'EE' => '[0-9]{16}', 'FO' => '[0-9]{14}', 'FI' => '[0-9]{14}', 'FR' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', 'PF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Polynesia 'TF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Southern Territories 'GP' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Guadeloupe 'MQ' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Martinique 'YT' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Mayotte 'NC' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // New Caledonia 'RE' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Reunion 'BL' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Saint Barthelemy 'MF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Saint Martin 'PM' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // Saint Pierre et Miquelon 'WF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // Wallis and Futuna Islands 'GE' => '[0-9A-Z]{2}[0-9]{16}', 'DE' => '[0-9]{18}', 'GI' => '[A-Z]{4}[0-9A-Z]{15}', 'GR' => '[0-9]{7}[0-9A-Z]{16}', 'GL' => '[0-9]{14}', 'HU' => '[0-9]{24}', 'IS' => '[0-9]{22}', 'IE' => '[0-9A-Z]{4}[0-9]{14}', 'IL' => '[0-9]{19}', 'IT' => '[A-Z][0-9]{10}[0-9A-Z]{12}', 'KZ' => '[0-9]{3}[0-9A-Z]{3}[0-9]{10}', 'KW' => '[A-Z]{4}[0-9]{22}', 'LV' => '[A-Z]{4}[0-9A-Z]{13}', 'LB' => '[0-9]{4}[0-9A-Z]{20}', 'LI' => '[0-9]{5}[0-9A-Z]{12}', 'LT' => '[0-9]{16}', 'LU' => '[0-9]{3}[0-9A-Z]{13}', 'MK' => '[0-9]{3}[0-9A-Z]{10}[0-9]{2}', 'MT' => '[A-Z]{4}[0-9]{5}[0-9A-Z]{18}', 'MR' => '[0-9]{23}', 'MU' => '[A-Z]{4}[0-9]{19}[A-Z]{3}', 'MC' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', 'ME' => '[0-9]{18}', 'NL' => '[A-Z]{4}[0-9]{10}', 'NO' => '[0-9]{11}', 'PL' => '[0-9]{24}', 'PT' => '[0-9]{21}', 'RO' => '[A-Z]{4}[0-9A-Z]{16}', 'SM' => '[A-Z][0-9]{10}[0-9A-Z]{12}', 'SA' => '[0-9]{2}[0-9A-Z]{18}', 'RS' => '[0-9]{18}', 'SK' => '[0-9]{20}', 'SI' => '[0-9]{15}', 'ES' => '[0-9]{20}', 'SE' => '[0-9]{20}', 'CH' => '[0-9]{5}[0-9A-Z]{12}', 'TN' => '[0-9]{20}', 'TR' => '[0-9]{5}[0-9A-Z]{17}', 'AE' => '[0-9]{19}', 'GB' => '[A-Z]{4}[0-9]{14}', 'CI' => '[0-9A-Z]{2}[0-9]{22}', 'BR' => '[0-9]{8}[0-9]{5}[0-9]{10}[A-Z]{1}[A-Z0-9]{1}', ); // Min length check if (mb_strlen($iban) < 15) { return false; } // Fetch country code from IBAN $ctr = substr($iban, 0, 2); if (isset($rules[$ctr]) === false) { return false; } // Fetch country validation rule $check = substr($iban, 4); if (preg_match('~^'.$rules[$ctr].'$~', $check) !== 1) { return false; } // Fetch needed string for validation $check = $check.substr($iban, 0, 4); // Replace characters by decimal values $check = str_replace( array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'), array('10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35'), $check ); // Final check return bcmod($check, 97) === '1'; }
php
public static function validate($iban) { if (!extension_loaded('bcmath')) { throw new \RuntimeException(__METHOD__.' needs the bcmath extension.'); } // Per country validation rules static $rules = array( 'AL' => '[0-9]{8}[0-9A-Z]{16}', 'AD' => '[0-9]{8}[0-9A-Z]{12}', 'AT' => '[0-9]{16}', 'BE' => '[0-9]{12}', 'BA' => '[0-9]{16}', 'BG' => '[A-Z]{4}[0-9]{6}[0-9A-Z]{8}', 'HR' => '[0-9]{17}', 'CY' => '[0-9]{8}[0-9A-Z]{16}', 'CZ' => '[0-9]{20}', 'DK' => '[0-9]{14}', 'EE' => '[0-9]{16}', 'FO' => '[0-9]{14}', 'FI' => '[0-9]{14}', 'FR' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', 'PF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Polynesia 'TF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Southern Territories 'GP' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Guadeloupe 'MQ' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Martinique 'YT' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Mayotte 'NC' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // New Caledonia 'RE' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Reunion 'BL' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Saint Barthelemy 'MF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // French Saint Martin 'PM' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // Saint Pierre et Miquelon 'WF' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', // Wallis and Futuna Islands 'GE' => '[0-9A-Z]{2}[0-9]{16}', 'DE' => '[0-9]{18}', 'GI' => '[A-Z]{4}[0-9A-Z]{15}', 'GR' => '[0-9]{7}[0-9A-Z]{16}', 'GL' => '[0-9]{14}', 'HU' => '[0-9]{24}', 'IS' => '[0-9]{22}', 'IE' => '[0-9A-Z]{4}[0-9]{14}', 'IL' => '[0-9]{19}', 'IT' => '[A-Z][0-9]{10}[0-9A-Z]{12}', 'KZ' => '[0-9]{3}[0-9A-Z]{3}[0-9]{10}', 'KW' => '[A-Z]{4}[0-9]{22}', 'LV' => '[A-Z]{4}[0-9A-Z]{13}', 'LB' => '[0-9]{4}[0-9A-Z]{20}', 'LI' => '[0-9]{5}[0-9A-Z]{12}', 'LT' => '[0-9]{16}', 'LU' => '[0-9]{3}[0-9A-Z]{13}', 'MK' => '[0-9]{3}[0-9A-Z]{10}[0-9]{2}', 'MT' => '[A-Z]{4}[0-9]{5}[0-9A-Z]{18}', 'MR' => '[0-9]{23}', 'MU' => '[A-Z]{4}[0-9]{19}[A-Z]{3}', 'MC' => '[0-9]{10}[0-9A-Z]{11}[0-9]{2}', 'ME' => '[0-9]{18}', 'NL' => '[A-Z]{4}[0-9]{10}', 'NO' => '[0-9]{11}', 'PL' => '[0-9]{24}', 'PT' => '[0-9]{21}', 'RO' => '[A-Z]{4}[0-9A-Z]{16}', 'SM' => '[A-Z][0-9]{10}[0-9A-Z]{12}', 'SA' => '[0-9]{2}[0-9A-Z]{18}', 'RS' => '[0-9]{18}', 'SK' => '[0-9]{20}', 'SI' => '[0-9]{15}', 'ES' => '[0-9]{20}', 'SE' => '[0-9]{20}', 'CH' => '[0-9]{5}[0-9A-Z]{12}', 'TN' => '[0-9]{20}', 'TR' => '[0-9]{5}[0-9A-Z]{17}', 'AE' => '[0-9]{19}', 'GB' => '[A-Z]{4}[0-9]{14}', 'CI' => '[0-9A-Z]{2}[0-9]{22}', 'BR' => '[0-9]{8}[0-9]{5}[0-9]{10}[A-Z]{1}[A-Z0-9]{1}', ); // Min length check if (mb_strlen($iban) < 15) { return false; } // Fetch country code from IBAN $ctr = substr($iban, 0, 2); if (isset($rules[$ctr]) === false) { return false; } // Fetch country validation rule $check = substr($iban, 4); if (preg_match('~^'.$rules[$ctr].'$~', $check) !== 1) { return false; } // Fetch needed string for validation $check = $check.substr($iban, 0, 4); // Replace characters by decimal values $check = str_replace( array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'), array('10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35'), $check ); // Final check return bcmod($check, 97) === '1'; }
[ "public", "static", "function", "validate", "(", "$", "iban", ")", "{", "if", "(", "!", "extension_loaded", "(", "'bcmath'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "__METHOD__", ".", "' needs the bcmath extension.'", ")", ";", "}", "//...
Iban validator. @author petitchevalroux @licence originale http://creativecommons.org/licenses/by-sa/2.0/fr/ @link http://dev.petitchevalroux.net/php/validation-iban-php.356.html + comments & links @param string $iban @return bool
[ "Iban", "validator", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Iban.php#L22-L123
ronanguilloux/IsoCodes
src/IsoCodes/Iswc.php
Iswc.validate
public static function validate($iswc) { if (!boolval(preg_match('/^\s*T[\-.]?(\d)(\d)(\d)[\-.]?(\d)(\d)(\d)[\-.]?(\d)(\d)(\d)[\-.]?(\d)\s*$/i', $iswc))) { return false; } $hyphens = ['‐', '-', '.']; $iswc = parent::unDecorate($iswc, $hyphens); $sum = 1; for ($i = 1; $i <= 9; ++$i) { $sum = $sum + $i * (int) $iswc[$i]; } $rem = $sum % 10; if ($rem !== 0) { $rem = 10 - $rem; } return (int) $iswc[10] === $rem; }
php
public static function validate($iswc) { if (!boolval(preg_match('/^\s*T[\-.]?(\d)(\d)(\d)[\-.]?(\d)(\d)(\d)[\-.]?(\d)(\d)(\d)[\-.]?(\d)\s*$/i', $iswc))) { return false; } $hyphens = ['‐', '-', '.']; $iswc = parent::unDecorate($iswc, $hyphens); $sum = 1; for ($i = 1; $i <= 9; ++$i) { $sum = $sum + $i * (int) $iswc[$i]; } $rem = $sum % 10; if ($rem !== 0) { $rem = 10 - $rem; } return (int) $iswc[10] === $rem; }
[ "public", "static", "function", "validate", "(", "$", "iswc", ")", "{", "if", "(", "!", "boolval", "(", "preg_match", "(", "'/^\\s*T[\\-.]?(\\d)(\\d)(\\d)[\\-.]?(\\d)(\\d)(\\d)[\\-.]?(\\d)(\\d)(\\d)[\\-.]?(\\d)\\s*$/i'", ",", "$", "iswc", ")", ")", ")", "{", "return",...
@param mixed $iswc @return bool
[ "@param", "mixed", "$iswc" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Iswc.php#L20-L40
ronanguilloux/IsoCodes
src/IsoCodes/Udi.php
Udi.validate
public static function validate($di) { $di = self::unDecorate($di); $validUdiLength = [8, 12, 13, 14]; $length = strlen($di); if (!in_array($length, $validUdiLength)) { return false; } return parent::check($di, $length); }
php
public static function validate($di) { $di = self::unDecorate($di); $validUdiLength = [8, 12, 13, 14]; $length = strlen($di); if (!in_array($length, $validUdiLength)) { return false; } return parent::check($di, $length); }
[ "public", "static", "function", "validate", "(", "$", "di", ")", "{", "$", "di", "=", "self", "::", "unDecorate", "(", "$", "di", ")", ";", "$", "validUdiLength", "=", "[", "8", ",", "12", ",", "13", ",", "14", "]", ";", "$", "length", "=", "st...
@param mixed $di - Device Identifier component @return bool
[ "@param", "mixed", "$di", "-", "Device", "Identifier", "component" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Udi.php#L22-L32
ronanguilloux/IsoCodes
src/IsoCodes/Hetu.php
Hetu.validate
public static function validate($hetu) { if (!is_string($hetu) || strlen($hetu) != 11) { return false; } $dd = substr($hetu, 0, 2); $mm = substr($hetu, 2, 2); $yy = substr($hetu, 4, 2); $centuryCode = strtoupper($hetu{6}); $id = (int) ($dd.$mm.$yy.substr($hetu, 7, 3)); $checksum = strtoupper($hetu{10}); if ($dd < 1 || $dd > 31) { return false; } if ($mm < 1 || $mm > 12) { return false; } if (!is_numeric($yy)) { return false; } if (!array_key_exists($centuryCode, static::$centuryCodes)) { return false; } $hetuChecksumKey = $id % strlen(static::$validationKeys); if (!isset(static::$validationKeys{$hetuChecksumKey}) || static::$validationKeys{$hetuChecksumKey} !== $checksum ) { return false; } return true; }
php
public static function validate($hetu) { if (!is_string($hetu) || strlen($hetu) != 11) { return false; } $dd = substr($hetu, 0, 2); $mm = substr($hetu, 2, 2); $yy = substr($hetu, 4, 2); $centuryCode = strtoupper($hetu{6}); $id = (int) ($dd.$mm.$yy.substr($hetu, 7, 3)); $checksum = strtoupper($hetu{10}); if ($dd < 1 || $dd > 31) { return false; } if ($mm < 1 || $mm > 12) { return false; } if (!is_numeric($yy)) { return false; } if (!array_key_exists($centuryCode, static::$centuryCodes)) { return false; } $hetuChecksumKey = $id % strlen(static::$validationKeys); if (!isset(static::$validationKeys{$hetuChecksumKey}) || static::$validationKeys{$hetuChecksumKey} !== $checksum ) { return false; } return true; }
[ "public", "static", "function", "validate", "(", "$", "hetu", ")", "{", "if", "(", "!", "is_string", "(", "$", "hetu", ")", "||", "strlen", "(", "$", "hetu", ")", "!=", "11", ")", "{", "return", "false", ";", "}", "$", "dd", "=", "substr", "(", ...
HETU validator. @param string $hetu @return bool
[ "HETU", "validator", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Hetu.php#L34-L71
ronanguilloux/IsoCodes
src/IsoCodes/Sedol.php
Sedol.validate
public static function validate($value) { if (strlen($value) !== 7) { return false; } $char6 = substr($value, 0, 6); if (!preg_match('/^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}$/', $char6)) { return false; } $weight = [1, 3, 1, 7, 3, 9, 1]; $sum = 0; for ($i = 0; $i < 6; ++$i) { $sum += $weight[$i] * intval($char6[$i], 36); } $check = (10 - $sum % 10) % 10; return $value === $char6.$check; }
php
public static function validate($value) { if (strlen($value) !== 7) { return false; } $char6 = substr($value, 0, 6); if (!preg_match('/^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}$/', $char6)) { return false; } $weight = [1, 3, 1, 7, 3, 9, 1]; $sum = 0; for ($i = 0; $i < 6; ++$i) { $sum += $weight[$i] * intval($char6[$i], 36); } $check = (10 - $sum % 10) % 10; return $value === $char6.$check; }
[ "public", "static", "function", "validate", "(", "$", "value", ")", "{", "if", "(", "strlen", "(", "$", "value", ")", "!==", "7", ")", "{", "return", "false", ";", "}", "$", "char6", "=", "substr", "(", "$", "value", ",", "0", ",", "6", ")", ";...
{@inheritdoc}
[ "{" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Sedol.php#L15-L35
ronanguilloux/IsoCodes
src/IsoCodes/Vat.php
Vat.validate
public static function validate($vat) { if (empty($vat) || null === $vat || '' === $vat) { return false; } $countryCode = substr($vat, 0, 2); if (false === self::isValidCountryCode($countryCode)) { return false; } $vat = substr($vat, 2); if (0 === preg_match('/^'.self::$patterns[$countryCode].'$/', $vat)) { return false; } return true; }
php
public static function validate($vat) { if (empty($vat) || null === $vat || '' === $vat) { return false; } $countryCode = substr($vat, 0, 2); if (false === self::isValidCountryCode($countryCode)) { return false; } $vat = substr($vat, 2); if (0 === preg_match('/^'.self::$patterns[$countryCode].'$/', $vat)) { return false; } return true; }
[ "public", "static", "function", "validate", "(", "$", "vat", ")", "{", "if", "(", "empty", "(", "$", "vat", ")", "||", "null", "===", "$", "vat", "||", "''", "===", "$", "vat", ")", "{", "return", "false", ";", "}", "$", "countryCode", "=", "subs...
validate Checks if $vat is a valid, European Union VAT number. @param mixed $vat @return bool
[ "validate", "Checks", "if", "$vat", "is", "a", "valid", "European", "Union", "VAT", "number", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Vat.php#L89-L106
ronanguilloux/IsoCodes
src/IsoCodes/OrganismeType12NormeB2.php
OrganismeType12NormeB2.validate
public static function validate($code = '', $key = -1) { if (strlen($key) < 1) { return false; } if (!is_numeric($key)) { return false; } if (!is_string($code)) { return false; } if (strlen($code) < 2) { return false; } $numerals = str_split($code); $rank = array_reverse(array_keys($numerals)); $orderedNumerals = array(); foreach ($rank as $i => $rankValue) { $orderedNumerals[$rankValue + 1] = $numerals[$i]; } $results = array(); foreach ($orderedNumerals as $cle => $value) { $results[$value] = ($cle % 2 == 0) ? ((int) $value * 1) : ((int) $value * 2); } $sum = 0; foreach ($results as $cle => $value) { $sum += array_sum(str_split($value)); } $validKey = str_split($sum); $validKey = 10 - array_pop($validKey); return $key === $validKey; }
php
public static function validate($code = '', $key = -1) { if (strlen($key) < 1) { return false; } if (!is_numeric($key)) { return false; } if (!is_string($code)) { return false; } if (strlen($code) < 2) { return false; } $numerals = str_split($code); $rank = array_reverse(array_keys($numerals)); $orderedNumerals = array(); foreach ($rank as $i => $rankValue) { $orderedNumerals[$rankValue + 1] = $numerals[$i]; } $results = array(); foreach ($orderedNumerals as $cle => $value) { $results[$value] = ($cle % 2 == 0) ? ((int) $value * 1) : ((int) $value * 2); } $sum = 0; foreach ($results as $cle => $value) { $sum += array_sum(str_split($value)); } $validKey = str_split($sum); $validKey = 10 - array_pop($validKey); return $key === $validKey; }
[ "public", "static", "function", "validate", "(", "$", "code", "=", "''", ",", "$", "key", "=", "-", "1", ")", "{", "if", "(", "strlen", "(", "$", "key", ")", "<", "1", ")", "{", "return", "false", ";", "}", "if", "(", "!", "is_numeric", "(", ...
validate 1-2 type keys, based on Social Scurity B2 Norm French & Belgian "Clef type 1-2 Norme B2 Securité Sociale". @param string $code @param int $key @return bool
[ "validate", "1", "-", "2", "type", "keys", "based", "on", "Social", "Scurity", "B2", "Norm", "French", "&", "Belgian", "Clef", "type", "1", "-", "2", "Norme", "B2", "Securité", "Sociale", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/OrganismeType12NormeB2.php#L19-L55
ronanguilloux/IsoCodes
src/IsoCodes/Nif.php
Nif.validate
public static function validate($nif) { $nifCodes = 'TRWAGMYFPDXBNJZSQVHLCKE'; if (9 !== strlen($nif)) { return false; } $nif = strtoupper(trim($nif)); $sum = (string) self::getCifSum($nif); $n = 10 - substr($sum, -1); if (preg_match('/^[0-9]{8}[A-Z]{1}$/', $nif)) { // DNIs $num = substr($nif, 0, 8); return $nif[8] == $nifCodes[$num % 23]; } elseif (preg_match('/^[XYZ][0-9]{7}[A-Z]{1}$/', $nif)) { // NIEs normales $tmp = substr($nif, 1, 7); $tmp = strtr(substr($nif, 0, 1), 'XYZ', '012').$tmp; return $nif[8] == $nifCodes[$tmp % 23]; } elseif (preg_match('/^[KLM]{1}/', $nif)) { // NIFs especiales return $nif[8] == chr($n + 64); } elseif (preg_match('/^[T]{1}[A-Z0-9]{8}$/', $nif)) { // NIE extraño return true; } return false; }
php
public static function validate($nif) { $nifCodes = 'TRWAGMYFPDXBNJZSQVHLCKE'; if (9 !== strlen($nif)) { return false; } $nif = strtoupper(trim($nif)); $sum = (string) self::getCifSum($nif); $n = 10 - substr($sum, -1); if (preg_match('/^[0-9]{8}[A-Z]{1}$/', $nif)) { // DNIs $num = substr($nif, 0, 8); return $nif[8] == $nifCodes[$num % 23]; } elseif (preg_match('/^[XYZ][0-9]{7}[A-Z]{1}$/', $nif)) { // NIEs normales $tmp = substr($nif, 1, 7); $tmp = strtr(substr($nif, 0, 1), 'XYZ', '012').$tmp; return $nif[8] == $nifCodes[$tmp % 23]; } elseif (preg_match('/^[KLM]{1}/', $nif)) { // NIFs especiales return $nif[8] == chr($n + 64); } elseif (preg_match('/^[T]{1}[A-Z0-9]{8}$/', $nif)) { // NIE extraño return true; } return false; }
[ "public", "static", "function", "validate", "(", "$", "nif", ")", "{", "$", "nifCodes", "=", "'TRWAGMYFPDXBNJZSQVHLCKE'", ";", "if", "(", "9", "!==", "strlen", "(", "$", "nif", ")", ")", "{", "return", "false", ";", "}", "$", "nif", "=", "strtoupper", ...
NIF and DNI validation. @param string $nif The NIF or NIE @return bool
[ "NIF", "and", "DNI", "validation", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Nif.php#L30-L62
ronanguilloux/IsoCodes
src/IsoCodes/Nif.php
Nif.getCifSum
public static function getCifSum($cif) { $sum = $cif[2] + $cif[4] + $cif[6]; for ($i = 1; $i < 8; $i += 2) { $tmp = (string) (2 * $cif[$i]); $tmp = $tmp[0] + ((strlen($tmp) == 2) ? $tmp[1] : 0); $sum += $tmp; } return $sum; }
php
public static function getCifSum($cif) { $sum = $cif[2] + $cif[4] + $cif[6]; for ($i = 1; $i < 8; $i += 2) { $tmp = (string) (2 * $cif[$i]); $tmp = $tmp[0] + ((strlen($tmp) == 2) ? $tmp[1] : 0); $sum += $tmp; } return $sum; }
[ "public", "static", "function", "getCifSum", "(", "$", "cif", ")", "{", "$", "sum", "=", "$", "cif", "[", "2", "]", "+", "$", "cif", "[", "4", "]", "+", "$", "cif", "[", "6", "]", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", ...
Used to calculate the sum of the CIF, DNI and NIE. @param string $cif @codeCoverageIgnore @return mixed
[ "Used", "to", "calculate", "the", "sum", "of", "the", "CIF", "DNI", "and", "NIE", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Nif.php#L73-L84
ronanguilloux/IsoCodes
src/IsoCodes/Isbn.php
Isbn.validate
public static function validate($isbn, $type = null) { if ($type !== null && !in_array($type, [10, 13], true)) { throw new \InvalidArgumentException('ISBN type option must be 10 or 13'); } $isbn = str_replace(' ', '', $isbn); $isbn = str_replace('-', '', $isbn); // this is a dash $isbn = str_replace('‐', '', $isbn); // this is an authentic hyphen if ($type === 10) { return self::validateIsbn10($isbn); } if ($type === 13) { return self::validateIsbn13($isbn); } return self::validateIsbn10($isbn) || self::validateIsbn13($isbn); }
php
public static function validate($isbn, $type = null) { if ($type !== null && !in_array($type, [10, 13], true)) { throw new \InvalidArgumentException('ISBN type option must be 10 or 13'); } $isbn = str_replace(' ', '', $isbn); $isbn = str_replace('-', '', $isbn); // this is a dash $isbn = str_replace('‐', '', $isbn); // this is an authentic hyphen if ($type === 10) { return self::validateIsbn10($isbn); } if ($type === 13) { return self::validateIsbn13($isbn); } return self::validateIsbn10($isbn) || self::validateIsbn13($isbn); }
[ "public", "static", "function", "validate", "(", "$", "isbn", ",", "$", "type", "=", "null", ")", "{", "if", "(", "$", "type", "!==", "null", "&&", "!", "in_array", "(", "$", "type", ",", "[", "10", ",", "13", "]", ",", "true", ")", ")", "{", ...
@param string $isbn @param int|null $type 10 or 13. Leave empty for both @return bool
[ "@param", "string", "$isbn", "@param", "int|null", "$type", "10", "or", "13", ".", "Leave", "empty", "for", "both" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Isbn.php#L18-L36
ronanguilloux/IsoCodes
src/IsoCodes/Ssn.php
Ssn.initialize
protected static function initialize() { $highgroup = static::$highgroup; // Trim the high group list and remove asterisks, fix space/tabs, and replace new lines with tabs. // The data isn't formatted well so we have to do quite a bit of random replacing. $highgroup = trim((string) $highgroup); $highgroup = str_replace(array('*', " \t", "\n", ' '), array('', "\t", "\t", "\t"), $highgroup); // Explode on tab. This should give us an array of prefixes and group numbers, IE '203 82', '204 82', etc $highgroup = explode("\t", $highgroup); // Make array useful by splitting the prefix and group number // We also convert the string to an int for easier handling later down the road $cleangroup = array(); foreach ($highgroup as $value) { if (trim($value) != '') { $temp = explode(' ', $value); if (isset($temp[1])) { $cleangroup[(int) trim($temp[0])] = (int) trim($temp[1]); static::$highgroup = (string) $cleangroup; } } } }
php
protected static function initialize() { $highgroup = static::$highgroup; // Trim the high group list and remove asterisks, fix space/tabs, and replace new lines with tabs. // The data isn't formatted well so we have to do quite a bit of random replacing. $highgroup = trim((string) $highgroup); $highgroup = str_replace(array('*', " \t", "\n", ' '), array('', "\t", "\t", "\t"), $highgroup); // Explode on tab. This should give us an array of prefixes and group numbers, IE '203 82', '204 82', etc $highgroup = explode("\t", $highgroup); // Make array useful by splitting the prefix and group number // We also convert the string to an int for easier handling later down the road $cleangroup = array(); foreach ($highgroup as $value) { if (trim($value) != '') { $temp = explode(' ', $value); if (isset($temp[1])) { $cleangroup[(int) trim($temp[0])] = (int) trim($temp[1]); static::$highgroup = (string) $cleangroup; } } } }
[ "protected", "static", "function", "initialize", "(", ")", "{", "$", "highgroup", "=", "static", "::", "$", "highgroup", ";", "// Trim the high group list and remove asterisks, fix space/tabs, and replace new lines with tabs.", "// The data isn't formatted well so we have to do quite...
Cleans the high group number list so it is useful.
[ "Cleans", "the", "high", "group", "number", "list", "so", "it", "is", "useful", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Ssn.php#L222-L246
ronanguilloux/IsoCodes
src/IsoCodes/Ssn.php
Ssn.generate
public static function generate($state = false, $separator = '-') { if (!static::$initialized) { static::initialize(); static::$initialized = true; } $states = static::$states; $statePrefixes = static::$statePrefixes; $highgroup = static::$highgroup; $possibleGroups = static::$possibleGroups; if ($state === false) { $state = $states[mt_rand(0, count($states) - 1)]; } $state = strtoupper($state); // Sanity check: is this a valid state? if (!isset($statePrefixes[$state])) { return false; } // Generate area number $area = $statePrefixes[$state][array_rand($statePrefixes[$state])]; // Generate group number $group = $possibleGroups[mt_rand(0, array_search($highgroup[$area], $possibleGroups))]; // Generate valid group number // Generate last four $lastfour = sprintf('%04s', trim(mt_rand(0, 9999))); return sprintf('%03s', $area).$separator.sprintf('%02s', $group).$separator.$lastfour; }
php
public static function generate($state = false, $separator = '-') { if (!static::$initialized) { static::initialize(); static::$initialized = true; } $states = static::$states; $statePrefixes = static::$statePrefixes; $highgroup = static::$highgroup; $possibleGroups = static::$possibleGroups; if ($state === false) { $state = $states[mt_rand(0, count($states) - 1)]; } $state = strtoupper($state); // Sanity check: is this a valid state? if (!isset($statePrefixes[$state])) { return false; } // Generate area number $area = $statePrefixes[$state][array_rand($statePrefixes[$state])]; // Generate group number $group = $possibleGroups[mt_rand(0, array_search($highgroup[$area], $possibleGroups))]; // Generate valid group number // Generate last four $lastfour = sprintf('%04s', trim(mt_rand(0, 9999))); return sprintf('%03s', $area).$separator.sprintf('%02s', $group).$separator.$lastfour; }
[ "public", "static", "function", "generate", "(", "$", "state", "=", "false", ",", "$", "separator", "=", "'-'", ")", "{", "if", "(", "!", "static", "::", "$", "initialized", ")", "{", "static", "::", "initialize", "(", ")", ";", "static", "::", "$", ...
Generate an SSN based on state. @param mixed $state @param string $separator @return false|string (false: bad state found)
[ "Generate", "an", "SSN", "based", "on", "state", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Ssn.php#L256-L289
ronanguilloux/IsoCodes
src/IsoCodes/Ssn.php
Ssn.validate
public static function validate($ssn) { if (!static::$initialized) { static::initialize(); static::$initialized = true; } if (!is_string($ssn)) { return false; } if (trim($ssn) === '') { return false; } $statePrefixes = static::$statePrefixes; $highgroup = static::$highgroup; $possibleGroups = static::$possibleGroups; // Split up the SSN // If not 9 or 11 long, then return false $length = strlen($ssn); if ($length == 9) { $areaNumber = substr($ssn, 0, 3); $groupNumber = substr($ssn, 3, 2); $lastFour = substr($ssn, 5); } elseif ($length == 11) { $areaNumber = substr($ssn, 0, 3); $groupNumber = substr($ssn, 4, 2); $lastFour = substr($ssn, 7); } else { return false; } // Strip leading zeros $areaNumber = ltrim($areaNumber, 0); $groupNumber = ltrim($groupNumber, 0); // Check if parts are numeric if (!is_numeric($areaNumber) || !is_numeric($groupNumber) || !is_numeric($lastFour)) { return false; } foreach ($statePrefixes as $numbers) { // Search for the area number in the state list if (in_array($areaNumber, $numbers)) { // Make sure the group number is valid if (array_search($highgroup[$areaNumber], $possibleGroups) >= array_search($groupNumber, $possibleGroups)) { //return $state => must use "as $state => numbers" in the foreach loop; return true; } else { return false; } } } return false; }
php
public static function validate($ssn) { if (!static::$initialized) { static::initialize(); static::$initialized = true; } if (!is_string($ssn)) { return false; } if (trim($ssn) === '') { return false; } $statePrefixes = static::$statePrefixes; $highgroup = static::$highgroup; $possibleGroups = static::$possibleGroups; // Split up the SSN // If not 9 or 11 long, then return false $length = strlen($ssn); if ($length == 9) { $areaNumber = substr($ssn, 0, 3); $groupNumber = substr($ssn, 3, 2); $lastFour = substr($ssn, 5); } elseif ($length == 11) { $areaNumber = substr($ssn, 0, 3); $groupNumber = substr($ssn, 4, 2); $lastFour = substr($ssn, 7); } else { return false; } // Strip leading zeros $areaNumber = ltrim($areaNumber, 0); $groupNumber = ltrim($groupNumber, 0); // Check if parts are numeric if (!is_numeric($areaNumber) || !is_numeric($groupNumber) || !is_numeric($lastFour)) { return false; } foreach ($statePrefixes as $numbers) { // Search for the area number in the state list if (in_array($areaNumber, $numbers)) { // Make sure the group number is valid if (array_search($highgroup[$areaNumber], $possibleGroups) >= array_search($groupNumber, $possibleGroups)) { //return $state => must use "as $state => numbers" in the foreach loop; return true; } else { return false; } } } return false; }
[ "public", "static", "function", "validate", "(", "$", "ssn", ")", "{", "if", "(", "!", "static", "::", "$", "initialized", ")", "{", "static", "::", "initialize", "(", ")", ";", "static", "::", "$", "initialized", "=", "true", ";", "}", "if", "(", ...
Validate a SSN. @param mixed $ssn @return bool : false, or two letter state abbreviation if it is valid
[ "Validate", "a", "SSN", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Ssn.php#L298-L353
ronanguilloux/IsoCodes
src/IsoCodes/StructuredCommunication.php
StructuredCommunication.validate
public static function validate($structure) { if (12 !== strlen($structure) ) { return false; } $sequences = substr($structure, 0, 10); $key = substr($structure, -2); $control = $sequences % 97; // final control must be a 2-digits: $control = (1 < strlen($control)) ? $control : sprintf('0%d', $control); return $key === $control; }
php
public static function validate($structure) { if (12 !== strlen($structure) ) { return false; } $sequences = substr($structure, 0, 10); $key = substr($structure, -2); $control = $sequences % 97; // final control must be a 2-digits: $control = (1 < strlen($control)) ? $control : sprintf('0%d', $control); return $key === $control; }
[ "public", "static", "function", "validate", "(", "$", "structure", ")", "{", "if", "(", "12", "!==", "strlen", "(", "$", "structure", ")", ")", "{", "return", "false", ";", "}", "$", "sequences", "=", "substr", "(", "$", "structure", ",", "0", ",", ...
@param string $structure @return bool
[ "@param", "string", "$structure" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/StructuredCommunication.php#L15-L28
ronanguilloux/IsoCodes
src/IsoCodes/Isin.php
Isin.validate
public static function validate($isin) { $isin = strtoupper($isin); if (!preg_match('/^[A-Z]{2}[A-Z0-9]{9}[0-9]$/i', $isin)) { return false; } $base10 = $rightmost = ''; $left = $right = []; $payload = substr($isin, 0, 11); $length = strlen($payload); // Converting letters to digits for ($i = 0; $i < $length; ++$i) { $digit = substr($payload, $i, 1); $base10 .= (string) base_convert($digit, 36, 10); } $checksum = substr($isin, 11, 1); $base10 = strrev($base10); $length = strlen($base10); // distinguishing leftmost from rightmost for ($i = $length - 1; $i >= 0; --$i) { $digit = substr($base10, $i, 1); $rightmost = 'left'; if ((($length - $i) % 2) == 0) { $left[] = $digit; } else { $right[] = $digit; $rightmost = 'right'; } } // Multiply the group containing the rightmost character $simple = ('left' === $rightmost) ? $right : $left; $doubled = ('left' === $rightmost) ? $left : $right; $doubledCount = count($doubled); for ($i = 0; $i < $doubledCount; ++$i) { $digit = $doubled[$i] * 2; if ($digit > 9) { $digit = array_sum(str_split($digit)); } $doubled[$i] = $digit; } $tot = array_sum($simple) + array_sum($doubled); $moduled = 10 - ($tot % 10); return (int) $moduled === (int) $checksum; }
php
public static function validate($isin) { $isin = strtoupper($isin); if (!preg_match('/^[A-Z]{2}[A-Z0-9]{9}[0-9]$/i', $isin)) { return false; } $base10 = $rightmost = ''; $left = $right = []; $payload = substr($isin, 0, 11); $length = strlen($payload); // Converting letters to digits for ($i = 0; $i < $length; ++$i) { $digit = substr($payload, $i, 1); $base10 .= (string) base_convert($digit, 36, 10); } $checksum = substr($isin, 11, 1); $base10 = strrev($base10); $length = strlen($base10); // distinguishing leftmost from rightmost for ($i = $length - 1; $i >= 0; --$i) { $digit = substr($base10, $i, 1); $rightmost = 'left'; if ((($length - $i) % 2) == 0) { $left[] = $digit; } else { $right[] = $digit; $rightmost = 'right'; } } // Multiply the group containing the rightmost character $simple = ('left' === $rightmost) ? $right : $left; $doubled = ('left' === $rightmost) ? $left : $right; $doubledCount = count($doubled); for ($i = 0; $i < $doubledCount; ++$i) { $digit = $doubled[$i] * 2; if ($digit > 9) { $digit = array_sum(str_split($digit)); } $doubled[$i] = $digit; } $tot = array_sum($simple) + array_sum($doubled); $moduled = 10 - ($tot % 10); return (int) $moduled === (int) $checksum; }
[ "public", "static", "function", "validate", "(", "$", "isin", ")", "{", "$", "isin", "=", "strtoupper", "(", "$", "isin", ")", ";", "if", "(", "!", "preg_match", "(", "'/^[A-Z]{2}[A-Z0-9]{9}[0-9]$/i'", ",", "$", "isin", ")", ")", "{", "return", "false", ...
Validate an ISIN (International Securities Identification Number, ISO 6166). @param string $isin ISIN to be validated @see https://en.wikipedia.org/wiki/International_Securities_Identification_Number#Examples @return bool true if ISIN is valid
[ "Validate", "an", "ISIN", "(", "International", "Securities", "Identification", "Number", "ISO", "6166", ")", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Isin.php#L19-L68
ronanguilloux/IsoCodes
src/IsoCodes/CreditCard.php
CreditCard.validate
public static function validate($creditCard) { if (trim($creditCard) === '') { return false; } if (!boolval(preg_match('/.*[1-9].*/', $creditCard))) { return false; } //longueur de la chaine $creditCard $length = strlen($creditCard); //resultat de l'addition de tous les chiffres $tot = 0; for ($i = $length - 1; $i >= 0; --$i) { $digit = substr($creditCard, $i, 1); if ((($length - $i) % 2) == 0) { $digit = (int) $digit * 2; if ($digit > 9) { $digit = $digit - 9; } } $tot += (int) $digit; } return ($tot % 10) == 0; }
php
public static function validate($creditCard) { if (trim($creditCard) === '') { return false; } if (!boolval(preg_match('/.*[1-9].*/', $creditCard))) { return false; } //longueur de la chaine $creditCard $length = strlen($creditCard); //resultat de l'addition de tous les chiffres $tot = 0; for ($i = $length - 1; $i >= 0; --$i) { $digit = substr($creditCard, $i, 1); if ((($length - $i) % 2) == 0) { $digit = (int) $digit * 2; if ($digit > 9) { $digit = $digit - 9; } } $tot += (int) $digit; } return ($tot % 10) == 0; }
[ "public", "static", "function", "validate", "(", "$", "creditCard", ")", "{", "if", "(", "trim", "(", "$", "creditCard", ")", "===", "''", ")", "{", "return", "false", ";", "}", "if", "(", "!", "boolval", "(", "preg_match", "(", "'/.*[1-9].*/'", ",", ...
Credit Card validator. @param string $creditCard @return bool
[ "Credit", "Card", "validator", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/CreditCard.php#L17-L45
ronanguilloux/IsoCodes
src/IsoCodes/Gdti.php
Gdti.validate
public static function validate($grai) { if (strlen($grai) < 13) { return false; } $grai = self::unDecorate($grai); if (strlen($grai) > 30) { return false; } $gtin13 = substr($grai, 0, 13); return parent::check($gtin13, 13); // optional serial component not to be checked }
php
public static function validate($grai) { if (strlen($grai) < 13) { return false; } $grai = self::unDecorate($grai); if (strlen($grai) > 30) { return false; } $gtin13 = substr($grai, 0, 13); return parent::check($gtin13, 13); // optional serial component not to be checked }
[ "public", "static", "function", "validate", "(", "$", "grai", ")", "{", "if", "(", "strlen", "(", "$", "grai", ")", "<", "13", ")", "{", "return", "false", ";", "}", "$", "grai", "=", "self", "::", "unDecorate", "(", "$", "grai", ")", ";", "if", ...
@param mixed $grai @return bool
[ "@param", "mixed", "$grai" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Gdti.php#L20-L32
ronanguilloux/IsoCodes
src/IsoCodes/ZipCode.php
ZipCode.validate
public static function validate($zipcode, $country = null) { $zipcode = trim($zipcode); $country = trim($country); if (empty($zipcode) || empty($country)) { return false; } $country = strtoupper($country); if (!isset(self::$patterns[$country])) { throw new \InvalidArgumentException("ERROR: The zipcode validator for $country does not exists yet: feel free to add it."); } return (bool) preg_match('/^('.self::$patterns[$country].')$/', $zipcode); }
php
public static function validate($zipcode, $country = null) { $zipcode = trim($zipcode); $country = trim($country); if (empty($zipcode) || empty($country)) { return false; } $country = strtoupper($country); if (!isset(self::$patterns[$country])) { throw new \InvalidArgumentException("ERROR: The zipcode validator for $country does not exists yet: feel free to add it."); } return (bool) preg_match('/^('.self::$patterns[$country].')$/', $zipcode); }
[ "public", "static", "function", "validate", "(", "$", "zipcode", ",", "$", "country", "=", "null", ")", "{", "$", "zipcode", "=", "trim", "(", "$", "zipcode", ")", ";", "$", "country", "=", "trim", "(", "$", "country", ")", ";", "if", "(", "empty",...
@param string $zipcode @param string $country @return bool @throws \InvalidArgumentException
[ "@param", "string", "$zipcode", "@param", "string", "$country" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/ZipCode.php#L215-L229
ronanguilloux/IsoCodes
src/IsoCodes/Bsn.php
Bsn.validate
public static function validate($value) { if (!is_numeric($value)) { return false; } $stringLength = strlen($value); if ($stringLength !== 9 && $stringLength !== 8) { return false; } $sum = 0; $multiplier = $stringLength; for ($counter = 0; $counter < $stringLength; $counter++, $multiplier--) { if ($multiplier == 1) { $multiplier = -1; } $sum += substr($value, $counter, 1) * $multiplier; } return $sum % 11 === 0; }
php
public static function validate($value) { if (!is_numeric($value)) { return false; } $stringLength = strlen($value); if ($stringLength !== 9 && $stringLength !== 8) { return false; } $sum = 0; $multiplier = $stringLength; for ($counter = 0; $counter < $stringLength; $counter++, $multiplier--) { if ($multiplier == 1) { $multiplier = -1; } $sum += substr($value, $counter, 1) * $multiplier; } return $sum % 11 === 0; }
[ "public", "static", "function", "validate", "(", "$", "value", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "$", "stringLength", "=", "strlen", "(", "$", "value", ")", ";", "if", "(", "$", ...
@param string $value @return bool
[ "@param", "string", "$value" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Bsn.php#L23-L46
ronanguilloux/IsoCodes
src/IsoCodes/Insee.php
Insee.validate
public static function validate($numero) { //Expression de base d'Antoun et SNAFU (http://www.developpez.net/forums/d677820/php/langage/regex/verification-numero-securite-sociale/#post3969560), //mais corigée par mes soins pour respecter plus scrupuleusement le format $regexp = '/^ # début de chaîne (?<sexe>[1278]) # 1 et 7 pour les hommes ou 2 et 8 pour les femmes (?<annee>[0-9]{2}) # année de naissance (?<mois>0[1-9]|1[0-2]|20) # mois de naissance (si >= 20, c\'est qu\'on ne connaissait pas le mois de naissance de la personne (?<departement>[02][1-9]|2[AB]|[1345678][0-9]|9[012345789]) # le département : 01 à 19, 2A ou 2B, 21 à 95, 99 (attention, cas particulier hors métro traité hors expreg) (?<numcommune>[0-9]{3}) # numéro d\'ordre de la commune (attention car particuler pour hors métro traité hors expression régulière) (?<numacte>00[1-9]|0[1-9][0-9]|[1-9][0-9]{2}) # numéro d\'ordre d\'acte de naissance dans le mois et la commune ou pays (?<clef>0[1-9]|[1-8][0-9]|9[1-7])? # numéro de contrôle (facultatif) $ # fin de chaîne /x'; //références : http://fr.wikipedia.org/wiki/Num%C3%A9ro_de_s%C3%A9curit%C3%A9_sociale_en_France#Signification_des_chiffres_du_NIR if (!preg_match($regexp, $numero, $match)) { return false; } /* attention à l'overflow de php :) i.e : $test = '1850760057018' ; $clef = 97 - (substr($test, 0, 13) % 97) ; // => clef = 32 car l'opérande "%" travaille avec des entiers, et sur une archi 32 bits, 1850760057018 est transformé en 2147483647 ^_^ $clef = 97 - fmod(substr($test, 0, 13), 97) ; // => clef = 18 (la valeur correcte, car fmod travaille avec des flottants) */ $return = array( 'sexe' => $match['sexe'], //7,8 => homme et femme ayant un num de sécu temporaire 'annee' => $match['annee'], //année de naissance + ou - un siècle uhuh 'mois' => $match['mois'], //20 = inconnu 'departement' => $match['departement'], //99 = étranger 'numcommune' => $match['numcommune'], //990 = inconnu 'numacte' => $match['numacte'], //001 à 999 'clef' => isset($match['clef']) ? $match['clef'] : null, //00 à 97 'pays' => 'fra', //par défaut, on change que pour le cas spécifique ); //base du calcul par défaut pour la clef (est modifié pour la corse) $aChecker = floatval(substr($numero, 0, 13)); /*Traitement des cas des personnes nées hors métropole ou en corse*/ switch (true) { //départements corses. Le calcul de la cles est différent case $return['departement'] == '2A': $aChecker = floatval(str_replace('A', 0, substr($numero, 0, 13))); $aChecker -= 1000000; break; case $return['departement'] == '2B': $aChecker = floatval(str_replace('B', 1, substr($numero, 0, 13))); $aChecker -= 2000000; break; case $return['departement'] == 97 || $return['departement'] == 98: $return['departement'] .= substr($return['numcommune'], 0, 1); $return['numcommune'] = substr($return['numcommune'], 1, 2); if ($return['numcommune'] > 90) { //90 = commune inconnue return false; } break; case $return['departement'] == 99: $return['pays'] = $match['numcommune']; if ($return['numcommune'] > 990) { //990 = pays inconnu return false; } break; default: if (isset($return['numcommune'])) { if ($return['numcommune'] > 990) { //990 = commune inconnue return false; } } break; } $clef = 97 - fmod($aChecker, 97); if (empty($return['clef'])) { $return['clef'] = $clef; //la clef est optionnelle, si elle n'est pas spécifiée, le numéro est valide, mais on rajoute la clef } if ($clef != $return['clef']) { return false; } return true; }
php
public static function validate($numero) { //Expression de base d'Antoun et SNAFU (http://www.developpez.net/forums/d677820/php/langage/regex/verification-numero-securite-sociale/#post3969560), //mais corigée par mes soins pour respecter plus scrupuleusement le format $regexp = '/^ # début de chaîne (?<sexe>[1278]) # 1 et 7 pour les hommes ou 2 et 8 pour les femmes (?<annee>[0-9]{2}) # année de naissance (?<mois>0[1-9]|1[0-2]|20) # mois de naissance (si >= 20, c\'est qu\'on ne connaissait pas le mois de naissance de la personne (?<departement>[02][1-9]|2[AB]|[1345678][0-9]|9[012345789]) # le département : 01 à 19, 2A ou 2B, 21 à 95, 99 (attention, cas particulier hors métro traité hors expreg) (?<numcommune>[0-9]{3}) # numéro d\'ordre de la commune (attention car particuler pour hors métro traité hors expression régulière) (?<numacte>00[1-9]|0[1-9][0-9]|[1-9][0-9]{2}) # numéro d\'ordre d\'acte de naissance dans le mois et la commune ou pays (?<clef>0[1-9]|[1-8][0-9]|9[1-7])? # numéro de contrôle (facultatif) $ # fin de chaîne /x'; //références : http://fr.wikipedia.org/wiki/Num%C3%A9ro_de_s%C3%A9curit%C3%A9_sociale_en_France#Signification_des_chiffres_du_NIR if (!preg_match($regexp, $numero, $match)) { return false; } /* attention à l'overflow de php :) i.e : $test = '1850760057018' ; $clef = 97 - (substr($test, 0, 13) % 97) ; // => clef = 32 car l'opérande "%" travaille avec des entiers, et sur une archi 32 bits, 1850760057018 est transformé en 2147483647 ^_^ $clef = 97 - fmod(substr($test, 0, 13), 97) ; // => clef = 18 (la valeur correcte, car fmod travaille avec des flottants) */ $return = array( 'sexe' => $match['sexe'], //7,8 => homme et femme ayant un num de sécu temporaire 'annee' => $match['annee'], //année de naissance + ou - un siècle uhuh 'mois' => $match['mois'], //20 = inconnu 'departement' => $match['departement'], //99 = étranger 'numcommune' => $match['numcommune'], //990 = inconnu 'numacte' => $match['numacte'], //001 à 999 'clef' => isset($match['clef']) ? $match['clef'] : null, //00 à 97 'pays' => 'fra', //par défaut, on change que pour le cas spécifique ); //base du calcul par défaut pour la clef (est modifié pour la corse) $aChecker = floatval(substr($numero, 0, 13)); /*Traitement des cas des personnes nées hors métropole ou en corse*/ switch (true) { //départements corses. Le calcul de la cles est différent case $return['departement'] == '2A': $aChecker = floatval(str_replace('A', 0, substr($numero, 0, 13))); $aChecker -= 1000000; break; case $return['departement'] == '2B': $aChecker = floatval(str_replace('B', 1, substr($numero, 0, 13))); $aChecker -= 2000000; break; case $return['departement'] == 97 || $return['departement'] == 98: $return['departement'] .= substr($return['numcommune'], 0, 1); $return['numcommune'] = substr($return['numcommune'], 1, 2); if ($return['numcommune'] > 90) { //90 = commune inconnue return false; } break; case $return['departement'] == 99: $return['pays'] = $match['numcommune']; if ($return['numcommune'] > 990) { //990 = pays inconnu return false; } break; default: if (isset($return['numcommune'])) { if ($return['numcommune'] > 990) { //990 = commune inconnue return false; } } break; } $clef = 97 - fmod($aChecker, 97); if (empty($return['clef'])) { $return['clef'] = $clef; //la clef est optionnelle, si elle n'est pas spécifiée, le numéro est valide, mais on rajoute la clef } if ($clef != $return['clef']) { return false; } return true; }
[ "public", "static", "function", "validate", "(", "$", "numero", ")", "{", "//Expression de base d'Antoun et SNAFU (http://www.developpez.net/forums/d677820/php/langage/regex/verification-numero-securite-sociale/#post3969560),", "//mais corigée par mes soins pour respecter plus scrupuleusement le...
Vérifie le numéro de sécurité sociale. S'il est valide, renvoit true (ou mieux : un tableau des infos) sinon renvoie FALSE. @param string $numero @author Webu (Dylann Cordel <d.cordel@webu.fr>) corrigé par Ronan @link http://www.developpez.net/forums/d677820/php/langage/regex/verification-numero-securite-sociale/ @return bool ou mieux mixed array avec les infos récupérées du num de sécu ou FALSE
[ "Vérifie", "le", "numéro", "de", "sécurité", "sociale", ".", "S", "il", "est", "valide", "renvoit", "true", "(", "ou", "mieux", ":", "un", "tableau", "des", "infos", ")", "sinon", "renvoie", "FALSE", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Insee.php#L22-L114
ronanguilloux/IsoCodes
src/IsoCodes/Gtin.php
Gtin.check
public static function check($gtin, $length, $unDecorate = true, $hyphens = self::HYPHENS) { return parent::check($gtin, $length, true, $hyphens); }
php
public static function check($gtin, $length, $unDecorate = true, $hyphens = self::HYPHENS) { return parent::check($gtin, $length, true, $hyphens); }
[ "public", "static", "function", "check", "(", "$", "gtin", ",", "$", "length", ",", "$", "unDecorate", "=", "true", ",", "$", "hyphens", "=", "self", "::", "HYPHENS", ")", "{", "return", "parent", "::", "check", "(", "$", "gtin", ",", "$", "length", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Gtin.php#L17-L20
ronanguilloux/IsoCodes
src/IsoCodes/Cif.php
Cif.validate
public static function validate($cif) { $cifCodes = 'JABCDEFGHI'; if (9 !== strlen($cif)) { return false; } $cif = strtoupper(trim($cif)); $sum = (string) Nif::getCifSum($cif); $n = (10 - substr($sum, -1)) % 10; if (preg_match('/^[ABCDEFGHJKNPQRSUVW]{1}/', $cif)) { if (in_array($cif[0], array('A', 'B', 'E', 'H'))) { // Numerico return $cif[8] == $n; } elseif (in_array($cif[0], array('K', 'P', 'Q', 'S'))) { // Letras return $cif[8] == $cifCodes[$n]; } else { // Alfanumérico if (is_numeric($cif[8])) { return $cif[8] == $n; } else { return $cif[8] == $cifCodes[$n]; } } } return false; }
php
public static function validate($cif) { $cifCodes = 'JABCDEFGHI'; if (9 !== strlen($cif)) { return false; } $cif = strtoupper(trim($cif)); $sum = (string) Nif::getCifSum($cif); $n = (10 - substr($sum, -1)) % 10; if (preg_match('/^[ABCDEFGHJKNPQRSUVW]{1}/', $cif)) { if (in_array($cif[0], array('A', 'B', 'E', 'H'))) { // Numerico return $cif[8] == $n; } elseif (in_array($cif[0], array('K', 'P', 'Q', 'S'))) { // Letras return $cif[8] == $cifCodes[$n]; } else { // Alfanumérico if (is_numeric($cif[8])) { return $cif[8] == $n; } else { return $cif[8] == $cifCodes[$n]; } } } return false; }
[ "public", "static", "function", "validate", "(", "$", "cif", ")", "{", "$", "cifCodes", "=", "'JABCDEFGHI'", ";", "if", "(", "9", "!==", "strlen", "(", "$", "cif", ")", ")", "{", "return", "false", ";", "}", "$", "cif", "=", "strtoupper", "(", "tri...
CIF validation. @param string $cif The CIF @return bool
[ "CIF", "validation", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Cif.php#L25-L55
ronanguilloux/IsoCodes
src/IsoCodes/Siren.php
Siren.validate
public static function validate($insee, $length = 9) { if (!is_numeric($insee)) { return false; } if (strlen($insee) != $length) { return false; } $sum = 0; for ($i = 0; $i < $length; ++$i) { $indice = ($length - $i); $tmp = (2 - ($indice % 2)) * $insee[$i]; if ($tmp >= 10) { $tmp -= 9; } $sum += $tmp; } return ($sum % 10) == 0; }
php
public static function validate($insee, $length = 9) { if (!is_numeric($insee)) { return false; } if (strlen($insee) != $length) { return false; } $sum = 0; for ($i = 0; $i < $length; ++$i) { $indice = ($length - $i); $tmp = (2 - ($indice % 2)) * $insee[$i]; if ($tmp >= 10) { $tmp -= 9; } $sum += $tmp; } return ($sum % 10) == 0; }
[ "public", "static", "function", "validate", "(", "$", "insee", ",", "$", "length", "=", "9", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "insee", ")", ")", "{", "return", "false", ";", "}", "if", "(", "strlen", "(", "$", "insee", ")", "!=",...
SIREN validator. @param string $insee @param int $length @author ronan.guilloux @link http://fr.wikipedia.org/wiki/SIREN @return bool
[ "SIREN", "validator", "." ]
train
https://github.com/ronanguilloux/IsoCodes/blob/7ad5cd60bf5a84611d07292b5b3436d6c4b4865d/src/IsoCodes/Siren.php#L25-L46
fontis/auspost-api-php
src/HttpClient/HttpApi.php
HttpApi.get
public function get(string $path, array $parameters = [], array $requestHeaders = []): ResponseInterface { if (count($parameters) > 0) { $path .= '?' . http_build_query($parameters); } $response = $this->httpClient->sendRequest( $this->requestBuilder->create('GET', $path, $requestHeaders) ); $statusCode = $response->getStatusCode(); if ($statusCode !== 200) { $errorResponse = $response->getBody()->__toString(); $errorMessage = !empty($errorResponse) ? $errorResponse : "Invalid Auspost API response."; throw new EndpointServiceError($errorMessage); } return $response; }
php
public function get(string $path, array $parameters = [], array $requestHeaders = []): ResponseInterface { if (count($parameters) > 0) { $path .= '?' . http_build_query($parameters); } $response = $this->httpClient->sendRequest( $this->requestBuilder->create('GET', $path, $requestHeaders) ); $statusCode = $response->getStatusCode(); if ($statusCode !== 200) { $errorResponse = $response->getBody()->__toString(); $errorMessage = !empty($errorResponse) ? $errorResponse : "Invalid Auspost API response."; throw new EndpointServiceError($errorMessage); } return $response; }
[ "public", "function", "get", "(", "string", "$", "path", ",", "array", "$", "parameters", "=", "[", "]", ",", "array", "$", "requestHeaders", "=", "[", "]", ")", ":", "ResponseInterface", "{", "if", "(", "count", "(", "$", "parameters", ")", ">", "0"...
Send a GET request with query parameters. @param string $path Request path. @param array $parameters GET parameters. @param array $requestHeaders Request Headers. @return ResponseInterface @throws EndpointServiceError If the network has issue.
[ "Send", "a", "GET", "request", "with", "query", "parameters", "." ]
train
https://github.com/fontis/auspost-api-php/blob/74a77bc0365df9f84bf9c7f3c3db8a7580960357/src/HttpClient/HttpApi.php#L59-L78
fontis/auspost-api-php
src/HttpClient/RequestBuilder.php
RequestBuilder.create
public function create(string $method, string $uri, array $headers = [], $body = null): RequestInterface { if (!is_array($body)) { return $this->getRequestFactory()->createRequest($method, $uri, $headers, $body); } return $this->getRequestFactory()->createRequest($method, $uri, $headers); }
php
public function create(string $method, string $uri, array $headers = [], $body = null): RequestInterface { if (!is_array($body)) { return $this->getRequestFactory()->createRequest($method, $uri, $headers, $body); } return $this->getRequestFactory()->createRequest($method, $uri, $headers); }
[ "public", "function", "create", "(", "string", "$", "method", ",", "string", "$", "uri", ",", "array", "$", "headers", "=", "[", "]", ",", "$", "body", "=", "null", ")", ":", "RequestInterface", "{", "if", "(", "!", "is_array", "(", "$", "body", ")...
Create request. @param string $method @param string $uri @param array $headers @param mixed|null $body @return RequestInterface
[ "Create", "request", "." ]
train
https://github.com/fontis/auspost-api-php/blob/74a77bc0365df9f84bf9c7f3c3db8a7580960357/src/HttpClient/RequestBuilder.php#L42-L49
reactphp/child-process
src/Process.php
Process.start
public function start(LoopInterface $loop, $interval = 0.1) { if ($this->isRunning()) { throw new \RuntimeException('Process is already running'); } $cmd = $this->cmd; $fdSpec = $this->fds; $sigchild = null; // Read exit code through fourth pipe to work around --enable-sigchild if ($this->enhanceSigchildCompatibility) { $fdSpec[] = array('pipe', 'w'); \end($fdSpec); $sigchild = \key($fdSpec); // make sure this is fourth or higher (do not mess with STDIO) if ($sigchild < 3) { $fdSpec[3] = $fdSpec[$sigchild]; unset($fdSpec[$sigchild]); $sigchild = 3; } $cmd = \sprintf('(%s) ' . $sigchild . '>/dev/null; code=$?; echo $code >&' . $sigchild . '; exit $code', $cmd); } // on Windows, we do not launch the given command line in a shell (cmd.exe) by default and omit any error dialogs // the cmd.exe shell can explicitly be given as part of the command as detailed in both documentation and tests $options = array(); if (\DIRECTORY_SEPARATOR === '\\') { $options['bypass_shell'] = true; $options['suppress_errors'] = true; } $this->process = @\proc_open($cmd, $fdSpec, $pipes, $this->cwd, $this->env, $options); if (!\is_resource($this->process)) { $error = \error_get_last(); throw new \RuntimeException('Unable to launch a new process: ' . $error['message']); } // count open process pipes and await close event for each to drain buffers before detecting exit $that = $this; $closeCount = 0; $streamCloseHandler = function () use (&$closeCount, $loop, $interval, $that) { $closeCount--; if ($closeCount > 0) { return; } // process already closed => report immediately if (!$that->isRunning()) { $that->close(); $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); return; } // close not detected immediately => check regularly $loop->addPeriodicTimer($interval, function ($timer) use ($that, $loop) { if (!$that->isRunning()) { $loop->cancelTimer($timer); $that->close(); $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); } }); }; if ($sigchild !== null) { $this->sigchildPipe = $pipes[$sigchild]; unset($pipes[$sigchild]); } foreach ($pipes as $n => $fd) { if (\strpos($this->fds[$n][1], 'w') === false) { $stream = new WritableResourceStream($fd, $loop); } else { $stream = new ReadableResourceStream($fd, $loop); $stream->on('close', $streamCloseHandler); $closeCount++; } $this->pipes[$n] = $stream; } $this->stdin = isset($this->pipes[0]) ? $this->pipes[0] : null; $this->stdout = isset($this->pipes[1]) ? $this->pipes[1] : null; $this->stderr = isset($this->pipes[2]) ? $this->pipes[2] : null; // immediately start checking for process exit when started without any I/O pipes if (!$closeCount) { $streamCloseHandler(); } }
php
public function start(LoopInterface $loop, $interval = 0.1) { if ($this->isRunning()) { throw new \RuntimeException('Process is already running'); } $cmd = $this->cmd; $fdSpec = $this->fds; $sigchild = null; // Read exit code through fourth pipe to work around --enable-sigchild if ($this->enhanceSigchildCompatibility) { $fdSpec[] = array('pipe', 'w'); \end($fdSpec); $sigchild = \key($fdSpec); // make sure this is fourth or higher (do not mess with STDIO) if ($sigchild < 3) { $fdSpec[3] = $fdSpec[$sigchild]; unset($fdSpec[$sigchild]); $sigchild = 3; } $cmd = \sprintf('(%s) ' . $sigchild . '>/dev/null; code=$?; echo $code >&' . $sigchild . '; exit $code', $cmd); } // on Windows, we do not launch the given command line in a shell (cmd.exe) by default and omit any error dialogs // the cmd.exe shell can explicitly be given as part of the command as detailed in both documentation and tests $options = array(); if (\DIRECTORY_SEPARATOR === '\\') { $options['bypass_shell'] = true; $options['suppress_errors'] = true; } $this->process = @\proc_open($cmd, $fdSpec, $pipes, $this->cwd, $this->env, $options); if (!\is_resource($this->process)) { $error = \error_get_last(); throw new \RuntimeException('Unable to launch a new process: ' . $error['message']); } // count open process pipes and await close event for each to drain buffers before detecting exit $that = $this; $closeCount = 0; $streamCloseHandler = function () use (&$closeCount, $loop, $interval, $that) { $closeCount--; if ($closeCount > 0) { return; } // process already closed => report immediately if (!$that->isRunning()) { $that->close(); $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); return; } // close not detected immediately => check regularly $loop->addPeriodicTimer($interval, function ($timer) use ($that, $loop) { if (!$that->isRunning()) { $loop->cancelTimer($timer); $that->close(); $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); } }); }; if ($sigchild !== null) { $this->sigchildPipe = $pipes[$sigchild]; unset($pipes[$sigchild]); } foreach ($pipes as $n => $fd) { if (\strpos($this->fds[$n][1], 'w') === false) { $stream = new WritableResourceStream($fd, $loop); } else { $stream = new ReadableResourceStream($fd, $loop); $stream->on('close', $streamCloseHandler); $closeCount++; } $this->pipes[$n] = $stream; } $this->stdin = isset($this->pipes[0]) ? $this->pipes[0] : null; $this->stdout = isset($this->pipes[1]) ? $this->pipes[1] : null; $this->stderr = isset($this->pipes[2]) ? $this->pipes[2] : null; // immediately start checking for process exit when started without any I/O pipes if (!$closeCount) { $streamCloseHandler(); } }
[ "public", "function", "start", "(", "LoopInterface", "$", "loop", ",", "$", "interval", "=", "0.1", ")", "{", "if", "(", "$", "this", "->", "isRunning", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Process is already running'", ")",...
Start the process. After the process is started, the standard I/O streams will be constructed and available via public properties. @param LoopInterface $loop Loop interface for stream construction @param float $interval Interval to periodically monitor process state (seconds) @throws \RuntimeException If the process is already running or fails to start
[ "Start", "the", "process", "." ]
train
https://github.com/reactphp/child-process/blob/6895afa583d51dc10a4b9e93cd3bce17b3b77ac3/src/Process.php#L158-L250
reactphp/child-process
src/Process.php
Process.close
public function close() { if ($this->process === null) { return; } foreach ($this->pipes as $pipe) { $pipe->close(); } if ($this->enhanceSigchildCompatibility) { $this->pollExitCodePipe(); $this->closeExitCodePipe(); } $exitCode = \proc_close($this->process); $this->process = null; if ($this->exitCode === null && $exitCode !== -1) { $this->exitCode = $exitCode; } if ($this->exitCode === null && $this->status['exitcode'] !== -1) { $this->exitCode = $this->status['exitcode']; } if ($this->exitCode === null && $this->fallbackExitCode !== null) { $this->exitCode = $this->fallbackExitCode; $this->fallbackExitCode = null; } }
php
public function close() { if ($this->process === null) { return; } foreach ($this->pipes as $pipe) { $pipe->close(); } if ($this->enhanceSigchildCompatibility) { $this->pollExitCodePipe(); $this->closeExitCodePipe(); } $exitCode = \proc_close($this->process); $this->process = null; if ($this->exitCode === null && $exitCode !== -1) { $this->exitCode = $exitCode; } if ($this->exitCode === null && $this->status['exitcode'] !== -1) { $this->exitCode = $this->status['exitcode']; } if ($this->exitCode === null && $this->fallbackExitCode !== null) { $this->exitCode = $this->fallbackExitCode; $this->fallbackExitCode = null; } }
[ "public", "function", "close", "(", ")", "{", "if", "(", "$", "this", "->", "process", "===", "null", ")", "{", "return", ";", "}", "foreach", "(", "$", "this", "->", "pipes", "as", "$", "pipe", ")", "{", "$", "pipe", "->", "close", "(", ")", "...
Close the process. This method should only be invoked via the periodic timer that monitors the process state.
[ "Close", "the", "process", "." ]
train
https://github.com/reactphp/child-process/blob/6895afa583d51dc10a4b9e93cd3bce17b3b77ac3/src/Process.php#L258-L288
reactphp/child-process
src/Process.php
Process.terminate
public function terminate($signal = null) { if ($this->process === null) { return false; } if ($signal !== null) { return \proc_terminate($this->process, $signal); } return \proc_terminate($this->process); }
php
public function terminate($signal = null) { if ($this->process === null) { return false; } if ($signal !== null) { return \proc_terminate($this->process, $signal); } return \proc_terminate($this->process); }
[ "public", "function", "terminate", "(", "$", "signal", "=", "null", ")", "{", "if", "(", "$", "this", "->", "process", "===", "null", ")", "{", "return", "false", ";", "}", "if", "(", "$", "signal", "!==", "null", ")", "{", "return", "\\", "proc_te...
Terminate the process with an optional signal. @param int $signal Optional signal (default: SIGTERM) @return bool Whether the signal was sent successfully
[ "Terminate", "the", "process", "with", "an", "optional", "signal", "." ]
train
https://github.com/reactphp/child-process/blob/6895afa583d51dc10a4b9e93cd3bce17b3b77ac3/src/Process.php#L296-L307
reactphp/child-process
src/Process.php
Process.closeExitCodePipe
private function closeExitCodePipe() { if ($this->sigchildPipe === null) { return; } \fclose($this->sigchildPipe); $this->sigchildPipe = null; }
php
private function closeExitCodePipe() { if ($this->sigchildPipe === null) { return; } \fclose($this->sigchildPipe); $this->sigchildPipe = null; }
[ "private", "function", "closeExitCodePipe", "(", ")", "{", "if", "(", "$", "this", "->", "sigchildPipe", "===", "null", ")", "{", "return", ";", "}", "\\", "fclose", "(", "$", "this", "->", "sigchildPipe", ")", ";", "$", "this", "->", "sigchildPipe", "...
Close the fourth pipe used to relay an exit code. This should only be used if --enable-sigchild compatibility was enabled.
[ "Close", "the", "fourth", "pipe", "used", "to", "relay", "an", "exit", "code", "." ]
train
https://github.com/reactphp/child-process/blob/6895afa583d51dc10a4b9e93cd3bce17b3b77ac3/src/Process.php#L478-L486
reactphp/child-process
src/Process.php
Process.updateStatus
private function updateStatus() { if ($this->process === null) { return; } $this->status = \proc_get_status($this->process); if ($this->status === false) { throw new \UnexpectedValueException('proc_get_status() failed'); } if ($this->status['stopped']) { $this->stopSignal = $this->status['stopsig']; } if ($this->status['signaled']) { $this->termSignal = $this->status['termsig']; } if (!$this->status['running'] && -1 !== $this->status['exitcode']) { $this->exitCode = $this->status['exitcode']; } }
php
private function updateStatus() { if ($this->process === null) { return; } $this->status = \proc_get_status($this->process); if ($this->status === false) { throw new \UnexpectedValueException('proc_get_status() failed'); } if ($this->status['stopped']) { $this->stopSignal = $this->status['stopsig']; } if ($this->status['signaled']) { $this->termSignal = $this->status['termsig']; } if (!$this->status['running'] && -1 !== $this->status['exitcode']) { $this->exitCode = $this->status['exitcode']; } }
[ "private", "function", "updateStatus", "(", ")", "{", "if", "(", "$", "this", "->", "process", "===", "null", ")", "{", "return", ";", "}", "$", "this", "->", "status", "=", "\\", "proc_get_status", "(", "$", "this", "->", "process", ")", ";", "if", ...
Update the process status, stop/term signals, and exit code. Stop/term signals are only updated if the process is currently stopped or signaled, respectively. Otherwise, signal values will remain as-is so the corresponding getter methods may be used at a later point in time.
[ "Update", "the", "process", "status", "stop", "/", "term", "signals", "and", "exit", "code", "." ]
train
https://github.com/reactphp/child-process/blob/6895afa583d51dc10a4b9e93cd3bce17b3b77ac3/src/Process.php#L521-L544
rize/UriTemplate
src/Rize/UriTemplate/Operator/Abstraction.php
Abstraction.expandNonExplode
public function expandNonExplode(Parser $parser, Node\Variable $var, array $val) { if (empty($val)) { return null; } return $this->encode($parser, $var, $val); }
php
public function expandNonExplode(Parser $parser, Node\Variable $var, array $val) { if (empty($val)) { return null; } return $this->encode($parser, $var, $val); }
[ "public", "function", "expandNonExplode", "(", "Parser", "$", "parser", ",", "Node", "\\", "Variable", "$", "var", ",", "array", "$", "val", ")", "{", "if", "(", "empty", "(", "$", "val", ")", ")", "{", "return", "null", ";", "}", "return", "$", "t...
Non explode modifier ':' @param Parser $parser @param Node\Variable $var @param array $val @return null|string
[ "Non", "explode", "modifier", ":" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Operator/Abstraction.php#L231-L238
rize/UriTemplate
src/Rize/UriTemplate/Operator/Abstraction.php
Abstraction.encode
public function encode(Parser $parser, Node\Variable $var, $values) { $values = (array)$values; $list = isset($values[0]); $reserved = $this->reserved; $maps = static::$reserved_chars; $sep = $this->sep; $assoc_sep = '='; // non-explode modifier always use ',' as a separator if ($var->options['modifier'] !== '*') { $assoc_sep = $sep = ','; } array_walk($values, function(&$v, $k) use ($assoc_sep, $reserved, $list, $maps) { $encoded = rawurlencode($v); // assoc? encode key too if (!$list) { $encoded = rawurlencode($k).$assoc_sep.$encoded; } // rawurlencode is compliant with 'unreserved' set if (!$reserved) { $v = $encoded; } // decode chars in reserved set else { $v = str_replace( array_keys($maps), $maps, $encoded ); } }); return implode($sep, $values); }
php
public function encode(Parser $parser, Node\Variable $var, $values) { $values = (array)$values; $list = isset($values[0]); $reserved = $this->reserved; $maps = static::$reserved_chars; $sep = $this->sep; $assoc_sep = '='; // non-explode modifier always use ',' as a separator if ($var->options['modifier'] !== '*') { $assoc_sep = $sep = ','; } array_walk($values, function(&$v, $k) use ($assoc_sep, $reserved, $list, $maps) { $encoded = rawurlencode($v); // assoc? encode key too if (!$list) { $encoded = rawurlencode($k).$assoc_sep.$encoded; } // rawurlencode is compliant with 'unreserved' set if (!$reserved) { $v = $encoded; } // decode chars in reserved set else { $v = str_replace( array_keys($maps), $maps, $encoded ); } }); return implode($sep, $values); }
[ "public", "function", "encode", "(", "Parser", "$", "parser", ",", "Node", "\\", "Variable", "$", "var", ",", "$", "values", ")", "{", "$", "values", "=", "(", "array", ")", "$", "values", ";", "$", "list", "=", "isset", "(", "$", "values", "[", ...
Encodes variable according to spec (reserved or unreserved) @param Parser $parser @param Node\Variable $var @param mixed $values @return string encoded string
[ "Encodes", "variable", "according", "to", "spec", "(", "reserved", "or", "unreserved", ")" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Operator/Abstraction.php#L266-L306
rize/UriTemplate
src/Rize/UriTemplate/Operator/Abstraction.php
Abstraction.decode
public function decode(Parser $parser, Node\Variable $var, $values) { $single = !is_array($values); $values = (array)$values; array_walk($values, function(&$v, $k) { $v = rawurldecode($v); }); return $single ? reset($values) : $values; }
php
public function decode(Parser $parser, Node\Variable $var, $values) { $single = !is_array($values); $values = (array)$values; array_walk($values, function(&$v, $k) { $v = rawurldecode($v); }); return $single ? reset($values) : $values; }
[ "public", "function", "decode", "(", "Parser", "$", "parser", ",", "Node", "\\", "Variable", "$", "var", ",", "$", "values", ")", "{", "$", "single", "=", "!", "is_array", "(", "$", "values", ")", ";", "$", "values", "=", "(", "array", ")", "$", ...
Decodes variable @param Parser $parser @param Node\Variable $var @param mixed $values @return string decoded string
[ "Decodes", "variable" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Operator/Abstraction.php#L317-L327
rize/UriTemplate
src/Rize/UriTemplate/Operator/Abstraction.php
Abstraction.extract
public function extract(Parser $parser, Node\Variable $var, $data) { $value = $data; $vals = array_filter(explode($this->sep, $data)); $options = $var->options; switch ($options['modifier']) { case '*': $data = array(); foreach($vals as $val) { if (strpos($val, '=') !== false) { list($k, $v) = explode('=', $val); $data[$k] = $v; } else { $data[] = $val; } } break; case ':': break; default: $data = strpos($data, $this->sep) !== false ? $vals : $value; } return $this->decode($parser, $var, $data); }
php
public function extract(Parser $parser, Node\Variable $var, $data) { $value = $data; $vals = array_filter(explode($this->sep, $data)); $options = $var->options; switch ($options['modifier']) { case '*': $data = array(); foreach($vals as $val) { if (strpos($val, '=') !== false) { list($k, $v) = explode('=', $val); $data[$k] = $v; } else { $data[] = $val; } } break; case ':': break; default: $data = strpos($data, $this->sep) !== false ? $vals : $value; } return $this->decode($parser, $var, $data); }
[ "public", "function", "extract", "(", "Parser", "$", "parser", ",", "Node", "\\", "Variable", "$", "var", ",", "$", "data", ")", "{", "$", "value", "=", "$", "data", ";", "$", "vals", "=", "array_filter", "(", "explode", "(", "$", "this", "->", "se...
Extracts value from variable @param Parser $parser @param Node\Variable $var @param string $data @return string
[ "Extracts", "value", "from", "variable" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Operator/Abstraction.php#L337-L368
rize/UriTemplate
src/Rize/UriTemplate.php
UriTemplate.expand
public function expand($uri, $params = array()) { $params += $this->params; $uri = $this->base_uri.$uri; $result = array(); // quick check if (($start = strpos($uri, '{')) === false) { return $uri; } $parser = $this->parser; $nodes = $parser->parse($uri); foreach($nodes as $node) { $result[] = $node->expand($parser, $params); } return implode('', $result); }
php
public function expand($uri, $params = array()) { $params += $this->params; $uri = $this->base_uri.$uri; $result = array(); // quick check if (($start = strpos($uri, '{')) === false) { return $uri; } $parser = $this->parser; $nodes = $parser->parse($uri); foreach($nodes as $node) { $result[] = $node->expand($parser, $params); } return implode('', $result); }
[ "public", "function", "expand", "(", "$", "uri", ",", "$", "params", "=", "array", "(", ")", ")", "{", "$", "params", "+=", "$", "this", "->", "params", ";", "$", "uri", "=", "$", "this", "->", "base_uri", ".", "$", "uri", ";", "$", "result", "...
Expands URI Template @param string $uri URI Template @param array $params URI Template's parameters @return string
[ "Expands", "URI", "Template" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate.php#L34-L53
rize/UriTemplate
src/Rize/UriTemplate.php
UriTemplate.extract
public function extract($template, $uri, $strict = false) { $params = array(); $nodes = $this->parser->parse($template); foreach($nodes as $node) { // if strict is given, and there's no remaining uri just return null if ($strict && !strlen($uri)) { return null; } // uri'll be truncated from the start when a match is found $match = $node->match($this->parser, $uri, $params, $strict); list($uri, $params) = $match; } // if there's remaining $uri, matching is failed if ($strict && strlen($uri)) { return null; } return $params; }
php
public function extract($template, $uri, $strict = false) { $params = array(); $nodes = $this->parser->parse($template); foreach($nodes as $node) { // if strict is given, and there's no remaining uri just return null if ($strict && !strlen($uri)) { return null; } // uri'll be truncated from the start when a match is found $match = $node->match($this->parser, $uri, $params, $strict); list($uri, $params) = $match; } // if there's remaining $uri, matching is failed if ($strict && strlen($uri)) { return null; } return $params; }
[ "public", "function", "extract", "(", "$", "template", ",", "$", "uri", ",", "$", "strict", "=", "false", ")", "{", "$", "params", "=", "array", "(", ")", ";", "$", "nodes", "=", "$", "this", "->", "parser", "->", "parse", "(", "$", "template", "...
Extracts variables from URI @param string $template @param string $uri @param bool $strict This will perform a full match @return null|array params or null if not match and $strict is true
[ "Extracts", "variables", "from", "URI" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate.php#L63-L87
rize/UriTemplate
src/Rize/UriTemplate/Parser.php
Parser.parse
public function parse($template) { $parts = preg_split('#(\{[^\}]+\})#', $template, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $nodes = array(); foreach($parts as $part) { $node = $this->createNode($part); // if current node has dot separator that requires a forward lookup // for the previous node iff previous node's operator is UnNamed if ($node instanceof Expression && $node->getOperator()->id === '.') { if (sizeof($nodes) > 0) { $previousNode = $nodes[sizeof($nodes) - 1]; if ($previousNode instanceof Expression && $previousNode->getOperator() instanceof UnNamed) { $previousNode->setForwardLookupSeparator($node->getOperator()->id); } } } $nodes[] = $node; } return $nodes; }
php
public function parse($template) { $parts = preg_split('#(\{[^\}]+\})#', $template, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $nodes = array(); foreach($parts as $part) { $node = $this->createNode($part); // if current node has dot separator that requires a forward lookup // for the previous node iff previous node's operator is UnNamed if ($node instanceof Expression && $node->getOperator()->id === '.') { if (sizeof($nodes) > 0) { $previousNode = $nodes[sizeof($nodes) - 1]; if ($previousNode instanceof Expression && $previousNode->getOperator() instanceof UnNamed) { $previousNode->setForwardLookupSeparator($node->getOperator()->id); } } } $nodes[] = $node; } return $nodes; }
[ "public", "function", "parse", "(", "$", "template", ")", "{", "$", "parts", "=", "preg_split", "(", "'#(\\{[^\\}]+\\})#'", ",", "$", "template", ",", "null", ",", "PREG_SPLIT_DELIM_CAPTURE", "|", "PREG_SPLIT_NO_EMPTY", ")", ";", "$", "nodes", "=", "array", ...
Parses URI Template and returns nodes @param string $template @return Node\Abstraction[]
[ "Parses", "URI", "Template", "and", "returns", "nodes" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Parser.php#L20-L43
rize/UriTemplate
src/Rize/UriTemplate/Node/Abstraction.php
Abstraction.match
public function match(Parser $parser, $uri, $params = array(), $strict = false) { // match literal string from start to end $length = strlen($this->token); if (substr($uri, 0, $length) === $this->token) { $uri = substr($uri, $length); } // when there's no match, just return null if strict mode is given else if ($strict) { return null; } return array($uri, $params); }
php
public function match(Parser $parser, $uri, $params = array(), $strict = false) { // match literal string from start to end $length = strlen($this->token); if (substr($uri, 0, $length) === $this->token) { $uri = substr($uri, $length); } // when there's no match, just return null if strict mode is given else if ($strict) { return null; } return array($uri, $params); }
[ "public", "function", "match", "(", "Parser", "$", "parser", ",", "$", "uri", ",", "$", "params", "=", "array", "(", ")", ",", "$", "strict", "=", "false", ")", "{", "// match literal string from start to end", "$", "length", "=", "strlen", "(", "$", "th...
Matches given URI against current node @param Parser $parser @param string $uri @param array $params @param bool $strict @return null|array `uri and params` or `null` if not match and $strict is true
[ "Matches", "given", "URI", "against", "current", "node" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Node/Abstraction.php#L43-L57
rize/UriTemplate
src/Rize/UriTemplate/Node/Expression.php
Expression.match
public function match(Parser $parser, $uri, $params = array(), $strict = false) { $op = $this->operator; // check expression operator first if ($op->id && $uri[0] !== $op->id) { return array($uri, $params); } // remove operator from input if ($op->id) { $uri = substr($uri, 1); } foreach($this->sortVariables($this->variables) as $var) { /** @var \Rize\UriTemplate\Node\Variable $regex */ $regex = '#'.$op->toRegex($parser, $var).'#'; $val = null; // do a forward lookup and get just the relevant part $remainingUri = ''; $preparedUri = $uri; if ($this->forwardLookupSeparator) { $lastOccurrenceOfSeparator = stripos($uri, $this->forwardLookupSeparator); $preparedUri = substr($uri, 0, $lastOccurrenceOfSeparator); $remainingUri = substr($uri, $lastOccurrenceOfSeparator); } if (preg_match($regex, $preparedUri, $match)) { // remove matched part from input $preparedUri = preg_replace($regex, '', $preparedUri, $limit = 1); $val = $op->extract($parser, $var, $match[0]); } // if strict is given, we quit immediately when there's no match else if ($strict) { return null; } $uri = $preparedUri . $remainingUri; $params[$var->getToken()] = $val; } return array($uri, $params); }
php
public function match(Parser $parser, $uri, $params = array(), $strict = false) { $op = $this->operator; // check expression operator first if ($op->id && $uri[0] !== $op->id) { return array($uri, $params); } // remove operator from input if ($op->id) { $uri = substr($uri, 1); } foreach($this->sortVariables($this->variables) as $var) { /** @var \Rize\UriTemplate\Node\Variable $regex */ $regex = '#'.$op->toRegex($parser, $var).'#'; $val = null; // do a forward lookup and get just the relevant part $remainingUri = ''; $preparedUri = $uri; if ($this->forwardLookupSeparator) { $lastOccurrenceOfSeparator = stripos($uri, $this->forwardLookupSeparator); $preparedUri = substr($uri, 0, $lastOccurrenceOfSeparator); $remainingUri = substr($uri, $lastOccurrenceOfSeparator); } if (preg_match($regex, $preparedUri, $match)) { // remove matched part from input $preparedUri = preg_replace($regex, '', $preparedUri, $limit = 1); $val = $op->extract($parser, $var, $match[0]); } // if strict is given, we quit immediately when there's no match else if ($strict) { return null; } $uri = $preparedUri . $remainingUri; $params[$var->getToken()] = $val; } return array($uri, $params); }
[ "public", "function", "match", "(", "Parser", "$", "parser", ",", "$", "uri", ",", "$", "params", "=", "array", "(", ")", ",", "$", "strict", "=", "false", ")", "{", "$", "op", "=", "$", "this", "->", "operator", ";", "// check expression operator firs...
Matches given URI against current node @param Parser $parser @param string $uri @param array $params @param bool $strict @return null|array `uri and params` or `null` if not match and $strict is true
[ "Matches", "given", "URI", "against", "current", "node" ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Node/Expression.php#L102-L148
rize/UriTemplate
src/Rize/UriTemplate/Node/Expression.php
Expression.sortVariables
protected function sortVariables(array $vars) { usort($vars, function($a, $b) { return $a->options['modifier'] >= $b->options['modifier'] ? 1 : -1; }); return $vars; }
php
protected function sortVariables(array $vars) { usort($vars, function($a, $b) { return $a->options['modifier'] >= $b->options['modifier'] ? 1 : -1; }); return $vars; }
[ "protected", "function", "sortVariables", "(", "array", "$", "vars", ")", "{", "usort", "(", "$", "vars", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "$", "a", "->", "options", "[", "'modifier'", "]", ">=", "$", "b", "->", ...
Sort variables before extracting data from uri. We have to sort vars by non-explode to explode. @param array $vars @return array
[ "Sort", "variables", "before", "extracting", "data", "from", "uri", ".", "We", "have", "to", "sort", "vars", "by", "non", "-", "explode", "to", "explode", "." ]
train
https://github.com/rize/UriTemplate/blob/9e5fdd5c47147aa5adf7f760002ee591ed37b9ca/src/Rize/UriTemplate/Node/Expression.php#L157-L164
php-coveralls/php-coveralls
src/Component/File/Path.php
Path.isRelativePath
public function isRelativePath($path) { if (strlen($path) === 0) { return true; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return !preg_match('/^[a-z]+\:\\\\/i', $path); } return strpos($path, DIRECTORY_SEPARATOR) !== 0; }
php
public function isRelativePath($path) { if (strlen($path) === 0) { return true; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return !preg_match('/^[a-z]+\:\\\\/i', $path); } return strpos($path, DIRECTORY_SEPARATOR) !== 0; }
[ "public", "function", "isRelativePath", "(", "$", "path", ")", "{", "if", "(", "strlen", "(", "$", "path", ")", "===", "0", ")", "{", "return", "true", ";", "}", "if", "(", "strtoupper", "(", "substr", "(", "PHP_OS", ",", "0", ",", "3", ")", ")",...
Return whether the path is relative path. @param string $path path @return bool true if the path is relative path, false otherwise
[ "Return", "whether", "the", "path", "is", "relative", "path", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Component/File/Path.php#L19-L30
php-coveralls/php-coveralls
src/Component/File/Path.php
Path.toAbsolutePath
public function toAbsolutePath($path, $rootDir) { if (!is_string($path)) { return false; } if ($this->isRelativePath($path)) { return $rootDir . DIRECTORY_SEPARATOR . $path; } return $path; }
php
public function toAbsolutePath($path, $rootDir) { if (!is_string($path)) { return false; } if ($this->isRelativePath($path)) { return $rootDir . DIRECTORY_SEPARATOR . $path; } return $path; }
[ "public", "function", "toAbsolutePath", "(", "$", "path", ",", "$", "rootDir", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "isRelativePath", "(", "$", "path", ")...
Cat file path. @param string $path file path @param string $rootDir absolute path to project root directory @return false|string absolute path
[ "Cat", "file", "path", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Component/File/Path.php#L40-L51
php-coveralls/php-coveralls
src/Component/File/Path.php
Path.getRealPath
public function getRealPath($path, $rootDir) { if (!is_string($path)) { return false; } if ($this->isRelativePath($path)) { return realpath($rootDir . DIRECTORY_SEPARATOR . $path); } return realpath($path); }
php
public function getRealPath($path, $rootDir) { if (!is_string($path)) { return false; } if ($this->isRelativePath($path)) { return realpath($rootDir . DIRECTORY_SEPARATOR . $path); } return realpath($path); }
[ "public", "function", "getRealPath", "(", "$", "path", ",", "$", "rootDir", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "isRelativePath", "(", "$", "path", ")", ...
Return real file path. @param string $path file path @param string $rootDir absolute path to project root directory @return false|string real path string if the path string is passed and real path exists, false otherwise
[ "Return", "real", "file", "path", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Component/File/Path.php#L61-L72
php-coveralls/php-coveralls
src/Component/File/Path.php
Path.getRealDir
public function getRealDir($path, $rootDir) { if (!is_string($path)) { return false; } if ($this->isRelativePath($path)) { return realpath($rootDir . DIRECTORY_SEPARATOR . dirname($path)); } return realpath(dirname($path)); }
php
public function getRealDir($path, $rootDir) { if (!is_string($path)) { return false; } if ($this->isRelativePath($path)) { return realpath($rootDir . DIRECTORY_SEPARATOR . dirname($path)); } return realpath(dirname($path)); }
[ "public", "function", "getRealDir", "(", "$", "path", ",", "$", "rootDir", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "isRelativePath", "(", "$", "path", ")", ...
Return real directory path. @param string $path path @param string $rootDir absolute path to project root directory @return false|string real directory path string if the path string is passed and real directory exists, false otherwise
[ "Return", "real", "directory", "path", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Component/File/Path.php#L82-L93
php-coveralls/php-coveralls
src/Component/File/Path.php
Path.getRealWritingFilePath
public function getRealWritingFilePath($path, $rootDir) { $realDir = $this->getRealDir($path, $rootDir); if (!is_string($realDir)) { return false; } return $realDir . DIRECTORY_SEPARATOR . basename($path); }
php
public function getRealWritingFilePath($path, $rootDir) { $realDir = $this->getRealDir($path, $rootDir); if (!is_string($realDir)) { return false; } return $realDir . DIRECTORY_SEPARATOR . basename($path); }
[ "public", "function", "getRealWritingFilePath", "(", "$", "path", ",", "$", "rootDir", ")", "{", "$", "realDir", "=", "$", "this", "->", "getRealDir", "(", "$", "path", ",", "$", "rootDir", ")", ";", "if", "(", "!", "is_string", "(", "$", "realDir", ...
Return real file path to write. @param string $path file path @param string $rootDir absolute path to project root directory @return false|string real file path string if the parent directory exists, false otherwise
[ "Return", "real", "file", "path", "to", "write", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Component/File/Path.php#L103-L112
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Repository/JobsRepository.php
JobsRepository.persist
public function persist() { try { return $this ->collectCloverXml() ->collectGitInfo() ->collectEnvVars() ->dumpJsonFile() ->send(); } catch (\PhpCoveralls\Bundle\CoverallsBundle\Entity\Exception\RequirementsNotSatisfiedException $e) { $this->logger->error(sprintf('%s', $e->getHelpMessage())); return false; } catch (\Exception $e) { $this->logger->error(sprintf("%s\n\n%s", $e->getMessage(), $e->getTraceAsString())); return false; } }
php
public function persist() { try { return $this ->collectCloverXml() ->collectGitInfo() ->collectEnvVars() ->dumpJsonFile() ->send(); } catch (\PhpCoveralls\Bundle\CoverallsBundle\Entity\Exception\RequirementsNotSatisfiedException $e) { $this->logger->error(sprintf('%s', $e->getHelpMessage())); return false; } catch (\Exception $e) { $this->logger->error(sprintf("%s\n\n%s", $e->getMessage(), $e->getTraceAsString())); return false; } }
[ "public", "function", "persist", "(", ")", "{", "try", "{", "return", "$", "this", "->", "collectCloverXml", "(", ")", "->", "collectGitInfo", "(", ")", "->", "collectEnvVars", "(", ")", "->", "dumpJsonFile", "(", ")", "->", "send", "(", ")", ";", "}",...
Persist coverage data to Coveralls. @return bool
[ "Persist", "coverage", "data", "to", "Coveralls", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Repository/JobsRepository.php#L61-L79
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Repository/JobsRepository.php
JobsRepository.collectCloverXml
protected function collectCloverXml() { $this->logger->info('Load coverage clover log:'); foreach ($this->config->getCloverXmlPaths() as $path) { $this->logger->info(sprintf(' - %s', $path)); } $jsonFile = $this->api->collectCloverXml()->getJsonFile(); if ($jsonFile->hasSourceFiles()) { $this->logCollectedSourceFiles($jsonFile); } return $this; }
php
protected function collectCloverXml() { $this->logger->info('Load coverage clover log:'); foreach ($this->config->getCloverXmlPaths() as $path) { $this->logger->info(sprintf(' - %s', $path)); } $jsonFile = $this->api->collectCloverXml()->getJsonFile(); if ($jsonFile->hasSourceFiles()) { $this->logCollectedSourceFiles($jsonFile); } return $this; }
[ "protected", "function", "collectCloverXml", "(", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Load coverage clover log:'", ")", ";", "foreach", "(", "$", "this", "->", "config", "->", "getCloverXmlPaths", "(", ")", "as", "$", "path", ")", "...
Collect clover XML into json_file. @return $this
[ "Collect", "clover", "XML", "into", "json_file", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Repository/JobsRepository.php#L101-L116
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Repository/JobsRepository.php
JobsRepository.dumpJsonFile
protected function dumpJsonFile() { $jsonPath = $this->config->getJsonPath(); $this->logger->info(sprintf('Dump submitting json file: %s', $jsonPath)); $this->api->dumpJsonFile(); $filesize = number_format(filesize($jsonPath) / 1024, 2); // kB $this->logger->info(sprintf('File size: <info>%s</info> kB', $filesize)); return $this; }
php
protected function dumpJsonFile() { $jsonPath = $this->config->getJsonPath(); $this->logger->info(sprintf('Dump submitting json file: %s', $jsonPath)); $this->api->dumpJsonFile(); $filesize = number_format(filesize($jsonPath) / 1024, 2); // kB $this->logger->info(sprintf('File size: <info>%s</info> kB', $filesize)); return $this; }
[ "protected", "function", "dumpJsonFile", "(", ")", "{", "$", "jsonPath", "=", "$", "this", "->", "config", "->", "getJsonPath", "(", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "sprintf", "(", "'Dump submitting json file: %s'", ",", "$", "jso...
Dump submitting json file. @return $this
[ "Dump", "submitting", "json", "file", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Repository/JobsRepository.php#L151-L162
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Repository/JobsRepository.php
JobsRepository.send
protected function send() { $this->logger->info(sprintf('Submitting to %s', Jobs::URL)); try { $response = $this->api->send(); $message = $response ? sprintf('Finish submitting. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase()) : 'Finish dry run'; $this->logger->info($message); if ($response instanceof Response) { $this->logResponse($response); } return true; } catch (\GuzzleHttp\Exception\ConnectException $e) { // connection error $message = sprintf("Connection error occurred. %s\n\n%s", $e->getMessage(), $e->getTraceAsString()); } catch (\GuzzleHttp\Exception\ClientException $e) { // 422 Unprocessable Entity $response = $e->getResponse(); $message = sprintf('Client error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase()); } catch (\GuzzleHttp\Exception\ServerException $e) { // 500 Internal Server Error // 503 Service Unavailable $response = $e->getResponse(); $message = sprintf('Server error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase()); } $this->logger->error($message); if (isset($response)) { $this->logResponse($response); } return false; }
php
protected function send() { $this->logger->info(sprintf('Submitting to %s', Jobs::URL)); try { $response = $this->api->send(); $message = $response ? sprintf('Finish submitting. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase()) : 'Finish dry run'; $this->logger->info($message); if ($response instanceof Response) { $this->logResponse($response); } return true; } catch (\GuzzleHttp\Exception\ConnectException $e) { // connection error $message = sprintf("Connection error occurred. %s\n\n%s", $e->getMessage(), $e->getTraceAsString()); } catch (\GuzzleHttp\Exception\ClientException $e) { // 422 Unprocessable Entity $response = $e->getResponse(); $message = sprintf('Client error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase()); } catch (\GuzzleHttp\Exception\ServerException $e) { // 500 Internal Server Error // 503 Service Unavailable $response = $e->getResponse(); $message = sprintf('Server error occurred. status: %s %s', $response->getStatusCode(), $response->getReasonPhrase()); } $this->logger->error($message); if (isset($response)) { $this->logResponse($response); } return false; }
[ "protected", "function", "send", "(", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "sprintf", "(", "'Submitting to %s'", ",", "Jobs", "::", "URL", ")", ")", ";", "try", "{", "$", "response", "=", "$", "this", "->", "api", "->", "send", ...
Send json_file to Jobs API. @return bool
[ "Send", "json_file", "to", "Jobs", "API", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Repository/JobsRepository.php#L169-L207
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Repository/JobsRepository.php
JobsRepository.colorizeCoverage
protected function colorizeCoverage($coverage, $format) { if ($coverage >= 90) { return sprintf('<info>%s</info>', $format); } if ($coverage >= 80) { return sprintf('<comment>%s</comment>', $format); } return sprintf('<fg=red>%s</fg=red>', $format); }
php
protected function colorizeCoverage($coverage, $format) { if ($coverage >= 90) { return sprintf('<info>%s</info>', $format); } if ($coverage >= 80) { return sprintf('<comment>%s</comment>', $format); } return sprintf('<fg=red>%s</fg=red>', $format); }
[ "protected", "function", "colorizeCoverage", "(", "$", "coverage", ",", "$", "format", ")", "{", "if", "(", "$", "coverage", ">=", "90", ")", "{", "return", "sprintf", "(", "'<info>%s</info>'", ",", "$", "format", ")", ";", "}", "if", "(", "$", "covera...
Colorize coverage. * green 90% - 100% <info> * yellow 80% - 90% <comment> * red 0% - 80% <fg=red> @param float $coverage coverage @param string $format format string to colorize @return string
[ "Colorize", "coverage", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Repository/JobsRepository.php#L223-L234
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Repository/JobsRepository.php
JobsRepository.logCollectedSourceFiles
protected function logCollectedSourceFiles(JsonFile $jsonFile) { $sourceFiles = $jsonFile->getSourceFiles(); $numFiles = count($sourceFiles); $this->logger->info(sprintf('Found <info>%s</info> source file%s:', number_format($numFiles), $numFiles > 1 ? 's' : '')); foreach ($sourceFiles as $sourceFile) { /* @var $sourceFile \PhpCoveralls\Bundle\CoverallsBundle\Entity\SourceFile */ $coverage = $sourceFile->reportLineCoverage(); $template = ' - ' . $this->colorizeCoverage($coverage, '%6.2f%%') . ' %s'; $this->logger->info(sprintf($template, $coverage, $sourceFile->getName())); } $coverage = $jsonFile->reportLineCoverage(); $template = 'Coverage: ' . $this->colorizeCoverage($coverage, '%6.2f%% (%d/%d)'); $metrics = $jsonFile->getMetrics(); $this->logger->info(sprintf($template, $coverage, $metrics->getCoveredStatements(), $metrics->getStatements())); }
php
protected function logCollectedSourceFiles(JsonFile $jsonFile) { $sourceFiles = $jsonFile->getSourceFiles(); $numFiles = count($sourceFiles); $this->logger->info(sprintf('Found <info>%s</info> source file%s:', number_format($numFiles), $numFiles > 1 ? 's' : '')); foreach ($sourceFiles as $sourceFile) { /* @var $sourceFile \PhpCoveralls\Bundle\CoverallsBundle\Entity\SourceFile */ $coverage = $sourceFile->reportLineCoverage(); $template = ' - ' . $this->colorizeCoverage($coverage, '%6.2f%%') . ' %s'; $this->logger->info(sprintf($template, $coverage, $sourceFile->getName())); } $coverage = $jsonFile->reportLineCoverage(); $template = 'Coverage: ' . $this->colorizeCoverage($coverage, '%6.2f%% (%d/%d)'); $metrics = $jsonFile->getMetrics(); $this->logger->info(sprintf($template, $coverage, $metrics->getCoveredStatements(), $metrics->getStatements())); }
[ "protected", "function", "logCollectedSourceFiles", "(", "JsonFile", "$", "jsonFile", ")", "{", "$", "sourceFiles", "=", "$", "jsonFile", "->", "getSourceFiles", "(", ")", ";", "$", "numFiles", "=", "count", "(", "$", "sourceFiles", ")", ";", "$", "this", ...
Log collected source files. @param JsonFile $jsonFile json file
[ "Log", "collected", "source", "files", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Repository/JobsRepository.php#L241-L261
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Repository/JobsRepository.php
JobsRepository.logResponse
protected function logResponse(Response $response) { $raw_body = (string) $response->getBody(); $body = json_decode($raw_body, true); if ($body === null) { // the response body is not in JSON format $this->logger->error($raw_body); } elseif (isset($body['error'])) { if (isset($body['message'])) { $this->logger->error($body['message']); } } else { if (isset($body['message'])) { $this->logger->info(sprintf('Accepted %s', $body['message'])); } if (isset($body['url'])) { $this->logger->info(sprintf('You can see the build on %s', $body['url'])); } } }
php
protected function logResponse(Response $response) { $raw_body = (string) $response->getBody(); $body = json_decode($raw_body, true); if ($body === null) { // the response body is not in JSON format $this->logger->error($raw_body); } elseif (isset($body['error'])) { if (isset($body['message'])) { $this->logger->error($body['message']); } } else { if (isset($body['message'])) { $this->logger->info(sprintf('Accepted %s', $body['message'])); } if (isset($body['url'])) { $this->logger->info(sprintf('You can see the build on %s', $body['url'])); } } }
[ "protected", "function", "logResponse", "(", "Response", "$", "response", ")", "{", "$", "raw_body", "=", "(", "string", ")", "$", "response", "->", "getBody", "(", ")", ";", "$", "body", "=", "json_decode", "(", "$", "raw_body", ",", "true", ")", ";",...
Log response. @param Response $response aPI response
[ "Log", "response", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Repository/JobsRepository.php#L268-L288
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/Git/Git.php
Git.toArray
public function toArray() { $remotes = []; foreach ($this->remotes as $remote) { $remotes[] = $remote->toArray(); } return [ 'branch' => $this->branch, 'head' => $this->head->toArray(), 'remotes' => $remotes, ]; }
php
public function toArray() { $remotes = []; foreach ($this->remotes as $remote) { $remotes[] = $remote->toArray(); } return [ 'branch' => $this->branch, 'head' => $this->head->toArray(), 'remotes' => $remotes, ]; }
[ "public", "function", "toArray", "(", ")", "{", "$", "remotes", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "remotes", "as", "$", "remote", ")", "{", "$", "remotes", "[", "]", "=", "$", "remote", "->", "toArray", "(", ")", ";", "}", ...
{@inheritdoc} @see \PhpCoveralls\Bundle\CoverallsBundle\Entity\ArrayConvertable::toArray()
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/Git/Git.php#L74-L87
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/Exception/RequirementsNotSatisfiedException.php
RequirementsNotSatisfiedException.getHelpMessage
public function getHelpMessage() { $message = $this->message . "\n"; if (is_array($this->readEnv)) { foreach ($this->readEnv as $envVarName => $value) { $message .= $this->format($envVarName, $value); } } $message .= <<< 'EOL' Set environment variables properly like the following. For Travis users: - TRAVIS - TRAVIS_JOB_ID For CircleCI users: - CIRCLECI - CIRCLE_BUILD_NUM - COVERALLS_REPO_TOKEN For Jenkins users: - JENKINS_URL - BUILD_NUMBER - COVERALLS_REPO_TOKEN For AppVeyor users: - APPVEYOR - APPVEYOR_BUILD_NUMBER From local environment: - COVERALLS_RUN_LOCALLY - COVERALLS_REPO_TOKEN EOL; return $message; }
php
public function getHelpMessage() { $message = $this->message . "\n"; if (is_array($this->readEnv)) { foreach ($this->readEnv as $envVarName => $value) { $message .= $this->format($envVarName, $value); } } $message .= <<< 'EOL' Set environment variables properly like the following. For Travis users: - TRAVIS - TRAVIS_JOB_ID For CircleCI users: - CIRCLECI - CIRCLE_BUILD_NUM - COVERALLS_REPO_TOKEN For Jenkins users: - JENKINS_URL - BUILD_NUMBER - COVERALLS_REPO_TOKEN For AppVeyor users: - APPVEYOR - APPVEYOR_BUILD_NUMBER From local environment: - COVERALLS_RUN_LOCALLY - COVERALLS_REPO_TOKEN EOL; return $message; }
[ "public", "function", "getHelpMessage", "(", ")", "{", "$", "message", "=", "$", "this", "->", "message", ".", "\"\\n\"", ";", "if", "(", "is_array", "(", "$", "this", "->", "readEnv", ")", ")", "{", "foreach", "(", "$", "this", "->", "readEnv", "as"...
Return help message. @return string
[ "Return", "help", "message", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/Exception/RequirementsNotSatisfiedException.php#L40-L83
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/Exception/RequirementsNotSatisfiedException.php
RequirementsNotSatisfiedException.format
protected function format($key, $value) { if (in_array($key, self::$secretEnvVars, true) && is_string($value) && strlen($value) > 0) { $value = '********(HIDDEN)'; } return sprintf(" - %s=%s\n", $key, var_export($value, true)); }
php
protected function format($key, $value) { if (in_array($key, self::$secretEnvVars, true) && is_string($value) && strlen($value) > 0) { $value = '********(HIDDEN)'; } return sprintf(" - %s=%s\n", $key, var_export($value, true)); }
[ "protected", "function", "format", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "key", ",", "self", "::", "$", "secretEnvVars", ",", "true", ")", "&&", "is_string", "(", "$", "value", ")", "&&", "strlen", "(", "$",...
Format a pair of the envVarName and the value. @param string $key the env var name @param string $value the value of the env var @return string
[ "Format", "a", "pair", "of", "the", "envVarName", "and", "the", "value", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/Exception/RequirementsNotSatisfiedException.php#L113-L122
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Api/Jobs.php
Jobs.collectCloverXml
public function collectCloverXml() { $rootDir = $this->config->getRootDir(); $cloverXmlPaths = $this->config->getCloverXmlPaths(); $xmlCollector = new CloverXmlCoverageCollector(); foreach ($cloverXmlPaths as $cloverXmlPath) { $xml = simplexml_load_file($cloverXmlPath); $xmlCollector->collect($xml, $rootDir); } $this->jsonFile = $xmlCollector->getJsonFile(); if ($this->config->isExcludeNoStatements()) { $this->jsonFile->excludeNoStatementsFiles(); } $this->jsonFile->sortSourceFiles(); return $this; }
php
public function collectCloverXml() { $rootDir = $this->config->getRootDir(); $cloverXmlPaths = $this->config->getCloverXmlPaths(); $xmlCollector = new CloverXmlCoverageCollector(); foreach ($cloverXmlPaths as $cloverXmlPath) { $xml = simplexml_load_file($cloverXmlPath); $xmlCollector->collect($xml, $rootDir); } $this->jsonFile = $xmlCollector->getJsonFile(); if ($this->config->isExcludeNoStatements()) { $this->jsonFile->excludeNoStatementsFiles(); } $this->jsonFile->sortSourceFiles(); return $this; }
[ "public", "function", "collectCloverXml", "(", ")", "{", "$", "rootDir", "=", "$", "this", "->", "config", "->", "getRootDir", "(", ")", ";", "$", "cloverXmlPaths", "=", "$", "this", "->", "config", "->", "getCloverXmlPaths", "(", ")", ";", "$", "xmlColl...
Collect clover XML into json_file. @return $this
[ "Collect", "clover", "XML", "into", "json_file", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Api/Jobs.php#L46-L67
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Api/Jobs.php
Jobs.collectGitInfo
public function collectGitInfo() { $command = new GitCommand(); $gitCollector = new GitInfoCollector($command); $this->jsonFile->setGit($gitCollector->collect()); return $this; }
php
public function collectGitInfo() { $command = new GitCommand(); $gitCollector = new GitInfoCollector($command); $this->jsonFile->setGit($gitCollector->collect()); return $this; }
[ "public", "function", "collectGitInfo", "(", ")", "{", "$", "command", "=", "new", "GitCommand", "(", ")", ";", "$", "gitCollector", "=", "new", "GitInfoCollector", "(", "$", "command", ")", ";", "$", "this", "->", "jsonFile", "->", "setGit", "(", "$", ...
Collect git repository info into json_file. @return $this
[ "Collect", "git", "repository", "info", "into", "json_file", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Api/Jobs.php#L74-L82
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Api/Jobs.php
Jobs.collectEnvVars
public function collectEnvVars(array $env) { $envCollector = new CiEnvVarsCollector($this->config); try { $this->jsonFile->fillJobs($envCollector->collect($env)); } catch (\PhpCoveralls\Bundle\CoverallsBundle\Entity\Exception\RequirementsNotSatisfiedException $e) { $e->setReadEnv($envCollector->getReadEnv()); throw $e; } return $this; }
php
public function collectEnvVars(array $env) { $envCollector = new CiEnvVarsCollector($this->config); try { $this->jsonFile->fillJobs($envCollector->collect($env)); } catch (\PhpCoveralls\Bundle\CoverallsBundle\Entity\Exception\RequirementsNotSatisfiedException $e) { $e->setReadEnv($envCollector->getReadEnv()); throw $e; } return $this; }
[ "public", "function", "collectEnvVars", "(", "array", "$", "env", ")", "{", "$", "envCollector", "=", "new", "CiEnvVarsCollector", "(", "$", "this", "->", "config", ")", ";", "try", "{", "$", "this", "->", "jsonFile", "->", "fillJobs", "(", "$", "envColl...
Collect environment variables. @param array $env $_SERVER environment @throws \PhpCoveralls\Bundle\CoverallsBundle\Entity\Exception\RequirementsNotSatisfiedException @return $this
[ "Collect", "environment", "variables", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Api/Jobs.php#L93-L106
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Api/Jobs.php
Jobs.dumpJsonFile
public function dumpJsonFile() { $jsonPath = $this->config->getJsonPath(); file_put_contents($jsonPath, $this->jsonFile); return $this; }
php
public function dumpJsonFile() { $jsonPath = $this->config->getJsonPath(); file_put_contents($jsonPath, $this->jsonFile); return $this; }
[ "public", "function", "dumpJsonFile", "(", ")", "{", "$", "jsonPath", "=", "$", "this", "->", "config", "->", "getJsonPath", "(", ")", ";", "file_put_contents", "(", "$", "jsonPath", ",", "$", "this", "->", "jsonFile", ")", ";", "return", "$", "this", ...
Dump uploading json file. @return $this
[ "Dump", "uploading", "json", "file", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Api/Jobs.php#L113-L120
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Api/Jobs.php
Jobs.send
public function send() { if ($this->config->isDryRun()) { return; } $jsonPath = $this->config->getJsonPath(); return $this->upload(static::URL, $jsonPath, static::FILENAME); }
php
public function send() { if ($this->config->isDryRun()) { return; } $jsonPath = $this->config->getJsonPath(); return $this->upload(static::URL, $jsonPath, static::FILENAME); }
[ "public", "function", "send", "(", ")", "{", "if", "(", "$", "this", "->", "config", "->", "isDryRun", "(", ")", ")", "{", "return", ";", "}", "$", "jsonPath", "=", "$", "this", "->", "config", "->", "getJsonPath", "(", ")", ";", "return", "$", "...
Send json_file to jobs API. @return null|\GuzzleHttp\Psr7\Response
[ "Send", "json_file", "to", "jobs", "API", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Api/Jobs.php#L127-L136
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Api/Jobs.php
Jobs.upload
protected function upload($url, $path, $filename) { $options = [ 'multipart' => [ [ 'name' => $filename, 'contents' => file_get_contents($path), 'filename' => basename($path), ], ], ]; return $this->client->post($url, $options); }
php
protected function upload($url, $path, $filename) { $options = [ 'multipart' => [ [ 'name' => $filename, 'contents' => file_get_contents($path), 'filename' => basename($path), ], ], ]; return $this->client->post($url, $options); }
[ "protected", "function", "upload", "(", "$", "url", ",", "$", "path", ",", "$", "filename", ")", "{", "$", "options", "=", "[", "'multipart'", "=>", "[", "[", "'name'", "=>", "$", "filename", ",", "'contents'", "=>", "file_get_contents", "(", "$", "pat...
Upload a file. @param string $url uRL to upload @param string $path file path @param string $filename filename @return \GuzzleHttp\Psr7\Response
[ "Upload", "a", "file", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Api/Jobs.php#L175-L188
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php
CloverXmlCoverageCollector.collect
public function collect(\SimpleXMLElement $xml, $rootDir) { $root = rtrim($rootDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if ($this->jsonFile === null) { $this->jsonFile = new JsonFile(); } // overwrite if run_at has already been set $runAt = $this->collectRunAt($xml); $this->jsonFile->setRunAt($runAt); $xpaths = [ '/coverage/project/file', '/coverage/project/package/file', ]; foreach ($xpaths as $xpath) { foreach ($xml->xpath($xpath) as $file) { $srcFile = $this->collectFileCoverage($file, $root); if ($srcFile !== null) { $this->jsonFile->addSourceFile($srcFile); } } } return $this->jsonFile; }
php
public function collect(\SimpleXMLElement $xml, $rootDir) { $root = rtrim($rootDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if ($this->jsonFile === null) { $this->jsonFile = new JsonFile(); } // overwrite if run_at has already been set $runAt = $this->collectRunAt($xml); $this->jsonFile->setRunAt($runAt); $xpaths = [ '/coverage/project/file', '/coverage/project/package/file', ]; foreach ($xpaths as $xpath) { foreach ($xml->xpath($xpath) as $file) { $srcFile = $this->collectFileCoverage($file, $root); if ($srcFile !== null) { $this->jsonFile->addSourceFile($srcFile); } } } return $this->jsonFile; }
[ "public", "function", "collect", "(", "\\", "SimpleXMLElement", "$", "xml", ",", "$", "rootDir", ")", "{", "$", "root", "=", "rtrim", "(", "$", "rootDir", ",", "DIRECTORY_SEPARATOR", ")", ".", "DIRECTORY_SEPARATOR", ";", "if", "(", "$", "this", "->", "js...
Collect coverage from XML object. @param \SimpleXMLElement $xml clover XML object @param string $rootDir path to repository root directory @return \PhpCoveralls\Bundle\CoverallsBundle\Entity\JsonFile
[ "Collect", "coverage", "from", "XML", "object", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php#L32-L60
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php
CloverXmlCoverageCollector.collectRunAt
protected function collectRunAt(\SimpleXMLElement $xml, $format = 'Y-m-d H:i:s O') { $timestamp = $xml->project['timestamp']; $runAt = new \DateTime('@' . $timestamp); return $runAt->format($format); }
php
protected function collectRunAt(\SimpleXMLElement $xml, $format = 'Y-m-d H:i:s O') { $timestamp = $xml->project['timestamp']; $runAt = new \DateTime('@' . $timestamp); return $runAt->format($format); }
[ "protected", "function", "collectRunAt", "(", "\\", "SimpleXMLElement", "$", "xml", ",", "$", "format", "=", "'Y-m-d H:i:s O'", ")", "{", "$", "timestamp", "=", "$", "xml", "->", "project", "[", "'timestamp'", "]", ";", "$", "runAt", "=", "new", "\\", "D...
Collect timestamp when the job ran. @param \SimpleXMLElement $xml clover XML object of a file @param string $format dateTime format @return string
[ "Collect", "timestamp", "when", "the", "job", "ran", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php#L84-L90
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php
CloverXmlCoverageCollector.collectFileCoverage
protected function collectFileCoverage(\SimpleXMLElement $file, $root) { $absolutePath = realpath((string) ($file['path'] ?: $file['name'])); if (strpos($absolutePath, $root) === false) { return; } $filename = $absolutePath; if ($root !== DIRECTORY_SEPARATOR) { $filename = str_replace($root, '', $absolutePath); } return $this->collectCoverage($file, $absolutePath, $filename); }
php
protected function collectFileCoverage(\SimpleXMLElement $file, $root) { $absolutePath = realpath((string) ($file['path'] ?: $file['name'])); if (strpos($absolutePath, $root) === false) { return; } $filename = $absolutePath; if ($root !== DIRECTORY_SEPARATOR) { $filename = str_replace($root, '', $absolutePath); } return $this->collectCoverage($file, $absolutePath, $filename); }
[ "protected", "function", "collectFileCoverage", "(", "\\", "SimpleXMLElement", "$", "file", ",", "$", "root", ")", "{", "$", "absolutePath", "=", "realpath", "(", "(", "string", ")", "(", "$", "file", "[", "'path'", "]", "?", ":", "$", "file", "[", "'n...
Collect coverage data of a file. @param \SimpleXMLElement $file clover XML object of a file @param string $root path to src directory @return null|\PhpCoveralls\Bundle\CoverallsBundle\Entity\SourceFile
[ "Collect", "coverage", "data", "of", "a", "file", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php#L100-L115
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php
CloverXmlCoverageCollector.collectCoverage
protected function collectCoverage(\SimpleXMLElement $file, $path, $filename) { if ($this->jsonFile->hasSourceFile($path)) { $srcFile = $this->jsonFile->getSourceFile($path); } else { $srcFile = new SourceFile($path, $filename); } foreach ($file->line as $line) { if ((string) $line['type'] === 'stmt') { $lineNum = (int) $line['num']; if ($lineNum > 0) { $srcFile->addCoverage($lineNum - 1, (int) $line['count']); } } } return $srcFile; }
php
protected function collectCoverage(\SimpleXMLElement $file, $path, $filename) { if ($this->jsonFile->hasSourceFile($path)) { $srcFile = $this->jsonFile->getSourceFile($path); } else { $srcFile = new SourceFile($path, $filename); } foreach ($file->line as $line) { if ((string) $line['type'] === 'stmt') { $lineNum = (int) $line['num']; if ($lineNum > 0) { $srcFile->addCoverage($lineNum - 1, (int) $line['count']); } } } return $srcFile; }
[ "protected", "function", "collectCoverage", "(", "\\", "SimpleXMLElement", "$", "file", ",", "$", "path", ",", "$", "filename", ")", "{", "if", "(", "$", "this", "->", "jsonFile", "->", "hasSourceFile", "(", "$", "path", ")", ")", "{", "$", "srcFile", ...
Collect coverage data. @param \SimpleXMLElement $file clover XML object of a file @param string $path path to source file @param string $filename filename @return \PhpCoveralls\Bundle\CoverallsBundle\Entity\SourceFile
[ "Collect", "coverage", "data", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CloverXmlCoverageCollector.php#L126-L145
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php
CiEnvVarsCollector.collect
public function collect(array $env) { $this->env = $env; $this->readEnv = []; $this ->fillTravisCi() ->fillCircleCi() ->fillAppVeyor() ->fillJenkins() ->fillLocal() ->fillRepoToken(); return $this->env; }
php
public function collect(array $env) { $this->env = $env; $this->readEnv = []; $this ->fillTravisCi() ->fillCircleCi() ->fillAppVeyor() ->fillJenkins() ->fillLocal() ->fillRepoToken(); return $this->env; }
[ "public", "function", "collect", "(", "array", "$", "env", ")", "{", "$", "this", "->", "env", "=", "$", "env", ";", "$", "this", "->", "readEnv", "=", "[", "]", ";", "$", "this", "->", "fillTravisCi", "(", ")", "->", "fillCircleCi", "(", ")", "-...
Collect environment variables. @param array $env $_SERVER environment @return array
[ "Collect", "environment", "variables", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php#L56-L70
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php
CiEnvVarsCollector.fillTravisCi
protected function fillTravisCi() { if (isset($this->env['TRAVIS']) && $this->env['TRAVIS'] && isset($this->env['TRAVIS_JOB_ID'])) { $this->env['CI_JOB_ID'] = $this->env['TRAVIS_JOB_ID']; if ($this->config->hasServiceName()) { $this->env['CI_NAME'] = $this->config->getServiceName(); } else { $this->env['CI_NAME'] = 'travis-ci'; } // backup $this->readEnv['TRAVIS'] = $this->env['TRAVIS']; $this->readEnv['TRAVIS_JOB_ID'] = $this->env['TRAVIS_JOB_ID']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
php
protected function fillTravisCi() { if (isset($this->env['TRAVIS']) && $this->env['TRAVIS'] && isset($this->env['TRAVIS_JOB_ID'])) { $this->env['CI_JOB_ID'] = $this->env['TRAVIS_JOB_ID']; if ($this->config->hasServiceName()) { $this->env['CI_NAME'] = $this->config->getServiceName(); } else { $this->env['CI_NAME'] = 'travis-ci'; } // backup $this->readEnv['TRAVIS'] = $this->env['TRAVIS']; $this->readEnv['TRAVIS_JOB_ID'] = $this->env['TRAVIS_JOB_ID']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
[ "protected", "function", "fillTravisCi", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "env", "[", "'TRAVIS'", "]", ")", "&&", "$", "this", "->", "env", "[", "'TRAVIS'", "]", "&&", "isset", "(", "$", "this", "->", "env", "[", "'TRAVIS_...
Fill Travis CI environment variables. "TRAVIS", "TRAVIS_JOB_ID" must be set. @return $this
[ "Fill", "Travis", "CI", "environment", "variables", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php#L93-L111
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php
CiEnvVarsCollector.fillCircleCi
protected function fillCircleCi() { if (isset($this->env['CIRCLECI']) && $this->env['CIRCLECI'] && isset($this->env['CIRCLE_BUILD_NUM'])) { $this->env['CI_BUILD_NUMBER'] = $this->env['CIRCLE_BUILD_NUM']; $this->env['CI_NAME'] = 'circleci'; // backup $this->readEnv['CIRCLECI'] = $this->env['CIRCLECI']; $this->readEnv['CIRCLE_BUILD_NUM'] = $this->env['CIRCLE_BUILD_NUM']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
php
protected function fillCircleCi() { if (isset($this->env['CIRCLECI']) && $this->env['CIRCLECI'] && isset($this->env['CIRCLE_BUILD_NUM'])) { $this->env['CI_BUILD_NUMBER'] = $this->env['CIRCLE_BUILD_NUM']; $this->env['CI_NAME'] = 'circleci'; // backup $this->readEnv['CIRCLECI'] = $this->env['CIRCLECI']; $this->readEnv['CIRCLE_BUILD_NUM'] = $this->env['CIRCLE_BUILD_NUM']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
[ "protected", "function", "fillCircleCi", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "env", "[", "'CIRCLECI'", "]", ")", "&&", "$", "this", "->", "env", "[", "'CIRCLECI'", "]", "&&", "isset", "(", "$", "this", "->", "env", "[", "'CIR...
Fill CircleCI environment variables. "CIRCLECI", "CIRCLE_BUILD_NUM" must be set. @return $this
[ "Fill", "CircleCI", "environment", "variables", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php#L120-L133
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php
CiEnvVarsCollector.fillAppVeyor
protected function fillAppVeyor() { if (isset($this->env['APPVEYOR']) && $this->env['APPVEYOR'] && isset($this->env['APPVEYOR_BUILD_NUMBER'])) { $this->env['CI_BUILD_NUMBER'] = $this->env['APPVEYOR_BUILD_NUMBER']; $this->env['CI_JOB_ID'] = $this->env['APPVEYOR_JOB_NUMBER']; $this->env['CI_BRANCH'] = $this->env['APPVEYOR_REPO_BRANCH']; $this->env['CI_PULL_REQUEST'] = $this->env['APPVEYOR_PULL_REQUEST_NUMBER']; $this->env['CI_NAME'] = 'AppVeyor'; // backup $this->readEnv['APPVEYOR'] = $this->env['APPVEYOR']; $this->readEnv['APPVEYOR_BUILD_NUMBER'] = $this->env['APPVEYOR_BUILD_NUMBER']; $this->readEnv['APPVEYOR_JOB_NUMBER'] = $this->env['APPVEYOR_JOB_NUMBER']; $this->readEnv['APPVEYOR_REPO_BRANCH'] = $this->env['APPVEYOR_REPO_BRANCH']; $this->readEnv['APPVEYOR_PULL_REQUEST_NUMBER'] = $this->env['APPVEYOR_PULL_REQUEST_NUMBER']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
php
protected function fillAppVeyor() { if (isset($this->env['APPVEYOR']) && $this->env['APPVEYOR'] && isset($this->env['APPVEYOR_BUILD_NUMBER'])) { $this->env['CI_BUILD_NUMBER'] = $this->env['APPVEYOR_BUILD_NUMBER']; $this->env['CI_JOB_ID'] = $this->env['APPVEYOR_JOB_NUMBER']; $this->env['CI_BRANCH'] = $this->env['APPVEYOR_REPO_BRANCH']; $this->env['CI_PULL_REQUEST'] = $this->env['APPVEYOR_PULL_REQUEST_NUMBER']; $this->env['CI_NAME'] = 'AppVeyor'; // backup $this->readEnv['APPVEYOR'] = $this->env['APPVEYOR']; $this->readEnv['APPVEYOR_BUILD_NUMBER'] = $this->env['APPVEYOR_BUILD_NUMBER']; $this->readEnv['APPVEYOR_JOB_NUMBER'] = $this->env['APPVEYOR_JOB_NUMBER']; $this->readEnv['APPVEYOR_REPO_BRANCH'] = $this->env['APPVEYOR_REPO_BRANCH']; $this->readEnv['APPVEYOR_PULL_REQUEST_NUMBER'] = $this->env['APPVEYOR_PULL_REQUEST_NUMBER']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
[ "protected", "function", "fillAppVeyor", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "env", "[", "'APPVEYOR'", "]", ")", "&&", "$", "this", "->", "env", "[", "'APPVEYOR'", "]", "&&", "isset", "(", "$", "this", "->", "env", "[", "'APP...
Fill AppVeyor environment variables. "APPVEYOR", "APPVEYOR_BUILD_NUMBER" must be set. @return $this
[ "Fill", "AppVeyor", "environment", "variables", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php#L142-L161
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php
CiEnvVarsCollector.fillLocal
protected function fillLocal() { if (isset($this->env['COVERALLS_RUN_LOCALLY']) && $this->env['COVERALLS_RUN_LOCALLY']) { $this->env['CI_JOB_ID'] = null; $this->env['CI_NAME'] = 'php-coveralls'; $this->env['COVERALLS_EVENT_TYPE'] = 'manual'; // backup $this->readEnv['COVERALLS_RUN_LOCALLY'] = $this->env['COVERALLS_RUN_LOCALLY']; $this->readEnv['COVERALLS_EVENT_TYPE'] = $this->env['COVERALLS_EVENT_TYPE']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
php
protected function fillLocal() { if (isset($this->env['COVERALLS_RUN_LOCALLY']) && $this->env['COVERALLS_RUN_LOCALLY']) { $this->env['CI_JOB_ID'] = null; $this->env['CI_NAME'] = 'php-coveralls'; $this->env['COVERALLS_EVENT_TYPE'] = 'manual'; // backup $this->readEnv['COVERALLS_RUN_LOCALLY'] = $this->env['COVERALLS_RUN_LOCALLY']; $this->readEnv['COVERALLS_EVENT_TYPE'] = $this->env['COVERALLS_EVENT_TYPE']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
[ "protected", "function", "fillLocal", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "env", "[", "'COVERALLS_RUN_LOCALLY'", "]", ")", "&&", "$", "this", "->", "env", "[", "'COVERALLS_RUN_LOCALLY'", "]", ")", "{", "$", "this", "->", "env", "...
Fill local environment variables. "COVERALLS_RUN_LOCALLY" must be set. @return $this
[ "Fill", "local", "environment", "variables", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php#L193-L207
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php
CiEnvVarsCollector.fillRepoToken
protected function fillRepoToken() { if ($this->config->hasRepoToken()) { $this->env['COVERALLS_REPO_TOKEN'] = $this->config->getRepoToken(); } // backup if (isset($this->env['COVERALLS_REPO_TOKEN'])) { $this->readEnv['COVERALLS_REPO_TOKEN'] = $this->env['COVERALLS_REPO_TOKEN']; } return $this; }
php
protected function fillRepoToken() { if ($this->config->hasRepoToken()) { $this->env['COVERALLS_REPO_TOKEN'] = $this->config->getRepoToken(); } // backup if (isset($this->env['COVERALLS_REPO_TOKEN'])) { $this->readEnv['COVERALLS_REPO_TOKEN'] = $this->env['COVERALLS_REPO_TOKEN']; } return $this; }
[ "protected", "function", "fillRepoToken", "(", ")", "{", "if", "(", "$", "this", "->", "config", "->", "hasRepoToken", "(", ")", ")", "{", "$", "this", "->", "env", "[", "'COVERALLS_REPO_TOKEN'", "]", "=", "$", "this", "->", "config", "->", "getRepoToken...
Fill repo_token for unsupported CI service. "COVERALLS_REPO_TOKEN" must be set. @return $this
[ "Fill", "repo_token", "for", "unsupported", "CI", "service", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/CiEnvVarsCollector.php#L216-L228
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/GitInfoCollector.php
GitInfoCollector.collectBranch
protected function collectBranch() { $branchesResult = $this->command->getBranches(); foreach ($branchesResult as $result) { if (strpos($result, '* ') === 0) { $exploded = explode('* ', $result, 2); return $exploded[1]; } } throw new \RuntimeException(); }
php
protected function collectBranch() { $branchesResult = $this->command->getBranches(); foreach ($branchesResult as $result) { if (strpos($result, '* ') === 0) { $exploded = explode('* ', $result, 2); return $exploded[1]; } } throw new \RuntimeException(); }
[ "protected", "function", "collectBranch", "(", ")", "{", "$", "branchesResult", "=", "$", "this", "->", "command", "->", "getBranches", "(", ")", ";", "foreach", "(", "$", "branchesResult", "as", "$", "result", ")", "{", "if", "(", "strpos", "(", "$", ...
Collect branch name. @throws \RuntimeException @return string
[ "Collect", "branch", "name", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/GitInfoCollector.php#L71-L84
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/GitInfoCollector.php
GitInfoCollector.collectCommit
protected function collectCommit() { $commitResult = $this->command->getHeadCommit(); if (count($commitResult) !== 6 || array_keys($commitResult) !== range(0, 5)) { throw new \RuntimeException(); } $commit = new Commit(); return $commit ->setId($commitResult[0]) ->setAuthorName($commitResult[1]) ->setAuthorEmail($commitResult[2]) ->setCommitterName($commitResult[3]) ->setCommitterEmail($commitResult[4]) ->setMessage($commitResult[5]); }
php
protected function collectCommit() { $commitResult = $this->command->getHeadCommit(); if (count($commitResult) !== 6 || array_keys($commitResult) !== range(0, 5)) { throw new \RuntimeException(); } $commit = new Commit(); return $commit ->setId($commitResult[0]) ->setAuthorName($commitResult[1]) ->setAuthorEmail($commitResult[2]) ->setCommitterName($commitResult[3]) ->setCommitterEmail($commitResult[4]) ->setMessage($commitResult[5]); }
[ "protected", "function", "collectCommit", "(", ")", "{", "$", "commitResult", "=", "$", "this", "->", "command", "->", "getHeadCommit", "(", ")", ";", "if", "(", "count", "(", "$", "commitResult", ")", "!==", "6", "||", "array_keys", "(", "$", "commitRes...
Collect commit info. @throws \RuntimeException @return \PhpCoveralls\Bundle\CoverallsBundle\Entity\Git\Commit
[ "Collect", "commit", "info", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/GitInfoCollector.php#L93-L110
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Collector/GitInfoCollector.php
GitInfoCollector.collectRemotes
protected function collectRemotes() { $remotesResult = $this->command->getRemotes(); if (count($remotesResult) === 0) { throw new \RuntimeException(); } // parse command result $results = []; foreach ($remotesResult as $result) { if (strpos($result, ' ') !== false) { list($remote) = explode(' ', $result, 2); $results[] = $remote; } } // filter $results = array_unique($results); // create Remote instances $remotes = []; foreach ($results as $result) { if (strpos($result, "\t") !== false) { list($name, $url) = explode("\t", $result, 2); $remote = new Remote(); $remotes[] = $remote->setName($name)->setUrl($url); } } return $remotes; }
php
protected function collectRemotes() { $remotesResult = $this->command->getRemotes(); if (count($remotesResult) === 0) { throw new \RuntimeException(); } // parse command result $results = []; foreach ($remotesResult as $result) { if (strpos($result, ' ') !== false) { list($remote) = explode(' ', $result, 2); $results[] = $remote; } } // filter $results = array_unique($results); // create Remote instances $remotes = []; foreach ($results as $result) { if (strpos($result, "\t") !== false) { list($name, $url) = explode("\t", $result, 2); $remote = new Remote(); $remotes[] = $remote->setName($name)->setUrl($url); } } return $remotes; }
[ "protected", "function", "collectRemotes", "(", ")", "{", "$", "remotesResult", "=", "$", "this", "->", "command", "->", "getRemotes", "(", ")", ";", "if", "(", "count", "(", "$", "remotesResult", ")", "===", "0", ")", "{", "throw", "new", "\\", "Runti...
Collect remotes info. @throws \RuntimeException @return \PhpCoveralls\Bundle\CoverallsBundle\Entity\Git\Remote[]
[ "Collect", "remotes", "info", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Collector/GitInfoCollector.php#L119-L154
php-coveralls/php-coveralls
src/Component/System/SystemCommandExecutor.php
SystemCommandExecutor.execute
public function execute($command) { exec($command, $result, $returnValue); if ($returnValue === 0) { return $result; } throw new \RuntimeException(sprintf('Failed to execute command: %s', $command), $returnValue); }
php
public function execute($command) { exec($command, $result, $returnValue); if ($returnValue === 0) { return $result; } throw new \RuntimeException(sprintf('Failed to execute command: %s', $command), $returnValue); }
[ "public", "function", "execute", "(", "$", "command", ")", "{", "exec", "(", "$", "command", ",", "$", "result", ",", "$", "returnValue", ")", ";", "if", "(", "$", "returnValue", "===", "0", ")", "{", "return", "$", "result", ";", "}", "throw", "ne...
Execute command. @param string $command @throws \RuntimeException @return array
[ "Execute", "command", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Component/System/SystemCommandExecutor.php#L22-L31
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Command/CoverallsJobsCommand.php
CoverallsJobsCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $stopwatch = new Stopwatch(); $stopwatch->start(__CLASS__); $file = new Path(); if ($input->getOption('root_dir') !== '.') { $this->rootDir = $file->toAbsolutePath( $input->getOption('root_dir'), $this->rootDir ); } $config = $this->loadConfiguration($input, $this->rootDir); $this->logger = $config->isVerbose() && !$config->isTestEnv() ? new ConsoleLogger($output) : new NullLogger(); $executionStatus = $this->executeApi($config); $event = $stopwatch->stop(__CLASS__); $time = number_format($event->getDuration() / 1000, 3); // sec $mem = number_format($event->getMemory() / (1024 * 1024), 2); // MB $this->logger->info(sprintf('elapsed time: <info>%s</info> sec memory: <info>%s</info> MB', $time, $mem)); return $executionStatus ? 0 : 1; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $stopwatch = new Stopwatch(); $stopwatch->start(__CLASS__); $file = new Path(); if ($input->getOption('root_dir') !== '.') { $this->rootDir = $file->toAbsolutePath( $input->getOption('root_dir'), $this->rootDir ); } $config = $this->loadConfiguration($input, $this->rootDir); $this->logger = $config->isVerbose() && !$config->isTestEnv() ? new ConsoleLogger($output) : new NullLogger(); $executionStatus = $this->executeApi($config); $event = $stopwatch->stop(__CLASS__); $time = number_format($event->getDuration() / 1000, 3); // sec $mem = number_format($event->getMemory() / (1024 * 1024), 2); // MB $this->logger->info(sprintf('elapsed time: <info>%s</info> sec memory: <info>%s</info> MB', $time, $mem)); return $executionStatus ? 0 : 1; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "stopwatch", "=", "new", "Stopwatch", "(", ")", ";", "$", "stopwatch", "->", "start", "(", "__CLASS__", ")", ";", "$", "file", ...
{@inheritdoc} @see \Symfony\Component\Console\Command\Command::execute()
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Command/CoverallsJobsCommand.php#L118-L141
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Command/CoverallsJobsCommand.php
CoverallsJobsCommand.loadConfiguration
protected function loadConfiguration(InputInterface $input, $rootDir) { $coverallsYmlPath = $input->getOption('config'); $ymlPath = $this->rootDir . DIRECTORY_SEPARATOR . $coverallsYmlPath; $configurator = new Configurator(); return $configurator ->load($ymlPath, $rootDir, $input) ->setDryRun($input->getOption('dry-run')) ->setExcludeNoStatementsUnlessFalse($input->getOption('exclude-no-stmt')) ->setVerbose($input->getOption('verbose')) ->setEnv($input->getOption('env')); }
php
protected function loadConfiguration(InputInterface $input, $rootDir) { $coverallsYmlPath = $input->getOption('config'); $ymlPath = $this->rootDir . DIRECTORY_SEPARATOR . $coverallsYmlPath; $configurator = new Configurator(); return $configurator ->load($ymlPath, $rootDir, $input) ->setDryRun($input->getOption('dry-run')) ->setExcludeNoStatementsUnlessFalse($input->getOption('exclude-no-stmt')) ->setVerbose($input->getOption('verbose')) ->setEnv($input->getOption('env')); }
[ "protected", "function", "loadConfiguration", "(", "InputInterface", "$", "input", ",", "$", "rootDir", ")", "{", "$", "coverallsYmlPath", "=", "$", "input", "->", "getOption", "(", "'config'", ")", ";", "$", "ymlPath", "=", "$", "this", "->", "rootDir", "...
Load configuration. @param InputInterface $input input arguments @param string $rootDir path to project root directory @return \PhpCoveralls\Bundle\CoverallsBundle\Config\Configuration
[ "Load", "configuration", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Command/CoverallsJobsCommand.php#L153-L166
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Command/CoverallsJobsCommand.php
CoverallsJobsCommand.executeApi
protected function executeApi(Configuration $config) { $client = new Client(); $api = new Jobs($config, $client); $repository = new JobsRepository($api, $config); $repository->setLogger($this->logger); return $repository->persist(); }
php
protected function executeApi(Configuration $config) { $client = new Client(); $api = new Jobs($config, $client); $repository = new JobsRepository($api, $config); $repository->setLogger($this->logger); return $repository->persist(); }
[ "protected", "function", "executeApi", "(", "Configuration", "$", "config", ")", "{", "$", "client", "=", "new", "Client", "(", ")", ";", "$", "api", "=", "new", "Jobs", "(", "$", "config", ",", "$", "client", ")", ";", "$", "repository", "=", "new",...
Execute Jobs API. @param Configuration $config configuration @return bool
[ "Execute", "Jobs", "API", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Command/CoverallsJobsCommand.php#L175-L184
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.load
public function load($coverallsYmlPath, $rootDir, InputInterface $input = null) { $yml = $this->parse($coverallsYmlPath); $options = $this->process($yml); return $this->createConfiguration($options, $rootDir, $input); }
php
public function load($coverallsYmlPath, $rootDir, InputInterface $input = null) { $yml = $this->parse($coverallsYmlPath); $options = $this->process($yml); return $this->createConfiguration($options, $rootDir, $input); }
[ "public", "function", "load", "(", "$", "coverallsYmlPath", ",", "$", "rootDir", ",", "InputInterface", "$", "input", "=", "null", ")", "{", "$", "yml", "=", "$", "this", "->", "parse", "(", "$", "coverallsYmlPath", ")", ";", "$", "options", "=", "$", ...
Load configuration. @param string $coverallsYmlPath Path to .coveralls.yml. @param string $rootDir path to project root directory @param InputInterface $input|null Input arguments @throws \Symfony\Component\Yaml\Exception\ParseException If the YAML is not valid @return \PhpCoveralls\Bundle\CoverallsBundle\Config\Configuration
[ "Load", "configuration", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L31-L37
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.parse
protected function parse($coverallsYmlPath) { $file = new Path(); $path = realpath($coverallsYmlPath); if ($file->isRealFileReadable($path)) { $parser = new Parser(); $yml = $parser->parse(file_get_contents($path)); return empty($yml) ? [] : $yml; } return []; }
php
protected function parse($coverallsYmlPath) { $file = new Path(); $path = realpath($coverallsYmlPath); if ($file->isRealFileReadable($path)) { $parser = new Parser(); $yml = $parser->parse(file_get_contents($path)); return empty($yml) ? [] : $yml; } return []; }
[ "protected", "function", "parse", "(", "$", "coverallsYmlPath", ")", "{", "$", "file", "=", "new", "Path", "(", ")", ";", "$", "path", "=", "realpath", "(", "$", "coverallsYmlPath", ")", ";", "if", "(", "$", "file", "->", "isRealFileReadable", "(", "$"...
Parse .coveralls.yml. @param string $coverallsYmlPath Path to .coveralls.yml. @throws \Symfony\Component\Yaml\Exception\ParseException If the YAML is not valid @return array
[ "Parse", ".", "coveralls", ".", "yml", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L50-L63
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.process
protected function process(array $yml) { $processor = new Processor(); $configuration = new CoverallsConfiguration(); return $processor->processConfiguration($configuration, ['coveralls' => $yml]); }
php
protected function process(array $yml) { $processor = new Processor(); $configuration = new CoverallsConfiguration(); return $processor->processConfiguration($configuration, ['coveralls' => $yml]); }
[ "protected", "function", "process", "(", "array", "$", "yml", ")", "{", "$", "processor", "=", "new", "Processor", "(", ")", ";", "$", "configuration", "=", "new", "CoverallsConfiguration", "(", ")", ";", "return", "$", "processor", "->", "processConfigurati...
Process parsed configuration according to the configuration definition. @param array $yml parsed configuration @return array
[ "Process", "parsed", "configuration", "according", "to", "the", "configuration", "definition", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L72-L78
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.createConfiguration
protected function createConfiguration(array $options, $rootDir, InputInterface $input = null) { $configuration = new Configuration(); $file = new Path(); $repoToken = $options['repo_token']; $repoSecretToken = $options['repo_secret_token']; // handle coverage clover $coverage_clover = $options['coverage_clover']; if ($input !== null && $input->hasOption('coverage_clover')) { $option = $input->getOption('coverage_clover'); if (!empty($option)) { $coverage_clover = $option; } } // handle output json path $json_path = $options['json_path']; if ($input !== null && $input->hasOption('json_path')) { $option = $input->getOption('json_path'); if (!empty($option)) { $json_path = $option; } } return $configuration ->setRepoToken($repoToken !== null ? $repoToken : $repoSecretToken) ->setServiceName($options['service_name']) ->setRootDir($rootDir) ->setCloverXmlPaths($this->ensureCloverXmlPaths($coverage_clover, $rootDir, $file)) ->setJsonPath($this->ensureJsonPath($json_path, $rootDir, $file)) ->setExcludeNoStatements($options['exclude_no_stmt']); }
php
protected function createConfiguration(array $options, $rootDir, InputInterface $input = null) { $configuration = new Configuration(); $file = new Path(); $repoToken = $options['repo_token']; $repoSecretToken = $options['repo_secret_token']; // handle coverage clover $coverage_clover = $options['coverage_clover']; if ($input !== null && $input->hasOption('coverage_clover')) { $option = $input->getOption('coverage_clover'); if (!empty($option)) { $coverage_clover = $option; } } // handle output json path $json_path = $options['json_path']; if ($input !== null && $input->hasOption('json_path')) { $option = $input->getOption('json_path'); if (!empty($option)) { $json_path = $option; } } return $configuration ->setRepoToken($repoToken !== null ? $repoToken : $repoSecretToken) ->setServiceName($options['service_name']) ->setRootDir($rootDir) ->setCloverXmlPaths($this->ensureCloverXmlPaths($coverage_clover, $rootDir, $file)) ->setJsonPath($this->ensureJsonPath($json_path, $rootDir, $file)) ->setExcludeNoStatements($options['exclude_no_stmt']); }
[ "protected", "function", "createConfiguration", "(", "array", "$", "options", ",", "$", "rootDir", ",", "InputInterface", "$", "input", "=", "null", ")", "{", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "file", "=", "new", "Path"...
Create coveralls configuration. @param array $options processed configuration @param string $rootDir path to project root directory @param InputInterface $input|null Input arguments @return \PhpCoveralls\Bundle\CoverallsBundle\Config\Configuration
[ "Create", "coveralls", "configuration", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L89-L122
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.ensureCloverXmlPaths
protected function ensureCloverXmlPaths($option, $rootDir, Path $file) { if (is_array($option)) { return $this->getGlobPathsFromArrayOption($option, $rootDir, $file); } return $this->getGlobPathsFromStringOption($option, $rootDir, $file); }
php
protected function ensureCloverXmlPaths($option, $rootDir, Path $file) { if (is_array($option)) { return $this->getGlobPathsFromArrayOption($option, $rootDir, $file); } return $this->getGlobPathsFromStringOption($option, $rootDir, $file); }
[ "protected", "function", "ensureCloverXmlPaths", "(", "$", "option", ",", "$", "rootDir", ",", "Path", "$", "file", ")", "{", "if", "(", "is_array", "(", "$", "option", ")", ")", "{", "return", "$", "this", "->", "getGlobPathsFromArrayOption", "(", "$", ...
Ensure coverage_clover is valid. @param string $option coverage_clover option @param string $rootDir path to project root directory @param Path $file path object @throws \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException @return string[] valid Absolute paths of coverage_clover
[ "Ensure", "coverage_clover", "is", "valid", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L135-L142
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.getGlobPaths
protected function getGlobPaths($path) { $paths = []; $iterator = new \GlobIterator($path); foreach ($iterator as $fileInfo) { /* @var $fileInfo \SplFileInfo */ $paths[] = $fileInfo->getPathname(); } // validate if (count($paths) === 0) { throw new InvalidConfigurationException("coverage_clover XML file is not readable: ${path}"); } return $paths; }
php
protected function getGlobPaths($path) { $paths = []; $iterator = new \GlobIterator($path); foreach ($iterator as $fileInfo) { /* @var $fileInfo \SplFileInfo */ $paths[] = $fileInfo->getPathname(); } // validate if (count($paths) === 0) { throw new InvalidConfigurationException("coverage_clover XML file is not readable: ${path}"); } return $paths; }
[ "protected", "function", "getGlobPaths", "(", "$", "path", ")", "{", "$", "paths", "=", "[", "]", ";", "$", "iterator", "=", "new", "\\", "GlobIterator", "(", "$", "path", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "fileInfo", ")", "{", ...
Return absolute paths from glob path. @param string $path absolute path @throws \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException @return string[] absolute paths
[ "Return", "absolute", "paths", "from", "glob", "path", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L153-L169
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.getGlobPathsFromStringOption
protected function getGlobPathsFromStringOption($option, $rootDir, Path $file) { if (!is_string($option)) { throw new InvalidConfigurationException('coverage_clover XML file option must be a string'); } // normalize $path = $file->toAbsolutePath($option, $rootDir); return $this->getGlobPaths($path); }
php
protected function getGlobPathsFromStringOption($option, $rootDir, Path $file) { if (!is_string($option)) { throw new InvalidConfigurationException('coverage_clover XML file option must be a string'); } // normalize $path = $file->toAbsolutePath($option, $rootDir); return $this->getGlobPaths($path); }
[ "protected", "function", "getGlobPathsFromStringOption", "(", "$", "option", ",", "$", "rootDir", ",", "Path", "$", "file", ")", "{", "if", "(", "!", "is_string", "(", "$", "option", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "'cove...
Return absolute paths from string option value. @param string $option coverage_clover option value @param string $rootDir path to project root directory @param Path $file path object @throws \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException @return string[] absolute paths
[ "Return", "absolute", "paths", "from", "string", "option", "value", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L182-L192
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.getGlobPathsFromArrayOption
protected function getGlobPathsFromArrayOption(array $options, $rootDir, Path $file) { $paths = []; foreach ($options as $option) { $paths = array_merge($paths, $this->getGlobPathsFromStringOption($option, $rootDir, $file)); } return $paths; }
php
protected function getGlobPathsFromArrayOption(array $options, $rootDir, Path $file) { $paths = []; foreach ($options as $option) { $paths = array_merge($paths, $this->getGlobPathsFromStringOption($option, $rootDir, $file)); } return $paths; }
[ "protected", "function", "getGlobPathsFromArrayOption", "(", "array", "$", "options", ",", "$", "rootDir", ",", "Path", "$", "file", ")", "{", "$", "paths", "=", "[", "]", ";", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "$", "paths"...
Return absolute paths from array option values. @param array $options coverage_clover option values @param string $rootDir path to project root directory @param Path $file path object @throws \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException @return string[] absolute paths
[ "Return", "absolute", "paths", "from", "array", "option", "values", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L205-L214
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Config/Configurator.php
Configurator.ensureJsonPath
protected function ensureJsonPath($option, $rootDir, Path $file) { // normalize $realpath = $file->getRealWritingFilePath($option, $rootDir); // validate file $realFilePath = $file->getRealPath($realpath, $rootDir); if ($realFilePath !== false && !$file->isRealFileWritable($realFilePath)) { throw new InvalidConfigurationException("json_path is not writable: ${realFilePath}"); } // validate parent dir $realDir = $file->getRealDir($realpath, $rootDir); if (!$file->isRealDirWritable($realDir)) { throw new InvalidConfigurationException("json_path is not writable: ${realFilePath}"); } return $realpath; }
php
protected function ensureJsonPath($option, $rootDir, Path $file) { // normalize $realpath = $file->getRealWritingFilePath($option, $rootDir); // validate file $realFilePath = $file->getRealPath($realpath, $rootDir); if ($realFilePath !== false && !$file->isRealFileWritable($realFilePath)) { throw new InvalidConfigurationException("json_path is not writable: ${realFilePath}"); } // validate parent dir $realDir = $file->getRealDir($realpath, $rootDir); if (!$file->isRealDirWritable($realDir)) { throw new InvalidConfigurationException("json_path is not writable: ${realFilePath}"); } return $realpath; }
[ "protected", "function", "ensureJsonPath", "(", "$", "option", ",", "$", "rootDir", ",", "Path", "$", "file", ")", "{", "// normalize", "$", "realpath", "=", "$", "file", "->", "getRealWritingFilePath", "(", "$", "option", ",", "$", "rootDir", ")", ";", ...
Ensure json_path is valid. @param string $option json_path option @param string $rootDir path to project root directory @param Path $file path object @throws \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException @return string valid json_path
[ "Ensure", "json_path", "is", "valid", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Config/Configurator.php#L227-L247
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/SourceFile.php
SourceFile.addCoverage
public function addCoverage($lineNum, $count) { if (array_key_exists($lineNum, $this->coverage)) { $this->coverage[$lineNum] += $count; } }
php
public function addCoverage($lineNum, $count) { if (array_key_exists($lineNum, $this->coverage)) { $this->coverage[$lineNum] += $count; } }
[ "public", "function", "addCoverage", "(", "$", "lineNum", ",", "$", "count", ")", "{", "if", "(", "array_key_exists", "(", "$", "lineNum", ",", "$", "this", "->", "coverage", ")", ")", "{", "$", "this", "->", "coverage", "[", "$", "lineNum", "]", "+=...
Add coverage. @param int $lineNum line number @param int $count number of covered
[ "Add", "coverage", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/SourceFile.php#L94-L99
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/SourceFile.php
SourceFile.getMetrics
public function getMetrics() { if ($this->metrics === null) { $this->metrics = new Metrics($this->coverage); } return $this->metrics; }
php
public function getMetrics() { if ($this->metrics === null) { $this->metrics = new Metrics($this->coverage); } return $this->metrics; }
[ "public", "function", "getMetrics", "(", ")", "{", "if", "(", "$", "this", "->", "metrics", "===", "null", ")", "{", "$", "this", "->", "metrics", "=", "new", "Metrics", "(", "$", "this", "->", "coverage", ")", ";", "}", "return", "$", "this", "->"...
Return metrics. @return Metrics
[ "Return", "metrics", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/SourceFile.php#L168-L175
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/Git/Commit.php
Commit.toArray
public function toArray() { return [ 'id' => $this->id, 'author_name' => $this->authorName, 'author_email' => $this->authorEmail, 'committer_name' => $this->committerName, 'committer_email' => $this->committerEmail, 'message' => $this->message, ]; }
php
public function toArray() { return [ 'id' => $this->id, 'author_name' => $this->authorName, 'author_email' => $this->authorEmail, 'committer_name' => $this->committerName, 'committer_email' => $this->committerEmail, 'message' => $this->message, ]; }
[ "public", "function", "toArray", "(", ")", "{", "return", "[", "'id'", "=>", "$", "this", "->", "id", ",", "'author_name'", "=>", "$", "this", "->", "authorName", ",", "'author_email'", "=>", "$", "this", "->", "authorEmail", ",", "'committer_name'", "=>",...
{@inheritdoc} @see \PhpCoveralls\Bundle\CoverallsBundle\Entity\ArrayConvertable::toArray()
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/Git/Commit.php#L63-L73
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/JsonFile.php
JsonFile.toArray
public function toArray() { $array = []; $arrayMap = [ // json key => property name 'service_name' => 'serviceName', 'service_job_id' => 'serviceJobId', 'service_number' => 'serviceNumber', 'service_build_url' => 'serviceBuildUrl', 'service_branch' => 'serviceBranch', 'service_pull_request' => 'servicePullRequest', 'service_event_type' => 'serviceEventType', 'repo_token' => 'repoToken', 'git' => 'git', 'run_at' => 'runAt', 'source_files' => 'sourceFiles', ]; foreach ($arrayMap as $jsonKey => $propName) { if (isset($this->$propName)) { $array[$jsonKey] = $this->toJsonProperty($this->$propName); } } $array['environment'] = [ 'packagist_version' => Version::VERSION, ]; return $array; }
php
public function toArray() { $array = []; $arrayMap = [ // json key => property name 'service_name' => 'serviceName', 'service_job_id' => 'serviceJobId', 'service_number' => 'serviceNumber', 'service_build_url' => 'serviceBuildUrl', 'service_branch' => 'serviceBranch', 'service_pull_request' => 'servicePullRequest', 'service_event_type' => 'serviceEventType', 'repo_token' => 'repoToken', 'git' => 'git', 'run_at' => 'runAt', 'source_files' => 'sourceFiles', ]; foreach ($arrayMap as $jsonKey => $propName) { if (isset($this->$propName)) { $array[$jsonKey] = $this->toJsonProperty($this->$propName); } } $array['environment'] = [ 'packagist_version' => Version::VERSION, ]; return $array; }
[ "public", "function", "toArray", "(", ")", "{", "$", "array", "=", "[", "]", ";", "$", "arrayMap", "=", "[", "// json key => property name", "'service_name'", "=>", "'serviceName'", ",", "'service_job_id'", "=>", "'serviceJobId'", ",", "'service_number'", "=>", ...
{@inheritdoc} @see \PhpCoveralls\Bundle\CoverallsBundle\Entity\ArrayConvertable::toArray()
[ "{", "@inheritdoc", "}" ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/JsonFile.php#L109-L139
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/JsonFile.php
JsonFile.excludeNoStatementsFiles
public function excludeNoStatementsFiles() { $this->sourceFiles = array_filter( $this->sourceFiles, function (SourceFile $sourceFile) { return $sourceFile->getMetrics()->hasStatements(); } ); }
php
public function excludeNoStatementsFiles() { $this->sourceFiles = array_filter( $this->sourceFiles, function (SourceFile $sourceFile) { return $sourceFile->getMetrics()->hasStatements(); } ); }
[ "public", "function", "excludeNoStatementsFiles", "(", ")", "{", "$", "this", "->", "sourceFiles", "=", "array_filter", "(", "$", "this", "->", "sourceFiles", ",", "function", "(", "SourceFile", "$", "sourceFile", ")", "{", "return", "$", "sourceFile", "->", ...
Exclude source files that have no executable statements.
[ "Exclude", "source", "files", "that", "have", "no", "executable", "statements", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/JsonFile.php#L160-L168
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/JsonFile.php
JsonFile.reportLineCoverage
public function reportLineCoverage() { $metrics = $this->getMetrics(); foreach ($this->sourceFiles as $sourceFile) { /* @var $sourceFile \PhpCoveralls\Bundle\CoverallsBundle\Entity\SourceFile */ $metrics->merge($sourceFile->getMetrics()); } return $metrics->getLineCoverage(); }
php
public function reportLineCoverage() { $metrics = $this->getMetrics(); foreach ($this->sourceFiles as $sourceFile) { /* @var $sourceFile \PhpCoveralls\Bundle\CoverallsBundle\Entity\SourceFile */ $metrics->merge($sourceFile->getMetrics()); } return $metrics->getLineCoverage(); }
[ "public", "function", "reportLineCoverage", "(", ")", "{", "$", "metrics", "=", "$", "this", "->", "getMetrics", "(", ")", ";", "foreach", "(", "$", "this", "->", "sourceFiles", "as", "$", "sourceFile", ")", "{", "/* @var $sourceFile \\PhpCoveralls\\Bundle\\Cove...
Return line coverage. @return float
[ "Return", "line", "coverage", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/JsonFile.php#L183-L193
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/JsonFile.php
JsonFile.toJsonProperty
protected function toJsonProperty($prop) { if ($prop instanceof Coveralls) { return $prop->toArray(); } if (is_array($prop)) { return $this->toJsonPropertyArray($prop); } return $prop; }
php
protected function toJsonProperty($prop) { if ($prop instanceof Coveralls) { return $prop->toArray(); } if (is_array($prop)) { return $this->toJsonPropertyArray($prop); } return $prop; }
[ "protected", "function", "toJsonProperty", "(", "$", "prop", ")", "{", "if", "(", "$", "prop", "instanceof", "Coveralls", ")", "{", "return", "$", "prop", "->", "toArray", "(", ")", ";", "}", "if", "(", "is_array", "(", "$", "prop", ")", ")", "{", ...
Convert to json property. @param mixed $prop @return mixed
[ "Convert", "to", "json", "property", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/JsonFile.php#L446-L457
php-coveralls/php-coveralls
src/Bundle/CoverallsBundle/Entity/JsonFile.php
JsonFile.fillStandardizedEnvVars
protected function fillStandardizedEnvVars(array $env) { $map = [ // defined in Ruby lib 'serviceName' => 'CI_NAME', 'serviceNumber' => 'CI_BUILD_NUMBER', 'serviceBuildUrl' => 'CI_BUILD_URL', 'serviceBranch' => 'CI_BRANCH', 'servicePullRequest' => 'CI_PULL_REQUEST', // extends by php-coveralls 'serviceJobId' => 'CI_JOB_ID', 'serviceEventType' => 'COVERALLS_EVENT_TYPE', 'repoToken' => 'COVERALLS_REPO_TOKEN', ]; foreach ($map as $propName => $envName) { if (isset($env[$envName])) { $this->$propName = $env[$envName]; } } return $this; }
php
protected function fillStandardizedEnvVars(array $env) { $map = [ // defined in Ruby lib 'serviceName' => 'CI_NAME', 'serviceNumber' => 'CI_BUILD_NUMBER', 'serviceBuildUrl' => 'CI_BUILD_URL', 'serviceBranch' => 'CI_BRANCH', 'servicePullRequest' => 'CI_PULL_REQUEST', // extends by php-coveralls 'serviceJobId' => 'CI_JOB_ID', 'serviceEventType' => 'COVERALLS_EVENT_TYPE', 'repoToken' => 'COVERALLS_REPO_TOKEN', ]; foreach ($map as $propName => $envName) { if (isset($env[$envName])) { $this->$propName = $env[$envName]; } } return $this; }
[ "protected", "function", "fillStandardizedEnvVars", "(", "array", "$", "env", ")", "{", "$", "map", "=", "[", "// defined in Ruby lib", "'serviceName'", "=>", "'CI_NAME'", ",", "'serviceNumber'", "=>", "'CI_BUILD_NUMBER'", ",", "'serviceBuildUrl'", "=>", "'CI_BUILD_UR...
Fill standardized environment variables. "CI_NAME", "CI_BUILD_NUMBER" must be set. Env vars are: * CI_NAME * CI_BUILD_NUMBER * CI_BUILD_URL * CI_BRANCH * CI_PULL_REQUEST These vars are supported by Codeship. @param array $env $_SERVER environment @return $this
[ "Fill", "standardized", "environment", "variables", "." ]
train
https://github.com/php-coveralls/php-coveralls/blob/0de855a138444f33372e1e787e5af68f24f3a12f/src/Bundle/CoverallsBundle/Entity/JsonFile.php#L496-L519