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 |
|---|---|---|---|---|---|---|---|---|---|---|
yiisoft/yii2-swiftmailer | src/Message.php | Message.getHeader | public function getHeader($name)
{
$headerSet = $this->getSwiftMessage()->getHeaders();
if (!$headerSet->has($name)) {
return [];
}
$headers = [];
foreach ($headerSet->getAll($name) as $header) {
$headers[] = $header->getValue();
}
return $headers;
} | php | public function getHeader($name)
{
$headerSet = $this->getSwiftMessage()->getHeaders();
if (!$headerSet->has($name)) {
return [];
}
$headers = [];
foreach ($headerSet->getAll($name) as $header) {
$headers[] = $header->getValue();
}
return $headers;
} | [
"public",
"function",
"getHeader",
"(",
"$",
"name",
")",
"{",
"$",
"headerSet",
"=",
"$",
"this",
"->",
"getSwiftMessage",
"(",
")",
"->",
"getHeaders",
"(",
")",
";",
"if",
"(",
"!",
"$",
"headerSet",
"->",
"has",
"(",
"$",
"name",
")",
")",
"{",... | Returns all values for the specified header.
@param string $name header name.
@return array header values list.
@since 2.0.6 | [
"Returns",
"all",
"values",
"for",
"the",
"specified",
"header",
"."
] | train | https://github.com/yiisoft/yii2-swiftmailer/blob/da440aba4d518a9ffa08c2d18a657a54a28919c9/src/Message.php#L484-L496 |
DivineOmega/password_exposed | src/PasswordExposedChecker.php | PasswordExposedChecker.getClient | protected function getClient(): ClientInterface
{
if ($this->client === null) {
$this->client = $this->createClient();
}
return $this->client;
} | php | protected function getClient(): ClientInterface
{
if ($this->client === null) {
$this->client = $this->createClient();
}
return $this->client;
} | [
"protected",
"function",
"getClient",
"(",
")",
":",
"ClientInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"client",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"client",
"=",
"$",
"this",
"->",
"createClient",
"(",
")",
";",
"}",
"return",
"$",
"thi... | {@inheritdoc} | [
"{"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/PasswordExposedChecker.php#L63-L70 |
DivineOmega/password_exposed | src/PasswordExposedChecker.php | PasswordExposedChecker.getCache | protected function getCache(): CacheItemPoolInterface
{
if ($this->cache === null) {
$this->cache = $this->createCache();
}
return $this->cache;
} | php | protected function getCache(): CacheItemPoolInterface
{
if ($this->cache === null) {
$this->cache = $this->createCache();
}
return $this->cache;
} | [
"protected",
"function",
"getCache",
"(",
")",
":",
"CacheItemPoolInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"cache",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"cache",
"=",
"$",
"this",
"->",
"createCache",
"(",
")",
";",
"}",
"return",
"$",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/PasswordExposedChecker.php#L95-L102 |
DivineOmega/password_exposed | src/PasswordExposedChecker.php | PasswordExposedChecker.getUriFactory | protected function getUriFactory(): UriFactoryInterface
{
if ($this->uriFactory === null) {
$this->uriFactory = $this->createUriFactory();
}
return $this->uriFactory;
} | php | protected function getUriFactory(): UriFactoryInterface
{
if ($this->uriFactory === null) {
$this->uriFactory = $this->createUriFactory();
}
return $this->uriFactory;
} | [
"protected",
"function",
"getUriFactory",
"(",
")",
":",
"UriFactoryInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"uriFactory",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"uriFactory",
"=",
"$",
"this",
"->",
"createUriFactory",
"(",
")",
";",
"}",
"re... | {@inheritdoc} | [
"{"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/PasswordExposedChecker.php#L154-L161 |
DivineOmega/password_exposed | src/PasswordExposedChecker.php | PasswordExposedChecker.getBundleFromCertainty | protected function getBundleFromCertainty(): Bundle
{
$ourCertaintyDataDir = __DIR__.'/../bundles';
if (!is_writable($ourCertaintyDataDir)) {
// If we can't write to the our Certainty data directory, just
// use the latest bundle from the Certainty package.
return (new Fetch($ourCertaintyDataDir))->getLatestBundle();
}
if (PHP_INT_SIZE === 4 && !extension_loaded('sodium')) {
// If the platform would run verification checks slowly, use the
// latest bundle from the Certainty package and disable verification.
return (new Fetch($ourCertaintyDataDir))->getLatestBundle(false, false);
}
// If the platform can run verification checks well enough, get
// latest remote bundle and verify it.
return (new RemoteFetch($ourCertaintyDataDir))->getLatestBundle();
} | php | protected function getBundleFromCertainty(): Bundle
{
$ourCertaintyDataDir = __DIR__.'/../bundles';
if (!is_writable($ourCertaintyDataDir)) {
// If we can't write to the our Certainty data directory, just
// use the latest bundle from the Certainty package.
return (new Fetch($ourCertaintyDataDir))->getLatestBundle();
}
if (PHP_INT_SIZE === 4 && !extension_loaded('sodium')) {
// If the platform would run verification checks slowly, use the
// latest bundle from the Certainty package and disable verification.
return (new Fetch($ourCertaintyDataDir))->getLatestBundle(false, false);
}
// If the platform can run verification checks well enough, get
// latest remote bundle and verify it.
return (new RemoteFetch($ourCertaintyDataDir))->getLatestBundle();
} | [
"protected",
"function",
"getBundleFromCertainty",
"(",
")",
":",
"Bundle",
"{",
"$",
"ourCertaintyDataDir",
"=",
"__DIR__",
".",
"'/../bundles'",
";",
"if",
"(",
"!",
"is_writable",
"(",
"$",
"ourCertaintyDataDir",
")",
")",
"{",
"// If we can't write to the our Ce... | @throws \ParagonIE\Certainty\Exception\CertaintyException
@throws \SodiumException
@return Bundle | [
"@throws",
"\\",
"ParagonIE",
"\\",
"Certainty",
"\\",
"Exception",
"\\",
"CertaintyException",
"@throws",
"\\",
"SodiumException"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/PasswordExposedChecker.php#L209-L230 |
DivineOmega/password_exposed | src/AbstractPasswordExposedChecker.php | AbstractPasswordExposedChecker.passwordExposedByHash | public function passwordExposedByHash(string $hash): string
{
$cache = $this->getCache();
$cacheKey = substr($hash, 0, 2).'_'.substr($hash, 2, 3);
$body = null;
try {
$cacheItem = $cache->getItem($cacheKey);
// try to get status from cache
if ($cacheItem->isHit()) {
$body = $cacheItem->get();
}
} catch (\Exception $e) {
$cacheItem = null;
}
// get status from api
if ($body === null) {
try {
/** @var ResponseInterface $response */
$response = $this->makeRequest($hash);
/** @var string $responseBody */
$body = $response->getBody()->getContents();
// cache status
if ($cacheItem !== null) {
$cacheLifeTime = $this->getCacheLifeTime();
if ($cacheLifeTime <= 0) {
$cacheLifeTime = self::CACHE_EXPIRY_SECONDS;
}
$cacheItem->set($body);
$cacheItem->expiresAfter($cacheLifeTime);
$cache->save($cacheItem);
}
} catch (ClientExceptionInterface $e) {
}
}
if ($body === null) {
return PasswordExposedCheckerInterface::UNKNOWN;
}
return $this->getPasswordStatus($hash, $body);
} | php | public function passwordExposedByHash(string $hash): string
{
$cache = $this->getCache();
$cacheKey = substr($hash, 0, 2).'_'.substr($hash, 2, 3);
$body = null;
try {
$cacheItem = $cache->getItem($cacheKey);
// try to get status from cache
if ($cacheItem->isHit()) {
$body = $cacheItem->get();
}
} catch (\Exception $e) {
$cacheItem = null;
}
// get status from api
if ($body === null) {
try {
/** @var ResponseInterface $response */
$response = $this->makeRequest($hash);
/** @var string $responseBody */
$body = $response->getBody()->getContents();
// cache status
if ($cacheItem !== null) {
$cacheLifeTime = $this->getCacheLifeTime();
if ($cacheLifeTime <= 0) {
$cacheLifeTime = self::CACHE_EXPIRY_SECONDS;
}
$cacheItem->set($body);
$cacheItem->expiresAfter($cacheLifeTime);
$cache->save($cacheItem);
}
} catch (ClientExceptionInterface $e) {
}
}
if ($body === null) {
return PasswordExposedCheckerInterface::UNKNOWN;
}
return $this->getPasswordStatus($hash, $body);
} | [
"public",
"function",
"passwordExposedByHash",
"(",
"string",
"$",
"hash",
")",
":",
"string",
"{",
"$",
"cache",
"=",
"$",
"this",
"->",
"getCache",
"(",
")",
";",
"$",
"cacheKey",
"=",
"substr",
"(",
"$",
"hash",
",",
"0",
",",
"2",
")",
".",
"'_... | {@inheritdoc} | [
"{"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/AbstractPasswordExposedChecker.php#L33-L80 |
DivineOmega/password_exposed | src/AbstractPasswordExposedChecker.php | AbstractPasswordExposedChecker.isExposedByHash | public function isExposedByHash(string $hash): ?bool
{
$status = $this->passwordExposedByHash($hash);
if ($status === PasswordExposedCheckerInterface::EXPOSED) {
return true;
}
if ($status === PasswordExposedCheckerInterface::NOT_EXPOSED) {
return false;
}
return null;
} | php | public function isExposedByHash(string $hash): ?bool
{
$status = $this->passwordExposedByHash($hash);
if ($status === PasswordExposedCheckerInterface::EXPOSED) {
return true;
}
if ($status === PasswordExposedCheckerInterface::NOT_EXPOSED) {
return false;
}
return null;
} | [
"public",
"function",
"isExposedByHash",
"(",
"string",
"$",
"hash",
")",
":",
"?",
"bool",
"{",
"$",
"status",
"=",
"$",
"this",
"->",
"passwordExposedByHash",
"(",
"$",
"hash",
")",
";",
"if",
"(",
"$",
"status",
"===",
"PasswordExposedCheckerInterface",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/AbstractPasswordExposedChecker.php#L93-L106 |
DivineOmega/password_exposed | src/AbstractPasswordExposedChecker.php | AbstractPasswordExposedChecker.makeRequest | protected function makeRequest(string $hash): ResponseInterface
{
$uri = $this->getUriFactory()->createUri('https://api.pwnedpasswords.com/range/'.substr($hash, 0, 5));
$request = $this->getRequestFactory()->createRequest('GET', $uri);
return $this->getClient()->sendRequest($request);
} | php | protected function makeRequest(string $hash): ResponseInterface
{
$uri = $this->getUriFactory()->createUri('https://api.pwnedpasswords.com/range/'.substr($hash, 0, 5));
$request = $this->getRequestFactory()->createRequest('GET', $uri);
return $this->getClient()->sendRequest($request);
} | [
"protected",
"function",
"makeRequest",
"(",
"string",
"$",
"hash",
")",
":",
"ResponseInterface",
"{",
"$",
"uri",
"=",
"$",
"this",
"->",
"getUriFactory",
"(",
")",
"->",
"createUri",
"(",
"'https://api.pwnedpasswords.com/range/'",
".",
"substr",
"(",
"$",
"... | @param $hash
@throws \Psr\Http\Client\ClientExceptionInterface
@return ResponseInterface | [
"@param",
"$hash"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/AbstractPasswordExposedChecker.php#L115-L121 |
DivineOmega/password_exposed | src/AbstractPasswordExposedChecker.php | AbstractPasswordExposedChecker.getPasswordStatus | protected function getPasswordStatus($hash, $responseBody): string
{
$hash = strtoupper($hash);
$hashSuffix = substr($hash, 5);
$lines = explode("\r\n", $responseBody);
foreach ($lines as $line) {
list($exposedHashSuffix, $occurrences) = explode(':', $line);
if (hash_equals($hashSuffix, $exposedHashSuffix)) {
return PasswordStatus::EXPOSED;
}
}
return PasswordStatus::NOT_EXPOSED;
} | php | protected function getPasswordStatus($hash, $responseBody): string
{
$hash = strtoupper($hash);
$hashSuffix = substr($hash, 5);
$lines = explode("\r\n", $responseBody);
foreach ($lines as $line) {
list($exposedHashSuffix, $occurrences) = explode(':', $line);
if (hash_equals($hashSuffix, $exposedHashSuffix)) {
return PasswordStatus::EXPOSED;
}
}
return PasswordStatus::NOT_EXPOSED;
} | [
"protected",
"function",
"getPasswordStatus",
"(",
"$",
"hash",
",",
"$",
"responseBody",
")",
":",
"string",
"{",
"$",
"hash",
"=",
"strtoupper",
"(",
"$",
"hash",
")",
";",
"$",
"hashSuffix",
"=",
"substr",
"(",
"$",
"hash",
",",
"5",
")",
";",
"$"... | @param string $hash
@param string $responseBody
@return string | [
"@param",
"string",
"$hash",
"@param",
"string",
"$responseBody"
] | train | https://github.com/DivineOmega/password_exposed/blob/3f000edde89180764052492a1661d9550d9bcf5e/src/AbstractPasswordExposedChecker.php#L139-L154 |
alexpechkarev/geometry-library | MathUtil.php | MathUtil.clamp | public static function clamp( $x, $low, $high) {
return $x < $low ? $low : ($x > $high ? $high : $x);
} | php | public static function clamp( $x, $low, $high) {
return $x < $low ? $low : ($x > $high ? $high : $x);
} | [
"public",
"static",
"function",
"clamp",
"(",
"$",
"x",
",",
"$",
"low",
",",
"$",
"high",
")",
"{",
"return",
"$",
"x",
"<",
"$",
"low",
"?",
"$",
"low",
":",
"(",
"$",
"x",
">",
"$",
"high",
"?",
"$",
"high",
":",
"$",
"x",
")",
";",
"}... | Restrict x to the range [low, high]. | [
"Restrict",
"x",
"to",
"the",
"range",
"[",
"low",
"high",
"]",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/MathUtil.php#L30-L32 |
alexpechkarev/geometry-library | MathUtil.php | MathUtil.wrap | public static function wrap($n, $min, $max) {
return ($n >= $min && $n < $max) ? $n : (self::mod($n - $min, $max - $min) + $min);
} | php | public static function wrap($n, $min, $max) {
return ($n >= $min && $n < $max) ? $n : (self::mod($n - $min, $max - $min) + $min);
} | [
"public",
"static",
"function",
"wrap",
"(",
"$",
"n",
",",
"$",
"min",
",",
"$",
"max",
")",
"{",
"return",
"(",
"$",
"n",
">=",
"$",
"min",
"&&",
"$",
"n",
"<",
"$",
"max",
")",
"?",
"$",
"n",
":",
"(",
"self",
"::",
"mod",
"(",
"$",
"n... | Wraps the given value into the inclusive-exclusive interval between min and max.
@param n The value to wrap.
@param min The minimum.
@param max The maximum. | [
"Wraps",
"the",
"given",
"value",
"into",
"the",
"inclusive",
"-",
"exclusive",
"interval",
"between",
"min",
"and",
"max",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/MathUtil.php#L40-L42 |
alexpechkarev/geometry-library | MathUtil.php | MathUtil.sinSumFromHav | public static function sinSumFromHav($x, $y) {
$a = sqrt($x * (1 - $x));
$b = sqrt($y * (1 - $y));
return 2 * ($a + $b - 2 * ($a * $y + $b * $x));
} | php | public static function sinSumFromHav($x, $y) {
$a = sqrt($x * (1 - $x));
$b = sqrt($y * (1 - $y));
return 2 * ($a + $b - 2 * ($a * $y + $b * $x));
} | [
"public",
"static",
"function",
"sinSumFromHav",
"(",
"$",
"x",
",",
"$",
"y",
")",
"{",
"$",
"a",
"=",
"sqrt",
"(",
"$",
"x",
"*",
"(",
"1",
"-",
"$",
"x",
")",
")",
";",
"$",
"b",
"=",
"sqrt",
"(",
"$",
"y",
"*",
"(",
"1",
"-",
"$",
"... | Returns sin(arcHav(x) + arcHav(y)). | [
"Returns",
"sin",
"(",
"arcHav",
"(",
"x",
")",
"+",
"arcHav",
"(",
"y",
"))",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/MathUtil.php#L98-L102 |
alexpechkarev/geometry-library | MathUtil.php | MathUtil.havDistance | public static function havDistance($lat1, $lat2, $dLng) {
return self::hav($lat1 - $lat2) + self::hav($dLng) * cos($lat1) * cos($lat2);
} | php | public static function havDistance($lat1, $lat2, $dLng) {
return self::hav($lat1 - $lat2) + self::hav($dLng) * cos($lat1) * cos($lat2);
} | [
"public",
"static",
"function",
"havDistance",
"(",
"$",
"lat1",
",",
"$",
"lat2",
",",
"$",
"dLng",
")",
"{",
"return",
"self",
"::",
"hav",
"(",
"$",
"lat1",
"-",
"$",
"lat2",
")",
"+",
"self",
"::",
"hav",
"(",
"$",
"dLng",
")",
"*",
"cos",
... | Returns hav() of distance from (lat1, lng1) to (lat2, lng2) on the unit sphere. | [
"Returns",
"hav",
"()",
"of",
"distance",
"from",
"(",
"lat1",
"lng1",
")",
"to",
"(",
"lat2",
"lng2",
")",
"on",
"the",
"unit",
"sphere",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/MathUtil.php#L107-L109 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.computeHeading | public static function computeHeading($from, $to) {
// http://williams.best.vwh.net/avform.htm#Crs
$fromLat = deg2rad($from['lat']);
$fromLng = deg2rad($from['lng']);
$toLat = deg2rad($to['lat']);
$toLng = deg2rad($to['lng']);
$dLng = $toLng - $fromLng;
$heading = atan2(
sin($dLng) * cos($toLat),
cos($fromLat) * sin($toLat) - sin($fromLat) * cos($toLat) * cos($dLng));
return MathUtil::wrap(rad2deg($heading), -180, 180);
} | php | public static function computeHeading($from, $to) {
// http://williams.best.vwh.net/avform.htm#Crs
$fromLat = deg2rad($from['lat']);
$fromLng = deg2rad($from['lng']);
$toLat = deg2rad($to['lat']);
$toLng = deg2rad($to['lng']);
$dLng = $toLng - $fromLng;
$heading = atan2(
sin($dLng) * cos($toLat),
cos($fromLat) * sin($toLat) - sin($fromLat) * cos($toLat) * cos($dLng));
return MathUtil::wrap(rad2deg($heading), -180, 180);
} | [
"public",
"static",
"function",
"computeHeading",
"(",
"$",
"from",
",",
"$",
"to",
")",
"{",
"// http://williams.best.vwh.net/avform.htm#Crs",
"$",
"fromLat",
"=",
"deg2rad",
"(",
"$",
"from",
"[",
"'lat'",
"]",
")",
";",
"$",
"fromLng",
"=",
"deg2rad",
"("... | Returns the heading from one LatLng to another LatLng. Headings are
expressed in degrees clockwise from North within the range [-180,180).
@return The heading in degrees clockwise from north. | [
"Returns",
"the",
"heading",
"from",
"one",
"LatLng",
"to",
"another",
"LatLng",
".",
"Headings",
"are",
"expressed",
"in",
"degrees",
"clockwise",
"from",
"North",
"within",
"the",
"range",
"[",
"-",
"180",
"180",
")",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L29-L41 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.computeOffset | public static function computeOffset($from, $distance, $heading) {
$distance /= MathUtil::EARTH_RADIUS;
$heading = deg2rad($heading);
// http://williams.best.vwh.net/avform.htm#LL
$fromLat = deg2rad($from['lat']);
$fromLng = deg2rad($from['lng']);
$cosDistance = cos($distance);
$sinDistance = sin($distance);
$sinFromLat = sin($fromLat);
$cosFromLat = cos($fromLat);
$sinLat = $cosDistance * $sinFromLat + $sinDistance * $cosFromLat * cos($heading);
$dLng = atan2(
$sinDistance * $cosFromLat * sin($heading),
$cosDistance - $sinFromLat * $sinLat);
return ['lat' => rad2deg(asin($sinLat)), 'lng' =>rad2deg($fromLng + $dLng)];
} | php | public static function computeOffset($from, $distance, $heading) {
$distance /= MathUtil::EARTH_RADIUS;
$heading = deg2rad($heading);
// http://williams.best.vwh.net/avform.htm#LL
$fromLat = deg2rad($from['lat']);
$fromLng = deg2rad($from['lng']);
$cosDistance = cos($distance);
$sinDistance = sin($distance);
$sinFromLat = sin($fromLat);
$cosFromLat = cos($fromLat);
$sinLat = $cosDistance * $sinFromLat + $sinDistance * $cosFromLat * cos($heading);
$dLng = atan2(
$sinDistance * $cosFromLat * sin($heading),
$cosDistance - $sinFromLat * $sinLat);
return ['lat' => rad2deg(asin($sinLat)), 'lng' =>rad2deg($fromLng + $dLng)];
} | [
"public",
"static",
"function",
"computeOffset",
"(",
"$",
"from",
",",
"$",
"distance",
",",
"$",
"heading",
")",
"{",
"$",
"distance",
"/=",
"MathUtil",
"::",
"EARTH_RADIUS",
";",
"$",
"heading",
"=",
"deg2rad",
"(",
"$",
"heading",
")",
";",
"// http:... | Returns the LatLng resulting from moving a distance from an origin
in the specified heading (expressed in degrees clockwise from north).
@param from The LatLng from which to start.
@param distance The distance to travel.
@param heading The heading in degrees clockwise from north. | [
"Returns",
"the",
"LatLng",
"resulting",
"from",
"moving",
"a",
"distance",
"from",
"an",
"origin",
"in",
"the",
"specified",
"heading",
"(",
"expressed",
"in",
"degrees",
"clockwise",
"from",
"north",
")",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L51-L67 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.computeOffsetOrigin | public static function computeOffsetOrigin($to, $distance, $heading) {
$heading = deg2rad($heading);
$distance /= MathUtil::EARTH_RADIUS;
// http://lists.maptools.org/pipermail/proj/2008-October/003939.html
$n1 = cos($distance);
$n2 = sin($distance) * cos($heading);
$n3 = sin($distance) * sin($heading);
$n4 = sin(rad2deg($to['lat']));
// There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results
// in the latitude outside the [-90, 90] range. We first try one solution and
// back off to the other if we are outside that range.
$n12 = $n1 * $n1;
$discriminant = $n2 * $n2 * $n12 + $n12 * $n12 - $n12 * $n4 * $n4;
if ($discriminant < 0) {
// No real solution which would make sense in LatLng-space.
return null;
}
$b = $n2 * $n4 + sqrt($discriminant);
$b /= $n1 * $n1 + $n2 * $n2;
$a = ($n4 - $n2 * $b) / $n1;
$fromLatRadians = atan2($a, $b);
if ($fromLatRadians < -M_PI / 2 || $fromLatRadians > M_PI / 2) {
$b = $n2 * $n4 - sqrt($discriminant);
$b /= $n1 * $n1 + $n2 * $n2;
$fromLatRadians = atan2($a, $b);
}
if ($fromLatRadians < -M_PI / 2 || $fromLatRadians > M_PI / 2) {
// No solution which would make sense in LatLng-space.
return null;
}
$fromLngRadians = rad2deg($to['lng']) -
atan2($n3, $n1 * cos($fromLatRadians) - $n2 * sin($fromLatRadians));
return ['lat' => rad2deg($fromLatRadians), 'lng' => rad2deg($fromLngRadians)];
} | php | public static function computeOffsetOrigin($to, $distance, $heading) {
$heading = deg2rad($heading);
$distance /= MathUtil::EARTH_RADIUS;
// http://lists.maptools.org/pipermail/proj/2008-October/003939.html
$n1 = cos($distance);
$n2 = sin($distance) * cos($heading);
$n3 = sin($distance) * sin($heading);
$n4 = sin(rad2deg($to['lat']));
// There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results
// in the latitude outside the [-90, 90] range. We first try one solution and
// back off to the other if we are outside that range.
$n12 = $n1 * $n1;
$discriminant = $n2 * $n2 * $n12 + $n12 * $n12 - $n12 * $n4 * $n4;
if ($discriminant < 0) {
// No real solution which would make sense in LatLng-space.
return null;
}
$b = $n2 * $n4 + sqrt($discriminant);
$b /= $n1 * $n1 + $n2 * $n2;
$a = ($n4 - $n2 * $b) / $n1;
$fromLatRadians = atan2($a, $b);
if ($fromLatRadians < -M_PI / 2 || $fromLatRadians > M_PI / 2) {
$b = $n2 * $n4 - sqrt($discriminant);
$b /= $n1 * $n1 + $n2 * $n2;
$fromLatRadians = atan2($a, $b);
}
if ($fromLatRadians < -M_PI / 2 || $fromLatRadians > M_PI / 2) {
// No solution which would make sense in LatLng-space.
return null;
}
$fromLngRadians = rad2deg($to['lng']) -
atan2($n3, $n1 * cos($fromLatRadians) - $n2 * sin($fromLatRadians));
return ['lat' => rad2deg($fromLatRadians), 'lng' => rad2deg($fromLngRadians)];
} | [
"public",
"static",
"function",
"computeOffsetOrigin",
"(",
"$",
"to",
",",
"$",
"distance",
",",
"$",
"heading",
")",
"{",
"$",
"heading",
"=",
"deg2rad",
"(",
"$",
"heading",
")",
";",
"$",
"distance",
"/=",
"MathUtil",
"::",
"EARTH_RADIUS",
";",
"// h... | Returns the location of origin when provided with a LatLng destination,
meters travelled and original heading. Headings are expressed in degrees
clockwise from North. This function returns null when no solution is
available.
@param to The destination LatLng.
@param distance The distance travelled, in meters.
@param heading The heading in degrees clockwise from north. | [
"Returns",
"the",
"location",
"of",
"origin",
"when",
"provided",
"with",
"a",
"LatLng",
"destination",
"meters",
"travelled",
"and",
"original",
"heading",
".",
"Headings",
"are",
"expressed",
"in",
"degrees",
"clockwise",
"from",
"North",
".",
"This",
"functio... | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L80-L113 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.interpolate | public static function interpolate($from, $to, $fraction) {
// http://en.wikipedia.org/wiki/Slerp
$fromLat = deg2rad($from['lat']);
$fromLng = deg2rad($from['lng']);
$toLat = deg2rad($to['lat']);
$toLng = deg2rad($to['lng']);
$cosFromLat = cos($fromLat);
$cosToLat = cos($toLat);
// Computes Spherical interpolation coefficients.
$angle = self::computeAngleBetween($from, $to);
$sinAngle = sin($angle);
if ($sinAngle < 1E-6) {
return $from;
}
$a = sin((1 - $fraction) * $angle) / $sinAngle;
$b = sin($fraction * $angle) / $sinAngle;
// Converts from polar to vector and interpolate.
$x = $a * $cosFromLat * cos($fromLng) + $b * $cosToLat * cos($toLng);
$y = $a * $cosFromLat * sin($fromLng) + $b * $cosToLat * sin($toLng);
$z = $a * sin($fromLat) + $b * sin($toLat);
// Converts interpolated vector back to polar.
$lat = atan2($z, sqrt($x * $x + $y * $y));
$lng = atan2($y, $x);
return [ 'lat' => rad2deg($lat), 'lng' => rad2deg($lng)];
} | php | public static function interpolate($from, $to, $fraction) {
// http://en.wikipedia.org/wiki/Slerp
$fromLat = deg2rad($from['lat']);
$fromLng = deg2rad($from['lng']);
$toLat = deg2rad($to['lat']);
$toLng = deg2rad($to['lng']);
$cosFromLat = cos($fromLat);
$cosToLat = cos($toLat);
// Computes Spherical interpolation coefficients.
$angle = self::computeAngleBetween($from, $to);
$sinAngle = sin($angle);
if ($sinAngle < 1E-6) {
return $from;
}
$a = sin((1 - $fraction) * $angle) / $sinAngle;
$b = sin($fraction * $angle) / $sinAngle;
// Converts from polar to vector and interpolate.
$x = $a * $cosFromLat * cos($fromLng) + $b * $cosToLat * cos($toLng);
$y = $a * $cosFromLat * sin($fromLng) + $b * $cosToLat * sin($toLng);
$z = $a * sin($fromLat) + $b * sin($toLat);
// Converts interpolated vector back to polar.
$lat = atan2($z, sqrt($x * $x + $y * $y));
$lng = atan2($y, $x);
return [ 'lat' => rad2deg($lat), 'lng' => rad2deg($lng)];
} | [
"public",
"static",
"function",
"interpolate",
"(",
"$",
"from",
",",
"$",
"to",
",",
"$",
"fraction",
")",
"{",
"// http://en.wikipedia.org/wiki/Slerp",
"$",
"fromLat",
"=",
"deg2rad",
"(",
"$",
"from",
"[",
"'lat'",
"]",
")",
";",
"$",
"fromLng",
"=",
... | Returns the LatLng which lies the given fraction of the way between the
origin LatLng and the destination LatLng.
@param from The LatLng from which to start.
@param to The LatLng toward which to travel.
@param fraction A fraction of the distance to travel.
@return The interpolated LatLng. | [
"Returns",
"the",
"LatLng",
"which",
"lies",
"the",
"given",
"fraction",
"of",
"the",
"way",
"between",
"the",
"origin",
"LatLng",
"and",
"the",
"destination",
"LatLng",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L125-L152 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.distanceRadians | private static function distanceRadians( $lat1, $lng1, $lat2, $lng2) {
return MathUtil::arcHav(MathUtil::havDistance($lat1, $lat2, $lng1 - $lng2));
} | php | private static function distanceRadians( $lat1, $lng1, $lat2, $lng2) {
return MathUtil::arcHav(MathUtil::havDistance($lat1, $lat2, $lng1 - $lng2));
} | [
"private",
"static",
"function",
"distanceRadians",
"(",
"$",
"lat1",
",",
"$",
"lng1",
",",
"$",
"lat2",
",",
"$",
"lng2",
")",
"{",
"return",
"MathUtil",
"::",
"arcHav",
"(",
"MathUtil",
"::",
"havDistance",
"(",
"$",
"lat1",
",",
"$",
"lat2",
",",
... | Returns distance on the unit sphere; the arguments are in radians. | [
"Returns",
"distance",
"on",
"the",
"unit",
"sphere",
";",
"the",
"arguments",
"are",
"in",
"radians",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L158-L160 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.computeAngleBetween | private static function computeAngleBetween($from, $to) {
return self::distanceRadians(deg2rad($from['lat']), deg2rad($from['lng']),
deg2rad($to['lat']), deg2rad($to['lng']));
} | php | private static function computeAngleBetween($from, $to) {
return self::distanceRadians(deg2rad($from['lat']), deg2rad($from['lng']),
deg2rad($to['lat']), deg2rad($to['lng']));
} | [
"private",
"static",
"function",
"computeAngleBetween",
"(",
"$",
"from",
",",
"$",
"to",
")",
"{",
"return",
"self",
"::",
"distanceRadians",
"(",
"deg2rad",
"(",
"$",
"from",
"[",
"'lat'",
"]",
")",
",",
"deg2rad",
"(",
"$",
"from",
"[",
"'lng'",
"]"... | Returns the angle between two LatLngs, in radians. This is the same as the distance
on the unit sphere. | [
"Returns",
"the",
"angle",
"between",
"two",
"LatLngs",
"in",
"radians",
".",
"This",
"is",
"the",
"same",
"as",
"the",
"distance",
"on",
"the",
"unit",
"sphere",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L166-L169 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.computeLength | public static function computeLength($path) {
if (count($path) < 2) {
return 0;
}
$length = 0;
$prev = $path[0];
$prevLat = deg2rad($prev['lat']);
$prevLng = deg2rad($prev['lng']);
foreach($path as $point) {
$lat = deg2rad($point['lat']);
$lng = deg2rad($point['lng']);
$length += self::distanceRadians($prevLat, $prevLng, $lat, $lng);
$prevLat = $lat;
$prevLng = $lng;
}
return $length * MathUtil::EARTH_RADIUS;
} | php | public static function computeLength($path) {
if (count($path) < 2) {
return 0;
}
$length = 0;
$prev = $path[0];
$prevLat = deg2rad($prev['lat']);
$prevLng = deg2rad($prev['lng']);
foreach($path as $point) {
$lat = deg2rad($point['lat']);
$lng = deg2rad($point['lng']);
$length += self::distanceRadians($prevLat, $prevLng, $lat, $lng);
$prevLat = $lat;
$prevLng = $lng;
}
return $length * MathUtil::EARTH_RADIUS;
} | [
"public",
"static",
"function",
"computeLength",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"path",
")",
"<",
"2",
")",
"{",
"return",
"0",
";",
"}",
"$",
"length",
"=",
"0",
";",
"$",
"prev",
"=",
"$",
"path",
"[",
"0",
"]",
"... | Returns the length of the given path, in meters, on Earth. | [
"Returns",
"the",
"length",
"of",
"the",
"given",
"path",
"in",
"meters",
"on",
"Earth",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L183-L199 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.computeSignedAreaP | private static function computeSignedAreaP($path, $radius) {
$size = count($path);
if ($size < 3) { return 0; }
$total = 0;
$prev = $path[$size - 1];
$prevTanLat = tan((M_PI / 2 - deg2rad($prev['lat'])) / 2);
$prevLng = deg2rad($prev['lng']);
// For each edge, accumulate the signed area of the triangle formed by the North Pole
// and that edge ("polar triangle").
foreach($path as $point) {
$tanLat = tan((M_PI / 2 - deg2rad($point['lat'])) / 2);
$lng = deg2rad($point['lng']);
$total += self::polarTriangleArea($tanLat, $lng, $prevTanLat, $prevLng);
$prevTanLat = $tanLat;
$prevLng = $lng;
}
return $total * ($radius * $radius);
} | php | private static function computeSignedAreaP($path, $radius) {
$size = count($path);
if ($size < 3) { return 0; }
$total = 0;
$prev = $path[$size - 1];
$prevTanLat = tan((M_PI / 2 - deg2rad($prev['lat'])) / 2);
$prevLng = deg2rad($prev['lng']);
// For each edge, accumulate the signed area of the triangle formed by the North Pole
// and that edge ("polar triangle").
foreach($path as $point) {
$tanLat = tan((M_PI / 2 - deg2rad($point['lat'])) / 2);
$lng = deg2rad($point['lng']);
$total += self::polarTriangleArea($tanLat, $lng, $prevTanLat, $prevLng);
$prevTanLat = $tanLat;
$prevLng = $lng;
}
return $total * ($radius * $radius);
} | [
"private",
"static",
"function",
"computeSignedAreaP",
"(",
"$",
"path",
",",
"$",
"radius",
")",
"{",
"$",
"size",
"=",
"count",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"size",
"<",
"3",
")",
"{",
"return",
"0",
";",
"}",
"$",
"total",
"=",
... | Returns the signed area of a closed path on a sphere of given radius.
The computed area uses the same units as the radius squared.
Used by SphericalUtilTest. | [
"Returns",
"the",
"signed",
"area",
"of",
"a",
"closed",
"path",
"on",
"a",
"sphere",
"of",
"given",
"radius",
".",
"The",
"computed",
"area",
"uses",
"the",
"same",
"units",
"as",
"the",
"radius",
"squared",
".",
"Used",
"by",
"SphericalUtilTest",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L228-L245 |
alexpechkarev/geometry-library | SphericalUtil.php | SphericalUtil.polarTriangleArea | private static function polarTriangleArea($tan1, $lng1, $tan2, $lng2) {
$deltaLng = $lng1 - $lng2;
$t = $tan1 * $tan2;
return 2 * atan2($t * sin($deltaLng), 1 + $t * cos($deltaLng));
} | php | private static function polarTriangleArea($tan1, $lng1, $tan2, $lng2) {
$deltaLng = $lng1 - $lng2;
$t = $tan1 * $tan2;
return 2 * atan2($t * sin($deltaLng), 1 + $t * cos($deltaLng));
} | [
"private",
"static",
"function",
"polarTriangleArea",
"(",
"$",
"tan1",
",",
"$",
"lng1",
",",
"$",
"tan2",
",",
"$",
"lng2",
")",
"{",
"$",
"deltaLng",
"=",
"$",
"lng1",
"-",
"$",
"lng2",
";",
"$",
"t",
"=",
"$",
"tan1",
"*",
"$",
"tan2",
";",
... | Returns the signed area of a triangle which has North Pole as a vertex.
Formula derived from "Area of a spherical triangle given two edges and the included angle"
as per "Spherical Trigonometry" by Todhunter, page 71, section 103, point 2.
See http://books.google.com/books?id=3uBHAAAAIAAJ&pg=PA71
The arguments named "tan" are tan((pi/2 - latitude)/2). | [
"Returns",
"the",
"signed",
"area",
"of",
"a",
"triangle",
"which",
"has",
"North",
"Pole",
"as",
"a",
"vertex",
".",
"Formula",
"derived",
"from",
"Area",
"of",
"a",
"spherical",
"triangle",
"given",
"two",
"edges",
"and",
"the",
"included",
"angle",
"as"... | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/SphericalUtil.php#L255-L259 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.tanLatGC | private static function tanLatGC( $lat1, $lat2, $lng2, $lng3) {
return (tan($lat1) * sin($lng2 - $lng3) + tan($lat2) * sin($lng3)) / sin($lng2);
} | php | private static function tanLatGC( $lat1, $lat2, $lng2, $lng3) {
return (tan($lat1) * sin($lng2 - $lng3) + tan($lat2) * sin($lng3)) / sin($lng2);
} | [
"private",
"static",
"function",
"tanLatGC",
"(",
"$",
"lat1",
",",
"$",
"lat2",
",",
"$",
"lng2",
",",
"$",
"lng3",
")",
"{",
"return",
"(",
"tan",
"(",
"$",
"lat1",
")",
"*",
"sin",
"(",
"$",
"lng2",
"-",
"$",
"lng3",
")",
"+",
"tan",
"(",
... | Returns tan(latitude-at-lng3) on the great circle (lat1, lng1) to (lat2, lng2). lng1==0.
See http://williams.best.vwh.net/avform.htm . | [
"Returns",
"tan",
"(",
"latitude",
"-",
"at",
"-",
"lng3",
")",
"on",
"the",
"great",
"circle",
"(",
"lat1",
"lng1",
")",
"to",
"(",
"lat2",
"lng2",
")",
".",
"lng1",
"==",
"0",
".",
"See",
"http",
":",
"//",
"williams",
".",
"best",
".",
"vwh",
... | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L35-L37 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.mercatorLatRhumb | private static function mercatorLatRhumb( $lat1, $lat2, $lng2, $lng3) {
return (MathUtil::mercator($lat1) * ($lng2 - $lng3) + MathUtil::mercator($lat2) * $lng3) / $lng2;
} | php | private static function mercatorLatRhumb( $lat1, $lat2, $lng2, $lng3) {
return (MathUtil::mercator($lat1) * ($lng2 - $lng3) + MathUtil::mercator($lat2) * $lng3) / $lng2;
} | [
"private",
"static",
"function",
"mercatorLatRhumb",
"(",
"$",
"lat1",
",",
"$",
"lat2",
",",
"$",
"lng2",
",",
"$",
"lng3",
")",
"{",
"return",
"(",
"MathUtil",
"::",
"mercator",
"(",
"$",
"lat1",
")",
"*",
"(",
"$",
"lng2",
"-",
"$",
"lng3",
")",... | Returns mercator(latitude-at-lng3) on the Rhumb line (lat1, lng1) to (lat2, lng2). lng1==0. | [
"Returns",
"mercator",
"(",
"latitude",
"-",
"at",
"-",
"lng3",
")",
"on",
"the",
"Rhumb",
"line",
"(",
"lat1",
"lng1",
")",
"to",
"(",
"lat2",
"lng2",
")",
".",
"lng1",
"==",
"0",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L42-L45 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.intersects | private static function intersects( $lat1, $lat2, $lng2, $lat3, $lng3, $geodesic) {
// Both ends on the same side of lng3.
if (($lng3 >= 0 && $lng3 >= $lng2) || ($lng3 < 0 && $lng3 < $lng2)) {
return false;
}
// Point is South Pole.
if ($lat3 <= -M_PI/2) {
return false;
}
// Any segment end is a pole.
if ($lat1 <= -M_PI/2 || $lat2 <= -M_PI/2 || $lat1 >= M_PI/2 || $lat2 >= M_PI/2) {
return false;
}
if ($lng2 <= -M_PI) {
return false;
}
$linearLat = ($lat1 * ($lng2 - $lng3) + $lat2 * $lng3) / $lng2;
// Northern hemisphere and point under lat-lng line.
if ($lat1 >= 0 && $lat2 >= 0 && $lat3 < $linearLat) {
return false;
}
// Southern hemisphere and point above lat-lng line.
if ($lat1 <= 0 && $lat2 <= 0 && $lat3 >= $linearLat) {
return true;
}
// North Pole.
if ($lat3 >= M_PI/2) {
return true;
}
// Compare lat3 with latitude on the GC/Rhumb segment corresponding to lng3.
// Compare through a strictly-increasing function (tan() or mercator()) as convenient.
return $geodesic ?
tan($lat3) >= self::tanLatGC($lat1, $lat2, $lng2, $lng3) :
MathUtil::mercator($lat3) >= self::mercatorLatRhumb($lat1, $lat2, $lng2, $lng3);
} | php | private static function intersects( $lat1, $lat2, $lng2, $lat3, $lng3, $geodesic) {
// Both ends on the same side of lng3.
if (($lng3 >= 0 && $lng3 >= $lng2) || ($lng3 < 0 && $lng3 < $lng2)) {
return false;
}
// Point is South Pole.
if ($lat3 <= -M_PI/2) {
return false;
}
// Any segment end is a pole.
if ($lat1 <= -M_PI/2 || $lat2 <= -M_PI/2 || $lat1 >= M_PI/2 || $lat2 >= M_PI/2) {
return false;
}
if ($lng2 <= -M_PI) {
return false;
}
$linearLat = ($lat1 * ($lng2 - $lng3) + $lat2 * $lng3) / $lng2;
// Northern hemisphere and point under lat-lng line.
if ($lat1 >= 0 && $lat2 >= 0 && $lat3 < $linearLat) {
return false;
}
// Southern hemisphere and point above lat-lng line.
if ($lat1 <= 0 && $lat2 <= 0 && $lat3 >= $linearLat) {
return true;
}
// North Pole.
if ($lat3 >= M_PI/2) {
return true;
}
// Compare lat3 with latitude on the GC/Rhumb segment corresponding to lng3.
// Compare through a strictly-increasing function (tan() or mercator()) as convenient.
return $geodesic ?
tan($lat3) >= self::tanLatGC($lat1, $lat2, $lng2, $lng3) :
MathUtil::mercator($lat3) >= self::mercatorLatRhumb($lat1, $lat2, $lng2, $lng3);
} | [
"private",
"static",
"function",
"intersects",
"(",
"$",
"lat1",
",",
"$",
"lat2",
",",
"$",
"lng2",
",",
"$",
"lat3",
",",
"$",
"lng3",
",",
"$",
"geodesic",
")",
"{",
"// Both ends on the same side of lng3.",
"if",
"(",
"(",
"$",
"lng3",
">=",
"0",
"... | Computes whether the vertical segment (lat3, lng3) to South Pole intersects the segment
(lat1, lng1) to (lat2, lng2).
Longitudes are offset by -lng1; the implicit lng1 becomes 0. | [
"Computes",
"whether",
"the",
"vertical",
"segment",
"(",
"lat3",
"lng3",
")",
"to",
"South",
"Pole",
"intersects",
"the",
"segment",
"(",
"lat1",
"lng1",
")",
"to",
"(",
"lat2",
"lng2",
")",
".",
"Longitudes",
"are",
"offset",
"by",
"-",
"lng1",
";",
... | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L55-L89 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.containsLocation | public static function containsLocation($point, $polygon, $geodesic = false) {
$size = count( $polygon );
if ($size == 0) {
return false;
}
$lat3 = deg2rad( $point['lat'] );
$lng3 = deg2rad( $point['lng'] );
$prev = $polygon[$size - 1];
$lat1 = deg2rad( $prev['lat'] );
$lng1 = deg2rad( $prev['lng'] );
$nIntersect = 0;
foreach($polygon as $key => $val) {
$dLng3 = MathUtil::wrap($lng3 - $lng1, -M_PI, M_PI);
// Special case: point equal to vertex is inside.
if ($lat3 == $lat1 && $dLng3 == 0) {
return true;
}
$lat2 = deg2rad($val['lat']);
$lng2 = deg2rad($val['lng']);
// Offset longitudes by -lng1.
if (self::intersects($lat1, $lat2, MathUtil::wrap($lng2 - $lng1, -M_PI, M_PI), $lat3, $dLng3, $geodesic)) {
++$nIntersect;
}
$lat1 = $lat2;
$lng1 = $lng2;
}
return ($nIntersect & 1) != 0;
} | php | public static function containsLocation($point, $polygon, $geodesic = false) {
$size = count( $polygon );
if ($size == 0) {
return false;
}
$lat3 = deg2rad( $point['lat'] );
$lng3 = deg2rad( $point['lng'] );
$prev = $polygon[$size - 1];
$lat1 = deg2rad( $prev['lat'] );
$lng1 = deg2rad( $prev['lng'] );
$nIntersect = 0;
foreach($polygon as $key => $val) {
$dLng3 = MathUtil::wrap($lng3 - $lng1, -M_PI, M_PI);
// Special case: point equal to vertex is inside.
if ($lat3 == $lat1 && $dLng3 == 0) {
return true;
}
$lat2 = deg2rad($val['lat']);
$lng2 = deg2rad($val['lng']);
// Offset longitudes by -lng1.
if (self::intersects($lat1, $lat2, MathUtil::wrap($lng2 - $lng1, -M_PI, M_PI), $lat3, $dLng3, $geodesic)) {
++$nIntersect;
}
$lat1 = $lat2;
$lng1 = $lng2;
}
return ($nIntersect & 1) != 0;
} | [
"public",
"static",
"function",
"containsLocation",
"(",
"$",
"point",
",",
"$",
"polygon",
",",
"$",
"geodesic",
"=",
"false",
")",
"{",
"$",
"size",
"=",
"count",
"(",
"$",
"polygon",
")",
";",
"if",
"(",
"$",
"size",
"==",
"0",
")",
"{",
"return... | Computes whether the given point lies inside the specified polygon.
The polygon is always cosidered closed, regardless of whether the last point equals
the first or not.
Inside is defined as not containing the South Pole -- the South Pole is always outside.
The polygon is formed of great circle segments if geodesic is true, and of rhumb
(loxodromic) segments otherwise. | [
"Computes",
"whether",
"the",
"given",
"point",
"lies",
"inside",
"the",
"specified",
"polygon",
".",
"The",
"polygon",
"is",
"always",
"cosidered",
"closed",
"regardless",
"of",
"whether",
"the",
"last",
"point",
"equals",
"the",
"first",
"or",
"not",
".",
... | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L100-L134 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.isLocationOnEdge | public static function isLocationOnEdge($point, $polygon, $tolerance = self::DEFAULT_TOLERANCE, $geodesic = true) {
return self::isLocationOnEdgeOrPath($point, $polygon, true, $geodesic, $tolerance);
} | php | public static function isLocationOnEdge($point, $polygon, $tolerance = self::DEFAULT_TOLERANCE, $geodesic = true) {
return self::isLocationOnEdgeOrPath($point, $polygon, true, $geodesic, $tolerance);
} | [
"public",
"static",
"function",
"isLocationOnEdge",
"(",
"$",
"point",
",",
"$",
"polygon",
",",
"$",
"tolerance",
"=",
"self",
"::",
"DEFAULT_TOLERANCE",
",",
"$",
"geodesic",
"=",
"true",
")",
"{",
"return",
"self",
"::",
"isLocationOnEdgeOrPath",
"(",
"$"... | Computes whether the given point lies on or near the edge of a polygon, within a specified
tolerance in meters. The polygon edge is composed of great circle segments if geodesic
is true, and of Rhumb segments otherwise. The polygon edge is implicitly closed -- the
closing segment between the first point and the last point is included. | [
"Computes",
"whether",
"the",
"given",
"point",
"lies",
"on",
"or",
"near",
"the",
"edge",
"of",
"a",
"polygon",
"within",
"a",
"specified",
"tolerance",
"in",
"meters",
".",
"The",
"polygon",
"edge",
"is",
"composed",
"of",
"great",
"circle",
"segments",
... | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L143-L145 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.isLocationOnPath | public static function isLocationOnPath($point, $polyline, $tolerance = self::DEFAULT_TOLERANCE, $geodesic = true) {
return self::isLocationOnEdgeOrPath($point, $polyline, false, $geodesic, $tolerance);
} | php | public static function isLocationOnPath($point, $polyline, $tolerance = self::DEFAULT_TOLERANCE, $geodesic = true) {
return self::isLocationOnEdgeOrPath($point, $polyline, false, $geodesic, $tolerance);
} | [
"public",
"static",
"function",
"isLocationOnPath",
"(",
"$",
"point",
",",
"$",
"polyline",
",",
"$",
"tolerance",
"=",
"self",
"::",
"DEFAULT_TOLERANCE",
",",
"$",
"geodesic",
"=",
"true",
")",
"{",
"return",
"self",
"::",
"isLocationOnEdgeOrPath",
"(",
"$... | Computes whether the given point lies on or near a polyline, within a specified
tolerance in meters. The polyline is composed of great circle segments if geodesic
is true, and of Rhumb segments otherwise. The polyline is not closed -- the closing
segment between the first point and the last point is not included. | [
"Computes",
"whether",
"the",
"given",
"point",
"lies",
"on",
"or",
"near",
"a",
"polyline",
"within",
"a",
"specified",
"tolerance",
"in",
"meters",
".",
"The",
"polyline",
"is",
"composed",
"of",
"great",
"circle",
"segments",
"if",
"geodesic",
"is",
"true... | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L154-L156 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.sinDeltaBearing | private static function sinDeltaBearing( $lat1, $lng1, $lat2, $lng2, $lat3, $lng3) {
$sinLat1 = sin($lat1);
$cosLat2 = cos($lat2);
$cosLat3 = cos($lat3);
$lat31 = $lat3 - $lat1;
$lng31 = $lng3 - $lng1;
$lat21 = $lat2 - $lat1;
$lng21 = $lng2 - $lng1;
$a = sin($lng31) * $cosLat3;
$c = sin($lng21) * $cosLat2;
$b = sin($lat31) + 2 * $sinLat1 * $cosLat3 * MathUtil::hav($lng31);
$d = sin($lat21) + 2 * $sinLat1 * $cosLat2 * MathUtil::hav($lng21);
$denom = ($a * $a + $b * $b) * ($c * $c + $d * $d);
return $denom <= 0 ? 1 : ($a * $d - $b * $c) / sqrt($denom);
} | php | private static function sinDeltaBearing( $lat1, $lng1, $lat2, $lng2, $lat3, $lng3) {
$sinLat1 = sin($lat1);
$cosLat2 = cos($lat2);
$cosLat3 = cos($lat3);
$lat31 = $lat3 - $lat1;
$lng31 = $lng3 - $lng1;
$lat21 = $lat2 - $lat1;
$lng21 = $lng2 - $lng1;
$a = sin($lng31) * $cosLat3;
$c = sin($lng21) * $cosLat2;
$b = sin($lat31) + 2 * $sinLat1 * $cosLat3 * MathUtil::hav($lng31);
$d = sin($lat21) + 2 * $sinLat1 * $cosLat2 * MathUtil::hav($lng21);
$denom = ($a * $a + $b * $b) * ($c * $c + $d * $d);
return $denom <= 0 ? 1 : ($a * $d - $b * $c) / sqrt($denom);
} | [
"private",
"static",
"function",
"sinDeltaBearing",
"(",
"$",
"lat1",
",",
"$",
"lng1",
",",
"$",
"lat2",
",",
"$",
"lng2",
",",
"$",
"lat3",
",",
"$",
"lng3",
")",
"{",
"$",
"sinLat1",
"=",
"sin",
"(",
"$",
"lat1",
")",
";",
"$",
"cosLat2",
"=",... | Returns sin(initial bearing from (lat1,lng1) to (lat3,lng3) minus initial bearing
from (lat1, lng1) to (lat2,lng2)). | [
"Returns",
"sin",
"(",
"initial",
"bearing",
"from",
"(",
"lat1",
"lng1",
")",
"to",
"(",
"lat3",
"lng3",
")",
"minus",
"initial",
"bearing",
"from",
"(",
"lat1",
"lng1",
")",
"to",
"(",
"lat2",
"lng2",
"))",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L236-L251 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.distanceToLine | public static function distanceToLine($p, $start, $end) {
if ($start == $end) {
return SphericalUtil::computeDistanceBetween($end, $p);
}
$s0lat = deg2rad($p['lat']);
$s0lng = deg2rad($p['lng']);
$s1lat = deg2rad($start['lat']);
$s1lng = deg2rad($start['lng']);
$s2lat = deg2rad($end['lat']);
$s2lng = deg2rad($end['lng']);
$s2s1lat = $s2lat - $s1lat;
$s2s1lng = $s2lng - $s1lng;
$u = (($s0lat - $s1lat) * $s2s1lat + ($s0lng - $s1lng) * $s2s1lng)
/ ($s2s1lat * $s2s1lat + $s2s1lng * $s2s1lng);
if ($u <= 0) {
return SphericalUtil::computeDistanceBetween($p, $start);
}
if ($u >= 1) {
return SphericalUtil::computeDistanceBetween($p, $end);
}
$sa = array('lat' => $p['lat'] - $start['lat'], 'lng' => $p['lng'] - $start['lng']);
$sb = array('lat' => ($u * ($end['lat'] - $start['lat'])), 'lng' => ($u * ($end['lng'] - $start['lng'])));
return SphericalUtil::computeDistanceBetween($sa, $sb);
} | php | public static function distanceToLine($p, $start, $end) {
if ($start == $end) {
return SphericalUtil::computeDistanceBetween($end, $p);
}
$s0lat = deg2rad($p['lat']);
$s0lng = deg2rad($p['lng']);
$s1lat = deg2rad($start['lat']);
$s1lng = deg2rad($start['lng']);
$s2lat = deg2rad($end['lat']);
$s2lng = deg2rad($end['lng']);
$s2s1lat = $s2lat - $s1lat;
$s2s1lng = $s2lng - $s1lng;
$u = (($s0lat - $s1lat) * $s2s1lat + ($s0lng - $s1lng) * $s2s1lng)
/ ($s2s1lat * $s2s1lat + $s2s1lng * $s2s1lng);
if ($u <= 0) {
return SphericalUtil::computeDistanceBetween($p, $start);
}
if ($u >= 1) {
return SphericalUtil::computeDistanceBetween($p, $end);
}
$sa = array('lat' => $p['lat'] - $start['lat'], 'lng' => $p['lng'] - $start['lng']);
$sb = array('lat' => ($u * ($end['lat'] - $start['lat'])), 'lng' => ($u * ($end['lng'] - $start['lng'])));
return SphericalUtil::computeDistanceBetween($sa, $sb);
} | [
"public",
"static",
"function",
"distanceToLine",
"(",
"$",
"p",
",",
"$",
"start",
",",
"$",
"end",
")",
"{",
"if",
"(",
"$",
"start",
"==",
"$",
"end",
")",
"{",
"return",
"SphericalUtil",
"::",
"computeDistanceBetween",
"(",
"$",
"end",
",",
"$",
... | Computes the distance on the sphere between the point p and the line segment start to end.
@param p the point to be measured
@param start the beginning of the line segment
@param end the end of the line segment
@return the distance in meters (assuming spherical earth) | [
"Computes",
"the",
"distance",
"on",
"the",
"sphere",
"between",
"the",
"point",
"p",
"and",
"the",
"line",
"segment",
"start",
"to",
"end",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L294-L319 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.decode | public static function decode($encodedPath) {
$len = strlen( $encodedPath ) -1;
// For speed we preallocate to an upper bound on the final length, then
// truncate the array before returning.
$path = [];
$index = 0;
$lat = 0;
$lng = 0;
while( $index < $len) {
$result = 1;
$shift = 0;
$b;
do {
$b = ord($encodedPath{$index++}) - 63 - 1;
$result += $b << $shift;
$shift += 5;
} while ($b >= hexdec("0x1f"));
$lat += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);
$result = 1;
$shift = 0;
do {
$b = ord($encodedPath{$index++}) - 63 - 1;
$result += $b << $shift;
$shift += 5;
} while ($b >= hexdec("0x1f"));
$lng += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);
array_push($path, ['lat' => $lat * 1e-5, 'lng' => $lng * 1e-5]);
}
return $path;
} | php | public static function decode($encodedPath) {
$len = strlen( $encodedPath ) -1;
// For speed we preallocate to an upper bound on the final length, then
// truncate the array before returning.
$path = [];
$index = 0;
$lat = 0;
$lng = 0;
while( $index < $len) {
$result = 1;
$shift = 0;
$b;
do {
$b = ord($encodedPath{$index++}) - 63 - 1;
$result += $b << $shift;
$shift += 5;
} while ($b >= hexdec("0x1f"));
$lat += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);
$result = 1;
$shift = 0;
do {
$b = ord($encodedPath{$index++}) - 63 - 1;
$result += $b << $shift;
$shift += 5;
} while ($b >= hexdec("0x1f"));
$lng += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);
array_push($path, ['lat' => $lat * 1e-5, 'lng' => $lng * 1e-5]);
}
return $path;
} | [
"public",
"static",
"function",
"decode",
"(",
"$",
"encodedPath",
")",
"{",
"$",
"len",
"=",
"strlen",
"(",
"$",
"encodedPath",
")",
"-",
"1",
";",
"// For speed we preallocate to an upper bound on the final length, then",
"// truncate the array before returning.",
"$",
... | Decodes an encoded path string into a sequence of LatLngs. | [
"Decodes",
"an",
"encoded",
"path",
"string",
"into",
"a",
"sequence",
"of",
"LatLngs",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L324-L359 |
alexpechkarev/geometry-library | PolyUtil.php | PolyUtil.encode | public static function encode($path) {
$lastLat = 0;
$lastLng = 0;
$result = '';
foreach( $path as $point ) {
$lat = round( $point['lat'] * 1e5);
$lng = round( $point['lng'] * 1e5);
$dLat = $lat - $lastLat;
$dLng = $lng - $lastLng;
self::enc($dLat);
self::enc($dLng);
$lastLat = $lat;
$lastLng = $lng;
}
return self::$result;
} | php | public static function encode($path) {
$lastLat = 0;
$lastLng = 0;
$result = '';
foreach( $path as $point ) {
$lat = round( $point['lat'] * 1e5);
$lng = round( $point['lng'] * 1e5);
$dLat = $lat - $lastLat;
$dLng = $lng - $lastLng;
self::enc($dLat);
self::enc($dLng);
$lastLat = $lat;
$lastLng = $lng;
}
return self::$result;
} | [
"public",
"static",
"function",
"encode",
"(",
"$",
"path",
")",
"{",
"$",
"lastLat",
"=",
"0",
";",
"$",
"lastLng",
"=",
"0",
";",
"$",
"result",
"=",
"''",
";",
"foreach",
"(",
"$",
"path",
"as",
"$",
"point",
")",
"{",
"$",
"lat",
"=",
"roun... | Encodes a sequence of LatLngs into an encoded path string. | [
"Encodes",
"a",
"sequence",
"of",
"LatLngs",
"into",
"an",
"encoded",
"path",
"string",
"."
] | train | https://github.com/alexpechkarev/geometry-library/blob/111d40d3cda148d167c32e09fa3097dea6c59f62/PolyUtil.php#L365-L386 |
Seldaek/cli-prompt | src/CliPrompt.php | CliPrompt.prompt | public static function prompt()
{
$stdin = fopen('php://stdin', 'r');
$answer = self::trimAnswer(fgets($stdin, 4096));
fclose($stdin);
return $answer;
} | php | public static function prompt()
{
$stdin = fopen('php://stdin', 'r');
$answer = self::trimAnswer(fgets($stdin, 4096));
fclose($stdin);
return $answer;
} | [
"public",
"static",
"function",
"prompt",
"(",
")",
"{",
"$",
"stdin",
"=",
"fopen",
"(",
"'php://stdin'",
",",
"'r'",
")",
";",
"$",
"answer",
"=",
"self",
"::",
"trimAnswer",
"(",
"fgets",
"(",
"$",
"stdin",
",",
"4096",
")",
")",
";",
"fclose",
... | Prompts the user for input and shows what they type
@return string | [
"Prompts",
"the",
"user",
"for",
"input",
"and",
"shows",
"what",
"they",
"type"
] | train | https://github.com/Seldaek/cli-prompt/blob/a19a7376a4689d4d94cab66ab4f3c816019ba8dd/src/CliPrompt.php#L21-L28 |
Seldaek/cli-prompt | src/CliPrompt.php | CliPrompt.hiddenPrompt | public static function hiddenPrompt($allowFallback = false)
{
// handle windows
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
// fallback to hiddeninput executable
$exe = __DIR__.'\\..\\res\\hiddeninput.exe';
// handle code running from a phar
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
// use stream_copy_to_stream instead of copy
// to work around https://bugs.php.net/bug.php?id=64634
$source = fopen($exe, 'r');
$target = fopen($tmpExe, 'w+');
stream_copy_to_stream($source, $target);
fclose($source);
fclose($target);
unset($source, $target);
$exe = $tmpExe;
}
$output = shell_exec($exe);
// clean up
if (isset($tmpExe)) {
unlink($tmpExe);
}
if ($output !== null) {
// output a newline to be on par with the regular prompt()
echo PHP_EOL;
return self::trimAnswer($output);
}
}
if (file_exists('/usr/bin/env')) {
// handle other OSs with bash/zsh/ksh/csh if available to hide the answer
$test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
foreach (array('bash', 'zsh', 'ksh', 'csh', 'sh') as $sh) {
if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
$shell = $sh;
break;
}
}
if (isset($shell)) {
$readCmd = ($shell === 'csh') ? 'set mypassword = $<' : 'read -r mypassword';
$command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
$output = shell_exec($command);
if ($output !== null) {
// output a newline to be on par with the regular prompt()
echo PHP_EOL;
return self::trimAnswer($output);
}
}
}
// not able to hide the answer
if (!$allowFallback) {
throw new \RuntimeException('Could not prompt for input in a secure fashion, aborting');
}
return self::prompt();
} | php | public static function hiddenPrompt($allowFallback = false)
{
// handle windows
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
// fallback to hiddeninput executable
$exe = __DIR__.'\\..\\res\\hiddeninput.exe';
// handle code running from a phar
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
// use stream_copy_to_stream instead of copy
// to work around https://bugs.php.net/bug.php?id=64634
$source = fopen($exe, 'r');
$target = fopen($tmpExe, 'w+');
stream_copy_to_stream($source, $target);
fclose($source);
fclose($target);
unset($source, $target);
$exe = $tmpExe;
}
$output = shell_exec($exe);
// clean up
if (isset($tmpExe)) {
unlink($tmpExe);
}
if ($output !== null) {
// output a newline to be on par with the regular prompt()
echo PHP_EOL;
return self::trimAnswer($output);
}
}
if (file_exists('/usr/bin/env')) {
// handle other OSs with bash/zsh/ksh/csh if available to hide the answer
$test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
foreach (array('bash', 'zsh', 'ksh', 'csh', 'sh') as $sh) {
if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
$shell = $sh;
break;
}
}
if (isset($shell)) {
$readCmd = ($shell === 'csh') ? 'set mypassword = $<' : 'read -r mypassword';
$command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
$output = shell_exec($command);
if ($output !== null) {
// output a newline to be on par with the regular prompt()
echo PHP_EOL;
return self::trimAnswer($output);
}
}
}
// not able to hide the answer
if (!$allowFallback) {
throw new \RuntimeException('Could not prompt for input in a secure fashion, aborting');
}
return self::prompt();
} | [
"public",
"static",
"function",
"hiddenPrompt",
"(",
"$",
"allowFallback",
"=",
"false",
")",
"{",
"// handle windows",
"if",
"(",
"defined",
"(",
"'PHP_WINDOWS_VERSION_BUILD'",
")",
")",
"{",
"// fallback to hiddeninput executable",
"$",
"exe",
"=",
"__DIR__",
".",... | Prompts the user for input and hides what they type
@param bool $allowFallback If prompting fails for any reason and this is set to true the prompt
will be done using the regular prompt() function, otherwise a
\RuntimeException is thrown.
@return string
@throws RuntimeException on failure to prompt, unless $allowFallback is true | [
"Prompts",
"the",
"user",
"for",
"input",
"and",
"hides",
"what",
"they",
"type"
] | train | https://github.com/Seldaek/cli-prompt/blob/a19a7376a4689d4d94cab66ab4f3c816019ba8dd/src/CliPrompt.php#L39-L107 |
illuminate/auth | SessionGuard.php | SessionGuard.logoutOtherDevices | public function logoutOtherDevices($password, $attribute = 'password')
{
if (! $this->user()) {
return;
}
$result = tap($this->user()->forceFill([
$attribute => Hash::make($password),
]))->save();
$this->queueRecallerCookie($this->user());
$this->fireOtherDeviceLogoutEvent($this->user());
return $result;
} | php | public function logoutOtherDevices($password, $attribute = 'password')
{
if (! $this->user()) {
return;
}
$result = tap($this->user()->forceFill([
$attribute => Hash::make($password),
]))->save();
$this->queueRecallerCookie($this->user());
$this->fireOtherDeviceLogoutEvent($this->user());
return $result;
} | [
"public",
"function",
"logoutOtherDevices",
"(",
"$",
"password",
",",
"$",
"attribute",
"=",
"'password'",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"user",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"result",
"=",
"tap",
"(",
"$",
"this",
"-... | Invalidate other sessions for the current user.
The application must be using the AuthenticateSession middleware.
@param string $password
@param string $attribute
@return bool|null | [
"Invalidate",
"other",
"sessions",
"for",
"the",
"current",
"user",
"."
] | train | https://github.com/illuminate/auth/blob/68a770af8b4546fd9e9d22547f299cef84bd9081/SessionGuard.php#L543-L558 |
mingyoung/easywechat-composer | src/Commands/ExtensionsCommand.php | ExtensionsCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$extensions = require __DIR__.'/../../extensions.php';
if (empty($extensions) || !is_array($extensions)) {
return $output->writeln('<info>No extension installed.</info>');
}
$table = new Table($output);
$table->setHeaders(['Name', 'Observers'])
->setRows(
array_map([$this, 'getRows'], array_keys($extensions), $extensions)
)->render();
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$extensions = require __DIR__.'/../../extensions.php';
if (empty($extensions) || !is_array($extensions)) {
return $output->writeln('<info>No extension installed.</info>');
}
$table = new Table($output);
$table->setHeaders(['Name', 'Observers'])
->setRows(
array_map([$this, 'getRows'], array_keys($extensions), $extensions)
)->render();
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"extensions",
"=",
"require",
"__DIR__",
".",
"'/../../extensions.php'",
";",
"if",
"(",
"empty",
"(",
"$",
"extensions",
")",
"||",
... | Executes the current command.
@param InputInterface $input
@param OutputInterface $output | [
"Executes",
"the",
"current",
"command",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Commands/ExtensionsCommand.php#L38-L51 |
mingyoung/easywechat-composer | src/ManifestManager.php | ManifestManager.build | public function build()
{
$packages = [];
if (file_exists($installed = $this->vendorPath.'/composer/installed.json')) {
$packages = json_decode(file_get_contents($installed), true);
}
$this->write($this->map($packages));
} | php | public function build()
{
$packages = [];
if (file_exists($installed = $this->vendorPath.'/composer/installed.json')) {
$packages = json_decode(file_get_contents($installed), true);
}
$this->write($this->map($packages));
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"packages",
"=",
"[",
"]",
";",
"if",
"(",
"file_exists",
"(",
"$",
"installed",
"=",
"$",
"this",
"->",
"vendorPath",
".",
"'/composer/installed.json'",
")",
")",
"{",
"$",
"packages",
"=",
"json_decode... | Build the manifest file. | [
"Build",
"the",
"manifest",
"file",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/ManifestManager.php#L63-L72 |
mingyoung/easywechat-composer | src/ManifestManager.php | ManifestManager.map | protected function map(array $packages): array
{
$manifest = [];
$packages = array_filter($packages, function ($package) {
return $package['type'] === self::PACKAGE_TYPE;
});
foreach ($packages as $package) {
$manifest[$package['name']] = [self::EXTRA_OBSERVER => $package['extra'][self::EXTRA_OBSERVER] ?? []];
}
return $manifest;
} | php | protected function map(array $packages): array
{
$manifest = [];
$packages = array_filter($packages, function ($package) {
return $package['type'] === self::PACKAGE_TYPE;
});
foreach ($packages as $package) {
$manifest[$package['name']] = [self::EXTRA_OBSERVER => $package['extra'][self::EXTRA_OBSERVER] ?? []];
}
return $manifest;
} | [
"protected",
"function",
"map",
"(",
"array",
"$",
"packages",
")",
":",
"array",
"{",
"$",
"manifest",
"=",
"[",
"]",
";",
"$",
"packages",
"=",
"array_filter",
"(",
"$",
"packages",
",",
"function",
"(",
"$",
"package",
")",
"{",
"return",
"$",
"pa... | @param array $packages
@return array | [
"@param",
"array",
"$packages"
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/ManifestManager.php#L79-L92 |
mingyoung/easywechat-composer | src/ManifestManager.php | ManifestManager.write | protected function write(array $manifest)
{
file_put_contents(
$this->manifestPath,
'<?php return '.var_export($manifest, true).';'
);
$this->invalidate($this->manifestPath);
} | php | protected function write(array $manifest)
{
file_put_contents(
$this->manifestPath,
'<?php return '.var_export($manifest, true).';'
);
$this->invalidate($this->manifestPath);
} | [
"protected",
"function",
"write",
"(",
"array",
"$",
"manifest",
")",
"{",
"file_put_contents",
"(",
"$",
"this",
"->",
"manifestPath",
",",
"'<?php return '",
".",
"var_export",
"(",
"$",
"manifest",
",",
"true",
")",
".",
"';'",
")",
";",
"$",
"this",
... | Write the manifest array to a file.
@param array $manifest | [
"Write",
"the",
"manifest",
"array",
"to",
"a",
"file",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/ManifestManager.php#L99-L107 |
mingyoung/easywechat-composer | src/Extension.php | Extension.observers | public function observers(): array
{
if ($this->shouldIgnore()) {
return [];
}
$observers = [];
foreach ($this->getManifest() as $name => $extra) {
$observers = array_merge($observers, $extra['observers'] ?? []);
}
return array_map([$this, 'listObserver'], array_filter($observers, [$this, 'validateObserver']));
} | php | public function observers(): array
{
if ($this->shouldIgnore()) {
return [];
}
$observers = [];
foreach ($this->getManifest() as $name => $extra) {
$observers = array_merge($observers, $extra['observers'] ?? []);
}
return array_map([$this, 'listObserver'], array_filter($observers, [$this, 'validateObserver']));
} | [
"public",
"function",
"observers",
"(",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"shouldIgnore",
"(",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"observers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getManifest",
... | Get observers.
@return array | [
"Get",
"observers",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Extension.php#L51-L64 |
mingyoung/easywechat-composer | src/Extension.php | Extension.validateObserver | protected function validateObserver($observer): bool
{
return !$this->isDisable($observer)
&& (new ReflectionClass($observer))->implementsInterface(EventHandlerInterface::class)
&& $this->accessible($observer);
} | php | protected function validateObserver($observer): bool
{
return !$this->isDisable($observer)
&& (new ReflectionClass($observer))->implementsInterface(EventHandlerInterface::class)
&& $this->accessible($observer);
} | [
"protected",
"function",
"validateObserver",
"(",
"$",
"observer",
")",
":",
"bool",
"{",
"return",
"!",
"$",
"this",
"->",
"isDisable",
"(",
"$",
"observer",
")",
"&&",
"(",
"new",
"ReflectionClass",
"(",
"$",
"observer",
")",
")",
"->",
"implementsInterf... | Validate the given observer.
@param mixed $observer
@return bool
@throws \ReflectionException | [
"Validate",
"the",
"given",
"observer",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Extension.php#L95-L100 |
mingyoung/easywechat-composer | src/Extension.php | Extension.accessible | protected function accessible($observer): bool
{
if (!method_exists($observer, 'getAccessor')) {
return true;
}
return in_array(get_class($this->app), (array) $observer::getAccessor());
} | php | protected function accessible($observer): bool
{
if (!method_exists($observer, 'getAccessor')) {
return true;
}
return in_array(get_class($this->app), (array) $observer::getAccessor());
} | [
"protected",
"function",
"accessible",
"(",
"$",
"observer",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"observer",
",",
"'getAccessor'",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"in_array",
"(",
"get_class",
"(",
"$",
... | Determine whether the given observer is accessible.
@param string $observer
@return bool | [
"Determine",
"whether",
"the",
"given",
"observer",
"is",
"accessible",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Extension.php#L109-L116 |
mingyoung/easywechat-composer | src/Extension.php | Extension.getManifest | protected function getManifest(): array
{
if (!is_null($this->manifest)) {
return $this->manifest;
}
return $this->manifest = file_exists($this->manifestPath) ? require $this->manifestPath : [];
} | php | protected function getManifest(): array
{
if (!is_null($this->manifest)) {
return $this->manifest;
}
return $this->manifest = file_exists($this->manifestPath) ? require $this->manifestPath : [];
} | [
"protected",
"function",
"getManifest",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"manifest",
")",
")",
"{",
"return",
"$",
"this",
"->",
"manifest",
";",
"}",
"return",
"$",
"this",
"->",
"manifest",
"=",
"file_... | Get the easywechat manifest.
@return array | [
"Get",
"the",
"easywechat",
"manifest",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Extension.php#L135-L142 |
mingyoung/easywechat-composer | src/Laravel/ServiceProvider.php | ServiceProvider.boot | public function boot()
{
$this->registerRoutes();
$this->publishes([
__DIR__.'/config.php' => config_path('easywechat-composer.php'),
]);
EasyWeChat::setEncryptionKey(
$defaultKey = $this->getKey()
);
EasyWeChat::withDelegation()
->toHost($this->config('delegation.host'))
->ability($this->config('delegation.enabled'));
$this->app->when(DefaultEncrypter::class)->needs('$key')->give($defaultKey);
} | php | public function boot()
{
$this->registerRoutes();
$this->publishes([
__DIR__.'/config.php' => config_path('easywechat-composer.php'),
]);
EasyWeChat::setEncryptionKey(
$defaultKey = $this->getKey()
);
EasyWeChat::withDelegation()
->toHost($this->config('delegation.host'))
->ability($this->config('delegation.enabled'));
$this->app->when(DefaultEncrypter::class)->needs('$key')->give($defaultKey);
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"this",
"->",
"registerRoutes",
"(",
")",
";",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/config.php'",
"=>",
"config_path",
"(",
"'easywechat-composer.php'",
")",
",",
"]",
")",
";",
"E... | Bootstrap any application services. | [
"Bootstrap",
"any",
"application",
"services",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Laravel/ServiceProvider.php#L28-L44 |
mingyoung/easywechat-composer | src/Laravel/ServiceProvider.php | ServiceProvider.config | protected function config($key = null, $default = null)
{
$config = $this->app['config']->get('easywechat-composer');
if (is_null($key)) {
return $config;
}
return array_get($config, $key, $default);
} | php | protected function config($key = null, $default = null)
{
$config = $this->app['config']->get('easywechat-composer');
if (is_null($key)) {
return $config;
}
return array_get($config, $key, $default);
} | [
"protected",
"function",
"config",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"app",
"[",
"'config'",
"]",
"->",
"get",
"(",
"'easywechat-composer'",
")",
";",
"if",
"(",
"is_null"... | Get the specified configuration value.
@param string|null $key
@param mixed $default
@return mixed | [
"Get",
"the",
"specified",
"configuration",
"value",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Laravel/ServiceProvider.php#L82-L91 |
mingyoung/easywechat-composer | src/Encryption/DefaultEncrypter.php | DefaultEncrypter.encrypt | public function encrypt($value)
{
$iv = random_bytes(openssl_cipher_iv_length($this->cipher));
$value = openssl_encrypt($value, $this->cipher, $this->key, 0, $iv);
if ($value === false) {
throw new EncryptException('Could not encrypt the data.');
}
$iv = base64_encode($iv);
return base64_encode(json_encode(compact('iv', 'value')));
} | php | public function encrypt($value)
{
$iv = random_bytes(openssl_cipher_iv_length($this->cipher));
$value = openssl_encrypt($value, $this->cipher, $this->key, 0, $iv);
if ($value === false) {
throw new EncryptException('Could not encrypt the data.');
}
$iv = base64_encode($iv);
return base64_encode(json_encode(compact('iv', 'value')));
} | [
"public",
"function",
"encrypt",
"(",
"$",
"value",
")",
"{",
"$",
"iv",
"=",
"random_bytes",
"(",
"openssl_cipher_iv_length",
"(",
"$",
"this",
"->",
"cipher",
")",
")",
";",
"$",
"value",
"=",
"openssl_encrypt",
"(",
"$",
"value",
",",
"$",
"this",
"... | Encrypt the given value.
@param string $value
@return string
@throws \EasyWeChatComposer\Exceptions\EncryptException | [
"Encrypt",
"the",
"given",
"value",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Encryption/DefaultEncrypter.php#L51-L64 |
mingyoung/easywechat-composer | src/Traits/MakesHttpRequests.php | MakesHttpRequests.request | protected function request($endpoint, array $payload)
{
$response = $this->getHttpClient()->request('POST', $endpoint, [
'form_params' => $this->buildFormParams($payload),
]);
$parsed = $this->parseResponse($response);
return $this->detectAndCastResponseToType(
$this->getEncrypter()->decrypt($parsed['response']),
($parsed['response_type'] === StreamResponse::class) ? 'raw' : $this->app['config']['response_type']
);
} | php | protected function request($endpoint, array $payload)
{
$response = $this->getHttpClient()->request('POST', $endpoint, [
'form_params' => $this->buildFormParams($payload),
]);
$parsed = $this->parseResponse($response);
return $this->detectAndCastResponseToType(
$this->getEncrypter()->decrypt($parsed['response']),
($parsed['response_type'] === StreamResponse::class) ? 'raw' : $this->app['config']['response_type']
);
} | [
"protected",
"function",
"request",
"(",
"$",
"endpoint",
",",
"array",
"$",
"payload",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"getHttpClient",
"(",
")",
"->",
"request",
"(",
"'POST'",
",",
"$",
"endpoint",
",",
"[",
"'form_params'",
"=>",
... | @param string $endpoint
@param array $payload
@return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
@throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
@throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
@throws \GuzzleHttp\Exception\GuzzleException | [
"@param",
"string",
"$endpoint",
"@param",
"array",
"$payload"
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Traits/MakesHttpRequests.php#L49-L61 |
mingyoung/easywechat-composer | src/Traits/MakesHttpRequests.php | MakesHttpRequests.parseResponse | protected function parseResponse($response)
{
$result = json_decode((string) $response->getBody(), true);
if (isset($result['exception'])) {
throw (new DelegationException($result['message']))->setException($result['exception']);
}
return $result;
} | php | protected function parseResponse($response)
{
$result = json_decode((string) $response->getBody(), true);
if (isset($result['exception'])) {
throw (new DelegationException($result['message']))->setException($result['exception']);
}
return $result;
} | [
"protected",
"function",
"parseResponse",
"(",
"$",
"response",
")",
"{",
"$",
"result",
"=",
"json_decode",
"(",
"(",
"string",
")",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"result",
"[",
"'ex... | @param \Psr\Http\Message\ResponseInterface $response
@return array | [
"@param",
"\\",
"Psr",
"\\",
"Http",
"\\",
"Message",
"\\",
"ResponseInterface",
"$response"
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Traits/MakesHttpRequests.php#L80-L89 |
mingyoung/easywechat-composer | src/Traits/WithAggregator.php | WithAggregator.aggregate | protected function aggregate()
{
foreach (EasyWeChat::config() as $key => $value) {
$this['config']->set($key, $value);
}
} | php | protected function aggregate()
{
foreach (EasyWeChat::config() as $key => $value) {
$this['config']->set($key, $value);
}
} | [
"protected",
"function",
"aggregate",
"(",
")",
"{",
"foreach",
"(",
"EasyWeChat",
"::",
"config",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"[",
"'config'",
"]",
"->",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
... | Aggregate. | [
"Aggregate",
"."
] | train | https://github.com/mingyoung/easywechat-composer/blob/970144fd245e62869edd60db6cc477053219d891/src/Traits/WithAggregator.php#L25-L30 |
tommy-muehle/tooly-composer-script | src/Script/Decision/IsAccessibleDecision.php | IsAccessibleDecision.canProceed | public function canProceed(Tool $tool)
{
if (false === $this->helper->getDownloader()->isAccessible($tool->getUrl())) {
return false;
}
if (empty($tool->getSignUrl())) {
return true;
}
if (false === $this->helper->getDownloader()->isAccessible($tool->getSignUrl())) {
return false;
}
return true;
} | php | public function canProceed(Tool $tool)
{
if (false === $this->helper->getDownloader()->isAccessible($tool->getUrl())) {
return false;
}
if (empty($tool->getSignUrl())) {
return true;
}
if (false === $this->helper->getDownloader()->isAccessible($tool->getSignUrl())) {
return false;
}
return true;
} | [
"public",
"function",
"canProceed",
"(",
"Tool",
"$",
"tool",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"helper",
"->",
"getDownloader",
"(",
")",
"->",
"isAccessible",
"(",
"$",
"tool",
"->",
"getUrl",
"(",
")",
")",
")",
"{",
"return"... | @param Tool $tool
@return bool | [
"@param",
"Tool",
"$tool"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Decision/IsAccessibleDecision.php#L17-L32 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Filesystem.php | Filesystem.createFile | public function createFile($filename, $content)
{
if (false === $this->createDirectory(dirname($filename))) {
return false;
}
Silencer::call('file_put_contents', $filename, $content);
Silencer::call('chmod', $filename, 0755);
return true;
} | php | public function createFile($filename, $content)
{
if (false === $this->createDirectory(dirname($filename))) {
return false;
}
Silencer::call('file_put_contents', $filename, $content);
Silencer::call('chmod', $filename, 0755);
return true;
} | [
"public",
"function",
"createFile",
"(",
"$",
"filename",
",",
"$",
"content",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"createDirectory",
"(",
"dirname",
"(",
"$",
"filename",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"Silencer",... | @param string $filename
@param string $content
@return bool
@SuppressWarnings(PHPMD.StaticAccess) | [
"@param",
"string",
"$filename",
"@param",
"string",
"$content"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Filesystem.php#L43-L53 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Filesystem.php | Filesystem.symlinkFile | public function symlinkFile($sourceFile, $file)
{
if (false === $this->createDirectory(dirname($file))) {
return false;
}
if (true === $this->isFileAlreadyExist($file)) {
return true;
}
return $this->filesystem->relativeSymlink($sourceFile, $file);
} | php | public function symlinkFile($sourceFile, $file)
{
if (false === $this->createDirectory(dirname($file))) {
return false;
}
if (true === $this->isFileAlreadyExist($file)) {
return true;
}
return $this->filesystem->relativeSymlink($sourceFile, $file);
} | [
"public",
"function",
"symlinkFile",
"(",
"$",
"sourceFile",
",",
"$",
"file",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"createDirectory",
"(",
"dirname",
"(",
"$",
"file",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
... | @param string $sourceFile
@param string $file
@return bool | [
"@param",
"string",
"$sourceFile",
"@param",
"string",
"$file"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Filesystem.php#L61-L72 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Filesystem.php | Filesystem.copyFile | public function copyFile($sourceFile, $file)
{
if (!$this->createDirectory(dirname($file))) {
return false;
}
if ($this->isFileAlreadyExist($file)) {
return true;
}
return Silencer::call(
'copy',
$this->filesystem->normalizePath($sourceFile),
$this->filesystem->normalizePath($file)
);
} | php | public function copyFile($sourceFile, $file)
{
if (!$this->createDirectory(dirname($file))) {
return false;
}
if ($this->isFileAlreadyExist($file)) {
return true;
}
return Silencer::call(
'copy',
$this->filesystem->normalizePath($sourceFile),
$this->filesystem->normalizePath($file)
);
} | [
"public",
"function",
"copyFile",
"(",
"$",
"sourceFile",
",",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"createDirectory",
"(",
"dirname",
"(",
"$",
"file",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
... | @param $sourceFile
@param $file
@return bool | [
"@param",
"$sourceFile",
"@param",
"$file"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Filesystem.php#L80-L95 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Filesystem.php | Filesystem.createDirectory | public function createDirectory($directory)
{
if (true === is_dir($directory)) {
return true;
}
return Silencer::call('mkdir', $directory, 0777, true);
} | php | public function createDirectory($directory)
{
if (true === is_dir($directory)) {
return true;
}
return Silencer::call('mkdir', $directory, 0777, true);
} | [
"public",
"function",
"createDirectory",
"(",
"$",
"directory",
")",
"{",
"if",
"(",
"true",
"===",
"is_dir",
"(",
"$",
"directory",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"Silencer",
"::",
"call",
"(",
"'mkdir'",
",",
"$",
"directory",
"... | @param string $directory
@return bool
@SuppressWarnings(PHPMD.StaticAccess) | [
"@param",
"string",
"$directory"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Filesystem.php#L124-L131 |
tommy-muehle/tooly-composer-script | src/Script/Decision/FileAlreadyExistDecision.php | FileAlreadyExistDecision.canProceed | public function canProceed(Tool $tool)
{
if (false === $this->helper->isFileAlreadyExist($tool->getFilename(), $tool->getUrl())) {
return true;
}
return false;
} | php | public function canProceed(Tool $tool)
{
if (false === $this->helper->isFileAlreadyExist($tool->getFilename(), $tool->getUrl())) {
return true;
}
return false;
} | [
"public",
"function",
"canProceed",
"(",
"Tool",
"$",
"tool",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"helper",
"->",
"isFileAlreadyExist",
"(",
"$",
"tool",
"->",
"getFilename",
"(",
")",
",",
"$",
"tool",
"->",
"getUrl",
"(",
")",
"... | @param Tool $tool
@return bool | [
"@param",
"Tool",
"$tool"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Decision/FileAlreadyExistDecision.php#L17-L24 |
tommy-muehle/tooly-composer-script | src/Script/Decision/IsVerifiedDecision.php | IsVerifiedDecision.canProceed | public function canProceed(Tool $tool)
{
if (null === $tool->getSignUrl()) {
return true;
}
return $this->helper->isVerified($tool->getSignUrl(), $tool->getUrl());
} | php | public function canProceed(Tool $tool)
{
if (null === $tool->getSignUrl()) {
return true;
}
return $this->helper->isVerified($tool->getSignUrl(), $tool->getUrl());
} | [
"public",
"function",
"canProceed",
"(",
"Tool",
"$",
"tool",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"tool",
"->",
"getSignUrl",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"$",
"this",
"->",
"helper",
"->",
"isVerified",
"(",
"$",
... | @param Tool $tool
@return bool | [
"@param",
"Tool",
"$tool"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Decision/IsVerifiedDecision.php#L17-L24 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Downloader.php | Downloader.isAccessible | public function isAccessible($url)
{
$context = $this->getContext($url);
return is_resource(@fopen($url, 'r', null, $context));
} | php | public function isAccessible($url)
{
$context = $this->getContext($url);
return is_resource(@fopen($url, 'r', null, $context));
} | [
"public",
"function",
"isAccessible",
"(",
"$",
"url",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"getContext",
"(",
"$",
"url",
")",
";",
"return",
"is_resource",
"(",
"@",
"fopen",
"(",
"$",
"url",
",",
"'r'",
",",
"null",
",",
"$",
"conte... | @param string $url
@return bool | [
"@param",
"string",
"$url"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Downloader.php#L17-L22 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Downloader.php | Downloader.download | public function download($url)
{
$context = $this->getContext($url);
return file_get_contents($url, false, $context);
} | php | public function download($url)
{
$context = $this->getContext($url);
return file_get_contents($url, false, $context);
} | [
"public",
"function",
"download",
"(",
"$",
"url",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"getContext",
"(",
"$",
"url",
")",
";",
"return",
"file_get_contents",
"(",
"$",
"url",
",",
"false",
",",
"$",
"context",
")",
";",
"}"
] | @param string $url
@return string | [
"@param",
"string",
"$url"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Downloader.php#L29-L34 |
tommy-muehle/tooly-composer-script | src/Factory/ToolFactory.php | ToolFactory.createTool | public static function createTool($name, $directory, array $parameters)
{
$defaults = [
'url' => null,
'sign-url' => null,
'only-dev' => true,
'force-replace' => false,
'rename' => false,
];
$parameters = array_merge($defaults, $parameters);
$tool = new Tool(
$name,
self::getFilename($name, $directory),
$parameters['url'],
$parameters['sign-url']
);
if (true === $parameters['force-replace']) {
$tool->activateForceReplace();
}
if (false === $parameters['only-dev']) {
$tool->disableOnlyDev();
}
if (true === $parameters['rename']) {
$tool->setNameToToolKey();
}
return $tool;
} | php | public static function createTool($name, $directory, array $parameters)
{
$defaults = [
'url' => null,
'sign-url' => null,
'only-dev' => true,
'force-replace' => false,
'rename' => false,
];
$parameters = array_merge($defaults, $parameters);
$tool = new Tool(
$name,
self::getFilename($name, $directory),
$parameters['url'],
$parameters['sign-url']
);
if (true === $parameters['force-replace']) {
$tool->activateForceReplace();
}
if (false === $parameters['only-dev']) {
$tool->disableOnlyDev();
}
if (true === $parameters['rename']) {
$tool->setNameToToolKey();
}
return $tool;
} | [
"public",
"static",
"function",
"createTool",
"(",
"$",
"name",
",",
"$",
"directory",
",",
"array",
"$",
"parameters",
")",
"{",
"$",
"defaults",
"=",
"[",
"'url'",
"=>",
"null",
",",
"'sign-url'",
"=>",
"null",
",",
"'only-dev'",
"=>",
"true",
",",
"... | @param string $name
@param string $directory
@param array $parameters
@return Tool | [
"@param",
"string",
"$name",
"@param",
"string",
"$directory",
"@param",
"array",
"$parameters"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Factory/ToolFactory.php#L19-L51 |
tommy-muehle/tooly-composer-script | src/Factory/ToolFactory.php | ToolFactory.createTools | public static function createTools($directory, array $data)
{
$tools = [];
foreach ($data as $name => $parameters) {
$tools[$name] = self::createTool($name, $directory, $parameters);
}
return $tools;
} | php | public static function createTools($directory, array $data)
{
$tools = [];
foreach ($data as $name => $parameters) {
$tools[$name] = self::createTool($name, $directory, $parameters);
}
return $tools;
} | [
"public",
"static",
"function",
"createTools",
"(",
"$",
"directory",
",",
"array",
"$",
"data",
")",
"{",
"$",
"tools",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"name",
"=>",
"$",
"parameters",
")",
"{",
"$",
"tools",
"[",
"$",
... | @param string $directory
@param array $data
@return array | [
"@param",
"string",
"$directory",
"@param",
"array",
"$data"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Factory/ToolFactory.php#L59-L68 |
tommy-muehle/tooly-composer-script | src/Factory/ToolFactory.php | ToolFactory.getFilename | private static function getFilename($name, $directory)
{
$filename = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$filename .= str_replace('.phar', '', $name) . '.phar';
return $filename;
} | php | private static function getFilename($name, $directory)
{
$filename = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$filename .= str_replace('.phar', '', $name) . '.phar';
return $filename;
} | [
"private",
"static",
"function",
"getFilename",
"(",
"$",
"name",
",",
"$",
"directory",
")",
"{",
"$",
"filename",
"=",
"rtrim",
"(",
"$",
"directory",
",",
"DIRECTORY_SEPARATOR",
")",
".",
"DIRECTORY_SEPARATOR",
";",
"$",
"filename",
".=",
"str_replace",
"... | @param string $name
@param string $directory
@return string | [
"@param",
"string",
"$name",
"@param",
"string",
"$directory"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Factory/ToolFactory.php#L76-L82 |
tommy-muehle/tooly-composer-script | src/Script/Decision/DoReplaceDecision.php | DoReplaceDecision.canProceed | public function canProceed(Tool $tool)
{
if (false === $this->helper->getFilesystem()->isFileAlreadyExist($tool->getFilename())) {
return true;
}
$doReplace = $tool->forceReplace();
if (true === $this->configuration->isInteractiveMode()) {
$this->io->write('<comment>Checksums are not equal!</comment>');
$this->io->write(sprintf(
'<comment>Do you want to overwrite the existing file "%s"?</comment>',
$tool->getName()
));
$doReplace = $this->io->askConfirmation('<question>[yes] or [no]?</question>', false);
}
return $doReplace;
} | php | public function canProceed(Tool $tool)
{
if (false === $this->helper->getFilesystem()->isFileAlreadyExist($tool->getFilename())) {
return true;
}
$doReplace = $tool->forceReplace();
if (true === $this->configuration->isInteractiveMode()) {
$this->io->write('<comment>Checksums are not equal!</comment>');
$this->io->write(sprintf(
'<comment>Do you want to overwrite the existing file "%s"?</comment>',
$tool->getName()
));
$doReplace = $this->io->askConfirmation('<question>[yes] or [no]?</question>', false);
}
return $doReplace;
} | [
"public",
"function",
"canProceed",
"(",
"Tool",
"$",
"tool",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"helper",
"->",
"getFilesystem",
"(",
")",
"->",
"isFileAlreadyExist",
"(",
"$",
"tool",
"->",
"getFilename",
"(",
")",
")",
")",
"{",... | @param Tool $tool
@return bool | [
"@param",
"Tool",
"$tool"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Decision/DoReplaceDecision.php#L37-L56 |
tommy-muehle/tooly-composer-script | src/Script/Processor.php | Processor.cleanUp | public function cleanUp()
{
$composerBinDirectory = $this->configuration->getComposerBinDirectory();
if (false === is_dir($composerBinDirectory)) {
$this->helper->getFilesystem()->createDirectory($composerBinDirectory);
}
$this->removeFromDir($composerBinDirectory);
$this->removeFromDir(
$this->configuration->getBinDirectory(),
array_keys($this->configuration->getTools())
);
} | php | public function cleanUp()
{
$composerBinDirectory = $this->configuration->getComposerBinDirectory();
if (false === is_dir($composerBinDirectory)) {
$this->helper->getFilesystem()->createDirectory($composerBinDirectory);
}
$this->removeFromDir($composerBinDirectory);
$this->removeFromDir(
$this->configuration->getBinDirectory(),
array_keys($this->configuration->getTools())
);
} | [
"public",
"function",
"cleanUp",
"(",
")",
"{",
"$",
"composerBinDirectory",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getComposerBinDirectory",
"(",
")",
";",
"if",
"(",
"false",
"===",
"is_dir",
"(",
"$",
"composerBinDirectory",
")",
")",
"{",
"$",
... | Removes symlinks from composer's bin-dir and old phar's
from own bin-dir. | [
"Removes",
"symlinks",
"from",
"composer",
"s",
"bin",
"-",
"dir",
"and",
"old",
"phar",
"s",
"from",
"own",
"bin",
"-",
"dir",
"."
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Processor.php#L51-L64 |
tommy-muehle/tooly-composer-script | src/Script/Processor.php | Processor.getDecisions | private function getDecisions()
{
return [
new OnlyDevDecision($this->configuration, $this->helper),
new IsAccessibleDecision($this->configuration, $this->helper),
new FileAlreadyExistDecision($this->configuration, $this->helper),
new IsVerifiedDecision($this->configuration, $this->helper),
new DoReplaceDecision($this->configuration, $this->helper, $this->io),
];
} | php | private function getDecisions()
{
return [
new OnlyDevDecision($this->configuration, $this->helper),
new IsAccessibleDecision($this->configuration, $this->helper),
new FileAlreadyExistDecision($this->configuration, $this->helper),
new IsVerifiedDecision($this->configuration, $this->helper),
new DoReplaceDecision($this->configuration, $this->helper, $this->io),
];
} | [
"private",
"function",
"getDecisions",
"(",
")",
"{",
"return",
"[",
"new",
"OnlyDevDecision",
"(",
"$",
"this",
"->",
"configuration",
",",
"$",
"this",
"->",
"helper",
")",
",",
"new",
"IsAccessibleDecision",
"(",
"$",
"this",
"->",
"configuration",
",",
... | Each decision can interrupt the download of a tool.
@return array | [
"Each",
"decision",
"can",
"interrupt",
"the",
"download",
"of",
"a",
"tool",
"."
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Processor.php#L122-L131 |
tommy-muehle/tooly-composer-script | src/Script/Helper.php | Helper.isFileAlreadyExist | public function isFileAlreadyExist($filename, $targetFile)
{
$alreadyExist = $this->filesystem->isFileAlreadyExist($filename);
$verification = $this->verifier->checkFileSum($filename, $targetFile);
if (true === $alreadyExist && true === $verification) {
return true;
}
return false;
} | php | public function isFileAlreadyExist($filename, $targetFile)
{
$alreadyExist = $this->filesystem->isFileAlreadyExist($filename);
$verification = $this->verifier->checkFileSum($filename, $targetFile);
if (true === $alreadyExist && true === $verification) {
return true;
}
return false;
} | [
"public",
"function",
"isFileAlreadyExist",
"(",
"$",
"filename",
",",
"$",
"targetFile",
")",
"{",
"$",
"alreadyExist",
"=",
"$",
"this",
"->",
"filesystem",
"->",
"isFileAlreadyExist",
"(",
"$",
"filename",
")",
";",
"$",
"verification",
"=",
"$",
"this",
... | @param string $filename
@param string $targetFile
@return bool | [
"@param",
"string",
"$filename",
"@param",
"string",
"$targetFile"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper.php#L47-L57 |
tommy-muehle/tooly-composer-script | src/Script/Helper.php | Helper.isVerified | public function isVerified($signatureUrl, $fileUrl)
{
$data = $this->downloader->download($fileUrl);
$signatureData = $this->downloader->download($signatureUrl);
$tmpFile = rtrim(sys_get_temp_dir(), '/') . '/_tool';
$this->filesystem->createFile($tmpFile, $data);
$tmpSignFile = rtrim(sys_get_temp_dir(), '/') . '/_tool.sign';
$this->filesystem->createFile($tmpSignFile, $signatureData);
$result = $this->verifier->checkGPGSignature($tmpSignFile, $tmpFile);
unlink($tmpFile);
unlink($tmpSignFile);
return $result;
} | php | public function isVerified($signatureUrl, $fileUrl)
{
$data = $this->downloader->download($fileUrl);
$signatureData = $this->downloader->download($signatureUrl);
$tmpFile = rtrim(sys_get_temp_dir(), '/') . '/_tool';
$this->filesystem->createFile($tmpFile, $data);
$tmpSignFile = rtrim(sys_get_temp_dir(), '/') . '/_tool.sign';
$this->filesystem->createFile($tmpSignFile, $signatureData);
$result = $this->verifier->checkGPGSignature($tmpSignFile, $tmpFile);
unlink($tmpFile);
unlink($tmpSignFile);
return $result;
} | [
"public",
"function",
"isVerified",
"(",
"$",
"signatureUrl",
",",
"$",
"fileUrl",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"downloader",
"->",
"download",
"(",
"$",
"fileUrl",
")",
";",
"$",
"signatureData",
"=",
"$",
"this",
"->",
"downloader",
... | @param string $signatureUrl
@param string $fileUrl
@return bool | [
"@param",
"string",
"$signatureUrl",
"@param",
"string",
"$fileUrl"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper.php#L65-L82 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Verifier.php | Verifier.checkFileSum | public function checkFileSum($targetFilename, $filename)
{
if (!file_exists($targetFilename)) {
return false;
}
return sha1_file($targetFilename) === sha1_file($filename);
} | php | public function checkFileSum($targetFilename, $filename)
{
if (!file_exists($targetFilename)) {
return false;
}
return sha1_file($targetFilename) === sha1_file($filename);
} | [
"public",
"function",
"checkFileSum",
"(",
"$",
"targetFilename",
",",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"targetFilename",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"sha1_file",
"(",
"$",
"targetFilename",
")",... | @param string $targetFilename
@param string $filename
@return bool | [
"@param",
"string",
"$targetFilename",
"@param",
"string",
"$filename"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Verifier.php#L32-L39 |
tommy-muehle/tooly-composer-script | src/Script/Helper/Verifier.php | Verifier.checkGPGSignature | public function checkGPGSignature($signatureFile, $file)
{
if (!$this->gpgVerifier instanceof GPGVerifier) {
return true;
}
try {
$this->gpgVerifier->verify($signatureFile, $file);
return true;
} catch (VerificationException $exception) {
return false;
}
} | php | public function checkGPGSignature($signatureFile, $file)
{
if (!$this->gpgVerifier instanceof GPGVerifier) {
return true;
}
try {
$this->gpgVerifier->verify($signatureFile, $file);
return true;
} catch (VerificationException $exception) {
return false;
}
} | [
"public",
"function",
"checkGPGSignature",
"(",
"$",
"signatureFile",
",",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"gpgVerifier",
"instanceof",
"GPGVerifier",
")",
"{",
"return",
"true",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"gpgVeri... | @param string $signatureFile
@param string $file
@return bool | [
"@param",
"string",
"$signatureFile",
"@param",
"string",
"$file"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Helper/Verifier.php#L47-L59 |
tommy-muehle/tooly-composer-script | src/Script/Decision/OnlyDevDecision.php | OnlyDevDecision.canProceed | public function canProceed(Tool $tool)
{
if (false === $this->configuration->isDevMode() && true === $tool->isOnlyDev()) {
return false;
}
return true;
} | php | public function canProceed(Tool $tool)
{
if (false === $this->configuration->isDevMode() && true === $tool->isOnlyDev()) {
return false;
}
return true;
} | [
"public",
"function",
"canProceed",
"(",
"Tool",
"$",
"tool",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"configuration",
"->",
"isDevMode",
"(",
")",
"&&",
"true",
"===",
"$",
"tool",
"->",
"isOnlyDev",
"(",
")",
")",
"{",
"return",
"fa... | @param Tool $tool
@return bool | [
"@param",
"Tool",
"$tool"
] | train | https://github.com/tommy-muehle/tooly-composer-script/blob/efd6809a616b41f43d3f68e2b4bf314a8f1f2db8/src/Script/Decision/OnlyDevDecision.php#L17-L24 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.__isset | public function __isset($name)
{
switch ($name) {
case 'key':
return !empty($this->secretKey);
case 'curl':
return !empty($this->internalCurl);
default:
return false;
}
} | php | public function __isset($name)
{
switch ($name) {
case 'key':
return !empty($this->secretKey);
case 'curl':
return !empty($this->internalCurl);
default:
return false;
}
} | [
"public",
"function",
"__isset",
"(",
"$",
"name",
")",
"{",
"switch",
"(",
"$",
"name",
")",
"{",
"case",
"'key'",
":",
"return",
"!",
"empty",
"(",
"$",
"this",
"->",
"secretKey",
")",
";",
"case",
"'curl'",
":",
"return",
"!",
"empty",
"(",
"$",... | Checker.
@param string $name The property name.
@return bool Property set or not.
@throws Exception Throw on unexpected property check. | [
"Checker",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L215-L226 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.checkNotificationSignature | public function checkNotificationSignature($signature, array $notificationBody, $merchantSecret)
{
// Preset required fields.
$notificationBody = array_replace_recursive(
[
'bill' => [
'billId' => null,
'amount' => [
'value' => null,
'currency' => null,
],
'siteId' => null,
'status' => ['value' => null],
],
],
$notificationBody
);
$processedNotificationData = [
'billId' => (string) $notificationBody['bill']['billId'],
'amount.value' => $this->normalizeAmount($notificationBody['bill']['amount']['value']),
'amount.currency' => (string) $notificationBody['bill']['amount']['currency'],
'siteId' => (string) $notificationBody['bill']['siteId'],
'status' => (string) $notificationBody['bill']['status']['value'],
];
ksort($processedNotificationData);
$processedNotificationDataKeys = join(self::VALUE_SEPARATOR, $processedNotificationData);
$hash = hash_hmac(self::DEFAULT_ALGORITHM, $processedNotificationDataKeys, $merchantSecret);
return $hash === $signature;
} | php | public function checkNotificationSignature($signature, array $notificationBody, $merchantSecret)
{
// Preset required fields.
$notificationBody = array_replace_recursive(
[
'bill' => [
'billId' => null,
'amount' => [
'value' => null,
'currency' => null,
],
'siteId' => null,
'status' => ['value' => null],
],
],
$notificationBody
);
$processedNotificationData = [
'billId' => (string) $notificationBody['bill']['billId'],
'amount.value' => $this->normalizeAmount($notificationBody['bill']['amount']['value']),
'amount.currency' => (string) $notificationBody['bill']['amount']['currency'],
'siteId' => (string) $notificationBody['bill']['siteId'],
'status' => (string) $notificationBody['bill']['status']['value'],
];
ksort($processedNotificationData);
$processedNotificationDataKeys = join(self::VALUE_SEPARATOR, $processedNotificationData);
$hash = hash_hmac(self::DEFAULT_ALGORITHM, $processedNotificationDataKeys, $merchantSecret);
return $hash === $signature;
} | [
"public",
"function",
"checkNotificationSignature",
"(",
"$",
"signature",
",",
"array",
"$",
"notificationBody",
",",
"$",
"merchantSecret",
")",
"{",
"// Preset required fields.",
"$",
"notificationBody",
"=",
"array_replace_recursive",
"(",
"[",
"'bill'",
"=>",
"["... | Checks notification data signature.
@param string $signature The signature.
@param object|array $notificationBody The notification body.
@param string $merchantSecret The merchant key for validating signature.
@return bool Signature is valid or not. | [
"Checks",
"notification",
"data",
"signature",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L238-L269 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.getLifetimeByDay | public function getLifetimeByDay($days=45)
{
$dateTime = new DateTime();
return $this->normalizeDate($dateTime->modify('+'.max(1, $days).' days'));
} | php | public function getLifetimeByDay($days=45)
{
$dateTime = new DateTime();
return $this->normalizeDate($dateTime->modify('+'.max(1, $days).' days'));
} | [
"public",
"function",
"getLifetimeByDay",
"(",
"$",
"days",
"=",
"45",
")",
"{",
"$",
"dateTime",
"=",
"new",
"DateTime",
"(",
")",
";",
"return",
"$",
"this",
"->",
"normalizeDate",
"(",
"$",
"dateTime",
"->",
"modify",
"(",
"'+'",
".",
"max",
"(",
... | Generate lifetime in format.
@param int $days Days of lifetime.
@return string Lifetime in ISO8601.
@throws Exception | [
"Generate",
"lifetime",
"in",
"format",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L281-L286 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.getPayUrl | public function getPayUrl(array $bill, $successUrl)
{
// Preset required fields.
$bill = array_replace(
['payUrl' => null],
$bill
);
$payUrl = parse_url((string) $bill['payUrl']);
if (true === array_key_exists('query', $payUrl)) {
parse_str($payUrl['query'], $query);
$query['successUrl'] = $successUrl;
} else {
$query = ['successUrl' => $successUrl];
}
$payUrl['query'] = http_build_query($query, '', '&', PHP_QUERY_RFC3986);
return $this->buildUrl($payUrl);
} | php | public function getPayUrl(array $bill, $successUrl)
{
// Preset required fields.
$bill = array_replace(
['payUrl' => null],
$bill
);
$payUrl = parse_url((string) $bill['payUrl']);
if (true === array_key_exists('query', $payUrl)) {
parse_str($payUrl['query'], $query);
$query['successUrl'] = $successUrl;
} else {
$query = ['successUrl' => $successUrl];
}
$payUrl['query'] = http_build_query($query, '', '&', PHP_QUERY_RFC3986);
return $this->buildUrl($payUrl);
} | [
"public",
"function",
"getPayUrl",
"(",
"array",
"$",
"bill",
",",
"$",
"successUrl",
")",
"{",
"// Preset required fields.",
"$",
"bill",
"=",
"array_replace",
"(",
"[",
"'payUrl'",
"=>",
"null",
"]",
",",
"$",
"bill",
")",
";",
"$",
"payUrl",
"=",
"par... | Get pay URL witch success URL param.
@param array $bill The bill data:
+ payUrl {string} Payment URL.
@param string $successUrl The success URL.
@return string | [
"Get",
"pay",
"URL",
"witch",
"success",
"URL",
"param",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L340-L360 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.createPaymentForm | public function createPaymentForm(array $params)
{
$params = array_replace_recursive(
[
'billId' => null,
'publicKey' => null,
'amount' => null,
'successUrl' => null,
'customFields' => [],
],
$params
);
$params['amount'] = $this->normalizeAmount($params['amount']);
$params['customFields']['apiClient'] = CLIENT_NAME;
$params['customFields']['apiClientVersion'] = CLIENT_VERSION;
return self::CREATE_URI.'?'.http_build_query($params, '', '&', PHP_QUERY_RFC3986);
} | php | public function createPaymentForm(array $params)
{
$params = array_replace_recursive(
[
'billId' => null,
'publicKey' => null,
'amount' => null,
'successUrl' => null,
'customFields' => [],
],
$params
);
$params['amount'] = $this->normalizeAmount($params['amount']);
$params['customFields']['apiClient'] = CLIENT_NAME;
$params['customFields']['apiClientVersion'] = CLIENT_VERSION;
return self::CREATE_URI.'?'.http_build_query($params, '', '&', PHP_QUERY_RFC3986);
} | [
"public",
"function",
"createPaymentForm",
"(",
"array",
"$",
"params",
")",
"{",
"$",
"params",
"=",
"array_replace_recursive",
"(",
"[",
"'billId'",
"=>",
"null",
",",
"'publicKey'",
"=>",
"null",
",",
"'amount'",
"=>",
"null",
",",
"'successUrl'",
"=>",
"... | Creating checkout link.
@param array $params The parameters:
+ billId {string|number} - The bill identifier;
+ publicKey {string} - The publicKey;
+ amount {string|number} - The amount;
+ successUrl {string} - The success url.
@return string Return result | [
"Creating",
"checkout",
"link",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L374-L393 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.createBill | public function createBill($billId, array $params)
{
$params = array_replace_recursive(
[
'amount' => null,
'currency' => null,
'comment' => null,
'expirationDateTime' => null,
'phone' => null,
'email' => null,
'account' => null,
'successUrl' => null,
'customFields' => [
'apiClient' => CLIENT_NAME,
'apiClientVersion' => CLIENT_VERSION,
],
],
$params
);
$bill = $this->requestBuilder(
$billId,
self::PUT,
array_filter(
[
'amount' => array_filter(
[
'currency' => (string) $params['currency'],
'value' => $this->normalizeAmount($params['amount']),
]
),
'comment' => (string) $params['comment'],
'expirationDateTime' => (string) $params['expirationDateTime'],
'customer' => array_filter(
[
'phone' => (string) $params['phone'],
'email' => (string) $params['email'],
'account' => (string) $params['account'],
]
),
'customFields' => array_filter($params['customFields']),
]
)
);
if (false === empty($bill['payUrl']) && false === empty($params['successUrl'])) {
$bill['payUrl'] = $this->getPayUrl($bill, $params['successUrl']);
}
return $bill;
} | php | public function createBill($billId, array $params)
{
$params = array_replace_recursive(
[
'amount' => null,
'currency' => null,
'comment' => null,
'expirationDateTime' => null,
'phone' => null,
'email' => null,
'account' => null,
'successUrl' => null,
'customFields' => [
'apiClient' => CLIENT_NAME,
'apiClientVersion' => CLIENT_VERSION,
],
],
$params
);
$bill = $this->requestBuilder(
$billId,
self::PUT,
array_filter(
[
'amount' => array_filter(
[
'currency' => (string) $params['currency'],
'value' => $this->normalizeAmount($params['amount']),
]
),
'comment' => (string) $params['comment'],
'expirationDateTime' => (string) $params['expirationDateTime'],
'customer' => array_filter(
[
'phone' => (string) $params['phone'],
'email' => (string) $params['email'],
'account' => (string) $params['account'],
]
),
'customFields' => array_filter($params['customFields']),
]
)
);
if (false === empty($bill['payUrl']) && false === empty($params['successUrl'])) {
$bill['payUrl'] = $this->getPayUrl($bill, $params['successUrl']);
}
return $bill;
} | [
"public",
"function",
"createBill",
"(",
"$",
"billId",
",",
"array",
"$",
"params",
")",
"{",
"$",
"params",
"=",
"array_replace_recursive",
"(",
"[",
"'amount'",
"=>",
"null",
",",
"'currency'",
"=>",
"null",
",",
"'comment'",
"=>",
"null",
",",
"'expira... | Creating bill.
@param string|number $billId The bill identifier.
@param array $params The parameters:
+ amount {string|number} The amount;
+ currency {string} The currency;
+ comment {string} The bill comment;
+ expirationDateTime {string} The bill expiration datetime (ISOstring);
+ phone {string} The phone;
+ email {string} The email;
+ account {string} The account;
+ successUrl {string} The success url;
+ customFields {array} The bill custom fields.
@return array Return result.
@throws BillPaymentsException Throw on API return invalid response. | [
"Creating",
"bill",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L415-L465 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.refund | public function refund($billId, $refundId, $amount='0', $currency='RUB')
{
return $this->requestBuilder(
$billId.'/refunds/'.$refundId,
self::PUT,
[
'amount' => [
'currency' => (string) $currency,
'value' => $this->normalizeAmount($amount),
],
]
);
} | php | public function refund($billId, $refundId, $amount='0', $currency='RUB')
{
return $this->requestBuilder(
$billId.'/refunds/'.$refundId,
self::PUT,
[
'amount' => [
'currency' => (string) $currency,
'value' => $this->normalizeAmount($amount),
],
]
);
} | [
"public",
"function",
"refund",
"(",
"$",
"billId",
",",
"$",
"refundId",
",",
"$",
"amount",
"=",
"'0'",
",",
"$",
"currency",
"=",
"'RUB'",
")",
"{",
"return",
"$",
"this",
"->",
"requestBuilder",
"(",
"$",
"billId",
".",
"'/refunds/'",
".",
"$",
"... | Refund paid bill.
@param string|number $billId The bill identifier.
@param string|number $refundId The refund identifier.
@param string|number $amount The amount.
@param string $currency The currency.
@return array|bool Return result.
@throws BillPaymentsException Throw on API return invalid response. | [
"Refund",
"paid",
"bill",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L512-L525 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.requestBuilder | protected function requestBuilder($uri, $method=self::GET, array $body=[])
{
$this->internalCurl->reset();
foreach ($this->options as $option => $value) {
$this->internalCurl->setOpt($option, $value);
}
$url = self::BILLS_URI.$uri;
$this->internalCurl->setHeader('Accept', 'application/json');
$this->internalCurl->setHeader('Authorization', 'Bearer '.$this->secretKey);
switch ($method) {
case self::GET:
$this->internalCurl->get($url);
break;
case self::POST:
$this->internalCurl->setHeader('Content-Type', 'application/json;charset=UTF-8');
$this->internalCurl->post($url, json_encode($body, JSON_UNESCAPED_UNICODE));
break;
case self::PUT:
$this->internalCurl->setHeader('Content-Type', 'application/json;charset=UTF-8');
$this->internalCurl->put($url, json_encode($body, JSON_UNESCAPED_UNICODE), true);
break;
default:
throw new Exception('Not supported method '.$method.'.');
}
if (true === $this->internalCurl->error) {
throw new BillPaymentsException(clone $this->internalCurl);
}
if (false === empty($this->internalCurl->response)) {
return @json_decode($this->internalCurl->response, true);
}
return true;
} | php | protected function requestBuilder($uri, $method=self::GET, array $body=[])
{
$this->internalCurl->reset();
foreach ($this->options as $option => $value) {
$this->internalCurl->setOpt($option, $value);
}
$url = self::BILLS_URI.$uri;
$this->internalCurl->setHeader('Accept', 'application/json');
$this->internalCurl->setHeader('Authorization', 'Bearer '.$this->secretKey);
switch ($method) {
case self::GET:
$this->internalCurl->get($url);
break;
case self::POST:
$this->internalCurl->setHeader('Content-Type', 'application/json;charset=UTF-8');
$this->internalCurl->post($url, json_encode($body, JSON_UNESCAPED_UNICODE));
break;
case self::PUT:
$this->internalCurl->setHeader('Content-Type', 'application/json;charset=UTF-8');
$this->internalCurl->put($url, json_encode($body, JSON_UNESCAPED_UNICODE), true);
break;
default:
throw new Exception('Not supported method '.$method.'.');
}
if (true === $this->internalCurl->error) {
throw new BillPaymentsException(clone $this->internalCurl);
}
if (false === empty($this->internalCurl->response)) {
return @json_decode($this->internalCurl->response, true);
}
return true;
} | [
"protected",
"function",
"requestBuilder",
"(",
"$",
"uri",
",",
"$",
"method",
"=",
"self",
"::",
"GET",
",",
"array",
"$",
"body",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"internalCurl",
"->",
"reset",
"(",
")",
";",
"foreach",
"(",
"$",
"thi... | Build request.
@param string $uri The url.
@param string $method The method.
@param array $body The body.
@return bool|array Return response.
@throws Exception Throw on unsupported $method use.
@throws BillPaymentsException Throw on API return invalid response. | [
"Build",
"request",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L557-L593 |
QIWI-API/bill-payments-php-sdk | src/BillPayments.php | BillPayments.buildUrl | protected function buildUrl(array $parsedUrl)
{
if (true === isset($parsedUrl['scheme'])) {
$scheme = $parsedUrl['scheme'].'://';
} else {
$scheme = '';
}
if (true === isset($parsedUrl['host'])) {
$host = $parsedUrl['host'];
} else {
$host = '';
}
if (true === isset($parsedUrl['port'])) {
$port = ':'.$parsedUrl['port'];
} else {
$port = '';
}
if (true === isset($parsedUrl['user'])) {
$user = (string) $parsedUrl['user'];
} else {
$user = '';
}
if (true === isset($parsedUrl['pass'])) {
$pass = ':'.$parsedUrl['pass'];
} else {
$pass = '';
}
if (false === empty($user) || false === empty($pass)) {
$host = '@'.$host;
}
if (true === isset($parsedUrl['path'])) {
$path = (string) $parsedUrl['path'];
} else {
$path = '';
}
if (true === isset($parsedUrl['query'])) {
$query = '?'.$parsedUrl['query'];
} else {
$query = '';
}
if (true === isset($parsedUrl['fragment'])) {
$fragment = '#'.$parsedUrl['fragment'];
} else {
$fragment = '';
}
return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
} | php | protected function buildUrl(array $parsedUrl)
{
if (true === isset($parsedUrl['scheme'])) {
$scheme = $parsedUrl['scheme'].'://';
} else {
$scheme = '';
}
if (true === isset($parsedUrl['host'])) {
$host = $parsedUrl['host'];
} else {
$host = '';
}
if (true === isset($parsedUrl['port'])) {
$port = ':'.$parsedUrl['port'];
} else {
$port = '';
}
if (true === isset($parsedUrl['user'])) {
$user = (string) $parsedUrl['user'];
} else {
$user = '';
}
if (true === isset($parsedUrl['pass'])) {
$pass = ':'.$parsedUrl['pass'];
} else {
$pass = '';
}
if (false === empty($user) || false === empty($pass)) {
$host = '@'.$host;
}
if (true === isset($parsedUrl['path'])) {
$path = (string) $parsedUrl['path'];
} else {
$path = '';
}
if (true === isset($parsedUrl['query'])) {
$query = '?'.$parsedUrl['query'];
} else {
$query = '';
}
if (true === isset($parsedUrl['fragment'])) {
$fragment = '#'.$parsedUrl['fragment'];
} else {
$fragment = '';
}
return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
} | [
"protected",
"function",
"buildUrl",
"(",
"array",
"$",
"parsedUrl",
")",
"{",
"if",
"(",
"true",
"===",
"isset",
"(",
"$",
"parsedUrl",
"[",
"'scheme'",
"]",
")",
")",
"{",
"$",
"scheme",
"=",
"$",
"parsedUrl",
"[",
"'scheme'",
"]",
".",
"'://'",
";... | Build URL.
@param array $parsedUrl The parsed URL.
@return string | [
"Build",
"URL",
"."
] | train | https://github.com/QIWI-API/bill-payments-php-sdk/blob/44a618ff202396872bc0b16c3835d5d55ed46b80/src/BillPayments.php#L603-L659 |
dancryer/php-docblock-checker | src/Command/CheckerCommand.php | CheckerCommand.configure | protected function configure()
{
$this
->setName('check')
->setDescription('Check PHP files within a directory for appropriate use of Docblocks.')
->addOption(
'exclude',
'x',
InputOption::VALUE_REQUIRED,
'Files and directories to exclude.'
)
->addOption(
'directory',
'd',
InputOption::VALUE_REQUIRED,
'Directory to scan.',
'./'
)
->addOption(
'skip-classes',
null,
InputOption::VALUE_NONE,
'Don\'t check classes for docblocks.'
)
->addOption(
'skip-methods',
null,
InputOption::VALUE_NONE,
'Don\'t check methods for docblocks.'
)
->addOption(
'skip-signatures',
null,
InputOption::VALUE_NONE,
'Don\'t check docblocks against method signatures.'
)
->addOption(
'only-signatures',
null,
InputOption::VALUE_NONE,
'Ignore missing docblocks where method doesn\'t have parameters or return type.'
)
->addOption(
'json',
'j',
InputOption::VALUE_NONE,
'Output JSON instead of a log.'
)
->addOption(
'files-per-line',
'l',
InputOption::VALUE_REQUIRED,
'Number of files per line in progress',
50
)
->addOption(
'fail-on-warnings',
'w',
InputOption::VALUE_NONE,
'Consider the check failed if any warnings are produced.'
)
->addOption(
'info-only',
'i',
InputOption::VALUE_NONE,
'Information-only mode, just show summary.'
)
->addOption(
'from-stdin',
null,
InputOption::VALUE_NONE,
'Use list of files from stdin (e.g. git diff)'
)
->addOption(
'cache-file',
null,
InputOption::VALUE_REQUIRED,
'Cache analysis of files based on filemtime.'
)
->addOption(
'config-file',
null,
InputOption::VALUE_REQUIRED,
'File to read doccheck config from in yml format'
);
} | php | protected function configure()
{
$this
->setName('check')
->setDescription('Check PHP files within a directory for appropriate use of Docblocks.')
->addOption(
'exclude',
'x',
InputOption::VALUE_REQUIRED,
'Files and directories to exclude.'
)
->addOption(
'directory',
'd',
InputOption::VALUE_REQUIRED,
'Directory to scan.',
'./'
)
->addOption(
'skip-classes',
null,
InputOption::VALUE_NONE,
'Don\'t check classes for docblocks.'
)
->addOption(
'skip-methods',
null,
InputOption::VALUE_NONE,
'Don\'t check methods for docblocks.'
)
->addOption(
'skip-signatures',
null,
InputOption::VALUE_NONE,
'Don\'t check docblocks against method signatures.'
)
->addOption(
'only-signatures',
null,
InputOption::VALUE_NONE,
'Ignore missing docblocks where method doesn\'t have parameters or return type.'
)
->addOption(
'json',
'j',
InputOption::VALUE_NONE,
'Output JSON instead of a log.'
)
->addOption(
'files-per-line',
'l',
InputOption::VALUE_REQUIRED,
'Number of files per line in progress',
50
)
->addOption(
'fail-on-warnings',
'w',
InputOption::VALUE_NONE,
'Consider the check failed if any warnings are produced.'
)
->addOption(
'info-only',
'i',
InputOption::VALUE_NONE,
'Information-only mode, just show summary.'
)
->addOption(
'from-stdin',
null,
InputOption::VALUE_NONE,
'Use list of files from stdin (e.g. git diff)'
)
->addOption(
'cache-file',
null,
InputOption::VALUE_REQUIRED,
'Cache analysis of files based on filemtime.'
)
->addOption(
'config-file',
null,
InputOption::VALUE_REQUIRED,
'File to read doccheck config from in yml format'
);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'check'",
")",
"->",
"setDescription",
"(",
"'Check PHP files within a directory for appropriate use of Docblocks.'",
")",
"->",
"addOption",
"(",
"'exclude'",
",",
"'x'",
",",
... | Configure the console command, add options, etc. | [
"Configure",
"the",
"console",
"command",
"add",
"options",
"etc",
"."
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/Command/CheckerCommand.php#L41-L126 |
dancryer/php-docblock-checker | src/Command/CheckerCommand.php | CheckerCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$startTime = microtime(true);
$config = (new ConfigProcessor(new ConfigParser($input, $this->getDefinition())))->processConfig();
// Get files to check:
$files = FileProviderFactory::getFileProvider($config)->getFileIterator();
// Check files:
$filesPerLine = $config->getFilesPerLine();
$totalFiles = iterator_count($files);
//$files = array_chunk($files, $filesPerLine);
$processed = 0;
$fileChecker = new FileChecker(
new FileInfoCacheProvider($config->getCacheFile()),
new FileParser(
(new ParserFactory())->create(ParserFactory::PREFER_PHP7),
new DocblockParser()
),
new Checker($config)
);
$statusCollection = new StatusCollection();
if ($config->isVerbose()) {
$output->writeln('');
$output->writeln('PHP Docblock Checker <fg=blue>by Dan Cryer (https://www.dancryer.com)</>');
$output->writeln('');
}
/** @var \SplFileInfo $file */
foreach ($files as $file) {
$processed++;
$status = $fileChecker->checkFile($file->getPathname());
$statusCollection->addFileStatus($status);
if ($config->isVerbose()) {
if ($status->hasErrors()) {
$output->write('<fg=red>F</>');
} elseif ($status->hasWarnings()) {
$output->write('<fg=yellow>W</>');
} else {
$output->write('<info>.</info>');
}
}
if ($processed % $config->getFilesPerLine() === 0 && $config->isVerbose()) {
$output->writeln(
sprintf(
'%s %s/%d (%d%%)',
str_pad('', $filesPerLine - $processed),
str_pad((string)$processed, strlen((string)$totalFiles), ' ', STR_PAD_LEFT),
$totalFiles,
floor((100 / $totalFiles) * $processed)
)
);
}
}
if ($config->isVerbose()) {
$time = round(microtime(true) - $startTime, 2);
$output->writeln('');
$output->writeln('');
$output->writeln('Checked ' . number_format($totalFiles) . ' files in ' . $time . ' seconds.');
$output->write('<info>' . number_format($statusCollection->getTotalPassed()) . ' Passed</info>');
$output->write(' / <fg=red>' . number_format($statusCollection->getTotalErrors()) . ' Errors</>');
$output->write(' / <fg=yellow>' . number_format($statusCollection->getTotalWarnings()) . ' Warnings</>');
$output->write(' / <fg=blue>' . number_format($statusCollection->getTotalInfos()) . ' Info</>');
$output->writeln('');
if ($statusCollection->hasErrors() && !$config->isInfoOnly()) {
$output->writeln('');
$output->writeln('');
foreach ($statusCollection->getErrors() as $warning) {
$output->writeln($warning->getDecoratedMessage());
}
}
if ($statusCollection->hasInfos() && !$config->isInfoOnly()) {
$output->writeln('');
$output->writeln('');
foreach ($statusCollection->getInfos() as $info) {
$output->writeln($info->getDecoratedMessage());
}
}
if ($statusCollection->hasWarnings() && !$config->isInfoOnly()) {
$output->writeln('');
$output->writeln('');
foreach ($statusCollection->getWarnings() as $warning) {
$output->writeln($warning->getDecoratedMessage());
}
}
$output->writeln('');
}
// Output JSON if requested:
if ($config->isJson()) {
print json_encode(array_merge($statusCollection->getErrors(), $statusCollection->getWarnings()));
}
return $statusCollection->hasErrors() ||
($config->isFailOnWarnings() && $statusCollection->hasWarnings()) ?
1 : 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$startTime = microtime(true);
$config = (new ConfigProcessor(new ConfigParser($input, $this->getDefinition())))->processConfig();
// Get files to check:
$files = FileProviderFactory::getFileProvider($config)->getFileIterator();
// Check files:
$filesPerLine = $config->getFilesPerLine();
$totalFiles = iterator_count($files);
//$files = array_chunk($files, $filesPerLine);
$processed = 0;
$fileChecker = new FileChecker(
new FileInfoCacheProvider($config->getCacheFile()),
new FileParser(
(new ParserFactory())->create(ParserFactory::PREFER_PHP7),
new DocblockParser()
),
new Checker($config)
);
$statusCollection = new StatusCollection();
if ($config->isVerbose()) {
$output->writeln('');
$output->writeln('PHP Docblock Checker <fg=blue>by Dan Cryer (https://www.dancryer.com)</>');
$output->writeln('');
}
/** @var \SplFileInfo $file */
foreach ($files as $file) {
$processed++;
$status = $fileChecker->checkFile($file->getPathname());
$statusCollection->addFileStatus($status);
if ($config->isVerbose()) {
if ($status->hasErrors()) {
$output->write('<fg=red>F</>');
} elseif ($status->hasWarnings()) {
$output->write('<fg=yellow>W</>');
} else {
$output->write('<info>.</info>');
}
}
if ($processed % $config->getFilesPerLine() === 0 && $config->isVerbose()) {
$output->writeln(
sprintf(
'%s %s/%d (%d%%)',
str_pad('', $filesPerLine - $processed),
str_pad((string)$processed, strlen((string)$totalFiles), ' ', STR_PAD_LEFT),
$totalFiles,
floor((100 / $totalFiles) * $processed)
)
);
}
}
if ($config->isVerbose()) {
$time = round(microtime(true) - $startTime, 2);
$output->writeln('');
$output->writeln('');
$output->writeln('Checked ' . number_format($totalFiles) . ' files in ' . $time . ' seconds.');
$output->write('<info>' . number_format($statusCollection->getTotalPassed()) . ' Passed</info>');
$output->write(' / <fg=red>' . number_format($statusCollection->getTotalErrors()) . ' Errors</>');
$output->write(' / <fg=yellow>' . number_format($statusCollection->getTotalWarnings()) . ' Warnings</>');
$output->write(' / <fg=blue>' . number_format($statusCollection->getTotalInfos()) . ' Info</>');
$output->writeln('');
if ($statusCollection->hasErrors() && !$config->isInfoOnly()) {
$output->writeln('');
$output->writeln('');
foreach ($statusCollection->getErrors() as $warning) {
$output->writeln($warning->getDecoratedMessage());
}
}
if ($statusCollection->hasInfos() && !$config->isInfoOnly()) {
$output->writeln('');
$output->writeln('');
foreach ($statusCollection->getInfos() as $info) {
$output->writeln($info->getDecoratedMessage());
}
}
if ($statusCollection->hasWarnings() && !$config->isInfoOnly()) {
$output->writeln('');
$output->writeln('');
foreach ($statusCollection->getWarnings() as $warning) {
$output->writeln($warning->getDecoratedMessage());
}
}
$output->writeln('');
}
// Output JSON if requested:
if ($config->isJson()) {
print json_encode(array_merge($statusCollection->getErrors(), $statusCollection->getWarnings()));
}
return $statusCollection->hasErrors() ||
($config->isFailOnWarnings() && $statusCollection->hasWarnings()) ?
1 : 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"startTime",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"config",
"=",
"(",
"new",
"ConfigProcessor",
"(",
"new",
"ConfigParser"... | Execute the actual docblock checker.
@param InputInterface $input
@param OutputInterface $output
@return int | [
"Execute",
"the",
"actual",
"docblock",
"checker",
"."
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/Command/CheckerCommand.php#L134-L245 |
dancryer/php-docblock-checker | src/DocblockParser/DocblockParser.php | DocblockParser.parseComment | public function parseComment($comment)
{
preg_match_all('/@([a-zA-Z]+) *(.*)\n/', $comment, $matches, PREG_SET_ORDER);
$tags = new TagCollection();
foreach ($matches as $match) {
array_shift($match);
list($tag, $body) = $match;
$tags->addTag($this->getTagEntity($tag, $body));
}
return $tags;
} | php | public function parseComment($comment)
{
preg_match_all('/@([a-zA-Z]+) *(.*)\n/', $comment, $matches, PREG_SET_ORDER);
$tags = new TagCollection();
foreach ($matches as $match) {
array_shift($match);
list($tag, $body) = $match;
$tags->addTag($this->getTagEntity($tag, $body));
}
return $tags;
} | [
"public",
"function",
"parseComment",
"(",
"$",
"comment",
")",
"{",
"preg_match_all",
"(",
"'/@([a-zA-Z]+) *(.*)\\n/'",
",",
"$",
"comment",
",",
"$",
"matches",
",",
"PREG_SET_ORDER",
")",
";",
"$",
"tags",
"=",
"new",
"TagCollection",
"(",
")",
";",
"fore... | Parse the comment into the component parts and set the state of the object.
@param string $comment The docblock
@return TagCollection | [
"Parse",
"the",
"comment",
"into",
"the",
"component",
"parts",
"and",
"set",
"the",
"state",
"of",
"the",
"object",
"."
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/DocblockParser/DocblockParser.php#L16-L29 |
dancryer/php-docblock-checker | src/FileProvider/FileExclusionFilter.php | FileExclusionFilter.accept | public function accept()
{
$file = $this->getInnerIterator()->current();
return !$this->isFileExcluded($this->baseDirectory, $file);
} | php | public function accept()
{
$file = $this->getInnerIterator()->current();
return !$this->isFileExcluded($this->baseDirectory, $file);
} | [
"public",
"function",
"accept",
"(",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"getInnerIterator",
"(",
")",
"->",
"current",
"(",
")",
";",
"return",
"!",
"$",
"this",
"->",
"isFileExcluded",
"(",
"$",
"this",
"->",
"baseDirectory",
",",
"$",
"... | Check whether the current element of the iterator is acceptable
@link https://php.net/manual/en/filteriterator.accept.php
@return bool true if the current element is acceptable, otherwise false.
@since 5.1.0 | [
"Check",
"whether",
"the",
"current",
"element",
"of",
"the",
"iterator",
"is",
"acceptable"
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/FileProvider/FileExclusionFilter.php#L34-L38 |
dancryer/php-docblock-checker | src/FileParser/FileParser.php | FileParser.processStatements | protected function processStatements($file, array $statements, $prefix = '')
{
$uses = [];
$methods = [];
$classes = [];
foreach ($statements as $statement) {
if ($statement instanceof Namespace_) {
return $this->processStatements($file, $statement->stmts, (string)$statement->name);
}
if ($statement instanceof Use_) {
foreach ($statement->uses as $use) {
// polyfill
$alias = $use->alias;
if (null === $alias && method_exists($use, 'getAlias')) {
$alias = $use->getAlias();
}
$uses[(string)$alias] = (string)$use->name;
}
}
if ($statement instanceof Class_) {
$class = $statement;
$fullClassName = $prefix . '\\' . $class->name;
$classes[$fullClassName] = [
'file' => $file,
'line' => $class->getAttribute('startLine'),
'name' => $fullClassName,
'docblock' => $this->getDocblock($class, $uses),
];
foreach ($statement->stmts as $method) {
if (!$method instanceof ClassMethod) {
continue;
}
$fullMethodName = $fullClassName . '::' . $method->name;
$type = $method->returnType;
if ($type instanceof NullableType) {
$type = $type->type->toString();
} elseif ($type instanceof NodeAbstract) {
$type = $type->toString();
}
if (isset($uses[$type])) {
$type = $uses[$type];
}
if ($type !== null) {
$type = strpos($type, '\\') === 0 ? substr($type, 1) : $type;
}
if ($method->returnType instanceof NullableType) {
$type = ['null', $type];
sort($type);
}
$thisMethod = [
'file' => $file,
'class' => $fullClassName,
'name' => $fullMethodName,
'line' => $method->getAttribute('startLine'),
'return' => $type,
'params' => [],
'docblock' => $this->getDocblock($method, $uses),
'has_return' => isset($method->stmts) ? $this->statementsContainReturn($method->stmts) : false,
];
/** @var Param $param */
foreach ($method->params as $param) {
$type = $param->type;
if ($type instanceof NullableType) {
$type = $type->type->toString();
} elseif ($type instanceof NodeAbstract) {
$type = $type->toString();
}
if (isset($uses[$type])) {
$type = $uses[$type];
}
if ($type !== null) {
$type = strpos($type, '\\') === 0 ? substr($type, 1) : $type;
}
if (property_exists($param, 'default') &&
$param->default instanceof Expr &&
property_exists($param->default, 'name') &&
property_exists($param->default->name, 'parts') &&
$type !== null &&
'null' === $param->default->name->parts[0]
) {
$type .= '|null';
}
$name = null;
// parser v3
if (property_exists($param, 'name')) {
$name = $param->name;
}
// parser v4
if (null === $name && property_exists($param, 'var') && property_exists($param->var, 'name')) {
$name = $param->var->name;
}
$thisMethod['params']['$' . $name] = $type;
}
$methods[$fullMethodName] = $thisMethod;
}
}
}
return ['methods' => $methods, 'classes' => $classes];
} | php | protected function processStatements($file, array $statements, $prefix = '')
{
$uses = [];
$methods = [];
$classes = [];
foreach ($statements as $statement) {
if ($statement instanceof Namespace_) {
return $this->processStatements($file, $statement->stmts, (string)$statement->name);
}
if ($statement instanceof Use_) {
foreach ($statement->uses as $use) {
// polyfill
$alias = $use->alias;
if (null === $alias && method_exists($use, 'getAlias')) {
$alias = $use->getAlias();
}
$uses[(string)$alias] = (string)$use->name;
}
}
if ($statement instanceof Class_) {
$class = $statement;
$fullClassName = $prefix . '\\' . $class->name;
$classes[$fullClassName] = [
'file' => $file,
'line' => $class->getAttribute('startLine'),
'name' => $fullClassName,
'docblock' => $this->getDocblock($class, $uses),
];
foreach ($statement->stmts as $method) {
if (!$method instanceof ClassMethod) {
continue;
}
$fullMethodName = $fullClassName . '::' . $method->name;
$type = $method->returnType;
if ($type instanceof NullableType) {
$type = $type->type->toString();
} elseif ($type instanceof NodeAbstract) {
$type = $type->toString();
}
if (isset($uses[$type])) {
$type = $uses[$type];
}
if ($type !== null) {
$type = strpos($type, '\\') === 0 ? substr($type, 1) : $type;
}
if ($method->returnType instanceof NullableType) {
$type = ['null', $type];
sort($type);
}
$thisMethod = [
'file' => $file,
'class' => $fullClassName,
'name' => $fullMethodName,
'line' => $method->getAttribute('startLine'),
'return' => $type,
'params' => [],
'docblock' => $this->getDocblock($method, $uses),
'has_return' => isset($method->stmts) ? $this->statementsContainReturn($method->stmts) : false,
];
/** @var Param $param */
foreach ($method->params as $param) {
$type = $param->type;
if ($type instanceof NullableType) {
$type = $type->type->toString();
} elseif ($type instanceof NodeAbstract) {
$type = $type->toString();
}
if (isset($uses[$type])) {
$type = $uses[$type];
}
if ($type !== null) {
$type = strpos($type, '\\') === 0 ? substr($type, 1) : $type;
}
if (property_exists($param, 'default') &&
$param->default instanceof Expr &&
property_exists($param->default, 'name') &&
property_exists($param->default->name, 'parts') &&
$type !== null &&
'null' === $param->default->name->parts[0]
) {
$type .= '|null';
}
$name = null;
// parser v3
if (property_exists($param, 'name')) {
$name = $param->name;
}
// parser v4
if (null === $name && property_exists($param, 'var') && property_exists($param->var, 'name')) {
$name = $param->var->name;
}
$thisMethod['params']['$' . $name] = $type;
}
$methods[$fullMethodName] = $thisMethod;
}
}
}
return ['methods' => $methods, 'classes' => $classes];
} | [
"protected",
"function",
"processStatements",
"(",
"$",
"file",
",",
"array",
"$",
"statements",
",",
"$",
"prefix",
"=",
"''",
")",
"{",
"$",
"uses",
"=",
"[",
"]",
";",
"$",
"methods",
"=",
"[",
"]",
";",
"$",
"classes",
"=",
"[",
"]",
";",
"fo... | Looks for class definitions, and then within them method definitions, docblocks, etc.
@param string $file
@param array $statements
@param string $prefix
@return mixed | [
"Looks",
"for",
"class",
"definitions",
"and",
"then",
"within",
"them",
"method",
"definitions",
"docblocks",
"etc",
"."
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/FileParser/FileParser.php#L78-L198 |
dancryer/php-docblock-checker | src/FileParser/FileParser.php | FileParser.statementsContainReturn | protected function statementsContainReturn(array $statements)
{
foreach ($statements as $statement) {
if ($statement instanceof Stmt\Return_) {
return true;
}
if (empty($statement->stmts)) {
continue;
}
if ($this->statementsContainReturn($statement->stmts)) {
return true;
}
}
return false;
} | php | protected function statementsContainReturn(array $statements)
{
foreach ($statements as $statement) {
if ($statement instanceof Stmt\Return_) {
return true;
}
if (empty($statement->stmts)) {
continue;
}
if ($this->statementsContainReturn($statement->stmts)) {
return true;
}
}
return false;
} | [
"protected",
"function",
"statementsContainReturn",
"(",
"array",
"$",
"statements",
")",
"{",
"foreach",
"(",
"$",
"statements",
"as",
"$",
"statement",
")",
"{",
"if",
"(",
"$",
"statement",
"instanceof",
"Stmt",
"\\",
"Return_",
")",
"{",
"return",
"true"... | Recursively search an array of statements for a return statement.
@param array $statements
@return bool | [
"Recursively",
"search",
"an",
"array",
"of",
"statements",
"for",
"a",
"return",
"statement",
"."
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/FileParser/FileParser.php#L205-L222 |
dancryer/php-docblock-checker | src/FileParser/FileParser.php | FileParser.getDocblock | protected function getDocblock(Stmt $stmt, array $uses = [])
{
$comments = $stmt->getAttribute('comments');
if (is_array($comments)) {
foreach ($comments as $comment) {
if ($comment instanceof Doc) {
return $this->processDocblock($comment->getText(), $uses);
}
}
}
return null;
} | php | protected function getDocblock(Stmt $stmt, array $uses = [])
{
$comments = $stmt->getAttribute('comments');
if (is_array($comments)) {
foreach ($comments as $comment) {
if ($comment instanceof Doc) {
return $this->processDocblock($comment->getText(), $uses);
}
}
}
return null;
} | [
"protected",
"function",
"getDocblock",
"(",
"Stmt",
"$",
"stmt",
",",
"array",
"$",
"uses",
"=",
"[",
"]",
")",
"{",
"$",
"comments",
"=",
"$",
"stmt",
"->",
"getAttribute",
"(",
"'comments'",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"comments",
"... | Find and parse a docblock for a given class or method.
@param Stmt $stmt
@param array $uses
@return array|null | [
"Find",
"and",
"parse",
"a",
"docblock",
"for",
"a",
"given",
"class",
"or",
"method",
"."
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/FileParser/FileParser.php#L230-L243 |
dancryer/php-docblock-checker | src/Config/ConfigParser.php | ConfigParser.parseOption | public function parseOption($optionName)
{
return $this->input->getOption($optionName) || isset($this->fileConfig['options'][$optionName]);
} | php | public function parseOption($optionName)
{
return $this->input->getOption($optionName) || isset($this->fileConfig['options'][$optionName]);
} | [
"public",
"function",
"parseOption",
"(",
"$",
"optionName",
")",
"{",
"return",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"$",
"optionName",
")",
"||",
"isset",
"(",
"$",
"this",
"->",
"fileConfig",
"[",
"'options'",
"]",
"[",
"$",
"optionName... | If the option is set in either the command line or config file, return true
@param string $optionName
@return bool | [
"If",
"the",
"option",
"is",
"set",
"in",
"either",
"the",
"command",
"line",
"or",
"config",
"file",
"return",
"true"
] | train | https://github.com/dancryer/php-docblock-checker/blob/687bb03a1cf6dd6d0115c018d97fa68e42203299/src/Config/ConfigParser.php#L55-L58 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.addComponent | public function addComponent(IComponent $component, $name, $insertBefore = NULL)
{
if ($name === NULL) {
$name = $component->getName();
}
if (is_int($name)) {
$name = (string) $name;
} elseif (!is_string($name)) {
throw new Nette\InvalidArgumentException(sprintf('Component name must be integer or string, %s given.', gettype($name)));
} elseif (!preg_match('#^[a-zA-Z0-9_]+\z#', $name)) {
throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");
}
if (isset($this->components[$name])) {
throw new Nette\InvalidStateException("Component with name '$name' already exists.");
}
// check circular reference
$obj = $this;
do {
if ($obj === $component) {
throw new Nette\InvalidStateException("Circular reference detected while adding component '$name'.");
}
$obj = $obj->getParent();
} while ($obj !== NULL);
// user checking
$this->validateChildComponent($component);
try {
if (isset($this->components[$insertBefore])) {
$tmp = [];
foreach ($this->components as $k => $v) {
if ($k === $insertBefore) {
$tmp[$name] = $component;
}
$tmp[$k] = $v;
}
$this->components = $tmp;
} else {
$this->components[$name] = $component;
}
$component->setParent($this, $name);
} catch (\Exception $e) {
unset($this->components[$name]); // undo
throw $e;
}
return $this;
} | php | public function addComponent(IComponent $component, $name, $insertBefore = NULL)
{
if ($name === NULL) {
$name = $component->getName();
}
if (is_int($name)) {
$name = (string) $name;
} elseif (!is_string($name)) {
throw new Nette\InvalidArgumentException(sprintf('Component name must be integer or string, %s given.', gettype($name)));
} elseif (!preg_match('#^[a-zA-Z0-9_]+\z#', $name)) {
throw new Nette\InvalidArgumentException("Component name must be non-empty alphanumeric string, '$name' given.");
}
if (isset($this->components[$name])) {
throw new Nette\InvalidStateException("Component with name '$name' already exists.");
}
// check circular reference
$obj = $this;
do {
if ($obj === $component) {
throw new Nette\InvalidStateException("Circular reference detected while adding component '$name'.");
}
$obj = $obj->getParent();
} while ($obj !== NULL);
// user checking
$this->validateChildComponent($component);
try {
if (isset($this->components[$insertBefore])) {
$tmp = [];
foreach ($this->components as $k => $v) {
if ($k === $insertBefore) {
$tmp[$name] = $component;
}
$tmp[$k] = $v;
}
$this->components = $tmp;
} else {
$this->components[$name] = $component;
}
$component->setParent($this, $name);
} catch (\Exception $e) {
unset($this->components[$name]); // undo
throw $e;
}
return $this;
} | [
"public",
"function",
"addComponent",
"(",
"IComponent",
"$",
"component",
",",
"$",
"name",
",",
"$",
"insertBefore",
"=",
"NULL",
")",
"{",
"if",
"(",
"$",
"name",
"===",
"NULL",
")",
"{",
"$",
"name",
"=",
"$",
"component",
"->",
"getName",
"(",
"... | Adds the specified component to the IContainer.
@param IComponent
@param string
@param string
@return self
@throws Nette\InvalidStateException | [
"Adds",
"the",
"specified",
"component",
"to",
"the",
"IContainer",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L59-L111 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.removeComponent | public function removeComponent(IComponent $component)
{
$name = $component->getName();
if (!isset($this->components[$name]) || $this->components[$name] !== $component) {
throw new Nette\InvalidArgumentException("Component named '$name' is not located in this container.");
}
unset($this->components[$name]);
$component->setParent(NULL);
} | php | public function removeComponent(IComponent $component)
{
$name = $component->getName();
if (!isset($this->components[$name]) || $this->components[$name] !== $component) {
throw new Nette\InvalidArgumentException("Component named '$name' is not located in this container.");
}
unset($this->components[$name]);
$component->setParent(NULL);
} | [
"public",
"function",
"removeComponent",
"(",
"IComponent",
"$",
"component",
")",
"{",
"$",
"name",
"=",
"$",
"component",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"components",
"[",
"$",
"name",
"]",
")",
"||... | Removes a component from the IContainer.
@return void | [
"Removes",
"a",
"component",
"from",
"the",
"IContainer",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L118-L127 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.getComponent | public function getComponent($name, $need = TRUE)
{
if (isset($this->components[$name])) {
return $this->components[$name];
}
if (is_int($name)) {
$name = (string) $name;
} elseif (!is_string($name)) {
throw new Nette\InvalidArgumentException(sprintf('Component name must be integer or string, %s given.', gettype($name)));
} else {
$a = strpos($name, self::NAME_SEPARATOR);
if ($a !== FALSE) {
$ext = (string) substr($name, $a + 1);
$name = substr($name, 0, $a);
}
if ($name === '') {
if ($need) {
throw new Nette\InvalidArgumentException('Component or subcomponent name must not be empty string.');
}
return;
}
}
if (!isset($this->components[$name])) {
$component = $this->createComponent($name);
if ($component) {
if (!$component instanceof IComponent) {
throw new Nette\UnexpectedValueException('Method createComponent() did not return Nette\ComponentModel\IComponent.');
} elseif (!isset($this->components[$name])) {
$this->addComponent($component, $name);
}
}
}
if (isset($this->components[$name])) {
if (!isset($ext)) {
return $this->components[$name];
} elseif ($this->components[$name] instanceof IContainer) {
return $this->components[$name]->getComponent($ext, $need);
} elseif ($need) {
throw new Nette\InvalidArgumentException("Component with name '$name' is not container and cannot have '$ext' component.");
}
} elseif ($need) {
$hint = Nette\Utils\ObjectMixin::getSuggestion(array_merge(
array_keys($this->components),
array_map('lcfirst', preg_filter('#^createComponent([A-Z0-9].*)#', '$1', get_class_methods($this)))
), $name);
throw new Nette\InvalidArgumentException("Component with name '$name' does not exist" . ($hint ? ", did you mean '$hint'?" : '.'));
}
} | php | public function getComponent($name, $need = TRUE)
{
if (isset($this->components[$name])) {
return $this->components[$name];
}
if (is_int($name)) {
$name = (string) $name;
} elseif (!is_string($name)) {
throw new Nette\InvalidArgumentException(sprintf('Component name must be integer or string, %s given.', gettype($name)));
} else {
$a = strpos($name, self::NAME_SEPARATOR);
if ($a !== FALSE) {
$ext = (string) substr($name, $a + 1);
$name = substr($name, 0, $a);
}
if ($name === '') {
if ($need) {
throw new Nette\InvalidArgumentException('Component or subcomponent name must not be empty string.');
}
return;
}
}
if (!isset($this->components[$name])) {
$component = $this->createComponent($name);
if ($component) {
if (!$component instanceof IComponent) {
throw new Nette\UnexpectedValueException('Method createComponent() did not return Nette\ComponentModel\IComponent.');
} elseif (!isset($this->components[$name])) {
$this->addComponent($component, $name);
}
}
}
if (isset($this->components[$name])) {
if (!isset($ext)) {
return $this->components[$name];
} elseif ($this->components[$name] instanceof IContainer) {
return $this->components[$name]->getComponent($ext, $need);
} elseif ($need) {
throw new Nette\InvalidArgumentException("Component with name '$name' is not container and cannot have '$ext' component.");
}
} elseif ($need) {
$hint = Nette\Utils\ObjectMixin::getSuggestion(array_merge(
array_keys($this->components),
array_map('lcfirst', preg_filter('#^createComponent([A-Z0-9].*)#', '$1', get_class_methods($this)))
), $name);
throw new Nette\InvalidArgumentException("Component with name '$name' does not exist" . ($hint ? ", did you mean '$hint'?" : '.'));
}
} | [
"public",
"function",
"getComponent",
"(",
"$",
"name",
",",
"$",
"need",
"=",
"TRUE",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"components",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"components",
"[",
"$",
... | Returns component specified by name or path.
@param string
@param bool throw exception if component doesn't exist?
@return IComponent|NULL | [
"Returns",
"component",
"specified",
"by",
"name",
"or",
"path",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L136-L193 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.createComponent | protected function createComponent($name)
{
$ucname = ucfirst($name);
$method = 'createComponent' . $ucname;
if ($ucname !== $name && method_exists($this, $method) && (new \ReflectionMethod($this, $method))->getName() === $method) {
$component = $this->$method($name);
if (!$component instanceof IComponent && !isset($this->components[$name])) {
$class = get_class($this);
throw new Nette\UnexpectedValueException("Method $class::$method() did not return or create the desired component.");
}
return $component;
}
} | php | protected function createComponent($name)
{
$ucname = ucfirst($name);
$method = 'createComponent' . $ucname;
if ($ucname !== $name && method_exists($this, $method) && (new \ReflectionMethod($this, $method))->getName() === $method) {
$component = $this->$method($name);
if (!$component instanceof IComponent && !isset($this->components[$name])) {
$class = get_class($this);
throw new Nette\UnexpectedValueException("Method $class::$method() did not return or create the desired component.");
}
return $component;
}
} | [
"protected",
"function",
"createComponent",
"(",
"$",
"name",
")",
"{",
"$",
"ucname",
"=",
"ucfirst",
"(",
"$",
"name",
")",
";",
"$",
"method",
"=",
"'createComponent'",
".",
"$",
"ucname",
";",
"if",
"(",
"$",
"ucname",
"!==",
"$",
"name",
"&&",
"... | Component factory. Delegates the creation of components to a createComponent<Name> method.
@param string component name
@return IComponent the created component (optionally) | [
"Component",
"factory",
".",
"Delegates",
"the",
"creation",
"of",
"components",
"to",
"a",
"createComponent<Name",
">",
"method",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L201-L213 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.getComponents | public function getComponents($deep = FALSE, $filterType = NULL)
{
$iterator = new RecursiveComponentIterator($this->components);
if ($deep) {
$deep = $deep > 0 ? \RecursiveIteratorIterator::SELF_FIRST : \RecursiveIteratorIterator::CHILD_FIRST;
$iterator = new \RecursiveIteratorIterator($iterator, $deep);
}
if ($filterType) {
$iterator = new \CallbackFilterIterator($iterator, function ($item) use ($filterType) {
return $item instanceof $filterType;
});
}
return $iterator;
} | php | public function getComponents($deep = FALSE, $filterType = NULL)
{
$iterator = new RecursiveComponentIterator($this->components);
if ($deep) {
$deep = $deep > 0 ? \RecursiveIteratorIterator::SELF_FIRST : \RecursiveIteratorIterator::CHILD_FIRST;
$iterator = new \RecursiveIteratorIterator($iterator, $deep);
}
if ($filterType) {
$iterator = new \CallbackFilterIterator($iterator, function ($item) use ($filterType) {
return $item instanceof $filterType;
});
}
return $iterator;
} | [
"public",
"function",
"getComponents",
"(",
"$",
"deep",
"=",
"FALSE",
",",
"$",
"filterType",
"=",
"NULL",
")",
"{",
"$",
"iterator",
"=",
"new",
"RecursiveComponentIterator",
"(",
"$",
"this",
"->",
"components",
")",
";",
"if",
"(",
"$",
"deep",
")",
... | Iterates over components.
@param bool recursive?
@param string class types filter
@return \ArrayIterator | [
"Iterates",
"over",
"components",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L222-L235 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.attached | protected function attached($presenter)
{
if ($presenter instanceof Presenter) {
$this->loadState($presenter->popGlobalParameters($this->getUniqueId()));
$this->onAnchor($this);
}
} | php | protected function attached($presenter)
{
if ($presenter instanceof Presenter) {
$this->loadState($presenter->popGlobalParameters($this->getUniqueId()));
$this->onAnchor($this);
}
} | [
"protected",
"function",
"attached",
"(",
"$",
"presenter",
")",
"{",
"if",
"(",
"$",
"presenter",
"instanceof",
"Presenter",
")",
"{",
"$",
"this",
"->",
"loadState",
"(",
"$",
"presenter",
"->",
"popGlobalParameters",
"(",
"$",
"this",
"->",
"getUniqueId",... | This method will be called when the component (or component's parent)
becomes attached to a monitored object. Do not call this method yourself.
@param Nette\ComponentModel\IComponent
@return void | [
"This",
"method",
"will",
"be",
"called",
"when",
"the",
"component",
"(",
"or",
"component",
"s",
"parent",
")",
"becomes",
"attached",
"to",
"a",
"monitored",
"object",
".",
"Do",
"not",
"call",
"this",
"method",
"yourself",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L317-L323 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.loadState | public function loadState(array $params)
{
$reflection = $this->getReflection();
foreach ($reflection->getPersistentParams() as $name => $meta) {
if (isset($params[$name])) { // NULLs are ignored
$type = gettype($meta['def']);
if (!$reflection->convertType($params[$name], $type)) {
throw new Nette\Application\BadRequestException(sprintf(
"Value passed to persistent parameter '%s' in %s must be %s, %s given.",
$name,
$this instanceof Presenter ? 'presenter ' . $this->getName() : "component '{$this->getUniqueId()}'",
$type === 'NULL' ? 'scalar' : $type,
is_object($params[$name]) ? get_class($params[$name]) : gettype($params[$name])
));
}
$this->$name = $params[$name];
} else {
$params[$name] = $this->$name;
}
}
$this->params = $params;
} | php | public function loadState(array $params)
{
$reflection = $this->getReflection();
foreach ($reflection->getPersistentParams() as $name => $meta) {
if (isset($params[$name])) { // NULLs are ignored
$type = gettype($meta['def']);
if (!$reflection->convertType($params[$name], $type)) {
throw new Nette\Application\BadRequestException(sprintf(
"Value passed to persistent parameter '%s' in %s must be %s, %s given.",
$name,
$this instanceof Presenter ? 'presenter ' . $this->getName() : "component '{$this->getUniqueId()}'",
$type === 'NULL' ? 'scalar' : $type,
is_object($params[$name]) ? get_class($params[$name]) : gettype($params[$name])
));
}
$this->$name = $params[$name];
} else {
$params[$name] = $this->$name;
}
}
$this->params = $params;
} | [
"public",
"function",
"loadState",
"(",
"array",
"$",
"params",
")",
"{",
"$",
"reflection",
"=",
"$",
"this",
"->",
"getReflection",
"(",
")",
";",
"foreach",
"(",
"$",
"reflection",
"->",
"getPersistentParams",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
... | Loads state informations.
@param array
@return void | [
"Loads",
"state",
"informations",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L384-L405 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.saveState | public function saveState(array & $params, $reflection = NULL)
{
$reflection = $reflection === NULL ? $this->getReflection() : $reflection;
foreach ($reflection->getPersistentParams() as $name => $meta) {
if (isset($params[$name])) {
// injected value
} elseif (array_key_exists($name, $params)) { // NULLs are skipped
continue;
} elseif ((!isset($meta['since']) || $this instanceof $meta['since']) && isset($this->$name)) {
$params[$name] = $this->$name; // object property value
} else {
continue; // ignored parameter
}
$type = gettype($meta['def']);
if (!ComponentReflection::convertType($params[$name], $type)) {
throw new InvalidLinkException(sprintf(
"Value passed to persistent parameter '%s' in %s must be %s, %s given.",
$name,
$this instanceof Presenter ? 'presenter ' . $this->getName() : "component '{$this->getUniqueId()}'",
$type === 'NULL' ? 'scalar' : $type,
is_object($params[$name]) ? get_class($params[$name]) : gettype($params[$name])
));
}
if ($params[$name] === $meta['def'] || ($meta['def'] === NULL && $params[$name] === '')) {
$params[$name] = NULL; // value transmit is unnecessary
}
}
} | php | public function saveState(array & $params, $reflection = NULL)
{
$reflection = $reflection === NULL ? $this->getReflection() : $reflection;
foreach ($reflection->getPersistentParams() as $name => $meta) {
if (isset($params[$name])) {
// injected value
} elseif (array_key_exists($name, $params)) { // NULLs are skipped
continue;
} elseif ((!isset($meta['since']) || $this instanceof $meta['since']) && isset($this->$name)) {
$params[$name] = $this->$name; // object property value
} else {
continue; // ignored parameter
}
$type = gettype($meta['def']);
if (!ComponentReflection::convertType($params[$name], $type)) {
throw new InvalidLinkException(sprintf(
"Value passed to persistent parameter '%s' in %s must be %s, %s given.",
$name,
$this instanceof Presenter ? 'presenter ' . $this->getName() : "component '{$this->getUniqueId()}'",
$type === 'NULL' ? 'scalar' : $type,
is_object($params[$name]) ? get_class($params[$name]) : gettype($params[$name])
));
}
if ($params[$name] === $meta['def'] || ($meta['def'] === NULL && $params[$name] === '')) {
$params[$name] = NULL; // value transmit is unnecessary
}
}
} | [
"public",
"function",
"saveState",
"(",
"array",
"&",
"$",
"params",
",",
"$",
"reflection",
"=",
"NULL",
")",
"{",
"$",
"reflection",
"=",
"$",
"reflection",
"===",
"NULL",
"?",
"$",
"this",
"->",
"getReflection",
"(",
")",
":",
"$",
"reflection",
";"... | Saves state informations for next request.
@param array
@param ComponentReflection (internal, used by Presenter)
@return void | [
"Saves",
"state",
"informations",
"for",
"next",
"request",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L414-L447 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.getParameter | public function getParameter($name, $default = NULL)
{
if (isset($this->params[$name])) {
return $this->params[$name];
} else {
return $default;
}
} | php | public function getParameter($name, $default = NULL)
{
if (isset($this->params[$name])) {
return $this->params[$name];
} else {
return $default;
}
} | [
"public",
"function",
"getParameter",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"NULL",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"params",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"params",
"[",
"$",
"name... | Returns component param.
@param string key
@param mixed default value
@return mixed | [
"Returns",
"component",
"param",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L456-L464 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.getParameterId | public function getParameterId($name)
{
$uid = $this->getUniqueId();
return $uid === '' ? $name : $uid . self::NAME_SEPARATOR . $name;
} | php | public function getParameterId($name)
{
$uid = $this->getUniqueId();
return $uid === '' ? $name : $uid . self::NAME_SEPARATOR . $name;
} | [
"public",
"function",
"getParameterId",
"(",
"$",
"name",
")",
"{",
"$",
"uid",
"=",
"$",
"this",
"->",
"getUniqueId",
"(",
")",
";",
"return",
"$",
"uid",
"===",
"''",
"?",
"$",
"name",
":",
"$",
"uid",
".",
"self",
"::",
"NAME_SEPARATOR",
".",
"$... | Returns a fully-qualified name that uniquely identifies the parameter.
@param string
@return string | [
"Returns",
"a",
"fully",
"-",
"qualified",
"name",
"that",
"uniquely",
"identifies",
"the",
"parameter",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L482-L486 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.getPersistentParams | public static function getPersistentParams()
{
$rc = new \ReflectionClass(get_called_class());
$params = [];
foreach ($rc->getProperties(\ReflectionProperty::IS_PUBLIC) as $rp) {
if (!$rp->isStatic() && ComponentReflection::parseAnnotation($rp, 'persistent')) {
$params[] = $rp->getName();
}
}
return $params;
} | php | public static function getPersistentParams()
{
$rc = new \ReflectionClass(get_called_class());
$params = [];
foreach ($rc->getProperties(\ReflectionProperty::IS_PUBLIC) as $rp) {
if (!$rp->isStatic() && ComponentReflection::parseAnnotation($rp, 'persistent')) {
$params[] = $rp->getName();
}
}
return $params;
} | [
"public",
"static",
"function",
"getPersistentParams",
"(",
")",
"{",
"$",
"rc",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"get_called_class",
"(",
")",
")",
";",
"$",
"params",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"rc",
"->",
"getProperties",
"(",
... | Returns array of classes persistent parameters. They have public visibility and are non-static.
This default implementation detects persistent parameters by annotation @persistent.
@return array | [
"Returns",
"array",
"of",
"classes",
"persistent",
"parameters",
".",
"They",
"have",
"public",
"visibility",
"and",
"are",
"non",
"-",
"static",
".",
"This",
"default",
"implementation",
"detects",
"persistent",
"parameters",
"by",
"annotation"
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L502-L512 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.signalReceived | public function signalReceived($signal)
{
if (!$this->tryCall($this->formatSignalMethod($signal), $this->params)) {
$class = get_class($this);
throw new BadSignalException("There is no handler for signal '$signal' in class $class.");
}
} | php | public function signalReceived($signal)
{
if (!$this->tryCall($this->formatSignalMethod($signal), $this->params)) {
$class = get_class($this);
throw new BadSignalException("There is no handler for signal '$signal' in class $class.");
}
} | [
"public",
"function",
"signalReceived",
"(",
"$",
"signal",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"tryCall",
"(",
"$",
"this",
"->",
"formatSignalMethod",
"(",
"$",
"signal",
")",
",",
"$",
"this",
"->",
"params",
")",
")",
"{",
"$",
"class",
... | Calls signal handler method.
@param string
@return void
@throws BadSignalException if there is not handler method | [
"Calls",
"signal",
"handler",
"method",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L524-L530 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.link | public function link($destination, $args = [])
{
// edit start
if (!$this->_createRequestMethodReflection) {
$this->_createRequestMethodReflection = new \ReflectionMethod(Presenter::class, 'createRequest');
$this->_createRequestMethodReflection->setAccessible(true);
$this->_handleInvalidLinkMethodReflection = new \ReflectionMethod(Presenter::class, 'handleInvalidLink');
$this->_handleInvalidLinkMethodReflection->setAccessible(true);
}
try {
$args = func_num_args() < 3 && is_array($args) ? $args : array_slice(func_get_args(), 1);
return $this->_createRequestMethodReflection->invoke($this->getPresenter(), $this, $destination, $args, 'link');
} catch (InvalidLinkException $e) {
$this->_handleInvalidLinkMethodReflection->invoke($e);
}
// edit end
} | php | public function link($destination, $args = [])
{
// edit start
if (!$this->_createRequestMethodReflection) {
$this->_createRequestMethodReflection = new \ReflectionMethod(Presenter::class, 'createRequest');
$this->_createRequestMethodReflection->setAccessible(true);
$this->_handleInvalidLinkMethodReflection = new \ReflectionMethod(Presenter::class, 'handleInvalidLink');
$this->_handleInvalidLinkMethodReflection->setAccessible(true);
}
try {
$args = func_num_args() < 3 && is_array($args) ? $args : array_slice(func_get_args(), 1);
return $this->_createRequestMethodReflection->invoke($this->getPresenter(), $this, $destination, $args, 'link');
} catch (InvalidLinkException $e) {
$this->_handleInvalidLinkMethodReflection->invoke($e);
}
// edit end
} | [
"public",
"function",
"link",
"(",
"$",
"destination",
",",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"// edit start",
"if",
"(",
"!",
"$",
"this",
"->",
"_createRequestMethodReflection",
")",
"{",
"$",
"this",
"->",
"_createRequestMethodReflection",
"=",
"new",... | Generates URL to presenter, action or signal.
@param string destination in format "[//] [[[module:]presenter:]action | signal! | this] [#fragment]"
@param array|mixed
@return string
@throws InvalidLinkException | [
"Generates",
"URL",
"to",
"presenter",
"action",
"or",
"signal",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L554-L572 |
nextras/forms | src/Controls/Fragments/ComponentControlTrait.php | ComponentControlTrait.offsetUnset | public function offsetUnset($name)
{
$component = $this->getComponent($name, FALSE);
if ($component !== NULL) {
$this->removeComponent($component);
}
} | php | public function offsetUnset($name)
{
$component = $this->getComponent($name, FALSE);
if ($component !== NULL) {
$this->removeComponent($component);
}
} | [
"public",
"function",
"offsetUnset",
"(",
"$",
"name",
")",
"{",
"$",
"component",
"=",
"$",
"this",
"->",
"getComponent",
"(",
"$",
"name",
",",
"FALSE",
")",
";",
"if",
"(",
"$",
"component",
"!==",
"NULL",
")",
"{",
"$",
"this",
"->",
"removeCompo... | Removes component from the container.
@param string component name
@return void | [
"Removes",
"component",
"from",
"the",
"container",
"."
] | train | https://github.com/nextras/forms/blob/548f93a0be0f5424b1a418bad3932de125ad31c8/src/Controls/Fragments/ComponentControlTrait.php#L618-L624 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.