repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.ipBetween | private static function ipBetween($version, $ip, $low, $high) {
if (4 === $version) {
// Use normal PHP ints
if ($low <= $ip) {
if ($ip < $high) {
return 0;
} else {
return 1;
}
} else {
return -1;
}
} else {
// Use BCMath
if (bccomp($low, $ip, 0) <= 0) {
if (bccomp($ip, $high, 0) <= -1) {
return 0;
} else {
return 1;
}
} else {
return -1;
}
}
} | php | private static function ipBetween($version, $ip, $low, $high) {
if (4 === $version) {
// Use normal PHP ints
if ($low <= $ip) {
if ($ip < $high) {
return 0;
} else {
return 1;
}
} else {
return -1;
}
} else {
// Use BCMath
if (bccomp($low, $ip, 0) <= 0) {
if (bccomp($ip, $high, 0) <= -1) {
return 0;
} else {
return 1;
}
} else {
return -1;
}
}
} | [
"private",
"static",
"function",
"ipBetween",
"(",
"$",
"version",
",",
"$",
"ip",
",",
"$",
"low",
",",
"$",
"high",
")",
"{",
"if",
"(",
"4",
"===",
"$",
"version",
")",
"{",
"// Use normal PHP ints",
"if",
"(",
"$",
"low",
"<=",
"$",
"ip",
")",
... | Determine whether the given IP number of the given version lies between the given bounds
This function will return 0 if the given ip number falls within the given bounds
for the given version, -1 if it falls below, and 1 if it falls above.
@access private
@static
@param int $version IP version to use (either 4 or 6)
@param int|string $ip IP number to check (int for IPv4, string for IPv6)
@param int|string $low Lower bound (int for IPv4, string for IPv6)
@param int|string $high Uppoer bound (int for IPv4, string for IPv6)
@return int | [
"Determine",
"whether",
"the",
"given",
"IP",
"number",
"of",
"the",
"given",
"version",
"lies",
"between",
"the",
"given",
"bounds"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L945-L969 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.ipVersionAndNumber | private static function ipVersionAndNumber($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return [4, sprintf('%u', ip2long($ip))];
} elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$result = 0;
foreach (str_split(bin2hex(inet_pton($ip)), 8) as $word) {
$result = bcadd(bcmul($result, '4294967296', 0), self::wrap32(hexdec($word)), 0);
}
return [6, $result];
} else {
// Invalid IP address, return falses
return [false, false];
}
} | php | private static function ipVersionAndNumber($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return [4, sprintf('%u', ip2long($ip))];
} elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$result = 0;
foreach (str_split(bin2hex(inet_pton($ip)), 8) as $word) {
$result = bcadd(bcmul($result, '4294967296', 0), self::wrap32(hexdec($word)), 0);
}
return [6, $result];
} else {
// Invalid IP address, return falses
return [false, false];
}
} | [
"private",
"static",
"function",
"ipVersionAndNumber",
"(",
"$",
"ip",
")",
"{",
"if",
"(",
"filter_var",
"(",
"$",
"ip",
",",
"FILTER_VALIDATE_IP",
",",
"FILTER_FLAG_IPV4",
")",
")",
"{",
"return",
"[",
"4",
",",
"sprintf",
"(",
"'%u'",
",",
"ip2long",
... | Get the IP version and number of the given IP address
This method will return an array, whose components will be:
- first: 4 if the given IP address is an IPv4 one, 6 if it's an IPv6 one,
or fase if it's neither.
- second: the IP address' number if its version is 4, the number string if
its version is 6, false otherwise.
@access private
@static
@param string $ip IP address to extract the version and number for
@return array | [
"Get",
"the",
"IP",
"version",
"and",
"number",
"of",
"the",
"given",
"IP",
"address"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L985-L1000 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.bcBin2Dec | private static function bcBin2Dec($data) {
$parts = array(
unpack('V', substr($data, 12, 4)),
unpack('V', substr($data, 8, 4)),
unpack('V', substr($data, 4, 4)),
unpack('V', substr($data, 0, 4)),
);
foreach($parts as &$part)
if($part[1] < 0)
$part[1] += 4294967296;
$result = bcadd(bcadd(bcmul($parts[0][1], bcpow(4294967296, 3)), bcmul($parts[1][1], bcpow(4294967296, 2))), bcadd(bcmul($parts[2][1], 4294967296), $parts[3][1]));
return $result;
} | php | private static function bcBin2Dec($data) {
$parts = array(
unpack('V', substr($data, 12, 4)),
unpack('V', substr($data, 8, 4)),
unpack('V', substr($data, 4, 4)),
unpack('V', substr($data, 0, 4)),
);
foreach($parts as &$part)
if($part[1] < 0)
$part[1] += 4294967296;
$result = bcadd(bcadd(bcmul($parts[0][1], bcpow(4294967296, 3)), bcmul($parts[1][1], bcpow(4294967296, 2))), bcadd(bcmul($parts[2][1], 4294967296), $parts[3][1]));
return $result;
} | [
"private",
"static",
"function",
"bcBin2Dec",
"(",
"$",
"data",
")",
"{",
"$",
"parts",
"=",
"array",
"(",
"unpack",
"(",
"'V'",
",",
"substr",
"(",
"$",
"data",
",",
"12",
",",
"4",
")",
")",
",",
"unpack",
"(",
"'V'",
",",
"substr",
"(",
"$",
... | Return the decimal string representing the binary data given
@access private
@static
@param string $data Binary data to parse
@return string | [
"Return",
"the",
"decimal",
"string",
"representing",
"the",
"binary",
"data",
"given"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1010-L1025 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.read | private function read($pos, $len) {
switch ($this->mode) {
case self::SHARED_MEMORY:
return shmop_read($this->resource, $pos, $len);
case self::MEMORY_CACHE:
return $data = substr(self::$buffer[$this->resource], $pos, $len);
default:
fseek($this->resource, $pos, SEEK_SET);
return fread($this->resource, $len);
}
} | php | private function read($pos, $len) {
switch ($this->mode) {
case self::SHARED_MEMORY:
return shmop_read($this->resource, $pos, $len);
case self::MEMORY_CACHE:
return $data = substr(self::$buffer[$this->resource], $pos, $len);
default:
fseek($this->resource, $pos, SEEK_SET);
return fread($this->resource, $len);
}
} | [
"private",
"function",
"read",
"(",
"$",
"pos",
",",
"$",
"len",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"mode",
")",
"{",
"case",
"self",
"::",
"SHARED_MEMORY",
":",
"return",
"shmop_read",
"(",
"$",
"this",
"->",
"resource",
",",
"$",
"pos",
... | Low level read function to abstract away the caching mode being used
@access private
@param int $pos Position from where to start reading
@param int $len Read this many bytes
@return string | [
"Low",
"level",
"read",
"function",
"to",
"abstract",
"away",
"the",
"caching",
"mode",
"being",
"used"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1039-L1051 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readString | private function readString($pos, $additional = 0) {
// Get the actual pointer to the string's head
$spos = $this->readWord($pos) + $additional;
// Read as much as the length (first "string" byte) indicates
return $this->read($spos + 1, $this->readByte($spos + 1));
} | php | private function readString($pos, $additional = 0) {
// Get the actual pointer to the string's head
$spos = $this->readWord($pos) + $additional;
// Read as much as the length (first "string" byte) indicates
return $this->read($spos + 1, $this->readByte($spos + 1));
} | [
"private",
"function",
"readString",
"(",
"$",
"pos",
",",
"$",
"additional",
"=",
"0",
")",
"{",
"// Get the actual pointer to the string's head",
"$",
"spos",
"=",
"$",
"this",
"->",
"readWord",
"(",
"$",
"pos",
")",
"+",
"$",
"additional",
";",
"// Read a... | Low level function to fetch a string from the caching backend
@access private
@param int $pos Position to read from
@param int $additional Additional offset to apply
@return string | [
"Low",
"level",
"function",
"to",
"fetch",
"a",
"string",
"from",
"the",
"caching",
"backend"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1065-L1071 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readCountryNameAndCode | private function readCountryNameAndCode($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$countryCode = self::INVALID_IP_ADDRESS;
$countryName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::COUNTRY_CODE][$this->type]) {
// If the field is not suported, return accordingly
$countryCode = self::FIELD_NOT_SUPPORTED;
$countryName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the country code and name (the name shares the country's pointer,
// but it must be artificially displaced 3 bytes ahead: 2 for the country code, one
// for the country name's length)
$countryCode = $this->readString($pointer + self::$columns[self::COUNTRY_CODE][$this->type]);
$countryName = $this->readString($pointer + self::$columns[self::COUNTRY_NAME][$this->type], 3);
}
return [$countryName, $countryCode];
} | php | private function readCountryNameAndCode($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$countryCode = self::INVALID_IP_ADDRESS;
$countryName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::COUNTRY_CODE][$this->type]) {
// If the field is not suported, return accordingly
$countryCode = self::FIELD_NOT_SUPPORTED;
$countryName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the country code and name (the name shares the country's pointer,
// but it must be artificially displaced 3 bytes ahead: 2 for the country code, one
// for the country name's length)
$countryCode = $this->readString($pointer + self::$columns[self::COUNTRY_CODE][$this->type]);
$countryName = $this->readString($pointer + self::$columns[self::COUNTRY_NAME][$this->type], 3);
}
return [$countryName, $countryCode];
} | [
"private",
"function",
"readCountryNameAndCode",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"countryCode",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"$",
"countryName",
"=",
"self",
... | High level function to fetch the country name and code
@access private
@param int|boolean $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return array | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"country",
"name",
"and",
"code"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1132-L1150 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readRegionName | private function readRegionName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$regionName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::REGION_NAME][$this->type]) {
// If the field is not suported, return accordingly
$regionName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the region name
$regionName = $this->readString($pointer + self::$columns[self::REGION_NAME][$this->type]);
}
return $regionName;
} | php | private function readRegionName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$regionName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::REGION_NAME][$this->type]) {
// If the field is not suported, return accordingly
$regionName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the region name
$regionName = $this->readString($pointer + self::$columns[self::REGION_NAME][$this->type]);
}
return $regionName;
} | [
"private",
"function",
"readRegionName",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"regionName",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
... | High level function to fetch the region name
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"region",
"name"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1159-L1171 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readCityName | private function readCityName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$cityName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::CITY_NAME][$this->type]) {
// If the field is not suported, return accordingly
$cityName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the city name
$cityName = $this->readString($pointer + self::$columns[self::CITY_NAME][$this->type]);
}
return $cityName;
} | php | private function readCityName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$cityName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::CITY_NAME][$this->type]) {
// If the field is not suported, return accordingly
$cityName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the city name
$cityName = $this->readString($pointer + self::$columns[self::CITY_NAME][$this->type]);
}
return $cityName;
} | [
"private",
"function",
"readCityName",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"cityName",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
":... | High level function to fetch the city name
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"city",
"name"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1180-L1192 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readLatitudeAndLongitude | private function readLatitudeAndLongitude($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$latitude = self::INVALID_IP_ADDRESS;
$longitude = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::LATITUDE][$this->type]) {
// If the field is not suported, return accordingly
$latitude = self::FIELD_NOT_SUPPORTED;
$longitude = self::FIELD_NOT_SUPPORTED;
} else {
// Read latitude and longitude
$latitude = $this->readFloat($pointer + self::$columns[self::LATITUDE][$this->type]);
$longitude = $this->readFloat($pointer + self::$columns[self::LONGITUDE][$this->type]);
}
return [$latitude, $longitude];
} | php | private function readLatitudeAndLongitude($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$latitude = self::INVALID_IP_ADDRESS;
$longitude = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::LATITUDE][$this->type]) {
// If the field is not suported, return accordingly
$latitude = self::FIELD_NOT_SUPPORTED;
$longitude = self::FIELD_NOT_SUPPORTED;
} else {
// Read latitude and longitude
$latitude = $this->readFloat($pointer + self::$columns[self::LATITUDE][$this->type]);
$longitude = $this->readFloat($pointer + self::$columns[self::LONGITUDE][$this->type]);
}
return [$latitude, $longitude];
} | [
"private",
"function",
"readLatitudeAndLongitude",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"latitude",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"$",
"longitude",
"=",
"self",
"::... | High level function to fetch the latitude and longitude
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return array | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"latitude",
"and",
"longitude"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1201-L1216 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readIsp | private function readIsp($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$isp = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::ISP][$this->type]) {
// If the field is not suported, return accordingly
$isp = self::FIELD_NOT_SUPPORTED;
} else {
// Read isp name
$isp = $this->readString($pointer + self::$columns[self::ISP][$this->type]);
}
return $isp;
} | php | private function readIsp($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$isp = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::ISP][$this->type]) {
// If the field is not suported, return accordingly
$isp = self::FIELD_NOT_SUPPORTED;
} else {
// Read isp name
$isp = $this->readString($pointer + self::$columns[self::ISP][$this->type]);
}
return $isp;
} | [
"private",
"function",
"readIsp",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"isp",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
"::",
"$",... | High level function to fetch the ISP name
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"ISP",
"name"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1225-L1237 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readDomainName | private function readDomainName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$domainName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::DOMAIN_NAME][$this->type]) {
// If the field is not suported, return accordingly
$domainName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the domain name
$domainName = $this->readString($pointer + self::$columns[self::DOMAIN_NAME][$this->type]);
}
return $domainName;
} | php | private function readDomainName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$domainName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::DOMAIN_NAME][$this->type]) {
// If the field is not suported, return accordingly
$domainName = self::FIELD_NOT_SUPPORTED;
} else {
// Read the domain name
$domainName = $this->readString($pointer + self::$columns[self::DOMAIN_NAME][$this->type]);
}
return $domainName;
} | [
"private",
"function",
"readDomainName",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"domainName",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
... | High level function to fetch the domain name
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"domain",
"name"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1246-L1258 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readZipCode | private function readZipCode($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$zipCode = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::ZIP_CODE][$this->type]) {
// If the field is not suported, return accordingly
$zipCode = self::FIELD_NOT_SUPPORTED;
} else {
// Read the zip code
$zipCode = $this->readString($pointer + self::$columns[self::ZIP_CODE][$this->type]);
}
return $zipCode;
} | php | private function readZipCode($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$zipCode = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::ZIP_CODE][$this->type]) {
// If the field is not suported, return accordingly
$zipCode = self::FIELD_NOT_SUPPORTED;
} else {
// Read the zip code
$zipCode = $this->readString($pointer + self::$columns[self::ZIP_CODE][$this->type]);
}
return $zipCode;
} | [
"private",
"function",
"readZipCode",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"zipCode",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
"::"... | High level function to fetch the zip code
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"zip",
"code"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1267-L1279 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readTimeZone | private function readTimeZone($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$timeZone = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::TIME_ZONE][$this->type]) {
// If the field is not suported, return accordingly
$timeZone = self::FIELD_NOT_SUPPORTED;
} else {
// Read the time zone
$timeZone = $this->readString($pointer + self::$columns[self::TIME_ZONE][$this->type]);
}
return $timeZone;
} | php | private function readTimeZone($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$timeZone = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::TIME_ZONE][$this->type]) {
// If the field is not suported, return accordingly
$timeZone = self::FIELD_NOT_SUPPORTED;
} else {
// Read the time zone
$timeZone = $this->readString($pointer + self::$columns[self::TIME_ZONE][$this->type]);
}
return $timeZone;
} | [
"private",
"function",
"readTimeZone",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"timeZone",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
":... | High level function to fetch the time zone
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"time",
"zone"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1288-L1300 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readNetSpeed | private function readNetSpeed($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$netSpeed = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::NET_SPEED][$this->type]) {
// If the field is not suported, return accordingly
$netSpeed = self::FIELD_NOT_SUPPORTED;
} else {
// Read the net speed
$netSpeed = $this->readString($pointer + self::$columns[self::NET_SPEED][$this->type]);
}
return $netSpeed;
} | php | private function readNetSpeed($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$netSpeed = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::NET_SPEED][$this->type]) {
// If the field is not suported, return accordingly
$netSpeed = self::FIELD_NOT_SUPPORTED;
} else {
// Read the net speed
$netSpeed = $this->readString($pointer + self::$columns[self::NET_SPEED][$this->type]);
}
return $netSpeed;
} | [
"private",
"function",
"readNetSpeed",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"netSpeed",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
":... | High level function to fetch the net speed
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"net",
"speed"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1309-L1321 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readIddAndAreaCodes | private function readIddAndAreaCodes($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$iddCode = self::INVALID_IP_ADDRESS;
$areaCode = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::IDD_CODE][$this->type]) {
// If the field is not suported, return accordingly
$iddCode = self::FIELD_NOT_SUPPORTED;
$areaCode = self::FIELD_NOT_SUPPORTED;
} else {
// Read IDD and area codes
$iddCode = $this->readString($pointer + self::$columns[self::IDD_CODE][$this->type]);
$areaCode = $this->readString($pointer + self::$columns[self::AREA_CODE][$this->type]);
}
return [$iddCode, $areaCode];
} | php | private function readIddAndAreaCodes($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$iddCode = self::INVALID_IP_ADDRESS;
$areaCode = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::IDD_CODE][$this->type]) {
// If the field is not suported, return accordingly
$iddCode = self::FIELD_NOT_SUPPORTED;
$areaCode = self::FIELD_NOT_SUPPORTED;
} else {
// Read IDD and area codes
$iddCode = $this->readString($pointer + self::$columns[self::IDD_CODE][$this->type]);
$areaCode = $this->readString($pointer + self::$columns[self::AREA_CODE][$this->type]);
}
return [$iddCode, $areaCode];
} | [
"private",
"function",
"readIddAndAreaCodes",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"iddCode",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"$",
"areaCode",
"=",
"self",
"::",
"I... | High level function to fetch the IDD and area codes
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return array | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"IDD",
"and",
"area",
"codes"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1330-L1345 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readWeatherStationNameAndCode | private function readWeatherStationNameAndCode($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$weatherStationName = self::INVALID_IP_ADDRESS;
$weatherStationCode = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::WEATHER_STATION_NAME][$this->type]) {
// If the field is not suported, return accordingly
$weatherStationName = self::FIELD_NOT_SUPPORTED;
$weatherStationCode = self::FIELD_NOT_SUPPORTED;
} else {
// Read weather station name and code
$weatherStationName = $this->readString($pointer + self::$columns[self::WEATHER_STATION_NAME][$this->type]);
$weatherStationCode = $this->readString($pointer + self::$columns[self::WEATHER_STATION_CODE][$this->type]);
}
return [$weatherStationName, $weatherStationCode];
} | php | private function readWeatherStationNameAndCode($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$weatherStationName = self::INVALID_IP_ADDRESS;
$weatherStationCode = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::WEATHER_STATION_NAME][$this->type]) {
// If the field is not suported, return accordingly
$weatherStationName = self::FIELD_NOT_SUPPORTED;
$weatherStationCode = self::FIELD_NOT_SUPPORTED;
} else {
// Read weather station name and code
$weatherStationName = $this->readString($pointer + self::$columns[self::WEATHER_STATION_NAME][$this->type]);
$weatherStationCode = $this->readString($pointer + self::$columns[self::WEATHER_STATION_CODE][$this->type]);
}
return [$weatherStationName, $weatherStationCode];
} | [
"private",
"function",
"readWeatherStationNameAndCode",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"weatherStationName",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"$",
"weatherStationCode"... | High level function to fetch the weather station name and code
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return array | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"weather",
"station",
"name",
"and",
"code"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1354-L1369 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readMccMncAndMobileCarrierName | private function readMccMncAndMobileCarrierName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$mcc = self::INVALID_IP_ADDRESS;
$mnc = self::INVALID_IP_ADDRESS;
$mobileCarrierName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::MCC][$this->type]) {
// If the field is not suported, return accordingly
$mcc = self::FIELD_NOT_SUPPORTED;
$mnc = self::FIELD_NOT_SUPPORTED;
$mobileCarrierName = self::FIELD_NOT_SUPPORTED;
} else {
// Read MCC, MNC, and mobile carrier name
$mcc = $this->readString($pointer + self::$columns[self::MCC][$this->type]);
$mnc = $this->readString($pointer + self::$columns[self::MNC][$this->type]);
$mobileCarrierName = $this->readString($pointer + self::$columns[self::MOBILE_CARRIER_NAME][$this->type]);
}
return [$mcc, $mnc, $mobileCarrierName];
} | php | private function readMccMncAndMobileCarrierName($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$mcc = self::INVALID_IP_ADDRESS;
$mnc = self::INVALID_IP_ADDRESS;
$mobileCarrierName = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::MCC][$this->type]) {
// If the field is not suported, return accordingly
$mcc = self::FIELD_NOT_SUPPORTED;
$mnc = self::FIELD_NOT_SUPPORTED;
$mobileCarrierName = self::FIELD_NOT_SUPPORTED;
} else {
// Read MCC, MNC, and mobile carrier name
$mcc = $this->readString($pointer + self::$columns[self::MCC][$this->type]);
$mnc = $this->readString($pointer + self::$columns[self::MNC][$this->type]);
$mobileCarrierName = $this->readString($pointer + self::$columns[self::MOBILE_CARRIER_NAME][$this->type]);
}
return [$mcc, $mnc, $mobileCarrierName];
} | [
"private",
"function",
"readMccMncAndMobileCarrierName",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"mcc",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"$",
"mnc",
"=",
"self",
"::",
... | High level function to fetch the MCC, MNC, and mobile carrier name
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return array | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"MCC",
"MNC",
"and",
"mobile",
"carrier",
"name"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1378-L1396 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readElevation | private function readElevation($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$elevation = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::ELEVATION][$this->type]) {
// If the field is not suported, return accordingly
$elevation = self::FIELD_NOT_SUPPORTED;
} else {
// Read the elevation
$elevation = $this->readString($pointer + self::$columns[self::ELEVATION][$this->type]);
}
return $elevation;
} | php | private function readElevation($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$elevation = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::ELEVATION][$this->type]) {
// If the field is not suported, return accordingly
$elevation = self::FIELD_NOT_SUPPORTED;
} else {
// Read the elevation
$elevation = $this->readString($pointer + self::$columns[self::ELEVATION][$this->type]);
}
return $elevation;
} | [
"private",
"function",
"readElevation",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"elevation",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
... | High level function to fetch the elevation
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"elevation"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1405-L1417 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readUsageType | private function readUsageType($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$usageType = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::USAGE_TYPE][$this->type]) {
// If the field is not suported, return accordingly
$usageType = self::FIELD_NOT_SUPPORTED;
} else {
$usageType = $this->readString($pointer + self::$columns[self::USAGE_TYPE][$this->type]);
}
return $usageType;
} | php | private function readUsageType($pointer) {
if (false === $pointer) {
// Deal with invalid IPs
$usageType = self::INVALID_IP_ADDRESS;
} elseif (0 === self::$columns[self::USAGE_TYPE][$this->type]) {
// If the field is not suported, return accordingly
$usageType = self::FIELD_NOT_SUPPORTED;
} else {
$usageType = $this->readString($pointer + self::$columns[self::USAGE_TYPE][$this->type]);
}
return $usageType;
} | [
"private",
"function",
"readUsageType",
"(",
"$",
"pointer",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pointer",
")",
"{",
"// Deal with invalid IPs",
"$",
"usageType",
"=",
"self",
"::",
"INVALID_IP_ADDRESS",
";",
"}",
"elseif",
"(",
"0",
"===",
"self",
... | High level function to fetch the usage type
@access private
@param int $pointer Position to read from, if false, return self::INVALID_IP_ADDRESS
@return string | [
"High",
"level",
"function",
"to",
"fetch",
"the",
"usage",
"type"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1426-L1437 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.readIp | private function readIp($version, $pos) {
if (4 === $version) {
// Read a standard PHP int
return self::wrap32($this->readWord($pos));
} elseif (6 === $version) {
// Read as BCMath int (quad)
return $this->readQuad($pos);
} else {
// unrecognized
return false;
}
} | php | private function readIp($version, $pos) {
if (4 === $version) {
// Read a standard PHP int
return self::wrap32($this->readWord($pos));
} elseif (6 === $version) {
// Read as BCMath int (quad)
return $this->readQuad($pos);
} else {
// unrecognized
return false;
}
} | [
"private",
"function",
"readIp",
"(",
"$",
"version",
",",
"$",
"pos",
")",
"{",
"if",
"(",
"4",
"===",
"$",
"version",
")",
"{",
"// Read a standard PHP int",
"return",
"self",
"::",
"wrap32",
"(",
"$",
"this",
"->",
"readWord",
"(",
"$",
"pos",
")",
... | High level fucntion to read an IP address of the given version
@access private
@param int $version IP version to read (either 4 or 6, returns false on anything else)
@param int $pos Position to read from
@return int|string|boolean | [
"High",
"level",
"fucntion",
"to",
"read",
"an",
"IP",
"address",
"of",
"the",
"given",
"version"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1451-L1462 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.binSearch | private function binSearch($version, $ipNumber, $cidr=false) {
if (false === $version) {
// unrecognized version
return false;
}
// initialize fields
$base = $this->ipBase[$version];
$offset = $this->offset[$version];
$width = $this->columnWidth[$version];
$high = $this->ipCount[$version];
$low = 0;
//hjlim
$indexBaseStart = $this->indexBaseAddr[$version];
if ($indexBaseStart > 0){
$indexPos = 0;
switch($version){
case 4:
$ipNum1_2 = intval($ipNumber / 65536);
$indexPos = $indexBaseStart + ($ipNum1_2 << 3);
break;
case 6:
$ipNum1 = intval(bcdiv($ipNumber, bcpow('2', '112')));
$indexPos = $indexBaseStart + ($ipNum1 << 3);
break;
default:
return false;
}
$low = $this->readWord($indexPos);
$high = $this->readWord($indexPos + 4);
}
// as long as we can narrow down the search...
while ($low <= $high) {
$mid = (int) ($low + (($high - $low) >> 1));
// Read IP ranges to get boundaries
$ip_from = $this->readIp($version, $base + $width * $mid);
$ip_to = $this->readIp($version, $base + $width * ($mid + 1));
// determine whether to return, repeat on the lower half, or repeat on the upper half
switch (self::ipBetween($version, $ipNumber, $ip_from, $ip_to)) {
case 0:
return ($cidr) ? array($ip_from, $ip_to) : $base + $offset + $mid * $width;
case -1:
$high = $mid - 1;
break;
case 1:
$low = $mid + 1;
break;
}
}
// nothing found
return false;
} | php | private function binSearch($version, $ipNumber, $cidr=false) {
if (false === $version) {
// unrecognized version
return false;
}
// initialize fields
$base = $this->ipBase[$version];
$offset = $this->offset[$version];
$width = $this->columnWidth[$version];
$high = $this->ipCount[$version];
$low = 0;
//hjlim
$indexBaseStart = $this->indexBaseAddr[$version];
if ($indexBaseStart > 0){
$indexPos = 0;
switch($version){
case 4:
$ipNum1_2 = intval($ipNumber / 65536);
$indexPos = $indexBaseStart + ($ipNum1_2 << 3);
break;
case 6:
$ipNum1 = intval(bcdiv($ipNumber, bcpow('2', '112')));
$indexPos = $indexBaseStart + ($ipNum1 << 3);
break;
default:
return false;
}
$low = $this->readWord($indexPos);
$high = $this->readWord($indexPos + 4);
}
// as long as we can narrow down the search...
while ($low <= $high) {
$mid = (int) ($low + (($high - $low) >> 1));
// Read IP ranges to get boundaries
$ip_from = $this->readIp($version, $base + $width * $mid);
$ip_to = $this->readIp($version, $base + $width * ($mid + 1));
// determine whether to return, repeat on the lower half, or repeat on the upper half
switch (self::ipBetween($version, $ipNumber, $ip_from, $ip_to)) {
case 0:
return ($cidr) ? array($ip_from, $ip_to) : $base + $offset + $mid * $width;
case -1:
$high = $mid - 1;
break;
case 1:
$low = $mid + 1;
break;
}
}
// nothing found
return false;
} | [
"private",
"function",
"binSearch",
"(",
"$",
"version",
",",
"$",
"ipNumber",
",",
"$",
"cidr",
"=",
"false",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"version",
")",
"{",
"// unrecognized version",
"return",
"false",
";",
"}",
"// initialize fields",
"$... | Perform a binary search on the given IP number and return a pointer to its record
@access private
@param int $version IP version to use for searching
@param int $ipNumber IP number to look for
@return int|boolean | [
"Perform",
"a",
"binary",
"search",
"on",
"the",
"given",
"IP",
"number",
"and",
"return",
"a",
"pointer",
"to",
"its",
"record"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1472-L1533 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.getFields | public function getFields($asNames = false) {
$result = array_keys(array_filter(self::$columns, function ($field) {
return 0 !== $field[$this->type];
}));
if ($asNames) {
$return = [];
foreach ($result as $field) {
$return[] = self::$names[$field];
}
return $return;
} else {
return $result;
}
} | php | public function getFields($asNames = false) {
$result = array_keys(array_filter(self::$columns, function ($field) {
return 0 !== $field[$this->type];
}));
if ($asNames) {
$return = [];
foreach ($result as $field) {
$return[] = self::$names[$field];
}
return $return;
} else {
return $result;
}
} | [
"public",
"function",
"getFields",
"(",
"$",
"asNames",
"=",
"false",
")",
"{",
"$",
"result",
"=",
"array_keys",
"(",
"array_filter",
"(",
"self",
"::",
"$",
"columns",
",",
"function",
"(",
"$",
"field",
")",
"{",
"return",
"0",
"!==",
"$",
"field",
... | Return this database's available fields
@access public
@param boolean $asNames Whether to return the mapped names intead of numbered constants
@return array | [
"Return",
"this",
"database",
"s",
"available",
"fields"
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1566-L1579 | train |
chrislim2888/IP2Location-PHP-Module | IP2Location.php | Database.get_cidr | public function get_cidr($ip) {
// extract IP version and number
list($ipVersion, $ipNumber) = self::ipVersionAndNumber($ip);
// perform the binary search proper (if the IP address was invalid, binSearch will return false)
$resp = $this->binSearch($ipVersion, $ipNumber, true);
if(!empty($resp)) {
list($ip_from, $ip_to) = $resp;
$i=32; $mask=1;
while(($ip_to & $mask) == 0) {
$mask *= 2; $i--;
}
$ip = long2ip($ip_from);
return "$ip/$i";
}
return false;
} | php | public function get_cidr($ip) {
// extract IP version and number
list($ipVersion, $ipNumber) = self::ipVersionAndNumber($ip);
// perform the binary search proper (if the IP address was invalid, binSearch will return false)
$resp = $this->binSearch($ipVersion, $ipNumber, true);
if(!empty($resp)) {
list($ip_from, $ip_to) = $resp;
$i=32; $mask=1;
while(($ip_to & $mask) == 0) {
$mask *= 2; $i--;
}
$ip = long2ip($ip_from);
return "$ip/$i";
}
return false;
} | [
"public",
"function",
"get_cidr",
"(",
"$",
"ip",
")",
"{",
"// extract IP version and number",
"list",
"(",
"$",
"ipVersion",
",",
"$",
"ipNumber",
")",
"=",
"self",
"::",
"ipVersionAndNumber",
"(",
"$",
"ip",
")",
";",
"// perform the binary search proper (if th... | For a given IP address, returns the cidr of his sub-network.
For example, calling get_cidr('91.200.12.233') returns '91.200.0.0/13'.
Useful to setup "Deny From 91.200.0.0/13" in .htaccess file for Apache2
server against spam. | [
"For",
"a",
"given",
"IP",
"address",
"returns",
"the",
"cidr",
"of",
"his",
"sub",
"-",
"network",
"."
] | 178e115645407284dc377a7b017a0cbb3681298f | https://github.com/chrislim2888/IP2Location-PHP-Module/blob/178e115645407284dc377a7b017a0cbb3681298f/IP2Location.php#L1912-L1927 | train |
stevenmaguire/oauth2-keycloak | src/Provider/Keycloak.php | Keycloak.decryptResponse | public function decryptResponse($response)
{
if (!is_string($response)) {
return $response;
}
if ($this->usesEncryption()) {
return json_decode(
json_encode(
JWT::decode(
$response,
$this->encryptionKey,
array($this->encryptionAlgorithm)
)
),
true
);
}
throw EncryptionConfigurationException::undeterminedEncryption();
} | php | public function decryptResponse($response)
{
if (!is_string($response)) {
return $response;
}
if ($this->usesEncryption()) {
return json_decode(
json_encode(
JWT::decode(
$response,
$this->encryptionKey,
array($this->encryptionAlgorithm)
)
),
true
);
}
throw EncryptionConfigurationException::undeterminedEncryption();
} | [
"public",
"function",
"decryptResponse",
"(",
"$",
"response",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"response",
")",
")",
"{",
"return",
"$",
"response",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"usesEncryption",
"(",
")",
")",
"{",
"retur... | Attempts to decrypt the given response.
@param string|array|null $response
@return string|array|null | [
"Attempts",
"to",
"decrypt",
"the",
"given",
"response",
"."
] | f6953409c3354385179f5b59bd2a36f5c9f5b1f7 | https://github.com/stevenmaguire/oauth2-keycloak/blob/f6953409c3354385179f5b59bd2a36f5c9f5b1f7/src/Provider/Keycloak.php#L77-L97 | train |
stevenmaguire/oauth2-keycloak | src/Provider/Keycloak.php | Keycloak.getLogoutUrl | public function getLogoutUrl(array $options = [])
{
$base = $this->getBaseLogoutUrl();
$params = $this->getAuthorizationParameters($options);
$query = $this->getAuthorizationQuery($params);
return $this->appendQuery($base, $query);
} | php | public function getLogoutUrl(array $options = [])
{
$base = $this->getBaseLogoutUrl();
$params = $this->getAuthorizationParameters($options);
$query = $this->getAuthorizationQuery($params);
return $this->appendQuery($base, $query);
} | [
"public",
"function",
"getLogoutUrl",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"base",
"=",
"$",
"this",
"->",
"getBaseLogoutUrl",
"(",
")",
";",
"$",
"params",
"=",
"$",
"this",
"->",
"getAuthorizationParameters",
"(",
"$",
"options",... | Builds the logout URL.
@param array $options
@return string Authorization URL | [
"Builds",
"the",
"logout",
"URL",
"."
] | f6953409c3354385179f5b59bd2a36f5c9f5b1f7 | https://github.com/stevenmaguire/oauth2-keycloak/blob/f6953409c3354385179f5b59bd2a36f5c9f5b1f7/src/Provider/Keycloak.php#L139-L145 | train |
tencentyun/cos-php-sdk-v5 | src/Qcloud/Cos/BucketStyleListener.php | BucketStyleListener.onCommandAfterPrepare | public function onCommandAfterPrepare(Event $event) {
$command = $event['command'];
$bucket = $command['Bucket'];
$request = $command->getRequest();
if ($command->getName() == 'ListBuckets')
{
if ($this->ipport != null) {
$request->setHost($this->ipport);
$request->setHeader('Host', 'service.cos.myqcloud.com');
} else if ($this->endpoint != null) {
$request->setHost($this->endpoint);
$request->setHeader('Host', 'service.cos.myqcloud.com');
}
else {
$request->setHost('service.cos.myqcloud.com');
}
return ;
}
if ($key = $command['Key']) {
// Modify the command Key to account for the {/Key*} explosion into an array
if (is_array($key)) {
$command['Key'] = $key = implode('/', $key);
}
}
$request->setHeader('Date', gmdate('D, d M Y H:i:s T'));
$request->setPath(preg_replace("#^/{$bucket}#", '', $request->getPath()));
if ($this->appId != null && endWith($bucket,'-'.$this->appId) == False)
{
$bucket = $bucket.'-'.$this->appId;
}
// $request->setPath(urldecode($request->getPath()));
$request->getParams()->set('bucket', $bucket)->set('key', $key);
$realHost = $bucket. '.' . $request->getHost();
if($this->ipport != null) {
$request->setHost($this->ipport);
$request->setHeader('Host', $realHost);
} else {
if($this->endpoint != null) {
$tmp = $bucket. '.' . $this->endpoint;
$request->setHost($tmp);
} else {
$request->setHost($realHost);
}
}
if (!$bucket) {
$request->getParams()->set('cos.resource', '/');
} else {
// Bucket style needs a trailing slash
$request->getParams()->set(
'cos.resource',
'/' . rawurlencode($bucket) . ($key ? ('/' . Client::encodeKey($key)) : '/')
);
}
} | php | public function onCommandAfterPrepare(Event $event) {
$command = $event['command'];
$bucket = $command['Bucket'];
$request = $command->getRequest();
if ($command->getName() == 'ListBuckets')
{
if ($this->ipport != null) {
$request->setHost($this->ipport);
$request->setHeader('Host', 'service.cos.myqcloud.com');
} else if ($this->endpoint != null) {
$request->setHost($this->endpoint);
$request->setHeader('Host', 'service.cos.myqcloud.com');
}
else {
$request->setHost('service.cos.myqcloud.com');
}
return ;
}
if ($key = $command['Key']) {
// Modify the command Key to account for the {/Key*} explosion into an array
if (is_array($key)) {
$command['Key'] = $key = implode('/', $key);
}
}
$request->setHeader('Date', gmdate('D, d M Y H:i:s T'));
$request->setPath(preg_replace("#^/{$bucket}#", '', $request->getPath()));
if ($this->appId != null && endWith($bucket,'-'.$this->appId) == False)
{
$bucket = $bucket.'-'.$this->appId;
}
// $request->setPath(urldecode($request->getPath()));
$request->getParams()->set('bucket', $bucket)->set('key', $key);
$realHost = $bucket. '.' . $request->getHost();
if($this->ipport != null) {
$request->setHost($this->ipport);
$request->setHeader('Host', $realHost);
} else {
if($this->endpoint != null) {
$tmp = $bucket. '.' . $this->endpoint;
$request->setHost($tmp);
} else {
$request->setHost($realHost);
}
}
if (!$bucket) {
$request->getParams()->set('cos.resource', '/');
} else {
// Bucket style needs a trailing slash
$request->getParams()->set(
'cos.resource',
'/' . rawurlencode($bucket) . ($key ? ('/' . Client::encodeKey($key)) : '/')
);
}
} | [
"public",
"function",
"onCommandAfterPrepare",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"command",
"=",
"$",
"event",
"[",
"'command'",
"]",
";",
"$",
"bucket",
"=",
"$",
"command",
"[",
"'Bucket'",
"]",
";",
"$",
"request",
"=",
"$",
"command",
"->"... | Change from path style to host style.
@param Event $event Event emitted. | [
"Change",
"from",
"path",
"style",
"to",
"host",
"style",
"."
] | 79a9f3eb52260ea5b0d9594da2025f962d85b258 | https://github.com/tencentyun/cos-php-sdk-v5/blob/79a9f3eb52260ea5b0d9594da2025f962d85b258/src/Qcloud/Cos/BucketStyleListener.php#L49-L106 | train |
tencentyun/cos-php-sdk-v5 | src/Qcloud/Cos/ExceptionParser.php | ExceptionParser.parseHeaders | protected function parseHeaders(RequestInterface $request, Response $response, array &$data) {
$data['message'] = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
if ($requestId = $response->getHeader('x-cos-request-id')) {
$data['request_id'] = $requestId;
$data['message'] .= " (Request-ID: $requestId)";
}
// Get the request
$status = $response->getStatusCode();
$method = $request->getMethod();
// Attempt to determine code for 403s and 404s
if ($status === 403) {
$data['code'] = 'AccessDenied';
} elseif ($method === 'HEAD' && $status === 404) {
$path = explode('/', trim($request->getPath(), '/'));
$host = explode('.', $request->getHost());
$bucket = (count($host) >= 4) ? $host[0] : array_shift($path);
$object = array_shift($path);
if ($bucket && $object) {
$data['code'] = 'NoSuchKey';
} elseif ($bucket) {
$data['code'] = 'NoSuchBucket';
}
}
} | php | protected function parseHeaders(RequestInterface $request, Response $response, array &$data) {
$data['message'] = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
if ($requestId = $response->getHeader('x-cos-request-id')) {
$data['request_id'] = $requestId;
$data['message'] .= " (Request-ID: $requestId)";
}
// Get the request
$status = $response->getStatusCode();
$method = $request->getMethod();
// Attempt to determine code for 403s and 404s
if ($status === 403) {
$data['code'] = 'AccessDenied';
} elseif ($method === 'HEAD' && $status === 404) {
$path = explode('/', trim($request->getPath(), '/'));
$host = explode('.', $request->getHost());
$bucket = (count($host) >= 4) ? $host[0] : array_shift($path);
$object = array_shift($path);
if ($bucket && $object) {
$data['code'] = 'NoSuchKey';
} elseif ($bucket) {
$data['code'] = 'NoSuchBucket';
}
}
} | [
"protected",
"function",
"parseHeaders",
"(",
"RequestInterface",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"array",
"&",
"$",
"data",
")",
"{",
"$",
"data",
"[",
"'message'",
"]",
"=",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
".",
... | Parses additional exception information from the response headers
@param RequestInterface $request Request that was issued
@param Response $response The response from the request
@param array $data The current set of exception data | [
"Parses",
"additional",
"exception",
"information",
"from",
"the",
"response",
"headers"
] | 79a9f3eb52260ea5b0d9594da2025f962d85b258 | https://github.com/tencentyun/cos-php-sdk-v5/blob/79a9f3eb52260ea5b0d9594da2025f962d85b258/src/Qcloud/Cos/ExceptionParser.php#L50-L76 | train |
tencentyun/cos-php-sdk-v5 | src/Qcloud/Cos/UploadBodyListener.php | UploadBodyListener.onCommandBeforePrepare | public function onCommandBeforePrepare(Event $event) {
/** @var Command $command */
$command = $event['command'];
if (in_array($command->getName(), $this->commands)) {
// Get the interesting parameters
$source = $command->get($this->sourceParameter);
$body = $command->get($this->bodyParameter);
// If a file path is passed in then get the file handle
if (is_string($source) && file_exists($source)) {
$body = fopen($source, 'rb');
}
// Prepare the body parameter and remove the source file parameter
if (null !== $body) {
$command->remove($this->sourceParameter);
$command->set($this->bodyParameter, EntityBody::factory($body));
} else {
throw new InvalidArgumentException(
"You must specify a non-null value for the {$this->bodyParameter} or {$this->sourceParameter} parameters.");
}
}
} | php | public function onCommandBeforePrepare(Event $event) {
/** @var Command $command */
$command = $event['command'];
if (in_array($command->getName(), $this->commands)) {
// Get the interesting parameters
$source = $command->get($this->sourceParameter);
$body = $command->get($this->bodyParameter);
// If a file path is passed in then get the file handle
if (is_string($source) && file_exists($source)) {
$body = fopen($source, 'rb');
}
// Prepare the body parameter and remove the source file parameter
if (null !== $body) {
$command->remove($this->sourceParameter);
$command->set($this->bodyParameter, EntityBody::factory($body));
} else {
throw new InvalidArgumentException(
"You must specify a non-null value for the {$this->bodyParameter} or {$this->sourceParameter} parameters.");
}
}
} | [
"public",
"function",
"onCommandBeforePrepare",
"(",
"Event",
"$",
"event",
")",
"{",
"/** @var Command $command */",
"$",
"command",
"=",
"$",
"event",
"[",
"'command'",
"]",
";",
"if",
"(",
"in_array",
"(",
"$",
"command",
"->",
"getName",
"(",
")",
",",
... | Converts filenames and file handles into EntityBody objects before the command is validated
@param Event $event Event emitted
@throws InvalidArgumentException | [
"Converts",
"filenames",
"and",
"file",
"handles",
"into",
"EntityBody",
"objects",
"before",
"the",
"command",
"is",
"validated"
] | 79a9f3eb52260ea5b0d9594da2025f962d85b258 | https://github.com/tencentyun/cos-php-sdk-v5/blob/79a9f3eb52260ea5b0d9594da2025f962d85b258/src/Qcloud/Cos/UploadBodyListener.php#L56-L78 | train |
tencentyun/cos-php-sdk-v5 | src/Qcloud/Cos/TokenListener.php | TokenListener.onRequestBeforeSend | public function onRequestBeforeSend(Event $event) {
if ($this->token != null) {
$event['request']->setHeader('x-cos-security-token', $this->token);
}
/*
if(!$this->credentials instanceof NullCredentials) {
$this->signature->signRequest($event['request'], $this->credentials);
}
*/
} | php | public function onRequestBeforeSend(Event $event) {
if ($this->token != null) {
$event['request']->setHeader('x-cos-security-token', $this->token);
}
/*
if(!$this->credentials instanceof NullCredentials) {
$this->signature->signRequest($event['request'], $this->credentials);
}
*/
} | [
"public",
"function",
"onRequestBeforeSend",
"(",
"Event",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"token",
"!=",
"null",
")",
"{",
"$",
"event",
"[",
"'request'",
"]",
"->",
"setHeader",
"(",
"'x-cos-security-token'",
",",
"$",
"this",
"->... | Signs requests before they are sent
@param Event $event Event emitted | [
"Signs",
"requests",
"before",
"they",
"are",
"sent"
] | 79a9f3eb52260ea5b0d9594da2025f962d85b258 | https://github.com/tencentyun/cos-php-sdk-v5/blob/79a9f3eb52260ea5b0d9594da2025f962d85b258/src/Qcloud/Cos/TokenListener.php#L38-L47 | train |
cakephp/authorization | src/Middleware/UnauthorizedHandler/RedirectHandler.php | RedirectHandler.handle | public function handle(Exception $exception, ServerRequestInterface $request, ResponseInterface $response, array $options = [])
{
$options += $this->defaultOptions;
if (!$this->checkException($exception, $options['exceptions'])) {
throw $exception;
}
$url = $this->getUrl($request, $options);
return $response
->withHeader('Location', $url)
->withStatus($options['statusCode']);
} | php | public function handle(Exception $exception, ServerRequestInterface $request, ResponseInterface $response, array $options = [])
{
$options += $this->defaultOptions;
if (!$this->checkException($exception, $options['exceptions'])) {
throw $exception;
}
$url = $this->getUrl($request, $options);
return $response
->withHeader('Location', $url)
->withStatus($options['statusCode']);
} | [
"public",
"function",
"handle",
"(",
"Exception",
"$",
"exception",
",",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"$",
"this",
"->",
"d... | Return a response with a location header set if an exception matches.
{@inheritDoc} | [
"Return",
"a",
"response",
"with",
"a",
"location",
"header",
"set",
"if",
"an",
"exception",
"matches",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Middleware/UnauthorizedHandler/RedirectHandler.php#L52-L65 | train |
cakephp/authorization | src/Middleware/UnauthorizedHandler/RedirectHandler.php | RedirectHandler.getUrl | protected function getUrl(ServerRequestInterface $request, array $options)
{
$url = $options['url'];
if ($options['queryParam'] !== null && $request->getMethod() === 'GET') {
$query = urlencode($options['queryParam']) . '=' . urlencode($request->getRequestTarget());
if (strpos($url, '?') !== false) {
$query = '&' . $query;
} else {
$query = '?' . $query;
}
$url .= $query;
}
return $url;
} | php | protected function getUrl(ServerRequestInterface $request, array $options)
{
$url = $options['url'];
if ($options['queryParam'] !== null && $request->getMethod() === 'GET') {
$query = urlencode($options['queryParam']) . '=' . urlencode($request->getRequestTarget());
if (strpos($url, '?') !== false) {
$query = '&' . $query;
} else {
$query = '?' . $query;
}
$url .= $query;
}
return $url;
} | [
"protected",
"function",
"getUrl",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
")",
"{",
"$",
"url",
"=",
"$",
"options",
"[",
"'url'",
"]",
";",
"if",
"(",
"$",
"options",
"[",
"'queryParam'",
"]",
"!==",
"null",
"&&",
... | Returns the url for the Location header.
@param \Psr\Http\Message\ServerRequestInterface $request Server request.
@param array $options Options.
@return string | [
"Returns",
"the",
"url",
"for",
"the",
"Location",
"header",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Middleware/UnauthorizedHandler/RedirectHandler.php#L92-L107 | train |
cakephp/authorization | src/Controller/Component/AuthorizationComponent.php | AuthorizationComponent.skipAuthorization | public function skipAuthorization()
{
$request = $this->getController()->request;
$service = $this->getService($request);
$service->skipAuthorization();
return $this;
} | php | public function skipAuthorization()
{
$request = $this->getController()->request;
$service = $this->getService($request);
$service->skipAuthorization();
return $this;
} | [
"public",
"function",
"skipAuthorization",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"request",
";",
"$",
"service",
"=",
"$",
"this",
"->",
"getService",
"(",
"$",
"request",
")",
";",
"$",
"service",
"->"... | Skips the authorization check.
@return $this | [
"Skips",
"the",
"authorization",
"check",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Controller/Component/AuthorizationComponent.php#L138-L146 | train |
cakephp/authorization | src/Controller/Component/AuthorizationComponent.php | AuthorizationComponent.getService | protected function getService(ServerRequestInterface $request)
{
$serviceAttribute = $this->getConfig('serviceAttribute');
$service = $request->getAttribute($serviceAttribute);
if (!$service instanceof AuthorizationServiceInterface) {
$type = is_object($service) ? get_class($service) : gettype($service);
throw new InvalidArgumentException(sprintf(
'Expected that `%s` would be an instance of %s, but got %s',
$serviceAttribute,
AuthorizationServiceInterface::class,
$type
));
}
return $service;
} | php | protected function getService(ServerRequestInterface $request)
{
$serviceAttribute = $this->getConfig('serviceAttribute');
$service = $request->getAttribute($serviceAttribute);
if (!$service instanceof AuthorizationServiceInterface) {
$type = is_object($service) ? get_class($service) : gettype($service);
throw new InvalidArgumentException(sprintf(
'Expected that `%s` would be an instance of %s, but got %s',
$serviceAttribute,
AuthorizationServiceInterface::class,
$type
));
}
return $service;
} | [
"protected",
"function",
"getService",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"serviceAttribute",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'serviceAttribute'",
")",
";",
"$",
"service",
"=",
"$",
"request",
"->",
"getAttribute",
"(",
"... | Get the authorization service from a request.
@param \Psr\Http\Message\ServerRequestInterface $request The request
@return \Authorization\AuthorizationServiceInterface
@throws \InvalidArgumentException When invalid authorization service encountered. | [
"Get",
"the",
"authorization",
"service",
"from",
"a",
"request",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Controller/Component/AuthorizationComponent.php#L198-L213 | train |
cakephp/authorization | src/Controller/Component/AuthorizationComponent.php | AuthorizationComponent.getIdentity | protected function getIdentity(ServerRequestInterface $request)
{
$identityAttribute = $this->getConfig('identityAttribute');
$identity = $request->getAttribute($identityAttribute);
if ($identity === null) {
return $identity;
}
if (!$identity instanceof IdentityInterface) {
$type = is_object($identity) ? get_class($identity) : gettype($identity);
throw new InvalidArgumentException(sprintf(
'Expected that `%s` would be an instance of %s, but got %s',
$identityAttribute,
IdentityInterface::class,
$type
));
}
return $identity;
} | php | protected function getIdentity(ServerRequestInterface $request)
{
$identityAttribute = $this->getConfig('identityAttribute');
$identity = $request->getAttribute($identityAttribute);
if ($identity === null) {
return $identity;
}
if (!$identity instanceof IdentityInterface) {
$type = is_object($identity) ? get_class($identity) : gettype($identity);
throw new InvalidArgumentException(sprintf(
'Expected that `%s` would be an instance of %s, but got %s',
$identityAttribute,
IdentityInterface::class,
$type
));
}
return $identity;
} | [
"protected",
"function",
"getIdentity",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"identityAttribute",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'identityAttribute'",
")",
";",
"$",
"identity",
"=",
"$",
"request",
"->",
"getAttribute",
"(",... | Get the identity from a request.
@param \Psr\Http\Message\ServerRequestInterface $request The request
@return \Authorization\IdentityInterface|null
@throws \Authorization\Exception\MissingIdentityException When identity is not present in a request.
@throws \InvalidArgumentException When invalid identity encountered. | [
"Get",
"the",
"identity",
"from",
"a",
"request",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Controller/Component/AuthorizationComponent.php#L223-L241 | train |
cakephp/authorization | src/Controller/Component/AuthorizationComponent.php | AuthorizationComponent.authorizeAction | public function authorizeAction()
{
$request = $this->getController()->request;
$action = $request->getParam('action');
$skipAuthorization = $this->checkAction($action, 'skipAuthorization');
if ($skipAuthorization) {
$this->skipAuthorization();
return;
}
$authorizeModel = $this->checkAction($action, 'authorizeModel');
if ($authorizeModel) {
$this->authorize($this->getController()->loadModel());
}
} | php | public function authorizeAction()
{
$request = $this->getController()->request;
$action = $request->getParam('action');
$skipAuthorization = $this->checkAction($action, 'skipAuthorization');
if ($skipAuthorization) {
$this->skipAuthorization();
return;
}
$authorizeModel = $this->checkAction($action, 'authorizeModel');
if ($authorizeModel) {
$this->authorize($this->getController()->loadModel());
}
} | [
"public",
"function",
"authorizeAction",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"request",
";",
"$",
"action",
"=",
"$",
"request",
"->",
"getParam",
"(",
"'action'",
")",
";",
"$",
"skipAuthorization",
"=... | Action authorization handler.
Checks identity and model authorization.
@return void | [
"Action",
"authorization",
"handler",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Controller/Component/AuthorizationComponent.php#L250-L266 | train |
cakephp/authorization | src/Controller/Component/AuthorizationComponent.php | AuthorizationComponent.checkAction | protected function checkAction($action, $configKey)
{
$actions = (array)$this->getConfig($configKey);
return in_array($action, $actions, true);
} | php | protected function checkAction($action, $configKey)
{
$actions = (array)$this->getConfig($configKey);
return in_array($action, $actions, true);
} | [
"protected",
"function",
"checkAction",
"(",
"$",
"action",
",",
"$",
"configKey",
")",
"{",
"$",
"actions",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"getConfig",
"(",
"$",
"configKey",
")",
";",
"return",
"in_array",
"(",
"$",
"action",
",",
"$",
... | Checks whether an action should be authorized according to the config key provided.
@param string $action Action name.
@param string $configKey Configuration key with actions.
@return bool | [
"Checks",
"whether",
"an",
"action",
"should",
"be",
"authorized",
"according",
"to",
"the",
"config",
"key",
"provided",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Controller/Component/AuthorizationComponent.php#L275-L280 | train |
cakephp/authorization | src/Controller/Component/AuthorizationComponent.php | AuthorizationComponent.getDefaultAction | protected function getDefaultAction(ServerRequest $request)
{
$action = $request->getParam('action');
$name = $this->getConfig('actionMap.' . $action);
if ($name === null) {
return $action;
}
if (!is_string($name)) {
$type = is_object($name) ? get_class($name) : gettype($name);
$message = sprintf('Invalid action type for `%s`. Expected `string` or `null`, got `%s`.', $action, $type);
throw new UnexpectedValueException($message);
}
return $name;
} | php | protected function getDefaultAction(ServerRequest $request)
{
$action = $request->getParam('action');
$name = $this->getConfig('actionMap.' . $action);
if ($name === null) {
return $action;
}
if (!is_string($name)) {
$type = is_object($name) ? get_class($name) : gettype($name);
$message = sprintf('Invalid action type for `%s`. Expected `string` or `null`, got `%s`.', $action, $type);
throw new UnexpectedValueException($message);
}
return $name;
} | [
"protected",
"function",
"getDefaultAction",
"(",
"ServerRequest",
"$",
"request",
")",
"{",
"$",
"action",
"=",
"$",
"request",
"->",
"getParam",
"(",
"'action'",
")",
";",
"$",
"name",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'actionMap.'",
".",
"$",
... | Returns authorization action name for a controller action resolved from the request.
@param \Cake\Http\ServerRequest $request Server request.
@return string
@throws \UnexpectedValueException When invalid action type encountered. | [
"Returns",
"authorization",
"action",
"name",
"for",
"a",
"controller",
"action",
"resolved",
"from",
"the",
"request",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Controller/Component/AuthorizationComponent.php#L289-L304 | train |
cakephp/authorization | src/Middleware/AuthorizationMiddleware.php | AuthorizationMiddleware.getHandler | protected function getHandler()
{
$handler = $this->getConfig('unauthorizedHandler');
if (!is_array($handler)) {
$handler = [
'className' => $handler,
];
}
if (!isset($handler['className'])) {
throw new RuntimeException('Missing `className` key from handler config.');
}
return HandlerFactory::create($handler['className']);
} | php | protected function getHandler()
{
$handler = $this->getConfig('unauthorizedHandler');
if (!is_array($handler)) {
$handler = [
'className' => $handler,
];
}
if (!isset($handler['className'])) {
throw new RuntimeException('Missing `className` key from handler config.');
}
return HandlerFactory::create($handler['className']);
} | [
"protected",
"function",
"getHandler",
"(",
")",
"{",
"$",
"handler",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'unauthorizedHandler'",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"handler",
")",
")",
"{",
"$",
"handler",
"=",
"[",
"'className'",
... | Returns unauthorized handler.
@return \Authorization\Middleware\UnauthorizedHandler\HandlerInterface | [
"Returns",
"unauthorized",
"handler",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Middleware/AuthorizationMiddleware.php#L130-L143 | train |
cakephp/authorization | src/Middleware/AuthorizationMiddleware.php | AuthorizationMiddleware.getAuthorizationService | protected function getAuthorizationService($request, $response)
{
$service = $this->subject;
if ($this->subject instanceof AuthorizationServiceProviderInterface) {
$service = $this->subject->getAuthorizationService($request, $response);
}
if (!$service instanceof AuthorizationServiceInterface) {
throw new RuntimeException(sprintf(
'Invalid service returned from the provider. `%s` does not implement `%s`.',
is_object($service) ? get_class($service) : gettype($service),
AuthorizationServiceInterface::class
));
}
return $service;
} | php | protected function getAuthorizationService($request, $response)
{
$service = $this->subject;
if ($this->subject instanceof AuthorizationServiceProviderInterface) {
$service = $this->subject->getAuthorizationService($request, $response);
}
if (!$service instanceof AuthorizationServiceInterface) {
throw new RuntimeException(sprintf(
'Invalid service returned from the provider. `%s` does not implement `%s`.',
is_object($service) ? get_class($service) : gettype($service),
AuthorizationServiceInterface::class
));
}
return $service;
} | [
"protected",
"function",
"getAuthorizationService",
"(",
"$",
"request",
",",
"$",
"response",
")",
"{",
"$",
"service",
"=",
"$",
"this",
"->",
"subject",
";",
"if",
"(",
"$",
"this",
"->",
"subject",
"instanceof",
"AuthorizationServiceProviderInterface",
")",
... | Returns AuthorizationServiceInterface instance.
@param \Psr\Http\Message\ServerRequestInterface $request Server request.
@param \Psr\Http\Message\ResponseInterface $response Response.
@return \Authorization\AuthorizationServiceInterface
@throws \RuntimeException When authorization method has not been defined. | [
"Returns",
"AuthorizationServiceInterface",
"instance",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Middleware/AuthorizationMiddleware.php#L153-L169 | train |
cakephp/authorization | src/Middleware/AuthorizationMiddleware.php | AuthorizationMiddleware.buildIdentity | protected function buildIdentity(AuthorizationServiceInterface $service, $identity)
{
$class = $this->getConfig('identityDecorator');
if (is_callable($class)) {
$identity = $class($service, $identity);
} else {
if (!$identity instanceof IdentityInterface) {
$identity = new $class($service, $identity);
}
}
if (!$identity instanceof IdentityInterface) {
throw new RuntimeException(sprintf(
'Invalid identity returned by decorator. `%s` does not implement `%s`.',
is_object($identity) ? get_class($identity) : gettype($identity),
IdentityInterface::class
));
}
return $identity;
} | php | protected function buildIdentity(AuthorizationServiceInterface $service, $identity)
{
$class = $this->getConfig('identityDecorator');
if (is_callable($class)) {
$identity = $class($service, $identity);
} else {
if (!$identity instanceof IdentityInterface) {
$identity = new $class($service, $identity);
}
}
if (!$identity instanceof IdentityInterface) {
throw new RuntimeException(sprintf(
'Invalid identity returned by decorator. `%s` does not implement `%s`.',
is_object($identity) ? get_class($identity) : gettype($identity),
IdentityInterface::class
));
}
return $identity;
} | [
"protected",
"function",
"buildIdentity",
"(",
"AuthorizationServiceInterface",
"$",
"service",
",",
"$",
"identity",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'identityDecorator'",
")",
";",
"if",
"(",
"is_callable",
"(",
"$",
"class"... | Builds the identity object.
@param \Authorization\AuthorizationServiceInterface $service Authorization service.
@param \ArrayAccess|array $identity Identity data
@return \Authorization\IdentityInterface | [
"Builds",
"the",
"identity",
"object",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Middleware/AuthorizationMiddleware.php#L178-L199 | train |
cakephp/authorization | src/Middleware/UnauthorizedHandler/HandlerFactory.php | HandlerFactory.create | public static function create($name)
{
$class = App::className($name, 'Middleware/UnauthorizedHandler', 'Handler');
if (!$class) {
$message = sprintf('Handler `%s` does not exist.', $name);
throw new RuntimeException($message);
}
$instance = new $class();
if (!$instance instanceof HandlerInterface) {
$message = sprintf('Handler should implement `%s`, got `%s`.', HandlerInterface::class, get_class($instance));
throw new RuntimeException($message);
}
return $instance;
} | php | public static function create($name)
{
$class = App::className($name, 'Middleware/UnauthorizedHandler', 'Handler');
if (!$class) {
$message = sprintf('Handler `%s` does not exist.', $name);
throw new RuntimeException($message);
}
$instance = new $class();
if (!$instance instanceof HandlerInterface) {
$message = sprintf('Handler should implement `%s`, got `%s`.', HandlerInterface::class, get_class($instance));
throw new RuntimeException($message);
}
return $instance;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"name",
")",
"{",
"$",
"class",
"=",
"App",
"::",
"className",
"(",
"$",
"name",
",",
"'Middleware/UnauthorizedHandler'",
",",
"'Handler'",
")",
";",
"if",
"(",
"!",
"$",
"class",
")",
"{",
"$",
"mess... | Creates unauthorized request handler.
@param string $name UnauthorizedHandler name.
@return \Authorization\Middleware\UnauthorizedHandler\HandlerInterface
@throws \RuntimeException When invalid handler encountered. | [
"Creates",
"unauthorized",
"request",
"handler",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Middleware/UnauthorizedHandler/HandlerFactory.php#L32-L47 | train |
cakephp/authorization | src/Middleware/RequestAuthorizationMiddleware.php | RequestAuthorizationMiddleware.getServiceFromRequest | protected function getServiceFromRequest(ServerRequestInterface $request)
{
$serviceAttribute = $this->getConfig('authorizationAttribute');
$service = ($request->getAttribute($serviceAttribute));
if (!$service instanceof AuthorizationServiceInterface) {
$errorMessage = __CLASS__ . ' could not find the authorization service in the request attribute. ' .
'Make sure you added the AuthorizationMiddleware before this middleware or that you ' .
'somehow else added the service to the requests `' . $serviceAttribute . '` attribute.';
throw new RuntimeException($errorMessage);
}
return $service;
} | php | protected function getServiceFromRequest(ServerRequestInterface $request)
{
$serviceAttribute = $this->getConfig('authorizationAttribute');
$service = ($request->getAttribute($serviceAttribute));
if (!$service instanceof AuthorizationServiceInterface) {
$errorMessage = __CLASS__ . ' could not find the authorization service in the request attribute. ' .
'Make sure you added the AuthorizationMiddleware before this middleware or that you ' .
'somehow else added the service to the requests `' . $serviceAttribute . '` attribute.';
throw new RuntimeException($errorMessage);
}
return $service;
} | [
"protected",
"function",
"getServiceFromRequest",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"serviceAttribute",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'authorizationAttribute'",
")",
";",
"$",
"service",
"=",
"(",
"$",
"request",
"->",
"g... | Gets the authorization service from the request attribute
@param \Psr\Http\Message\ServerRequestInterface $request Server request.
@return \Authorization\AuthorizationServiceInterface | [
"Gets",
"the",
"authorization",
"service",
"from",
"the",
"request",
"attribute"
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Middleware/RequestAuthorizationMiddleware.php#L68-L82 | train |
cakephp/authorization | src/Policy/OrmResolver.php | OrmResolver.getPolicy | public function getPolicy($resource)
{
if ($resource instanceof EntityInterface) {
return $this->getEntityPolicy($resource);
}
if ($resource instanceof RepositoryInterface) {
return $this->getRepositoryPolicy($resource);
}
if ($resource instanceof QueryInterface) {
return $this->getRepositoryPolicy($resource->repository());
}
$name = is_object($resource) ? get_class($resource) : gettype($resource);
throw new MissingPolicyException([$name]);
} | php | public function getPolicy($resource)
{
if ($resource instanceof EntityInterface) {
return $this->getEntityPolicy($resource);
}
if ($resource instanceof RepositoryInterface) {
return $this->getRepositoryPolicy($resource);
}
if ($resource instanceof QueryInterface) {
return $this->getRepositoryPolicy($resource->repository());
}
$name = is_object($resource) ? get_class($resource) : gettype($resource);
throw new MissingPolicyException([$name]);
} | [
"public",
"function",
"getPolicy",
"(",
"$",
"resource",
")",
"{",
"if",
"(",
"$",
"resource",
"instanceof",
"EntityInterface",
")",
"{",
"return",
"$",
"this",
"->",
"getEntityPolicy",
"(",
"$",
"resource",
")",
";",
"}",
"if",
"(",
"$",
"resource",
"in... | Get a policy for an ORM Table, Entity or Query.
@param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\EntityInterface|\Cake\Datasource\QueryInterface $resource The resource.
@return object
@throws \Authorization\Policy\Exception\MissingPolicyException When a policy for the
resource has not been defined or cannot be resolved. | [
"Get",
"a",
"policy",
"for",
"an",
"ORM",
"Table",
"Entity",
"or",
"Query",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Policy/OrmResolver.php#L63-L76 | train |
cakephp/authorization | src/Policy/OrmResolver.php | OrmResolver.getEntityPolicy | protected function getEntityPolicy(EntityInterface $entity)
{
$class = get_class($entity);
$entityNamespace = '\Model\Entity\\';
$namespace = str_replace('\\', '/', substr($class, 0, strpos($class, $entityNamespace)));
$name = substr($class, strpos($class, $entityNamespace) + strlen($entityNamespace));
return $this->findPolicy($class, $name, $namespace);
} | php | protected function getEntityPolicy(EntityInterface $entity)
{
$class = get_class($entity);
$entityNamespace = '\Model\Entity\\';
$namespace = str_replace('\\', '/', substr($class, 0, strpos($class, $entityNamespace)));
$name = substr($class, strpos($class, $entityNamespace) + strlen($entityNamespace));
return $this->findPolicy($class, $name, $namespace);
} | [
"protected",
"function",
"getEntityPolicy",
"(",
"EntityInterface",
"$",
"entity",
")",
"{",
"$",
"class",
"=",
"get_class",
"(",
"$",
"entity",
")",
";",
"$",
"entityNamespace",
"=",
"'\\Model\\Entity\\\\'",
";",
"$",
"namespace",
"=",
"str_replace",
"(",
"'\... | Get a policy for an entity
@param \Cake\Datasource\EntityInterface $entity The entity to get a policy for
@return object | [
"Get",
"a",
"policy",
"for",
"an",
"entity"
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Policy/OrmResolver.php#L84-L92 | train |
cakephp/authorization | src/Policy/OrmResolver.php | OrmResolver.getRepositoryPolicy | protected function getRepositoryPolicy(RepositoryInterface $table)
{
$class = get_class($table);
$tableNamespace = '\Model\Table\\';
$namespace = str_replace('\\', '/', substr($class, 0, strpos($class, $tableNamespace)));
$name = substr($class, strpos($class, $tableNamespace) + strlen($tableNamespace));
return $this->findPolicy($class, $name, $namespace);
} | php | protected function getRepositoryPolicy(RepositoryInterface $table)
{
$class = get_class($table);
$tableNamespace = '\Model\Table\\';
$namespace = str_replace('\\', '/', substr($class, 0, strpos($class, $tableNamespace)));
$name = substr($class, strpos($class, $tableNamespace) + strlen($tableNamespace));
return $this->findPolicy($class, $name, $namespace);
} | [
"protected",
"function",
"getRepositoryPolicy",
"(",
"RepositoryInterface",
"$",
"table",
")",
"{",
"$",
"class",
"=",
"get_class",
"(",
"$",
"table",
")",
";",
"$",
"tableNamespace",
"=",
"'\\Model\\Table\\\\'",
";",
"$",
"namespace",
"=",
"str_replace",
"(",
... | Get a policy for a table
@param \Cake\Datasource\RepositoryInterface $table The table/repository to get a policy for.
@return object | [
"Get",
"a",
"policy",
"for",
"a",
"table"
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Policy/OrmResolver.php#L100-L108 | train |
cakephp/authorization | src/Policy/OrmResolver.php | OrmResolver.findPolicy | protected function findPolicy($class, $name, $namespace)
{
$namespace = $this->getNamespace($namespace);
$policyClass = false;
// plugin entities can have application overides defined.
if ($namespace !== $this->appNamespace) {
$policyClass = App::className($name, 'Policy\\' . $namespace, 'Policy');
}
// Check the application/plugin.
if ($policyClass === false) {
$policyClass = App::className($namespace . '.' . $name, 'Policy', 'Policy');
}
if ($policyClass === false) {
throw new MissingPolicyException([$class]);
}
return new $policyClass();
} | php | protected function findPolicy($class, $name, $namespace)
{
$namespace = $this->getNamespace($namespace);
$policyClass = false;
// plugin entities can have application overides defined.
if ($namespace !== $this->appNamespace) {
$policyClass = App::className($name, 'Policy\\' . $namespace, 'Policy');
}
// Check the application/plugin.
if ($policyClass === false) {
$policyClass = App::className($namespace . '.' . $name, 'Policy', 'Policy');
}
if ($policyClass === false) {
throw new MissingPolicyException([$class]);
}
return new $policyClass();
} | [
"protected",
"function",
"findPolicy",
"(",
"$",
"class",
",",
"$",
"name",
",",
"$",
"namespace",
")",
"{",
"$",
"namespace",
"=",
"$",
"this",
"->",
"getNamespace",
"(",
"$",
"namespace",
")",
";",
"$",
"policyClass",
"=",
"false",
";",
"// plugin enti... | Locate a policy class using conventions
@param string $class The full class name.
@param string $name The name suffix of the resource.
@param string $namespace The namespace to find the policy in.
@throws \Authorization\Policy\Exception\MissingPolicyException When a policy for the
resource has not been defined.
@return object | [
"Locate",
"a",
"policy",
"class",
"using",
"conventions"
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Policy/OrmResolver.php#L120-L140 | train |
cakephp/authorization | src/AuthorizationService.php | AuthorizationService.getCanHandler | protected function getCanHandler($policy, $action)
{
$method = 'can' . ucfirst($action);
if (!method_exists($policy, $method) && !method_exists($policy, '__call')) {
throw new MissingMethodException([$method, $action, get_class($policy)]);
}
return [$policy, $method];
} | php | protected function getCanHandler($policy, $action)
{
$method = 'can' . ucfirst($action);
if (!method_exists($policy, $method) && !method_exists($policy, '__call')) {
throw new MissingMethodException([$method, $action, get_class($policy)]);
}
return [$policy, $method];
} | [
"protected",
"function",
"getCanHandler",
"(",
"$",
"policy",
",",
"$",
"action",
")",
"{",
"$",
"method",
"=",
"'can'",
".",
"ucfirst",
"(",
"$",
"action",
")",
";",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"policy",
",",
"$",
"method",
")",
"&&",... | Returns a policy action handler.
@param mixed $policy Policy object.
@param string $action Action name.
@return callable
@throws \Authorization\Policy\Exception\MissingMethodException | [
"Returns",
"a",
"policy",
"action",
"handler",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/AuthorizationService.php#L98-L107 | train |
cakephp/authorization | src/AuthorizationService.php | AuthorizationService.getScopeHandler | protected function getScopeHandler($policy, $action)
{
$method = 'scope' . ucfirst($action);
if (!method_exists($policy, $method)) {
throw new MissingMethodException([$method, $action, get_class($policy)]);
}
return [$policy, $method];
} | php | protected function getScopeHandler($policy, $action)
{
$method = 'scope' . ucfirst($action);
if (!method_exists($policy, $method)) {
throw new MissingMethodException([$method, $action, get_class($policy)]);
}
return [$policy, $method];
} | [
"protected",
"function",
"getScopeHandler",
"(",
"$",
"policy",
",",
"$",
"action",
")",
"{",
"$",
"method",
"=",
"'scope'",
".",
"ucfirst",
"(",
"$",
"action",
")",
";",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"policy",
",",
"$",
"method",
")",
"... | Returns a policy scope action handler.
@param mixed $policy Policy object.
@param string $action Action name.
@return callable
@throws \Authorization\Policy\Exception\MissingMethodException | [
"Returns",
"a",
"policy",
"scope",
"action",
"handler",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/AuthorizationService.php#L117-L126 | train |
cakephp/authorization | src/Policy/MapResolver.php | MapResolver.map | public function map($resourceClass, $policy)
{
if (!class_exists($resourceClass)) {
$message = sprintf('Resource class `%s` does not exist.', $resourceClass);
throw new InvalidArgumentException($message);
}
if (!is_string($policy) && !is_object($policy) && !is_callable($policy)) {
$message = sprintf(
'Policy must be a valid class name, an object or a callable, `%s` given.',
gettype($policy)
);
throw new InvalidArgumentException($message);
}
if (is_string($policy) && !class_exists($policy)) {
$message = sprintf('Policy class `%s` does not exist.', $policy);
throw new InvalidArgumentException($message);
}
$this->map[$resourceClass] = $policy;
return $this;
} | php | public function map($resourceClass, $policy)
{
if (!class_exists($resourceClass)) {
$message = sprintf('Resource class `%s` does not exist.', $resourceClass);
throw new InvalidArgumentException($message);
}
if (!is_string($policy) && !is_object($policy) && !is_callable($policy)) {
$message = sprintf(
'Policy must be a valid class name, an object or a callable, `%s` given.',
gettype($policy)
);
throw new InvalidArgumentException($message);
}
if (is_string($policy) && !class_exists($policy)) {
$message = sprintf('Policy class `%s` does not exist.', $policy);
throw new InvalidArgumentException($message);
}
$this->map[$resourceClass] = $policy;
return $this;
} | [
"public",
"function",
"map",
"(",
"$",
"resourceClass",
",",
"$",
"policy",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"resourceClass",
")",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"'Resource class `%s` does not exist.'",
",",
"$",
"resourceC... | Maps a resource class to the policy class name.
@param string $resourceClass A resource class name.
@param string|object|callable $policy A policy class name, an object or a callable factory.
@return $this
@throws \InvalidArgumentException When a resource class does not exist or policy is invalid. | [
"Maps",
"a",
"resource",
"class",
"to",
"the",
"policy",
"class",
"name",
"."
] | 34ad2eb01433077d2a1c66f57891bdbd099ce987 | https://github.com/cakephp/authorization/blob/34ad2eb01433077d2a1c66f57891bdbd099ce987/src/Policy/MapResolver.php#L62-L84 | train |
edamov/pushok | src/Response.php | Response.fetchApnsId | private static function fetchApnsId(string $headers): string
{
$data = explode("\n", trim($headers));
foreach ($data as $part) {
$middle = explode(":", $part);
if ($middle[0] !== 'apns-id') {
continue;
}
return trim($middle[1]);
}
return '';
} | php | private static function fetchApnsId(string $headers): string
{
$data = explode("\n", trim($headers));
foreach ($data as $part) {
$middle = explode(":", $part);
if ($middle[0] !== 'apns-id') {
continue;
}
return trim($middle[1]);
}
return '';
} | [
"private",
"static",
"function",
"fetchApnsId",
"(",
"string",
"$",
"headers",
")",
":",
"string",
"{",
"$",
"data",
"=",
"explode",
"(",
"\"\\n\"",
",",
"trim",
"(",
"$",
"headers",
")",
")",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"part",
")",... | Fetch APNs Id from response headers.
@param string $headers
@return string | [
"Fetch",
"APNs",
"Id",
"from",
"response",
"headers",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Response.php#L166-L181 | train |
edamov/pushok | src/Response.php | Response.getErrorDescription | public function getErrorDescription(): string
{
if (isset(self::$errorReasons[$this->statusCode][$this->errorReason])) {
return self::$errorReasons[$this->statusCode][$this->errorReason];
}
return '';
} | php | public function getErrorDescription(): string
{
if (isset(self::$errorReasons[$this->statusCode][$this->errorReason])) {
return self::$errorReasons[$this->statusCode][$this->errorReason];
}
return '';
} | [
"public",
"function",
"getErrorDescription",
"(",
")",
":",
"string",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"errorReasons",
"[",
"$",
"this",
"->",
"statusCode",
"]",
"[",
"$",
"this",
"->",
"errorReason",
"]",
")",
")",
"{",
"return",
"self... | Get error description.
@return string | [
"Get",
"error",
"description",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Response.php#L265-L272 | train |
edamov/pushok | src/AuthProvider/Token.php | Token.create | public static function create(array $options): Token
{
$token = new self($options);
$token->token = $token->generate();
return $token;
} | php | public static function create(array $options): Token
{
$token = new self($options);
$token->token = $token->generate();
return $token;
} | [
"public",
"static",
"function",
"create",
"(",
"array",
"$",
"options",
")",
":",
"Token",
"{",
"$",
"token",
"=",
"new",
"self",
"(",
"$",
"options",
")",
";",
"$",
"token",
"->",
"token",
"=",
"$",
"token",
"->",
"generate",
"(",
")",
";",
"retur... | Create Token Auth Provider.
@param array $options
@return Token | [
"Create",
"Token",
"Auth",
"Provider",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/AuthProvider/Token.php#L100-L106 | train |
edamov/pushok | src/AuthProvider/Token.php | Token.useExisting | public static function useExisting(string $tokenString, array $options): Token
{
$token = new self($options);
$token->token = $tokenString;
return $token;
} | php | public static function useExisting(string $tokenString, array $options): Token
{
$token = new self($options);
$token->token = $tokenString;
return $token;
} | [
"public",
"static",
"function",
"useExisting",
"(",
"string",
"$",
"tokenString",
",",
"array",
"$",
"options",
")",
":",
"Token",
"{",
"$",
"token",
"=",
"new",
"self",
"(",
"$",
"options",
")",
";",
"$",
"token",
"->",
"token",
"=",
"$",
"tokenString... | Use previously generated token.
@param string $tokenString
@param array $options
@return Token | [
"Use",
"previously",
"generated",
"token",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/AuthProvider/Token.php#L115-L121 | train |
edamov/pushok | src/AuthProvider/Token.php | Token.generatePrivateECKey | private function generatePrivateECKey(): JWK
{
return JWKFactory::createFromKeyFile($this->privateKeyPath, $this->privateKeySecret, [
'kid' => $this->keyId,
'alg' => 'ES512',
'use' => 'sig'
]);
} | php | private function generatePrivateECKey(): JWK
{
return JWKFactory::createFromKeyFile($this->privateKeyPath, $this->privateKeySecret, [
'kid' => $this->keyId,
'alg' => 'ES512',
'use' => 'sig'
]);
} | [
"private",
"function",
"generatePrivateECKey",
"(",
")",
":",
"JWK",
"{",
"return",
"JWKFactory",
"::",
"createFromKeyFile",
"(",
"$",
"this",
"->",
"privateKeyPath",
",",
"$",
"this",
"->",
"privateKeySecret",
",",
"[",
"'kid'",
"=>",
"$",
"this",
"->",
"ke... | Generate private EC key.
@return JWK | [
"Generate",
"private",
"EC",
"key",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/AuthProvider/Token.php#L151-L158 | train |
edamov/pushok | src/Payload.php | Payload.setAlert | public function setAlert($alert): Payload
{
if ($alert instanceof Alert || is_string($alert)) {
$this->alert = $alert;
}
return $this;
} | php | public function setAlert($alert): Payload
{
if ($alert instanceof Alert || is_string($alert)) {
$this->alert = $alert;
}
return $this;
} | [
"public",
"function",
"setAlert",
"(",
"$",
"alert",
")",
":",
"Payload",
"{",
"if",
"(",
"$",
"alert",
"instanceof",
"Alert",
"||",
"is_string",
"(",
"$",
"alert",
")",
")",
"{",
"$",
"this",
"->",
"alert",
"=",
"$",
"alert",
";",
"}",
"return",
"... | Set Alert.
@param Alert|string $alert
@return Payload | [
"Set",
"Alert",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Payload.php#L112-L119 | train |
edamov/pushok | src/Payload.php | Payload.setCustomValue | public function setCustomValue(string $key, $value): Payload
{
if ($key === self::PAYLOAD_ROOT_KEY) {
throw InvalidPayloadException::reservedKey();
}
$this->customValues[$key] = $value;
return $this;
} | php | public function setCustomValue(string $key, $value): Payload
{
if ($key === self::PAYLOAD_ROOT_KEY) {
throw InvalidPayloadException::reservedKey();
}
$this->customValues[$key] = $value;
return $this;
} | [
"public",
"function",
"setCustomValue",
"(",
"string",
"$",
"key",
",",
"$",
"value",
")",
":",
"Payload",
"{",
"if",
"(",
"$",
"key",
"===",
"self",
"::",
"PAYLOAD_ROOT_KEY",
")",
"{",
"throw",
"InvalidPayloadException",
"::",
"reservedKey",
"(",
")",
";"... | Set custom value for Payload.
@param string $key
@param mixed $value
@return Payload
@throws InvalidPayloadException | [
"Set",
"custom",
"value",
"for",
"Payload",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Payload.php#L278-L287 | train |
edamov/pushok | src/Payload.php | Payload.getCustomValue | public function getCustomValue($key)
{
if (!array_key_exists($key, $this->customValues)) {
throw InvalidPayloadException::notExistingCustomValue($key);
}
return $this->customValues[$key];
} | php | public function getCustomValue($key)
{
if (!array_key_exists($key, $this->customValues)) {
throw InvalidPayloadException::notExistingCustomValue($key);
}
return $this->customValues[$key];
} | [
"public",
"function",
"getCustomValue",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"customValues",
")",
")",
"{",
"throw",
"InvalidPayloadException",
"::",
"notExistingCustomValue",
"(",
"$",
"key"... | Get custom value.
@param $key
@return mixed
@throws InvalidPayloadException | [
"Get",
"custom",
"value",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Payload.php#L296-L303 | train |
edamov/pushok | src/Request.php | Request.getDecoratedHeaders | public function getDecoratedHeaders(): array
{
$decoratedHeaders = [];
foreach ($this->headers as $name => $value) {
$decoratedHeaders[] = $name . ': ' . $value;
}
return $decoratedHeaders;
} | php | public function getDecoratedHeaders(): array
{
$decoratedHeaders = [];
foreach ($this->headers as $name => $value) {
$decoratedHeaders[] = $name . ': ' . $value;
}
return $decoratedHeaders;
} | [
"public",
"function",
"getDecoratedHeaders",
"(",
")",
":",
"array",
"{",
"$",
"decoratedHeaders",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"headers",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"decoratedHeaders",
"[",
"]",
"="... | Get decorated request headers.
@return array | [
"Get",
"decorated",
"request",
"headers",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Request.php#L120-L127 | train |
edamov/pushok | src/Request.php | Request.prepareApnsHeaders | private function prepareApnsHeaders(Notification $notification)
{
if (!empty($notification->getId())) {
$this->headers[self::HEADER_APNS_ID] = $notification->getId();
}
if ($notification->getExpirationAt() instanceof \DateTime) {
$this->headers[self::HEADER_APNS_EXPIRATION] = $notification->getExpirationAt()->getTimestamp();
}
if (is_int($notification->getPriority())) {
$this->headers[self::HEADER_APNS_PRIORITY] = $notification->getPriority();
}
if (!empty($notification->getCollapseId())) {
$this->headers[self::HEADER_APNS_COLLAPSE_ID ] = $notification->getCollapseId();
}
} | php | private function prepareApnsHeaders(Notification $notification)
{
if (!empty($notification->getId())) {
$this->headers[self::HEADER_APNS_ID] = $notification->getId();
}
if ($notification->getExpirationAt() instanceof \DateTime) {
$this->headers[self::HEADER_APNS_EXPIRATION] = $notification->getExpirationAt()->getTimestamp();
}
if (is_int($notification->getPriority())) {
$this->headers[self::HEADER_APNS_PRIORITY] = $notification->getPriority();
}
if (!empty($notification->getCollapseId())) {
$this->headers[self::HEADER_APNS_COLLAPSE_ID ] = $notification->getCollapseId();
}
} | [
"private",
"function",
"prepareApnsHeaders",
"(",
"Notification",
"$",
"notification",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"notification",
"->",
"getId",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"headers",
"[",
"self",
"::",
"HEADER_APNS_ID",
... | Prepare APNs headers before sending request.
@param Notification $notification | [
"Prepare",
"APNs",
"headers",
"before",
"sending",
"request",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Request.php#L197-L214 | train |
edamov/pushok | src/Client.php | Client.push | public function push(): array
{
$responseCollection = [];
if (!$this->curlMultiHandle) {
$this->curlMultiHandle = curl_multi_init();
if (!defined('CURLPIPE_MULTIPLEX')) {
define('CURLPIPE_MULTIPLEX', 2);
}
curl_multi_setopt($this->curlMultiHandle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
curl_multi_setopt($this->curlMultiHandle, CURLMOPT_MAX_HOST_CONNECTIONS, $this->maxConcurrentConnections);
}
$mh = $this->curlMultiHandle;
$i = 0;
while (!empty($this->notifications) && $i++ < $this->nbConcurrentRequests) {
$notification = array_pop($this->notifications);
curl_multi_add_handle($mh, $this->prepareHandle($notification));
}
// Clear out curl handle buffer
do {
$execrun = curl_multi_exec($mh, $running);
} while ($execrun === CURLM_CALL_MULTI_PERFORM);
// Continue processing while we have active curl handles
while ($running > 0 && $execrun === CURLM_OK) {
// Block until data is available
$select_fd = curl_multi_select($mh);
// If select returns -1 while running, wait 250 microseconds before continuing
// Using curl_multi_timeout would be better but it isn't available in PHP yet
// https://php.net/manual/en/function.curl-multi-select.php#115381
if ($running && $select_fd === -1) {
usleep(250);
}
// Continue to wait for more data if needed
do {
$execrun = curl_multi_exec($mh, $running);
} while ($execrun === CURLM_CALL_MULTI_PERFORM);
// Start reading results
while ($done = curl_multi_info_read($mh)) {
$handle = $done['handle'];
$result = curl_multi_getcontent($handle);
// find out which token the response is about
$token = curl_getinfo($handle, CURLINFO_PRIVATE);
$responseParts = explode("\r\n\r\n", $result, 2);
$headers = '';
$body = '';
if (isset($responseParts[0])) {
$headers = $responseParts[0];
}
if (isset($responseParts[1])) {
$body = $responseParts[1];
}
$statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$responseCollection[] = new Response($statusCode, $headers, (string)$body, $token);
curl_multi_remove_handle($mh, $handle);
curl_close($handle);
if (!empty($this->notifications)) {
$notification = array_pop($this->notifications);
curl_multi_add_handle($mh, $this->prepareHandle($notification));
}
}
}
if ($this->autoCloseConnections) {
curl_multi_close($mh);
$this->curlMultiHandle = null;
}
return $responseCollection;
} | php | public function push(): array
{
$responseCollection = [];
if (!$this->curlMultiHandle) {
$this->curlMultiHandle = curl_multi_init();
if (!defined('CURLPIPE_MULTIPLEX')) {
define('CURLPIPE_MULTIPLEX', 2);
}
curl_multi_setopt($this->curlMultiHandle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
curl_multi_setopt($this->curlMultiHandle, CURLMOPT_MAX_HOST_CONNECTIONS, $this->maxConcurrentConnections);
}
$mh = $this->curlMultiHandle;
$i = 0;
while (!empty($this->notifications) && $i++ < $this->nbConcurrentRequests) {
$notification = array_pop($this->notifications);
curl_multi_add_handle($mh, $this->prepareHandle($notification));
}
// Clear out curl handle buffer
do {
$execrun = curl_multi_exec($mh, $running);
} while ($execrun === CURLM_CALL_MULTI_PERFORM);
// Continue processing while we have active curl handles
while ($running > 0 && $execrun === CURLM_OK) {
// Block until data is available
$select_fd = curl_multi_select($mh);
// If select returns -1 while running, wait 250 microseconds before continuing
// Using curl_multi_timeout would be better but it isn't available in PHP yet
// https://php.net/manual/en/function.curl-multi-select.php#115381
if ($running && $select_fd === -1) {
usleep(250);
}
// Continue to wait for more data if needed
do {
$execrun = curl_multi_exec($mh, $running);
} while ($execrun === CURLM_CALL_MULTI_PERFORM);
// Start reading results
while ($done = curl_multi_info_read($mh)) {
$handle = $done['handle'];
$result = curl_multi_getcontent($handle);
// find out which token the response is about
$token = curl_getinfo($handle, CURLINFO_PRIVATE);
$responseParts = explode("\r\n\r\n", $result, 2);
$headers = '';
$body = '';
if (isset($responseParts[0])) {
$headers = $responseParts[0];
}
if (isset($responseParts[1])) {
$body = $responseParts[1];
}
$statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$responseCollection[] = new Response($statusCode, $headers, (string)$body, $token);
curl_multi_remove_handle($mh, $handle);
curl_close($handle);
if (!empty($this->notifications)) {
$notification = array_pop($this->notifications);
curl_multi_add_handle($mh, $this->prepareHandle($notification));
}
}
}
if ($this->autoCloseConnections) {
curl_multi_close($mh);
$this->curlMultiHandle = null;
}
return $responseCollection;
} | [
"public",
"function",
"push",
"(",
")",
":",
"array",
"{",
"$",
"responseCollection",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"curlMultiHandle",
")",
"{",
"$",
"this",
"->",
"curlMultiHandle",
"=",
"curl_multi_init",
"(",
")",
";",
"if",... | Push notifications to APNs.
@return ApnsResponseInterface[] | [
"Push",
"notifications",
"to",
"APNs",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Client.php#L86-L167 | train |
edamov/pushok | src/Client.php | Client.prepareHandle | private function prepareHandle(Notification $notification)
{
$request = new Request($notification, $this->isProductionEnv);
$ch = curl_init();
$this->authProvider->authenticateClient($request);
curl_setopt_array($ch, $request->getOptions());
curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getDecoratedHeaders());
// store device token to identify response
curl_setopt($ch, CURLOPT_PRIVATE, $notification->getDeviceToken());
return $ch;
} | php | private function prepareHandle(Notification $notification)
{
$request = new Request($notification, $this->isProductionEnv);
$ch = curl_init();
$this->authProvider->authenticateClient($request);
curl_setopt_array($ch, $request->getOptions());
curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getDecoratedHeaders());
// store device token to identify response
curl_setopt($ch, CURLOPT_PRIVATE, $notification->getDeviceToken());
return $ch;
} | [
"private",
"function",
"prepareHandle",
"(",
"Notification",
"$",
"notification",
")",
"{",
"$",
"request",
"=",
"new",
"Request",
"(",
"$",
"notification",
",",
"$",
"this",
"->",
"isProductionEnv",
")",
";",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
... | Prepares a curl handle from a Notification object.
@param Notification $notification | [
"Prepares",
"a",
"curl",
"handle",
"from",
"a",
"Notification",
"object",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Client.php#L174-L188 | train |
edamov/pushok | src/Client.php | Client.addNotifications | public function addNotifications(array $notifications)
{
foreach ($notifications as $notification) {
if (in_array($notification, $this->notifications, true)) {
continue;
}
$this->addNotification($notification);
}
} | php | public function addNotifications(array $notifications)
{
foreach ($notifications as $notification) {
if (in_array($notification, $this->notifications, true)) {
continue;
}
$this->addNotification($notification);
}
} | [
"public",
"function",
"addNotifications",
"(",
"array",
"$",
"notifications",
")",
"{",
"foreach",
"(",
"$",
"notifications",
"as",
"$",
"notification",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"notification",
",",
"$",
"this",
"->",
"notifications",
",",
... | Add several notifications in queue for sending.
@param Notification[] $notifications | [
"Add",
"several",
"notifications",
"in",
"queue",
"for",
"sending",
"."
] | 7fdfd1efd9c8c968bee58cb4a8faa41070dfebba | https://github.com/edamov/pushok/blob/7fdfd1efd9c8c968bee58cb4a8faa41070dfebba/src/Client.php#L205-L214 | train |
cakephp/authentication | src/AuthenticationService.php | AuthenticationService.identifiers | public function identifiers()
{
if (!$this->_identifiers) {
$this->_identifiers = new IdentifierCollection($this->getConfig('identifiers'));
}
return $this->_identifiers;
} | php | public function identifiers()
{
if (!$this->_identifiers) {
$this->_identifiers = new IdentifierCollection($this->getConfig('identifiers'));
}
return $this->_identifiers;
} | [
"public",
"function",
"identifiers",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_identifiers",
")",
"{",
"$",
"this",
"->",
"_identifiers",
"=",
"new",
"IdentifierCollection",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'identifiers'",
")",
")",
"... | Access the identifier collection
@return \Authentication\Identifier\IdentifierCollection | [
"Access",
"the",
"identifier",
"collection"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/AuthenticationService.php#L107-L114 | train |
cakephp/authentication | src/AuthenticationService.php | AuthenticationService.authenticators | public function authenticators()
{
if (!$this->_authenticators) {
$identifiers = $this->identifiers();
$authenticators = $this->getConfig('authenticators');
$this->_authenticators = new AuthenticatorCollection($identifiers, $authenticators);
}
return $this->_authenticators;
} | php | public function authenticators()
{
if (!$this->_authenticators) {
$identifiers = $this->identifiers();
$authenticators = $this->getConfig('authenticators');
$this->_authenticators = new AuthenticatorCollection($identifiers, $authenticators);
}
return $this->_authenticators;
} | [
"public",
"function",
"authenticators",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_authenticators",
")",
"{",
"$",
"identifiers",
"=",
"$",
"this",
"->",
"identifiers",
"(",
")",
";",
"$",
"authenticators",
"=",
"$",
"this",
"->",
"getConfig",
... | Access the authenticator collection
@return \Authentication\Authenticator\AuthenticatorCollection | [
"Access",
"the",
"authenticator",
"collection"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/AuthenticationService.php#L121-L130 | train |
cakephp/authentication | src/AuthenticationService.php | AuthenticationService.clearIdentity | public function clearIdentity(ServerRequestInterface $request, ResponseInterface $response)
{
foreach ($this->authenticators() as $authenticator) {
if ($authenticator instanceof PersistenceInterface) {
$result = $authenticator->clearIdentity($request, $response);
$request = $result['request'];
$response = $result['response'];
}
}
return [
'request' => $request->withoutAttribute($this->getConfig('identityAttribute')),
'response' => $response
];
} | php | public function clearIdentity(ServerRequestInterface $request, ResponseInterface $response)
{
foreach ($this->authenticators() as $authenticator) {
if ($authenticator instanceof PersistenceInterface) {
$result = $authenticator->clearIdentity($request, $response);
$request = $result['request'];
$response = $result['response'];
}
}
return [
'request' => $request->withoutAttribute($this->getConfig('identityAttribute')),
'response' => $response
];
} | [
"public",
"function",
"clearIdentity",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"authenticators",
"(",
")",
"as",
"$",
"authenticator",
")",
"{",
"if",
"(",
"$",
"a... | Clears the identity from authenticators that store them and the request
@param \Psr\Http\Message\ServerRequestInterface $request The request.
@param \Psr\Http\Message\ResponseInterface $response The response.
@return array Return an array containing the request and response objects. | [
"Clears",
"the",
"identity",
"from",
"authenticators",
"that",
"store",
"them",
"and",
"the",
"request"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/AuthenticationService.php#L211-L225 | train |
cakephp/authentication | src/AuthenticationService.php | AuthenticationService.persistIdentity | public function persistIdentity(ServerRequestInterface $request, ResponseInterface $response, $identity)
{
foreach ($this->authenticators() as $authenticator) {
if ($authenticator instanceof PersistenceInterface) {
$result = $authenticator->persistIdentity($request, $response, $identity);
$request = $result['request'];
$response = $result['response'];
}
}
if (!($identity instanceof IdentityInterface)) {
$identity = $this->buildIdentity($identity);
}
return [
'request' => $request->withAttribute($this->getConfig('identityAttribute'), $identity),
'response' => $response
];
} | php | public function persistIdentity(ServerRequestInterface $request, ResponseInterface $response, $identity)
{
foreach ($this->authenticators() as $authenticator) {
if ($authenticator instanceof PersistenceInterface) {
$result = $authenticator->persistIdentity($request, $response, $identity);
$request = $result['request'];
$response = $result['response'];
}
}
if (!($identity instanceof IdentityInterface)) {
$identity = $this->buildIdentity($identity);
}
return [
'request' => $request->withAttribute($this->getConfig('identityAttribute'), $identity),
'response' => $response
];
} | [
"public",
"function",
"persistIdentity",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
",",
"$",
"identity",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"authenticators",
"(",
")",
"as",
"$",
"authenticator",
")",
"... | Sets identity data and persists it in the authenticators that support it.
@param \Psr\Http\Message\ServerRequestInterface $request The request.
@param \Psr\Http\Message\ResponseInterface $response The response.
@param \ArrayAccess|array $identity Identity data.
@return array | [
"Sets",
"identity",
"data",
"and",
"persists",
"it",
"in",
"the",
"authenticators",
"that",
"support",
"it",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/AuthenticationService.php#L235-L253 | train |
cakephp/authentication | src/AuthenticationService.php | AuthenticationService.getIdentity | public function getIdentity()
{
if ($this->_result === null || !$this->_result->isValid()) {
return null;
}
$identity = $this->_result->getData();
if (!($identity instanceof IdentityInterface)) {
$identity = $this->buildIdentity($identity);
}
return $identity;
} | php | public function getIdentity()
{
if ($this->_result === null || !$this->_result->isValid()) {
return null;
}
$identity = $this->_result->getData();
if (!($identity instanceof IdentityInterface)) {
$identity = $this->buildIdentity($identity);
}
return $identity;
} | [
"public",
"function",
"getIdentity",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_result",
"===",
"null",
"||",
"!",
"$",
"this",
"->",
"_result",
"->",
"isValid",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"identity",
"=",
"$",
"this",... | Gets an identity object
@return null|\Authentication\IdentityInterface | [
"Gets",
"an",
"identity",
"object"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/AuthenticationService.php#L280-L292 | train |
cakephp/authentication | src/AuthenticationService.php | AuthenticationService.buildIdentity | public function buildIdentity($identityData)
{
$class = $this->getConfig('identityClass');
if (is_callable($class)) {
$identity = $class($identityData);
} else {
$identity = new $class($identityData);
}
if (!($identity instanceof IdentityInterface)) {
throw new RuntimeException(sprintf(
'Object `%s` does not implement `%s`',
get_class($identity),
IdentityInterface::class
));
}
return $identity;
} | php | public function buildIdentity($identityData)
{
$class = $this->getConfig('identityClass');
if (is_callable($class)) {
$identity = $class($identityData);
} else {
$identity = new $class($identityData);
}
if (!($identity instanceof IdentityInterface)) {
throw new RuntimeException(sprintf(
'Object `%s` does not implement `%s`',
get_class($identity),
IdentityInterface::class
));
}
return $identity;
} | [
"public",
"function",
"buildIdentity",
"(",
"$",
"identityData",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'identityClass'",
")",
";",
"if",
"(",
"is_callable",
"(",
"$",
"class",
")",
")",
"{",
"$",
"identity",
"=",
"$",
"clas... | Builds the identity object
@param \ArrayAccess|array $identityData Identity data
@return \Authentication\IdentityInterface | [
"Builds",
"the",
"identity",
"object"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/AuthenticationService.php#L300-L319 | train |
cakephp/authentication | src/Authenticator/JwtAuthenticator.php | JwtAuthenticator.authenticate | public function authenticate(ServerRequestInterface $request, ResponseInterface $response)
{
try {
$result = $this->getPayload($request);
} catch (Exception $e) {
return new Result(
null,
Result::FAILURE_CREDENTIALS_INVALID,
[
'message' => $e->getMessage(),
'exception' => $e
]
);
}
if (!($result instanceof stdClass)) {
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID);
}
$result = json_decode(json_encode($result), true);
$key = IdentifierInterface::CREDENTIAL_JWT_SUBJECT;
if (empty($result[$key])) {
return new Result(null, Result::FAILURE_CREDENTIALS_MISSING);
}
if ($this->getConfig('returnPayload')) {
$user = new ArrayObject($result);
return new Result($user, Result::SUCCESS);
}
$user = $this->_identifier->identify([
$key => $result[$key]
]);
if (empty($user)) {
return new Result(null, Result::FAILURE_IDENTITY_NOT_FOUND, $this->_identifier->getErrors());
}
return new Result($user, Result::SUCCESS);
} | php | public function authenticate(ServerRequestInterface $request, ResponseInterface $response)
{
try {
$result = $this->getPayload($request);
} catch (Exception $e) {
return new Result(
null,
Result::FAILURE_CREDENTIALS_INVALID,
[
'message' => $e->getMessage(),
'exception' => $e
]
);
}
if (!($result instanceof stdClass)) {
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID);
}
$result = json_decode(json_encode($result), true);
$key = IdentifierInterface::CREDENTIAL_JWT_SUBJECT;
if (empty($result[$key])) {
return new Result(null, Result::FAILURE_CREDENTIALS_MISSING);
}
if ($this->getConfig('returnPayload')) {
$user = new ArrayObject($result);
return new Result($user, Result::SUCCESS);
}
$user = $this->_identifier->identify([
$key => $result[$key]
]);
if (empty($user)) {
return new Result(null, Result::FAILURE_IDENTITY_NOT_FOUND, $this->_identifier->getErrors());
}
return new Result($user, Result::SUCCESS);
} | [
"public",
"function",
"authenticate",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"try",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"getPayload",
"(",
"$",
"request",
")",
";",
"}",
"catch",
"(",
"Ex... | Authenticates the identity based on a JWT token contained in a request.
@link https://jwt.io/
@param \Psr\Http\Message\ServerRequestInterface $request The request that contains login information.
@param \Psr\Http\Message\ResponseInterface $response Unused response object.
@return \Authentication\Authenticator\ResultInterface | [
"Authenticates",
"the",
"identity",
"based",
"on",
"a",
"JWT",
"token",
"contained",
"in",
"a",
"request",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/JwtAuthenticator.php#L72-L113 | train |
cakephp/authentication | src/Controller/Component/AuthenticationComponent.php | AuthenticationComponent.beforeFilter | public function beforeFilter()
{
$authentication = $this->getAuthenticationService();
$provider = $authentication->getAuthenticationProvider();
if ($provider === null ||
$provider instanceof PersistenceInterface ||
$provider instanceof StatelessInterface
) {
return;
}
$this->dispatchEvent('Authentication.afterIdentify', [
'provider' => $provider,
'identity' => $this->getIdentity(),
'service' => $authentication
], $this->getController());
} | php | public function beforeFilter()
{
$authentication = $this->getAuthenticationService();
$provider = $authentication->getAuthenticationProvider();
if ($provider === null ||
$provider instanceof PersistenceInterface ||
$provider instanceof StatelessInterface
) {
return;
}
$this->dispatchEvent('Authentication.afterIdentify', [
'provider' => $provider,
'identity' => $this->getIdentity(),
'service' => $authentication
], $this->getController());
} | [
"public",
"function",
"beforeFilter",
"(",
")",
"{",
"$",
"authentication",
"=",
"$",
"this",
"->",
"getAuthenticationService",
"(",
")",
";",
"$",
"provider",
"=",
"$",
"authentication",
"->",
"getAuthenticationProvider",
"(",
")",
";",
"if",
"(",
"$",
"pro... | Triggers the Authentication.afterIdentify event for non stateless adapters that are not persistent either
@return void | [
"Triggers",
"the",
"Authentication",
".",
"afterIdentify",
"event",
"for",
"non",
"stateless",
"adapters",
"that",
"are",
"not",
"persistent",
"either"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Controller/Component/AuthenticationComponent.php#L85-L102 | train |
cakephp/authentication | src/Controller/Component/AuthenticationComponent.php | AuthenticationComponent.getAuthenticationService | public function getAuthenticationService()
{
$controller = $this->getController();
$service = $controller->request->getAttribute('authentication');
if ($service === null) {
throw new Exception('The request object does not contain the required `authentication` attribute');
}
if (!($service instanceof AuthenticationServiceInterface)) {
throw new Exception('Authentication service does not implement ' . AuthenticationServiceInterface::class);
}
return $service;
} | php | public function getAuthenticationService()
{
$controller = $this->getController();
$service = $controller->request->getAttribute('authentication');
if ($service === null) {
throw new Exception('The request object does not contain the required `authentication` attribute');
}
if (!($service instanceof AuthenticationServiceInterface)) {
throw new Exception('Authentication service does not implement ' . AuthenticationServiceInterface::class);
}
return $service;
} | [
"public",
"function",
"getAuthenticationService",
"(",
")",
"{",
"$",
"controller",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
";",
"$",
"service",
"=",
"$",
"controller",
"->",
"request",
"->",
"getAttribute",
"(",
"'authentication'",
")",
";",
"if"... | Returns authentication service.
@return \Authentication\AuthenticationServiceInterface
@throws \Exception | [
"Returns",
"authentication",
"service",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Controller/Component/AuthenticationComponent.php#L110-L123 | train |
cakephp/authentication | src/Controller/Component/AuthenticationComponent.php | AuthenticationComponent.startup | public function startup()
{
if (!$this->getConfig('requireIdentity')) {
return;
}
$request = $this->getController()->request;
$action = $request->getParam('action');
if (in_array($action, $this->unauthenticatedActions)) {
return;
}
$identity = $request->getAttribute($this->getConfig('identityAttribute'));
if (!$identity) {
throw new UnauthenticatedException();
}
} | php | public function startup()
{
if (!$this->getConfig('requireIdentity')) {
return;
}
$request = $this->getController()->request;
$action = $request->getParam('action');
if (in_array($action, $this->unauthenticatedActions)) {
return;
}
$identity = $request->getAttribute($this->getConfig('identityAttribute'));
if (!$identity) {
throw new UnauthenticatedException();
}
} | [
"public",
"function",
"startup",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getConfig",
"(",
"'requireIdentity'",
")",
")",
"{",
"return",
";",
"}",
"$",
"request",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"request",
";",
"$",... | Start up event handler
@return void
@throws Exception when request is missing or has an invalid AuthenticationService
@throws UnauthenticatedException when requireIdentity is true and request is missing an identity | [
"Start",
"up",
"event",
"handler"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Controller/Component/AuthenticationComponent.php#L132-L148 | train |
cakephp/authentication | src/Controller/Component/AuthenticationComponent.php | AuthenticationComponent.addUnauthenticatedActions | public function addUnauthenticatedActions(array $actions)
{
$this->unauthenticatedActions = array_merge($this->unauthenticatedActions, $actions);
$this->unauthenticatedActions = array_values(array_unique($this->unauthenticatedActions));
return $this;
} | php | public function addUnauthenticatedActions(array $actions)
{
$this->unauthenticatedActions = array_merge($this->unauthenticatedActions, $actions);
$this->unauthenticatedActions = array_values(array_unique($this->unauthenticatedActions));
return $this;
} | [
"public",
"function",
"addUnauthenticatedActions",
"(",
"array",
"$",
"actions",
")",
"{",
"$",
"this",
"->",
"unauthenticatedActions",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"unauthenticatedActions",
",",
"$",
"actions",
")",
";",
"$",
"this",
"->",
"una... | Add to the list of actions that don't require an authentication identity to be present.
@param array $actions The action or actions to append.
@return $this | [
"Add",
"to",
"the",
"list",
"of",
"actions",
"that",
"don",
"t",
"require",
"an",
"authentication",
"identity",
"to",
"be",
"present",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Controller/Component/AuthenticationComponent.php#L172-L178 | train |
cakephp/authentication | src/Controller/Component/AuthenticationComponent.php | AuthenticationComponent.setIdentity | public function setIdentity(ArrayAccess $identity)
{
$controller = $this->getController();
$result = $this->getAuthenticationService()->persistIdentity(
$controller->request,
$controller->response,
$identity
);
$controller->setRequest($result['request']);
$controller->response = $result['response'];
return $this;
} | php | public function setIdentity(ArrayAccess $identity)
{
$controller = $this->getController();
$result = $this->getAuthenticationService()->persistIdentity(
$controller->request,
$controller->response,
$identity
);
$controller->setRequest($result['request']);
$controller->response = $result['response'];
return $this;
} | [
"public",
"function",
"setIdentity",
"(",
"ArrayAccess",
"$",
"identity",
")",
"{",
"$",
"controller",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"getAuthenticationService",
"(",
")",
"->",
"persistIdentity... | Set identity data to all authenticators that are loaded and support persistence.
@param \ArrayAccess $identity Identity data to persist.
@return $this | [
"Set",
"identity",
"data",
"to",
"all",
"authenticators",
"that",
"are",
"loaded",
"and",
"support",
"persistence",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Controller/Component/AuthenticationComponent.php#L237-L251 | train |
cakephp/authentication | src/Identifier/LdapIdentifier.php | LdapIdentifier._checkLdapConfig | protected function _checkLdapConfig()
{
if (!isset($this->_config['bindDN'])) {
throw new RuntimeException('Config `bindDN` is not set.');
}
if (!is_callable($this->_config['bindDN'])) {
throw new InvalidArgumentException(sprintf(
'The `bindDN` config is not a callable. Got `%s` instead.',
gettype($this->_config['bindDN'])
));
}
if (!isset($this->_config['host'])) {
throw new RuntimeException('Config `host` is not set.');
}
} | php | protected function _checkLdapConfig()
{
if (!isset($this->_config['bindDN'])) {
throw new RuntimeException('Config `bindDN` is not set.');
}
if (!is_callable($this->_config['bindDN'])) {
throw new InvalidArgumentException(sprintf(
'The `bindDN` config is not a callable. Got `%s` instead.',
gettype($this->_config['bindDN'])
));
}
if (!isset($this->_config['host'])) {
throw new RuntimeException('Config `host` is not set.');
}
} | [
"protected",
"function",
"_checkLdapConfig",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_config",
"[",
"'bindDN'",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Config `bindDN` is not set.'",
")",
";",
"}",
"if",
"(",... | Checks the LDAP config
@throws \RuntimeException
@throws \InvalidArgumentException
@return void | [
"Checks",
"the",
"LDAP",
"config"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/LdapIdentifier.php#L93-L107 | train |
cakephp/authentication | src/Identifier/LdapIdentifier.php | LdapIdentifier._buildLdapObject | protected function _buildLdapObject()
{
$ldap = $this->_config['ldap'];
if (is_string($ldap)) {
$class = App::className($ldap, 'Identifier/Ldap');
$ldap = new $class();
}
if (!($ldap instanceof AdapterInterface)) {
$message = sprintf('Option `ldap` must implement `%s`.', AdapterInterface::class);
throw new RuntimeException($message);
}
$this->_ldap = $ldap;
} | php | protected function _buildLdapObject()
{
$ldap = $this->_config['ldap'];
if (is_string($ldap)) {
$class = App::className($ldap, 'Identifier/Ldap');
$ldap = new $class();
}
if (!($ldap instanceof AdapterInterface)) {
$message = sprintf('Option `ldap` must implement `%s`.', AdapterInterface::class);
throw new RuntimeException($message);
}
$this->_ldap = $ldap;
} | [
"protected",
"function",
"_buildLdapObject",
"(",
")",
"{",
"$",
"ldap",
"=",
"$",
"this",
"->",
"_config",
"[",
"'ldap'",
"]",
";",
"if",
"(",
"is_string",
"(",
"$",
"ldap",
")",
")",
"{",
"$",
"class",
"=",
"App",
"::",
"className",
"(",
"$",
"ld... | Constructs the LDAP object and sets it to the property
@throws \RuntimeException
@return void | [
"Constructs",
"the",
"LDAP",
"object",
"and",
"sets",
"it",
"to",
"the",
"property"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/LdapIdentifier.php#L115-L130 | train |
cakephp/authentication | src/Identifier/LdapIdentifier.php | LdapIdentifier._connectLdap | protected function _connectLdap()
{
$config = $this->getConfig();
$this->_ldap->connect(
$config['host'],
$config['port'],
$this->getConfig('options')
);
} | php | protected function _connectLdap()
{
$config = $this->getConfig();
$this->_ldap->connect(
$config['host'],
$config['port'],
$this->getConfig('options')
);
} | [
"protected",
"function",
"_connectLdap",
"(",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"$",
"this",
"->",
"_ldap",
"->",
"connect",
"(",
"$",
"config",
"[",
"'host'",
"]",
",",
"$",
"config",
"[",
"'port'",
"]",
... | Initializes the LDAP connection
@return void | [
"Initializes",
"the",
"LDAP",
"connection"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/LdapIdentifier.php#L162-L171 | train |
cakephp/authentication | src/Identifier/LdapIdentifier.php | LdapIdentifier._bindUser | protected function _bindUser($username, $password)
{
$config = $this->getConfig();
try {
$ldapBind = $this->_ldap->bind($config['bindDN']($username), $password);
if ($ldapBind === true) {
$this->_ldap->unbind();
return new ArrayObject([
$config['fields'][self::CREDENTIAL_USERNAME] => $username
]);
}
} catch (ErrorException $e) {
$this->_handleLdapError($e->getMessage());
}
$this->_ldap->unbind();
return null;
} | php | protected function _bindUser($username, $password)
{
$config = $this->getConfig();
try {
$ldapBind = $this->_ldap->bind($config['bindDN']($username), $password);
if ($ldapBind === true) {
$this->_ldap->unbind();
return new ArrayObject([
$config['fields'][self::CREDENTIAL_USERNAME] => $username
]);
}
} catch (ErrorException $e) {
$this->_handleLdapError($e->getMessage());
}
$this->_ldap->unbind();
return null;
} | [
"protected",
"function",
"_bindUser",
"(",
"$",
"username",
",",
"$",
"password",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"try",
"{",
"$",
"ldapBind",
"=",
"$",
"this",
"->",
"_ldap",
"->",
"bind",
"(",
"$",
"co... | Try to bind the given user to the LDAP server
@param string $username The username
@param string $password The password
@return \ArrayAccess|null | [
"Try",
"to",
"bind",
"the",
"given",
"user",
"to",
"the",
"LDAP",
"server"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/LdapIdentifier.php#L180-L198 | train |
cakephp/authentication | src/Identifier/LdapIdentifier.php | LdapIdentifier._handleLdapError | protected function _handleLdapError($message)
{
$extendedError = $this->_ldap->getDiagnosticMessage();
if (!is_null($extendedError)) {
$this->_errors[] = $extendedError;
}
$this->_errors[] = $message;
} | php | protected function _handleLdapError($message)
{
$extendedError = $this->_ldap->getDiagnosticMessage();
if (!is_null($extendedError)) {
$this->_errors[] = $extendedError;
}
$this->_errors[] = $message;
} | [
"protected",
"function",
"_handleLdapError",
"(",
"$",
"message",
")",
"{",
"$",
"extendedError",
"=",
"$",
"this",
"->",
"_ldap",
"->",
"getDiagnosticMessage",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"extendedError",
")",
")",
"{",
"$",
"thi... | Handles an LDAP error
@param string $message Exception message
@return void | [
"Handles",
"an",
"LDAP",
"error"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/LdapIdentifier.php#L206-L213 | train |
cakephp/authentication | src/Authenticator/HttpDigestAuthenticator.php | HttpDigestAuthenticator.generateNonce | protected function generateNonce()
{
$expiryTime = microtime(true) + $this->getConfig('nonceLifetime');
$secret = $this->getConfig('secret');
$signatureValue = hash_hmac('sha1', $expiryTime . ':' . $secret, $secret);
$nonceValue = $expiryTime . ':' . $signatureValue;
return base64_encode($nonceValue);
} | php | protected function generateNonce()
{
$expiryTime = microtime(true) + $this->getConfig('nonceLifetime');
$secret = $this->getConfig('secret');
$signatureValue = hash_hmac('sha1', $expiryTime . ':' . $secret, $secret);
$nonceValue = $expiryTime . ':' . $signatureValue;
return base64_encode($nonceValue);
} | [
"protected",
"function",
"generateNonce",
"(",
")",
"{",
"$",
"expiryTime",
"=",
"microtime",
"(",
"true",
")",
"+",
"$",
"this",
"->",
"getConfig",
"(",
"'nonceLifetime'",
")",
";",
"$",
"secret",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'secret'",
")... | Generate a nonce value that is validated in future requests.
@return string | [
"Generate",
"a",
"nonce",
"value",
"that",
"is",
"validated",
"in",
"future",
"requests",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/HttpDigestAuthenticator.php#L246-L254 | train |
cakephp/authentication | src/Authenticator/HttpDigestAuthenticator.php | HttpDigestAuthenticator.validNonce | protected function validNonce($nonce)
{
$value = base64_decode($nonce);
if ($value === false) {
return false;
}
$parts = explode(':', $value);
if (count($parts) !== 2) {
return false;
}
list($expires, $checksum) = $parts;
if ($expires < microtime(true)) {
return false;
}
$secret = $this->getConfig('secret');
$check = hash_hmac('sha1', $expires . ':' . $secret, $secret);
return hash_equals($check, $checksum);
} | php | protected function validNonce($nonce)
{
$value = base64_decode($nonce);
if ($value === false) {
return false;
}
$parts = explode(':', $value);
if (count($parts) !== 2) {
return false;
}
list($expires, $checksum) = $parts;
if ($expires < microtime(true)) {
return false;
}
$secret = $this->getConfig('secret');
$check = hash_hmac('sha1', $expires . ':' . $secret, $secret);
return hash_equals($check, $checksum);
} | [
"protected",
"function",
"validNonce",
"(",
"$",
"nonce",
")",
"{",
"$",
"value",
"=",
"base64_decode",
"(",
"$",
"nonce",
")",
";",
"if",
"(",
"$",
"value",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"$",
"parts",
"=",
"explode",
"(",
... | Check the nonce to ensure it is valid and not expired.
@param string $nonce The nonce value to check.
@return bool | [
"Check",
"the",
"nonce",
"to",
"ensure",
"it",
"is",
"valid",
"and",
"not",
"expired",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/HttpDigestAuthenticator.php#L262-L280 | train |
cakephp/authentication | src/Identifier/CallbackIdentifier.php | CallbackIdentifier.checkCallable | protected function checkCallable()
{
$callback = $this->getConfig('callback');
if (!is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'The `callback` option is not a callable. Got `%s` instead.',
gettype($callback)
));
}
} | php | protected function checkCallable()
{
$callback = $this->getConfig('callback');
if (!is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'The `callback` option is not a callable. Got `%s` instead.',
gettype($callback)
));
}
} | [
"protected",
"function",
"checkCallable",
"(",
")",
"{",
"$",
"callback",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'callback'",
")",
";",
"if",
"(",
"!",
"is_callable",
"(",
"$",
"callback",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",... | Check the callable option
@throws \InvalidArgumentException
@return void | [
"Check",
"the",
"callable",
"option"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/CallbackIdentifier.php#L51-L61 | train |
cakephp/authentication | src/Middleware/AuthenticationMiddleware.php | AuthenticationMiddleware.getRedirectUrl | protected function getRedirectUrl($target, ServerRequestInterface $request)
{
$param = $this->getConfig('queryParam');
if ($param === null) {
return $target;
}
$uri = $request->getUri();
if (property_exists($uri, 'base')) {
$uri = $uri->withPath($uri->base . $uri->getPath());
}
$query = urlencode($param) . '=' . urlencode($uri);
$url = parse_url($target);
if (isset($url['query']) && strlen($url['query'])) {
$url['query'] .= '&' . $query;
} else {
$url['query'] = $query;
}
$fragment = isset($url['fragment']) ? '#' . $url['fragment'] : '';
return $url['path'] . '?' . $url['query'] . $fragment;
} | php | protected function getRedirectUrl($target, ServerRequestInterface $request)
{
$param = $this->getConfig('queryParam');
if ($param === null) {
return $target;
}
$uri = $request->getUri();
if (property_exists($uri, 'base')) {
$uri = $uri->withPath($uri->base . $uri->getPath());
}
$query = urlencode($param) . '=' . urlencode($uri);
$url = parse_url($target);
if (isset($url['query']) && strlen($url['query'])) {
$url['query'] .= '&' . $query;
} else {
$url['query'] = $query;
}
$fragment = isset($url['fragment']) ? '#' . $url['fragment'] : '';
return $url['path'] . '?' . $url['query'] . $fragment;
} | [
"protected",
"function",
"getRedirectUrl",
"(",
"$",
"target",
",",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"param",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'queryParam'",
")",
";",
"if",
"(",
"$",
"param",
"===",
"null",
")",
"{",
"r... | Returns redirect URL.
@param string $target Redirect target.
@param \Psr\Http\Message\ServerRequestInterface $request Request instance.
@return string | [
"Returns",
"redirect",
"URL",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Middleware/AuthenticationMiddleware.php#L142-L164 | train |
cakephp/authentication | src/Middleware/AuthenticationMiddleware.php | AuthenticationMiddleware.getAuthenticationService | protected function getAuthenticationService($request, $response)
{
$subject = $this->subject;
if ($subject instanceof AuthenticationServiceProviderInterface) {
$subject = $this->subject->getAuthenticationService($request, $response);
}
if (!$subject instanceof AuthenticationServiceInterface) {
$type = is_object($subject) ? get_class($subject) : gettype($subject);
$message = sprintf('Service provided by a subject must be an instance of `%s`, `%s` given.', AuthenticationServiceInterface::class, $type);
throw new RuntimeException($message);
}
return $subject;
} | php | protected function getAuthenticationService($request, $response)
{
$subject = $this->subject;
if ($subject instanceof AuthenticationServiceProviderInterface) {
$subject = $this->subject->getAuthenticationService($request, $response);
}
if (!$subject instanceof AuthenticationServiceInterface) {
$type = is_object($subject) ? get_class($subject) : gettype($subject);
$message = sprintf('Service provided by a subject must be an instance of `%s`, `%s` given.', AuthenticationServiceInterface::class, $type);
throw new RuntimeException($message);
}
return $subject;
} | [
"protected",
"function",
"getAuthenticationService",
"(",
"$",
"request",
",",
"$",
"response",
")",
"{",
"$",
"subject",
"=",
"$",
"this",
"->",
"subject",
";",
"if",
"(",
"$",
"subject",
"instanceof",
"AuthenticationServiceProviderInterface",
")",
"{",
"$",
... | Returns AuthenticationServiceInterface instance.
@param \Psr\Http\Message\ServerRequestInterface $request Server request.
@param \Psr\Http\Message\ResponseInterface $response Response.
@return \Authentication\AuthenticationServiceInterface
@throws \RuntimeException When authentication method has not been defined. | [
"Returns",
"AuthenticationServiceInterface",
"instance",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Middleware/AuthenticationMiddleware.php#L174-L190 | train |
cakephp/authentication | src/Authenticator/TokenAuthenticator.php | TokenAuthenticator.getToken | protected function getToken(ServerRequestInterface $request)
{
$token = $this->getTokenFromHeader($request, $this->getConfig('header'));
if ($token === null) {
$token = $this->getTokenFromQuery($request, $this->getConfig('queryParam'));
}
$prefix = $this->getConfig('tokenPrefix');
if ($prefix !== null && is_string($token)) {
return $this->stripTokenPrefix($token, $prefix);
}
return $token;
} | php | protected function getToken(ServerRequestInterface $request)
{
$token = $this->getTokenFromHeader($request, $this->getConfig('header'));
if ($token === null) {
$token = $this->getTokenFromQuery($request, $this->getConfig('queryParam'));
}
$prefix = $this->getConfig('tokenPrefix');
if ($prefix !== null && is_string($token)) {
return $this->stripTokenPrefix($token, $prefix);
}
return $token;
} | [
"protected",
"function",
"getToken",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"getTokenFromHeader",
"(",
"$",
"request",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'header'",
")",
")",
";",
"if",
"(",
... | Checks if the token is in the headers or a request parameter
@param \Psr\Http\Message\ServerRequestInterface $request The request that contains login information.
@return string|null | [
"Checks",
"if",
"the",
"token",
"is",
"in",
"the",
"headers",
"or",
"a",
"request",
"parameter"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/TokenAuthenticator.php#L44-L57 | train |
cakephp/authentication | src/Authenticator/CookieAuthenticator.php | CookieAuthenticator._createPlainToken | protected function _createPlainToken($identity)
{
$usernameField = $this->getConfig('fields.username');
$passwordField = $this->getConfig('fields.password');
return $identity[$usernameField] . $identity[$passwordField];
} | php | protected function _createPlainToken($identity)
{
$usernameField = $this->getConfig('fields.username');
$passwordField = $this->getConfig('fields.password');
return $identity[$usernameField] . $identity[$passwordField];
} | [
"protected",
"function",
"_createPlainToken",
"(",
"$",
"identity",
")",
"{",
"$",
"usernameField",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'fields.username'",
")",
";",
"$",
"passwordField",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'fields.password'",
")... | Creates a plain part of a cookie token.
Returns concatenated username and password hash.
@param array|\ArrayAccess $identity Identity data.
@return string | [
"Creates",
"a",
"plain",
"part",
"of",
"a",
"cookie",
"token",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/CookieAuthenticator.php#L155-L161 | train |
cakephp/authentication | src/Authenticator/CookieAuthenticator.php | CookieAuthenticator._createToken | protected function _createToken($identity)
{
$plain = $this->_createPlainToken($identity);
$hash = $this->getPasswordHasher()->hash($plain);
$usernameField = $this->getConfig('fields.username');
return json_encode([$identity[$usernameField], $hash]);
} | php | protected function _createToken($identity)
{
$plain = $this->_createPlainToken($identity);
$hash = $this->getPasswordHasher()->hash($plain);
$usernameField = $this->getConfig('fields.username');
return json_encode([$identity[$usernameField], $hash]);
} | [
"protected",
"function",
"_createToken",
"(",
"$",
"identity",
")",
"{",
"$",
"plain",
"=",
"$",
"this",
"->",
"_createPlainToken",
"(",
"$",
"identity",
")",
";",
"$",
"hash",
"=",
"$",
"this",
"->",
"getPasswordHasher",
"(",
")",
"->",
"hash",
"(",
"... | Creates a full cookie token serialized as a JSON sting.
Cookie token consists of a username and hashed username + password hash.
@param array|\ArrayAccess $identity Identity data.
@return string | [
"Creates",
"a",
"full",
"cookie",
"token",
"serialized",
"as",
"a",
"JSON",
"sting",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/CookieAuthenticator.php#L171-L179 | train |
cakephp/authentication | src/Authenticator/CookieAuthenticator.php | CookieAuthenticator._checkToken | protected function _checkToken($identity, $tokenHash)
{
$plain = $this->_createPlainToken($identity);
return $this->getPasswordHasher()->check($plain, $tokenHash);
} | php | protected function _checkToken($identity, $tokenHash)
{
$plain = $this->_createPlainToken($identity);
return $this->getPasswordHasher()->check($plain, $tokenHash);
} | [
"protected",
"function",
"_checkToken",
"(",
"$",
"identity",
",",
"$",
"tokenHash",
")",
"{",
"$",
"plain",
"=",
"$",
"this",
"->",
"_createPlainToken",
"(",
"$",
"identity",
")",
";",
"return",
"$",
"this",
"->",
"getPasswordHasher",
"(",
")",
"->",
"c... | Checks whether a token hash matches the identity data.
@param array|\ArrayAccess $identity Identity data.
@param string $tokenHash Hashed part of a cookie token.
@return bool | [
"Checks",
"whether",
"a",
"token",
"hash",
"matches",
"the",
"identity",
"data",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/CookieAuthenticator.php#L188-L193 | train |
cakephp/authentication | src/Authenticator/CookieAuthenticator.php | CookieAuthenticator._createCookie | protected function _createCookie($value)
{
$data = $this->getConfig('cookie');
$cookie = new Cookie(
$data['name'],
$value,
$data['expire'],
$data['path'],
$data['domain'],
$data['secure'],
$data['httpOnly']
);
return $cookie;
} | php | protected function _createCookie($value)
{
$data = $this->getConfig('cookie');
$cookie = new Cookie(
$data['name'],
$value,
$data['expire'],
$data['path'],
$data['domain'],
$data['secure'],
$data['httpOnly']
);
return $cookie;
} | [
"protected",
"function",
"_createCookie",
"(",
"$",
"value",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'cookie'",
")",
";",
"$",
"cookie",
"=",
"new",
"Cookie",
"(",
"$",
"data",
"[",
"'name'",
"]",
",",
"$",
"value",
",",
"... | Creates a cookie instance with configured defaults.
@param mixed $value Cookie value.
@return \Cake\Http\Cookie\CookieInterface | [
"Creates",
"a",
"cookie",
"instance",
"with",
"configured",
"defaults",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/CookieAuthenticator.php#L214-L229 | train |
cakephp/authentication | src/Identifier/Resolver/ResolverAwareTrait.php | ResolverAwareTrait.getResolver | public function getResolver()
{
if ($this->resolver === null) {
$config = $this->getConfig('resolver');
if ($config !== null) {
$this->resolver = $this->buildResolver($config);
} else {
throw new RuntimeException('Resolver has not been set.');
}
}
return $this->resolver;
} | php | public function getResolver()
{
if ($this->resolver === null) {
$config = $this->getConfig('resolver');
if ($config !== null) {
$this->resolver = $this->buildResolver($config);
} else {
throw new RuntimeException('Resolver has not been set.');
}
}
return $this->resolver;
} | [
"public",
"function",
"getResolver",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"resolver",
"===",
"null",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'resolver'",
")",
";",
"if",
"(",
"$",
"config",
"!==",
"null",
")",
"{... | Returns ResolverInterface instance.
@return \Authentication\Identifier\Resolver\ResolverInterface
@throws \RuntimeException When resolver has not been set. | [
"Returns",
"ResolverInterface",
"instance",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/Resolver/ResolverAwareTrait.php#L37-L49 | train |
cakephp/authentication | src/Identifier/Resolver/ResolverAwareTrait.php | ResolverAwareTrait.buildResolver | protected function buildResolver($config)
{
if (is_string($config)) {
$config = [
'className' => $config
];
}
if (!isset($config['className'])) {
$message = 'Option `className` is not present.';
throw new InvalidArgumentException($message);
}
$class = App::className($config['className'], 'Identifier/Resolver', 'Resolver');
if ($class === false) {
$message = sprintf('Resolver class `%s` does not exist.', $config['className']);
throw new InvalidArgumentException($message);
}
$instance = new $class($config);
if (!($instance instanceof ResolverInterface)) {
$message = sprintf('Resolver must implement `%s`.', ResolverInterface::class);
throw new RuntimeException($message);
}
return $instance;
} | php | protected function buildResolver($config)
{
if (is_string($config)) {
$config = [
'className' => $config
];
}
if (!isset($config['className'])) {
$message = 'Option `className` is not present.';
throw new InvalidArgumentException($message);
}
$class = App::className($config['className'], 'Identifier/Resolver', 'Resolver');
if ($class === false) {
$message = sprintf('Resolver class `%s` does not exist.', $config['className']);
throw new InvalidArgumentException($message);
}
$instance = new $class($config);
if (!($instance instanceof ResolverInterface)) {
$message = sprintf('Resolver must implement `%s`.', ResolverInterface::class);
throw new RuntimeException($message);
}
return $instance;
} | [
"protected",
"function",
"buildResolver",
"(",
"$",
"config",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"config",
")",
")",
"{",
"$",
"config",
"=",
"[",
"'className'",
"=>",
"$",
"config",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"confi... | Builds a ResolverInterface instance.
@param string|array $config Resolver class name or config.
@return \Authentication\Identifier\Resolver\ResolverInterface
@throws \InvalidArgumentException When className option is missing or class name does not exist.
@throws \RuntimeException When resolver does not implement ResolverInterface. | [
"Builds",
"a",
"ResolverInterface",
"instance",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/Resolver/ResolverAwareTrait.php#L72-L98 | train |
cakephp/authentication | src/Authenticator/HttpBasicAuthenticator.php | HttpBasicAuthenticator.authenticate | public function authenticate(ServerRequestInterface $request, ResponseInterface $response)
{
$user = $this->getUser($request);
if (empty($user)) {
return new Result(null, Result::FAILURE_CREDENTIALS_MISSING);
}
return new Result($user, Result::SUCCESS);
} | php | public function authenticate(ServerRequestInterface $request, ResponseInterface $response)
{
$user = $this->getUser($request);
if (empty($user)) {
return new Result(null, Result::FAILURE_CREDENTIALS_MISSING);
}
return new Result($user, Result::SUCCESS);
} | [
"public",
"function",
"authenticate",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
"$",
"request",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"user",
... | Authenticate a user using HTTP auth. Will use the configured User model and attempt a
login using HTTP auth.
@param \Psr\Http\Message\ServerRequestInterface $request The request to authenticate with.
@param \Psr\Http\Message\ResponseInterface $response The response to add headers to.
@return \Authentication\Authenticator\ResultInterface | [
"Authenticate",
"a",
"user",
"using",
"HTTP",
"auth",
".",
"Will",
"use",
"the",
"configured",
"User",
"model",
"and",
"attempt",
"a",
"login",
"using",
"HTTP",
"auth",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/HttpBasicAuthenticator.php#L36-L45 | train |
cakephp/authentication | src/UrlChecker/UrlCheckerTrait.php | UrlCheckerTrait._checkUrl | protected function _checkUrl(ServerRequestInterface $request)
{
return $this->_getUrlChecker()->check(
$request,
$this->getConfig('loginUrl'),
(array)$this->getConfig('urlChecker')
);
} | php | protected function _checkUrl(ServerRequestInterface $request)
{
return $this->_getUrlChecker()->check(
$request,
$this->getConfig('loginUrl'),
(array)$this->getConfig('urlChecker')
);
} | [
"protected",
"function",
"_checkUrl",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"return",
"$",
"this",
"->",
"_getUrlChecker",
"(",
")",
"->",
"check",
"(",
"$",
"request",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'loginUrl'",
")",
",",
"(... | Checks the Login URL
@param \Psr\Http\Message\ServerRequestInterface $request The request that contains login information.
@return bool | [
"Checks",
"the",
"Login",
"URL"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/UrlChecker/UrlCheckerTrait.php#L34-L41 | train |
cakephp/authentication | src/UrlChecker/UrlCheckerTrait.php | UrlCheckerTrait._getUrlChecker | protected function _getUrlChecker()
{
$options = $this->getConfig('urlChecker');
if (!is_array($options)) {
$options = [
'className' => $options
];
}
if (!isset($options['className'])) {
$options['className'] = DefaultUrlChecker::class;
}
$className = App::className($options['className'], 'UrlChecker', 'UrlChecker');
if ($className === false) {
throw new RuntimeException(sprintf('URL checker class `%s` was not found.', $options['className']));
}
$checker = new $className();
if (!($checker instanceof UrlCheckerInterface)) {
throw new RuntimeException(sprintf(
'The provided URL checker class `%s` does not implement the `%s` interface.',
$options['className'],
UrlCheckerInterface::class
));
}
return $checker;
} | php | protected function _getUrlChecker()
{
$options = $this->getConfig('urlChecker');
if (!is_array($options)) {
$options = [
'className' => $options
];
}
if (!isset($options['className'])) {
$options['className'] = DefaultUrlChecker::class;
}
$className = App::className($options['className'], 'UrlChecker', 'UrlChecker');
if ($className === false) {
throw new RuntimeException(sprintf('URL checker class `%s` was not found.', $options['className']));
}
$checker = new $className();
if (!($checker instanceof UrlCheckerInterface)) {
throw new RuntimeException(sprintf(
'The provided URL checker class `%s` does not implement the `%s` interface.',
$options['className'],
UrlCheckerInterface::class
));
}
return $checker;
} | [
"protected",
"function",
"_getUrlChecker",
"(",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'urlChecker'",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"options",
")",
")",
"{",
"$",
"options",
"=",
"[",
"'className'",
"=>",... | Gets the login URL checker
@return \Authentication\UrlChecker\UrlCheckerInterface | [
"Gets",
"the",
"login",
"URL",
"checker"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/UrlChecker/UrlCheckerTrait.php#L48-L76 | train |
cakephp/authentication | src/Authenticator/SessionAuthenticator.php | SessionAuthenticator.authenticate | public function authenticate(ServerRequestInterface $request, ResponseInterface $response)
{
$sessionKey = $this->getConfig('sessionKey');
$session = $request->getAttribute('session');
$user = $session->read($sessionKey);
if (empty($user)) {
return new Result(null, Result::FAILURE_IDENTITY_NOT_FOUND);
}
if ($this->getConfig('identify') === true) {
$credentials = [];
foreach ($this->getConfig('fields') as $key => $field) {
$credentials[$key] = $user[$field];
}
$user = $this->_identifier->identify($credentials);
if (empty($user)) {
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID);
}
}
if (!($user instanceof ArrayAccess)) {
$user = new ArrayObject($user);
}
return new Result($user, Result::SUCCESS);
} | php | public function authenticate(ServerRequestInterface $request, ResponseInterface $response)
{
$sessionKey = $this->getConfig('sessionKey');
$session = $request->getAttribute('session');
$user = $session->read($sessionKey);
if (empty($user)) {
return new Result(null, Result::FAILURE_IDENTITY_NOT_FOUND);
}
if ($this->getConfig('identify') === true) {
$credentials = [];
foreach ($this->getConfig('fields') as $key => $field) {
$credentials[$key] = $user[$field];
}
$user = $this->_identifier->identify($credentials);
if (empty($user)) {
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID);
}
}
if (!($user instanceof ArrayAccess)) {
$user = new ArrayObject($user);
}
return new Result($user, Result::SUCCESS);
} | [
"public",
"function",
"authenticate",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"$",
"sessionKey",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'sessionKey'",
")",
";",
"$",
"session",
"=",
"$",
"request"... | Authenticate a user using session data.
@param \Psr\Http\Message\ServerRequestInterface $request The request to authenticate with.
@param \Psr\Http\Message\ResponseInterface $response The response to add headers to.
@return \Authentication\Authenticator\ResultInterface | [
"Authenticate",
"a",
"user",
"using",
"session",
"data",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Authenticator/SessionAuthenticator.php#L52-L79 | train |
cakephp/authentication | src/Identifier/IdentifierCollection.php | IdentifierCollection.identify | public function identify(array $credentials)
{
/** @var \Authentication\Identifier\IdentifierInterface $identifier */
foreach ($this->_loaded as $name => $identifier) {
$result = $identifier->identify($credentials);
if ($result) {
return $result;
}
$this->_errors[$name] = $identifier->getErrors();
}
return null;
} | php | public function identify(array $credentials)
{
/** @var \Authentication\Identifier\IdentifierInterface $identifier */
foreach ($this->_loaded as $name => $identifier) {
$result = $identifier->identify($credentials);
if ($result) {
return $result;
}
$this->_errors[$name] = $identifier->getErrors();
}
return null;
} | [
"public",
"function",
"identify",
"(",
"array",
"$",
"credentials",
")",
"{",
"/** @var \\Authentication\\Identifier\\IdentifierInterface $identifier */",
"foreach",
"(",
"$",
"this",
"->",
"_loaded",
"as",
"$",
"name",
"=>",
"$",
"identifier",
")",
"{",
"$",
"resul... | Identifies an user or service by the passed credentials
@param array $credentials Authentication credentials
@return \ArrayAccess|array|null | [
"Identifies",
"an",
"user",
"or",
"service",
"by",
"the",
"passed",
"credentials"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/IdentifierCollection.php#L37-L49 | train |
cakephp/authentication | src/Identifier/IdentifierCollection.php | IdentifierCollection._create | protected function _create($className, $alias, $config)
{
$identifier = new $className($config);
if (!($identifier instanceof IdentifierInterface)) {
throw new RuntimeException(sprintf(
'Identifier class `%s` must implement `%s`.',
$className,
IdentifierInterface::class
));
}
return $identifier;
} | php | protected function _create($className, $alias, $config)
{
$identifier = new $className($config);
if (!($identifier instanceof IdentifierInterface)) {
throw new RuntimeException(sprintf(
'Identifier class `%s` must implement `%s`.',
$className,
IdentifierInterface::class
));
}
return $identifier;
} | [
"protected",
"function",
"_create",
"(",
"$",
"className",
",",
"$",
"alias",
",",
"$",
"config",
")",
"{",
"$",
"identifier",
"=",
"new",
"$",
"className",
"(",
"$",
"config",
")",
";",
"if",
"(",
"!",
"(",
"$",
"identifier",
"instanceof",
"Identifier... | Creates identifier instance.
@param string $className Identifier class.
@param string $alias Identifier alias.
@param array $config Config array.
@return \Authentication\Identifier\IdentifierInterface
@throws \RuntimeException | [
"Creates",
"identifier",
"instance",
"."
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/IdentifierCollection.php#L60-L72 | train |
cakephp/authentication | src/Identifier/Ldap/ExtensionAdapter.php | ExtensionAdapter.bind | public function bind($bind, $password)
{
$this->_setErrorHandler();
$result = ldap_bind($this->getConnection(), $bind, $password);
$this->_unsetErrorHandler();
return $result;
} | php | public function bind($bind, $password)
{
$this->_setErrorHandler();
$result = ldap_bind($this->getConnection(), $bind, $password);
$this->_unsetErrorHandler();
return $result;
} | [
"public",
"function",
"bind",
"(",
"$",
"bind",
",",
"$",
"password",
")",
"{",
"$",
"this",
"->",
"_setErrorHandler",
"(",
")",
";",
"$",
"result",
"=",
"ldap_bind",
"(",
"$",
"this",
"->",
"getConnection",
"(",
")",
",",
"$",
"bind",
",",
"$",
"p... | Bind to LDAP directory
@param string $bind Bind rdn
@param string $password Bind password
@return bool | [
"Bind",
"to",
"LDAP",
"directory"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/Ldap/ExtensionAdapter.php#L62-L69 | train |
cakephp/authentication | src/Identifier/Ldap/ExtensionAdapter.php | ExtensionAdapter.setOption | public function setOption($option, $value)
{
$this->_setErrorHandler();
ldap_set_option($this->getConnection(), $option, $value);
$this->_unsetErrorHandler();
} | php | public function setOption($option, $value)
{
$this->_setErrorHandler();
ldap_set_option($this->getConnection(), $option, $value);
$this->_unsetErrorHandler();
} | [
"public",
"function",
"setOption",
"(",
"$",
"option",
",",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"_setErrorHandler",
"(",
")",
";",
"ldap_set_option",
"(",
"$",
"this",
"->",
"getConnection",
"(",
")",
",",
"$",
"option",
",",
"$",
"value",
")",
... | Set the value of the given option
@param int $option Option to set
@param mixed $value The new value for the specified option
@return void | [
"Set",
"the",
"value",
"of",
"the",
"given",
"option"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/Ldap/ExtensionAdapter.php#L114-L119 | train |
cakephp/authentication | src/Identifier/Ldap/ExtensionAdapter.php | ExtensionAdapter.getOption | public function getOption($option)
{
$this->_setErrorHandler();
ldap_get_option($this->getConnection(), $option, $returnValue);
$this->_unsetErrorHandler();
return $returnValue;
} | php | public function getOption($option)
{
$this->_setErrorHandler();
ldap_get_option($this->getConnection(), $option, $returnValue);
$this->_unsetErrorHandler();
return $returnValue;
} | [
"public",
"function",
"getOption",
"(",
"$",
"option",
")",
"{",
"$",
"this",
"->",
"_setErrorHandler",
"(",
")",
";",
"ldap_get_option",
"(",
"$",
"this",
"->",
"getConnection",
"(",
")",
",",
"$",
"option",
",",
"$",
"returnValue",
")",
";",
"$",
"th... | Get the current value for given option
@param int $option Option to get
@return mixed This will be set to the option value. | [
"Get",
"the",
"current",
"value",
"for",
"given",
"option"
] | aad857210fc790073501925333ce3db6b6e20887 | https://github.com/cakephp/authentication/blob/aad857210fc790073501925333ce3db6b6e20887/src/Identifier/Ldap/ExtensionAdapter.php#L127-L134 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.