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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Gregwar/Image | Image.php | Image.cacheFile | public function cacheFile($type = 'jpg', $quality = 80, $actual = false)
{
if ($type == 'guess') {
$type = $this->guessType();
}
if (!count($this->operations) && $type == $this->guessType() && !$this->forceCache) {
return $this->getFilename($this->getFilePath());
}
// Computes the hash
$this->hash = $this->getHash($type, $quality);
// Generates the cache file
$cacheFile = '';
if (!$this->prettyName || $this->prettyPrefix) {
$cacheFile .= $this->hash;
}
if ($this->prettyPrefix) {
$cacheFile .= '-';
}
if ($this->prettyName) {
$cacheFile .= $this->prettyName;
}
$cacheFile .= '.'.$type;
// If the files does not exists, save it
$image = $this;
// Target file should be younger than all the current image
// dependencies
$conditions = array(
'younger-than' => $this->getDependencies(),
);
// The generating function
$generate = function ($target) use ($image, $type, $quality) {
$result = $image->save($target, $type, $quality);
if ($result != $target) {
throw new GenerationError($result);
}
};
// Asking the cache for the cacheFile
try {
$file = $this->getCacheSystem()->getOrCreateFile($cacheFile, $conditions, $generate, $actual);
} catch (GenerationError $e) {
$file = $e->getNewFile();
}
// Nulling the resource
$this->getAdapter()->setSource(new Source\File($file));
$this->getAdapter()->deinit();
if ($actual) {
return $file;
} else {
return $this->getFilename($file);
}
} | php | public function cacheFile($type = 'jpg', $quality = 80, $actual = false)
{
if ($type == 'guess') {
$type = $this->guessType();
}
if (!count($this->operations) && $type == $this->guessType() && !$this->forceCache) {
return $this->getFilename($this->getFilePath());
}
// Computes the hash
$this->hash = $this->getHash($type, $quality);
// Generates the cache file
$cacheFile = '';
if (!$this->prettyName || $this->prettyPrefix) {
$cacheFile .= $this->hash;
}
if ($this->prettyPrefix) {
$cacheFile .= '-';
}
if ($this->prettyName) {
$cacheFile .= $this->prettyName;
}
$cacheFile .= '.'.$type;
// If the files does not exists, save it
$image = $this;
// Target file should be younger than all the current image
// dependencies
$conditions = array(
'younger-than' => $this->getDependencies(),
);
// The generating function
$generate = function ($target) use ($image, $type, $quality) {
$result = $image->save($target, $type, $quality);
if ($result != $target) {
throw new GenerationError($result);
}
};
// Asking the cache for the cacheFile
try {
$file = $this->getCacheSystem()->getOrCreateFile($cacheFile, $conditions, $generate, $actual);
} catch (GenerationError $e) {
$file = $e->getNewFile();
}
// Nulling the resource
$this->getAdapter()->setSource(new Source\File($file));
$this->getAdapter()->deinit();
if ($actual) {
return $file;
} else {
return $this->getFilename($file);
}
} | [
"public",
"function",
"cacheFile",
"(",
"$",
"type",
"=",
"'jpg'",
",",
"$",
"quality",
"=",
"80",
",",
"$",
"actual",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"type",
"==",
"'guess'",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"guessType",
"(... | Gets the cache file name and generate it if it does not exists.
Note that if it exists, all the image computation process will
not be done.
@param string $type the image type
@param int $quality the quality (for JPEG) | [
"Gets",
"the",
"cache",
"file",
"name",
"and",
"generate",
"it",
"if",
"it",
"does",
"not",
"exists",
".",
"Note",
"that",
"if",
"it",
"exists",
"all",
"the",
"image",
"computation",
"process",
"will",
"not",
"be",
"done",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Image.php#L466-L530 | train |
Gregwar/Image | Image.php | Image.getDependencies | public function getDependencies()
{
$dependencies = array();
$file = $this->getFilePath();
if ($file) {
$dependencies[] = $file;
}
foreach ($this->operations as $operation) {
foreach ($operation[1] as $argument) {
if ($argument instanceof self) {
$dependencies = array_merge($dependencies, $argument->getDependencies());
}
}
}
return $dependencies;
} | php | public function getDependencies()
{
$dependencies = array();
$file = $this->getFilePath();
if ($file) {
$dependencies[] = $file;
}
foreach ($this->operations as $operation) {
foreach ($operation[1] as $argument) {
if ($argument instanceof self) {
$dependencies = array_merge($dependencies, $argument->getDependencies());
}
}
}
return $dependencies;
} | [
"public",
"function",
"getDependencies",
"(",
")",
"{",
"$",
"dependencies",
"=",
"array",
"(",
")",
";",
"$",
"file",
"=",
"$",
"this",
"->",
"getFilePath",
"(",
")",
";",
"if",
"(",
"$",
"file",
")",
"{",
"$",
"dependencies",
"[",
"]",
"=",
"$",
... | Get all the files that this image depends on.
@return string[] this is an array of strings containing all the files that the
current Image depends on | [
"Get",
"all",
"the",
"files",
"that",
"this",
"image",
"depends",
"on",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Image.php#L597-L615 | train |
Gregwar/Image | Image.php | Image.applyOperations | public function applyOperations()
{
// Renders the effects
foreach ($this->operations as $operation) {
call_user_func_array(array($this->adapter, $operation[0]), $operation[1]);
}
} | php | public function applyOperations()
{
// Renders the effects
foreach ($this->operations as $operation) {
call_user_func_array(array($this->adapter, $operation[0]), $operation[1]);
}
} | [
"public",
"function",
"applyOperations",
"(",
")",
"{",
"// Renders the effects",
"foreach",
"(",
"$",
"this",
"->",
"operations",
"as",
"$",
"operation",
")",
"{",
"call_user_func_array",
"(",
"array",
"(",
"$",
"this",
"->",
"adapter",
",",
"$",
"operation",... | Applies the operations. | [
"Applies",
"the",
"operations",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Image.php#L620-L626 | train |
Gregwar/Image | Image.php | Image.save | public function save($file, $type = 'guess', $quality = 80)
{
if ($file) {
$directory = dirname($file);
if (!is_dir($directory)) {
@mkdir($directory, 0777, true);
}
}
if (is_int($type)) {
$quality = $type;
$type = 'jpeg';
}
if ($type == 'guess') {
$type = $this->guessType();
}
if (!isset(self::$types[$type])) {
throw new \InvalidArgumentException('Given type ('.$type.') is not valid');
}
$type = self::$types[$type];
try {
$this->init();
$this->applyOperations();
$success = false;
if (null == $file) {
ob_start();
}
if ($type == 'jpeg') {
$success = $this->getAdapter()->saveJpeg($file, $quality);
}
if ($type == 'gif') {
$success = $this->getAdapter()->saveGif($file);
}
if ($type == 'png') {
$success = $this->getAdapter()->savePng($file);
}
if ($type == 'webp') {
$success = $this->getAdapter()->saveWebP($file, $quality);
}
if (!$success) {
return false;
}
return null === $file ? ob_get_clean() : $file;
} catch (\Exception $e) {
if ($this->useFallbackImage) {
return null === $file ? file_get_contents($this->fallback) : $this->getCacheFallback();
} else {
throw $e;
}
}
} | php | public function save($file, $type = 'guess', $quality = 80)
{
if ($file) {
$directory = dirname($file);
if (!is_dir($directory)) {
@mkdir($directory, 0777, true);
}
}
if (is_int($type)) {
$quality = $type;
$type = 'jpeg';
}
if ($type == 'guess') {
$type = $this->guessType();
}
if (!isset(self::$types[$type])) {
throw new \InvalidArgumentException('Given type ('.$type.') is not valid');
}
$type = self::$types[$type];
try {
$this->init();
$this->applyOperations();
$success = false;
if (null == $file) {
ob_start();
}
if ($type == 'jpeg') {
$success = $this->getAdapter()->saveJpeg($file, $quality);
}
if ($type == 'gif') {
$success = $this->getAdapter()->saveGif($file);
}
if ($type == 'png') {
$success = $this->getAdapter()->savePng($file);
}
if ($type == 'webp') {
$success = $this->getAdapter()->saveWebP($file, $quality);
}
if (!$success) {
return false;
}
return null === $file ? ob_get_clean() : $file;
} catch (\Exception $e) {
if ($this->useFallbackImage) {
return null === $file ? file_get_contents($this->fallback) : $this->getCacheFallback();
} else {
throw $e;
}
}
} | [
"public",
"function",
"save",
"(",
"$",
"file",
",",
"$",
"type",
"=",
"'guess'",
",",
"$",
"quality",
"=",
"80",
")",
"{",
"if",
"(",
"$",
"file",
")",
"{",
"$",
"directory",
"=",
"dirname",
"(",
"$",
"file",
")",
";",
"if",
"(",
"!",
"is_dir"... | Save the file to a given output. | [
"Save",
"the",
"file",
"to",
"a",
"given",
"output",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Image.php#L639-L702 | train |
Gregwar/Image | Image.php | Image.inline | public function inline($type = 'jpg', $quality = 80)
{
$mime = $type;
if ($mime == 'jpg') {
$mime = 'jpeg';
}
return 'data:image/'.$mime.';base64,'.base64_encode(file_get_contents($this->cacheFile($type, $quality, true)));
} | php | public function inline($type = 'jpg', $quality = 80)
{
$mime = $type;
if ($mime == 'jpg') {
$mime = 'jpeg';
}
return 'data:image/'.$mime.';base64,'.base64_encode(file_get_contents($this->cacheFile($type, $quality, true)));
} | [
"public",
"function",
"inline",
"(",
"$",
"type",
"=",
"'jpg'",
",",
"$",
"quality",
"=",
"80",
")",
"{",
"$",
"mime",
"=",
"$",
"type",
";",
"if",
"(",
"$",
"mime",
"==",
"'jpg'",
")",
"{",
"$",
"mime",
"=",
"'jpeg'",
";",
"}",
"return",
"'dat... | Returns the Base64 inlinable representation. | [
"Returns",
"the",
"Base64",
"inlinable",
"representation",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Image.php#L749-L757 | train |
Gregwar/Image | Adapter/GD.php | GD.TTFBox | public static function TTFBox($font, $text, $size, $angle = 0)
{
$box = imagettfbbox($size, $angle, $font, $text);
return array(
'width' => abs($box[2] - $box[0]),
'height' => abs($box[3] - $box[5]),
);
} | php | public static function TTFBox($font, $text, $size, $angle = 0)
{
$box = imagettfbbox($size, $angle, $font, $text);
return array(
'width' => abs($box[2] - $box[0]),
'height' => abs($box[3] - $box[5]),
);
} | [
"public",
"static",
"function",
"TTFBox",
"(",
"$",
"font",
",",
"$",
"text",
",",
"$",
"size",
",",
"$",
"angle",
"=",
"0",
")",
"{",
"$",
"box",
"=",
"imagettfbbox",
"(",
"$",
"size",
",",
"$",
"angle",
",",
"$",
"font",
",",
"$",
"text",
")"... | Gets the width and the height for writing some text. | [
"Gets",
"the",
"width",
"and",
"the",
"height",
"for",
"writing",
"some",
"text",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Adapter/GD.php#L25-L33 | train |
Gregwar/Image | Adapter/GD.php | GD.doResize | protected function doResize($bg, $target_width, $target_height, $new_width, $new_height)
{
$width = $this->width();
$height = $this->height();
$n = imagecreatetruecolor($target_width, $target_height);
if ($bg != 'transparent') {
imagefill($n, 0, 0, ImageColor::gdAllocate($this->resource, $bg));
} else {
imagealphablending($n, false);
$color = ImageColor::gdAllocate($this->resource, 'transparent');
imagefill($n, 0, 0, $color);
imagesavealpha($n, true);
}
imagecopyresampled($n, $this->resource, ($target_width - $new_width) / 2, ($target_height - $new_height) / 2, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($this->resource);
$this->resource = $n;
return $this;
} | php | protected function doResize($bg, $target_width, $target_height, $new_width, $new_height)
{
$width = $this->width();
$height = $this->height();
$n = imagecreatetruecolor($target_width, $target_height);
if ($bg != 'transparent') {
imagefill($n, 0, 0, ImageColor::gdAllocate($this->resource, $bg));
} else {
imagealphablending($n, false);
$color = ImageColor::gdAllocate($this->resource, 'transparent');
imagefill($n, 0, 0, $color);
imagesavealpha($n, true);
}
imagecopyresampled($n, $this->resource, ($target_width - $new_width) / 2, ($target_height - $new_height) / 2, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($this->resource);
$this->resource = $n;
return $this;
} | [
"protected",
"function",
"doResize",
"(",
"$",
"bg",
",",
"$",
"target_width",
",",
"$",
"target_height",
",",
"$",
"new_width",
",",
"$",
"new_height",
")",
"{",
"$",
"width",
"=",
"$",
"this",
"->",
"width",
"(",
")",
";",
"$",
"height",
"=",
"$",
... | Do the image resize.
@return $this | [
"Do",
"the",
"image",
"resize",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Adapter/GD.php#L73-L95 | train |
Gregwar/Image | Adapter/GD.php | GD.convertToTrueColor | protected function convertToTrueColor()
{
if (!imageistruecolor($this->resource)) {
if (function_exists('imagepalettetotruecolor')) {
// Available in PHP 5.5
imagepalettetotruecolor($this->resource);
} else {
$transparentIndex = imagecolortransparent($this->resource);
$w = $this->width();
$h = $this->height();
$img = imagecreatetruecolor($w, $h);
imagecopy($img, $this->resource, 0, 0, 0, 0, $w, $h);
if ($transparentIndex != -1) {
$width = $this->width();
$height = $this->height();
imagealphablending($img, false);
imagesavealpha($img, true);
for ($x = 0; $x < $width; ++$x) {
for ($y = 0; $y < $height; ++$y) {
if (imagecolorat($this->resource, $x, $y) == $transparentIndex) {
imagesetpixel($img, $x, $y, 127 << 24);
}
}
}
}
$this->resource = $img;
}
}
imagesavealpha($this->resource, true);
} | php | protected function convertToTrueColor()
{
if (!imageistruecolor($this->resource)) {
if (function_exists('imagepalettetotruecolor')) {
// Available in PHP 5.5
imagepalettetotruecolor($this->resource);
} else {
$transparentIndex = imagecolortransparent($this->resource);
$w = $this->width();
$h = $this->height();
$img = imagecreatetruecolor($w, $h);
imagecopy($img, $this->resource, 0, 0, 0, 0, $w, $h);
if ($transparentIndex != -1) {
$width = $this->width();
$height = $this->height();
imagealphablending($img, false);
imagesavealpha($img, true);
for ($x = 0; $x < $width; ++$x) {
for ($y = 0; $y < $height; ++$y) {
if (imagecolorat($this->resource, $x, $y) == $transparentIndex) {
imagesetpixel($img, $x, $y, 127 << 24);
}
}
}
}
$this->resource = $img;
}
}
imagesavealpha($this->resource, true);
} | [
"protected",
"function",
"convertToTrueColor",
"(",
")",
"{",
"if",
"(",
"!",
"imageistruecolor",
"(",
"$",
"this",
"->",
"resource",
")",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'imagepalettetotruecolor'",
")",
")",
"{",
"// Available in PHP 5.5",
"imagep... | Converts the image to true color. | [
"Converts",
"the",
"image",
"to",
"true",
"color",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Adapter/GD.php#L514-L550 | train |
Gregwar/Image | Adapter/GD.php | GD.openJpeg | protected function openJpeg($file)
{
if (file_exists($file) && filesize($file)) {
$this->resource = @imagecreatefromjpeg($file);
} else {
$this->resource = false;
}
} | php | protected function openJpeg($file)
{
if (file_exists($file) && filesize($file)) {
$this->resource = @imagecreatefromjpeg($file);
} else {
$this->resource = false;
}
} | [
"protected",
"function",
"openJpeg",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"file",
")",
"&&",
"filesize",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"resource",
"=",
"@",
"imagecreatefromjpeg",
"(",
"$",
"file",
")"... | Try to open the file using jpeg. | [
"Try",
"to",
"open",
"the",
"file",
"using",
"jpeg",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Adapter/GD.php#L597-L604 | train |
Gregwar/Image | Adapter/GD.php | GD.openGif | protected function openGif($file)
{
if (file_exists($file) && filesize($file)) {
$this->resource = @imagecreatefromgif($file);
} else {
$this->resource = false;
}
} | php | protected function openGif($file)
{
if (file_exists($file) && filesize($file)) {
$this->resource = @imagecreatefromgif($file);
} else {
$this->resource = false;
}
} | [
"protected",
"function",
"openGif",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"file",
")",
"&&",
"filesize",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"resource",
"=",
"@",
"imagecreatefromgif",
"(",
"$",
"file",
")",
... | Try to open the file using gif. | [
"Try",
"to",
"open",
"the",
"file",
"using",
"gif",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Adapter/GD.php#L609-L616 | train |
Gregwar/Image | Adapter/GD.php | GD.openPng | protected function openPng($file)
{
if (file_exists($file) && filesize($file)) {
$this->resource = @imagecreatefrompng($file);
} else {
$this->resource = false;
}
} | php | protected function openPng($file)
{
if (file_exists($file) && filesize($file)) {
$this->resource = @imagecreatefrompng($file);
} else {
$this->resource = false;
}
} | [
"protected",
"function",
"openPng",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"file",
")",
"&&",
"filesize",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"resource",
"=",
"@",
"imagecreatefrompng",
"(",
"$",
"file",
")",
... | Try to open the file using PNG. | [
"Try",
"to",
"open",
"the",
"file",
"using",
"PNG",
"."
] | 03534d5760cbea5c96e6292041ff81a3bb205c36 | https://github.com/Gregwar/Image/blob/03534d5760cbea5c96e6292041ff81a3bb205c36/Adapter/GD.php#L621-L628 | train |
bjeavons/zxcvbn-php | src/Matchers/Match.php | Match.findAll | public static function findAll($string, $regex)
{
$count = preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
if (!$count) {
return [];
}
$pos = 0;
$groups = [];
foreach ($matches as $group) {
$captureBegin = 0;
$match = array_shift($group);
$matchBegin = strpos($string, $match, $pos);
$captures = [
[
'begin' => $matchBegin,
'end' => $matchBegin + strlen($match) - 1,
'token' => $match,
],
];
foreach ($group as $capture) {
$captureBegin = strpos($match, $capture, $captureBegin);
$captures[] = [
'begin' => $matchBegin + $captureBegin,
'end' => $matchBegin + $captureBegin + strlen($capture) - 1,
'token' => $capture,
];
}
$groups[] = $captures;
$pos += strlen($match) - 1;
}
return $groups;
} | php | public static function findAll($string, $regex)
{
$count = preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
if (!$count) {
return [];
}
$pos = 0;
$groups = [];
foreach ($matches as $group) {
$captureBegin = 0;
$match = array_shift($group);
$matchBegin = strpos($string, $match, $pos);
$captures = [
[
'begin' => $matchBegin,
'end' => $matchBegin + strlen($match) - 1,
'token' => $match,
],
];
foreach ($group as $capture) {
$captureBegin = strpos($match, $capture, $captureBegin);
$captures[] = [
'begin' => $matchBegin + $captureBegin,
'end' => $matchBegin + $captureBegin + strlen($capture) - 1,
'token' => $capture,
];
}
$groups[] = $captures;
$pos += strlen($match) - 1;
}
return $groups;
} | [
"public",
"static",
"function",
"findAll",
"(",
"$",
"string",
",",
"$",
"regex",
")",
"{",
"$",
"count",
"=",
"preg_match_all",
"(",
"$",
"regex",
",",
"$",
"string",
",",
"$",
"matches",
",",
"PREG_SET_ORDER",
")",
";",
"if",
"(",
"!",
"$",
"count"... | Find all occurences of regular expression in a string.
@param string $string String to search
@param string $regex Regular expression with captures
@return array
Array of capture groups. Captures in a group have named indexes: 'begin', 'end', 'token'.
e.g. fishfish /(fish)/
array(
array(
array('begin' => 0, 'end' => 3, 'token' => 'fish'),
array('begin' => 0, 'end' => 3, 'token' => 'fish')
),
array(
array('begin' => 4, 'end' => 7, 'token' => 'fish'),
array('begin' => 4, 'end' => 7, 'token' => 'fish')
)
) | [
"Find",
"all",
"occurences",
"of",
"regular",
"expression",
"in",
"a",
"string",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/Match.php#L99-L132 | train |
bjeavons/zxcvbn-php | src/Matchers/Match.php | Match.getCardinality | public function getCardinality()
{
if (null !== $this->cardinality) {
return $this->cardinality;
}
$lower = $upper = $digits = $symbols = $unicode = 0;
// Use token instead of password to support bruteforce matches on sub-string
// of password.
$chars = str_split($this->token);
foreach ($chars as $char) {
$ord = ord($char);
if ($this->isDigit($ord)) {
$digits = 10;
} elseif ($this->isUpper($ord)) {
$upper = 26;
} elseif ($this->isLower($ord)) {
$lower = 26;
} elseif ($this->isSymbol($ord)) {
$symbols = 33;
} else {
$unicode = 100;
}
}
$this->cardinality = $lower + $digits + $upper + $symbols + $unicode;
return $this->cardinality;
} | php | public function getCardinality()
{
if (null !== $this->cardinality) {
return $this->cardinality;
}
$lower = $upper = $digits = $symbols = $unicode = 0;
// Use token instead of password to support bruteforce matches on sub-string
// of password.
$chars = str_split($this->token);
foreach ($chars as $char) {
$ord = ord($char);
if ($this->isDigit($ord)) {
$digits = 10;
} elseif ($this->isUpper($ord)) {
$upper = 26;
} elseif ($this->isLower($ord)) {
$lower = 26;
} elseif ($this->isSymbol($ord)) {
$symbols = 33;
} else {
$unicode = 100;
}
}
$this->cardinality = $lower + $digits + $upper + $symbols + $unicode;
return $this->cardinality;
} | [
"public",
"function",
"getCardinality",
"(",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"cardinality",
")",
"{",
"return",
"$",
"this",
"->",
"cardinality",
";",
"}",
"$",
"lower",
"=",
"$",
"upper",
"=",
"$",
"digits",
"=",
"$",
"symbols... | Get token's symbol space.
@return int | [
"Get",
"token",
"s",
"symbol",
"space",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/Match.php#L139-L167 | train |
bjeavons/zxcvbn-php | src/Zxcvbn.php | Zxcvbn.passwordStrength | public function passwordStrength($password, array $userInputs = [])
{
$timeStart = microtime(true);
if ('' === $password) {
$timeStop = microtime(true) - $timeStart;
return $this->result($password, 0, [], 0, ['calc_time' => $timeStop]);
}
// Get matches for $password.
$matches = $this->matcher->getMatches($password, $userInputs);
// Calcuate minimum entropy and get best match sequence.
$entropy = $this->searcher->getMinimumEntropy($password, $matches);
$bestMatches = $this->searcher->matchSequence;
// Calculate score and get crack time.
$score = $this->scorer->score($entropy);
$metrics = $this->scorer->getMetrics();
$timeStop = microtime(true) - $timeStart;
// Include metrics and calculation time.
$params = array_merge($metrics, ['calc_time' => $timeStop]);
return $this->result($password, $entropy, $bestMatches, $score, $params);
} | php | public function passwordStrength($password, array $userInputs = [])
{
$timeStart = microtime(true);
if ('' === $password) {
$timeStop = microtime(true) - $timeStart;
return $this->result($password, 0, [], 0, ['calc_time' => $timeStop]);
}
// Get matches for $password.
$matches = $this->matcher->getMatches($password, $userInputs);
// Calcuate minimum entropy and get best match sequence.
$entropy = $this->searcher->getMinimumEntropy($password, $matches);
$bestMatches = $this->searcher->matchSequence;
// Calculate score and get crack time.
$score = $this->scorer->score($entropy);
$metrics = $this->scorer->getMetrics();
$timeStop = microtime(true) - $timeStart;
// Include metrics and calculation time.
$params = array_merge($metrics, ['calc_time' => $timeStop]);
return $this->result($password, $entropy, $bestMatches, $score, $params);
} | [
"public",
"function",
"passwordStrength",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"$",
"timeStart",
"=",
"microtime",
"(",
"true",
")",
";",
"if",
"(",
"''",
"===",
"$",
"password",
")",
"{",
"$",
"timeStop",
"... | Calculate password strength via non-overlapping minimum entropy patterns.
@param string $password Password to measure
@param array $userInputs Optional user inputs
@return array Strength result array with keys:
password
entropy
match_sequence
score | [
"Calculate",
"password",
"strength",
"via",
"non",
"-",
"overlapping",
"minimum",
"entropy",
"patterns",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Zxcvbn.php#L41-L66 | train |
bjeavons/zxcvbn-php | src/Zxcvbn.php | Zxcvbn.result | protected function result($password, $entropy, $matches, $score, $params = [])
{
$r = [
'password' => $password,
'entropy' => $entropy,
'match_sequence' => $matches,
'score' => $score,
];
return array_merge($params, $r);
} | php | protected function result($password, $entropy, $matches, $score, $params = [])
{
$r = [
'password' => $password,
'entropy' => $entropy,
'match_sequence' => $matches,
'score' => $score,
];
return array_merge($params, $r);
} | [
"protected",
"function",
"result",
"(",
"$",
"password",
",",
"$",
"entropy",
",",
"$",
"matches",
",",
"$",
"score",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"r",
"=",
"[",
"'password'",
"=>",
"$",
"password",
",",
"'entropy'",
"=>",
"$",... | Result array.
@param string $password
@param float $entropy
@param array $matches
@param int $score
@param array $params
@return array | [
"Result",
"array",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Zxcvbn.php#L79-L89 | train |
bjeavons/zxcvbn-php | src/Matchers/SequenceMatch.php | SequenceMatch.match | public static function match($password, array $userInputs = [])
{
$matches = [];
$passwordLength = strlen($password);
$sequences = self::LOWER.self::UPPER.self::DIGITS;
$revSequences = strrev($sequences);
for ($i = 0; $i < $passwordLength; ++$i) {
$pattern = false;
$j = $i + 2;
// Check for sequence sizes of 3 or more.
if ($j < $passwordLength) {
$pattern = substr($password, $i, 3);
}
// Find beginning of pattern and then extract full sequences intersection.
if ($pattern && false !== ($pos = strpos($sequences, $pattern))) {
// Match only remaining password characters.
$remainder = substr($password, $j + 1);
$pattern .= static::intersect($sequences, $remainder, $pos + 3);
$params = [
'ascending' => true,
'sequenceName' => static::getSequenceName($pos),
'sequenceSpace' => static::getSequenceSpace($pos),
];
$matches[] = new static($password, $i, $i + strlen($pattern) - 1, $pattern, $params);
// Skip intersecting characters on next loop.
$i += strlen($pattern) - 1;
}
// Search the reverse sequence for pattern.
elseif ($pattern && false !== ($pos = strpos($revSequences, $pattern))) {
$remainder = substr($password, $j + 1);
$pattern .= static::intersect($revSequences, $remainder, $pos + 3);
$params = [
'ascending' => false,
'sequenceName' => static::getSequenceName($pos),
'sequenceSpace' => static::getSequenceSpace($pos),
];
$matches[] = new static($password, $i, $i + strlen($pattern) - 1, $pattern, $params);
$i += strlen($pattern) - 1;
}
}
return $matches;
} | php | public static function match($password, array $userInputs = [])
{
$matches = [];
$passwordLength = strlen($password);
$sequences = self::LOWER.self::UPPER.self::DIGITS;
$revSequences = strrev($sequences);
for ($i = 0; $i < $passwordLength; ++$i) {
$pattern = false;
$j = $i + 2;
// Check for sequence sizes of 3 or more.
if ($j < $passwordLength) {
$pattern = substr($password, $i, 3);
}
// Find beginning of pattern and then extract full sequences intersection.
if ($pattern && false !== ($pos = strpos($sequences, $pattern))) {
// Match only remaining password characters.
$remainder = substr($password, $j + 1);
$pattern .= static::intersect($sequences, $remainder, $pos + 3);
$params = [
'ascending' => true,
'sequenceName' => static::getSequenceName($pos),
'sequenceSpace' => static::getSequenceSpace($pos),
];
$matches[] = new static($password, $i, $i + strlen($pattern) - 1, $pattern, $params);
// Skip intersecting characters on next loop.
$i += strlen($pattern) - 1;
}
// Search the reverse sequence for pattern.
elseif ($pattern && false !== ($pos = strpos($revSequences, $pattern))) {
$remainder = substr($password, $j + 1);
$pattern .= static::intersect($revSequences, $remainder, $pos + 3);
$params = [
'ascending' => false,
'sequenceName' => static::getSequenceName($pos),
'sequenceSpace' => static::getSequenceSpace($pos),
];
$matches[] = new static($password, $i, $i + strlen($pattern) - 1, $pattern, $params);
$i += strlen($pattern) - 1;
}
}
return $matches;
} | [
"public",
"static",
"function",
"match",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"$",
"matches",
"=",
"[",
"]",
";",
"$",
"passwordLength",
"=",
"strlen",
"(",
"$",
"password",
")",
";",
"$",
"sequences",
"=",
... | Match sequences of three or more characters.
@copydoc Match::match()
@param $password
@param array $userInputs
@return array | [
"Match",
"sequences",
"of",
"three",
"or",
"more",
"characters",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/SequenceMatch.php#L54-L98 | train |
bjeavons/zxcvbn-php | src/Matchers/SequenceMatch.php | SequenceMatch.intersect | protected static function intersect($string, $subString, $start)
{
$cut = str_split(substr($string, $start, strlen($subString)));
$comp = str_split($subString);
foreach ($cut as $i => $c) {
if ($comp[$i] === $c) {
$intersect[] = $c;
} else {
break; // Stop loop since intersection ends.
}
}
if (!empty($intersect)) {
return implode('', $intersect);
}
return '';
} | php | protected static function intersect($string, $subString, $start)
{
$cut = str_split(substr($string, $start, strlen($subString)));
$comp = str_split($subString);
foreach ($cut as $i => $c) {
if ($comp[$i] === $c) {
$intersect[] = $c;
} else {
break; // Stop loop since intersection ends.
}
}
if (!empty($intersect)) {
return implode('', $intersect);
}
return '';
} | [
"protected",
"static",
"function",
"intersect",
"(",
"$",
"string",
",",
"$",
"subString",
",",
"$",
"start",
")",
"{",
"$",
"cut",
"=",
"str_split",
"(",
"substr",
"(",
"$",
"string",
",",
"$",
"start",
",",
"strlen",
"(",
"$",
"subString",
")",
")"... | Find sub-string intersection in a string.
@param string $string
@param string $subString
@param int $start
@return string | [
"Find",
"sub",
"-",
"string",
"intersection",
"in",
"a",
"string",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/SequenceMatch.php#L136-L152 | train |
bjeavons/zxcvbn-php | src/Matchers/SequenceMatch.php | SequenceMatch.getSequenceName | protected static function getSequenceName($pos, $reverse = false)
{
$sequences = self::LOWER.self::UPPER.self::DIGITS;
$end = strlen($sequences);
if (!$reverse && $pos < strlen(self::LOWER)) {
return 'lower';
}
if (!$reverse && $pos <= $end - strlen(self::DIGITS)) {
return 'upper';
}
if (!$reverse) {
return 'digits';
}
if ($pos < strlen(self::DIGITS)) {
return 'digits';
}
if ($pos <= $end - strlen(self::LOWER)) {
return 'upper';
}
return 'lower';
} | php | protected static function getSequenceName($pos, $reverse = false)
{
$sequences = self::LOWER.self::UPPER.self::DIGITS;
$end = strlen($sequences);
if (!$reverse && $pos < strlen(self::LOWER)) {
return 'lower';
}
if (!$reverse && $pos <= $end - strlen(self::DIGITS)) {
return 'upper';
}
if (!$reverse) {
return 'digits';
}
if ($pos < strlen(self::DIGITS)) {
return 'digits';
}
if ($pos <= $end - strlen(self::LOWER)) {
return 'upper';
}
return 'lower';
} | [
"protected",
"static",
"function",
"getSequenceName",
"(",
"$",
"pos",
",",
"$",
"reverse",
"=",
"false",
")",
"{",
"$",
"sequences",
"=",
"self",
"::",
"LOWER",
".",
"self",
"::",
"UPPER",
".",
"self",
"::",
"DIGITS",
";",
"$",
"end",
"=",
"strlen",
... | Name of sequence a sequences position belongs to.
@param int $pos
@param bool $reverse
@return string | [
"Name",
"of",
"sequence",
"a",
"sequences",
"position",
"belongs",
"to",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/SequenceMatch.php#L181-L206 | train |
bjeavons/zxcvbn-php | src/Scorer.php | Scorer.calcCrackTime | protected function calcCrackTime($entropy)
{
$this->crackTime = (0.5 * (2 ** $entropy)) * (self::SINGLE_GUESS / self::NUM_ATTACKERS);
return $this->crackTime;
} | php | protected function calcCrackTime($entropy)
{
$this->crackTime = (0.5 * (2 ** $entropy)) * (self::SINGLE_GUESS / self::NUM_ATTACKERS);
return $this->crackTime;
} | [
"protected",
"function",
"calcCrackTime",
"(",
"$",
"entropy",
")",
"{",
"$",
"this",
"->",
"crackTime",
"=",
"(",
"0.5",
"*",
"(",
"2",
"**",
"$",
"entropy",
")",
")",
"*",
"(",
"self",
"::",
"SINGLE_GUESS",
"/",
"self",
"::",
"NUM_ATTACKERS",
")",
... | Get average time to crack based on entropy.
@param $entropy
@return float | [
"Get",
"average",
"time",
"to",
"crack",
"based",
"on",
"entropy",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Scorer.php#L46-L51 | train |
bjeavons/zxcvbn-php | src/Matchers/L33tMatch.php | L33tMatch.match | public static function match($password, array $userInputs = [])
{
// Translate l33t password and dictionary match the translated password.
$map = static::getSubstitutions($password);
$indexSubs = array_filter($map);
if (empty($indexSubs)) {
return [];
}
$translatedWord = static::translate($password, $map);
$matches = [];
$dicts = static::getRankedDictionaries();
foreach ($dicts as $name => $dict) {
$results = static::dictionaryMatch($translatedWord, $dict);
foreach ($results as $result) {
// Set substituted elements.
$result['sub'] = [];
$result['sub_display'] = [];
foreach ($indexSubs as $i => $t) {
$result['sub'][$password[$i]] = $t;
$result['sub_display'][] = "{$password[$i]} -> ${t}";
}
$result['sub_display'] = implode(', ', $result['sub_display']);
$result['dictionary_name'] = $name;
// Replace translated token with orignal password token.
$token = substr($password, $result['begin'], $result['end'] - $result['begin'] + 1);
$matches[] = new static($password, $result['begin'], $result['end'], $token, $result);
}
}
return $matches;
} | php | public static function match($password, array $userInputs = [])
{
// Translate l33t password and dictionary match the translated password.
$map = static::getSubstitutions($password);
$indexSubs = array_filter($map);
if (empty($indexSubs)) {
return [];
}
$translatedWord = static::translate($password, $map);
$matches = [];
$dicts = static::getRankedDictionaries();
foreach ($dicts as $name => $dict) {
$results = static::dictionaryMatch($translatedWord, $dict);
foreach ($results as $result) {
// Set substituted elements.
$result['sub'] = [];
$result['sub_display'] = [];
foreach ($indexSubs as $i => $t) {
$result['sub'][$password[$i]] = $t;
$result['sub_display'][] = "{$password[$i]} -> ${t}";
}
$result['sub_display'] = implode(', ', $result['sub_display']);
$result['dictionary_name'] = $name;
// Replace translated token with orignal password token.
$token = substr($password, $result['begin'], $result['end'] - $result['begin'] + 1);
$matches[] = new static($password, $result['begin'], $result['end'], $token, $result);
}
}
return $matches;
} | [
"public",
"static",
"function",
"match",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"// Translate l33t password and dictionary match the translated password.",
"$",
"map",
"=",
"static",
"::",
"getSubstitutions",
"(",
"$",
"passw... | Match occurences of l33t words in password to dictionary words.
@copydoc Match::match()
@param $password
@param array $userInputs
@return array | [
"Match",
"occurences",
"of",
"l33t",
"words",
"in",
"password",
"to",
"dictionary",
"words",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/L33tMatch.php#L52-L83 | train |
bjeavons/zxcvbn-php | src/Matcher.php | Matcher.getMatches | public function getMatches($password, array $userInputs = [])
{
$matches = [];
foreach ($this->getMatchers() as $matcher) {
$matched = $matcher::match($password, $userInputs);
if (is_array($matched) && !empty($matched)) {
$matches = array_merge($matches, $matched);
}
}
return $matches;
} | php | public function getMatches($password, array $userInputs = [])
{
$matches = [];
foreach ($this->getMatchers() as $matcher) {
$matched = $matcher::match($password, $userInputs);
if (is_array($matched) && !empty($matched)) {
$matches = array_merge($matches, $matched);
}
}
return $matches;
} | [
"public",
"function",
"getMatches",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"$",
"matches",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getMatchers",
"(",
")",
"as",
"$",
"matcher",
")",
"{",
"$",... | Get matches for a password.
@param string $password Password string to match
@param array $userInputs Array of values related to the user (optional)
@code array('Alice Smith')
@endcode
@return array Array of Match objects | [
"Get",
"matches",
"for",
"a",
"password",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matcher.php#L17-L28 | train |
bjeavons/zxcvbn-php | src/Matcher.php | Matcher.getMatchers | protected function getMatchers()
{
// @todo change to dynamic
return [
Matchers\DateMatch::class,
Matchers\DigitMatch::class,
Matchers\L33tMatch::class,
Matchers\RepeatMatch::class,
Matchers\SequenceMatch::class,
Matchers\SpatialMatch::class,
Matchers\YearMatch::class,
Matchers\DictionaryMatch::class,
];
} | php | protected function getMatchers()
{
// @todo change to dynamic
return [
Matchers\DateMatch::class,
Matchers\DigitMatch::class,
Matchers\L33tMatch::class,
Matchers\RepeatMatch::class,
Matchers\SequenceMatch::class,
Matchers\SpatialMatch::class,
Matchers\YearMatch::class,
Matchers\DictionaryMatch::class,
];
} | [
"protected",
"function",
"getMatchers",
"(",
")",
"{",
"// @todo change to dynamic",
"return",
"[",
"Matchers",
"\\",
"DateMatch",
"::",
"class",
",",
"Matchers",
"\\",
"DigitMatch",
"::",
"class",
",",
"Matchers",
"\\",
"L33tMatch",
"::",
"class",
",",
"Matcher... | Load available Match objects to match against a password.
@return array Array of classes implementing MatchInterface | [
"Load",
"available",
"Match",
"objects",
"to",
"match",
"against",
"a",
"password",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matcher.php#L35-L48 | train |
bjeavons/zxcvbn-php | src/Matchers/DateMatch.php | DateMatch.match | public static function match($password, array $userInputs = [])
{
$matches = [];
$dates = static::datesWithoutSeparators($password) + static::datesWithSeparators($password);
foreach ($dates as $date) {
$matches[] = new static($password, $date['begin'], $date['end'], $date['token'], $date);
}
return $matches;
} | php | public static function match($password, array $userInputs = [])
{
$matches = [];
$dates = static::datesWithoutSeparators($password) + static::datesWithSeparators($password);
foreach ($dates as $date) {
$matches[] = new static($password, $date['begin'], $date['end'], $date['token'], $date);
}
return $matches;
} | [
"public",
"static",
"function",
"match",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"$",
"matches",
"=",
"[",
"]",
";",
"$",
"dates",
"=",
"static",
"::",
"datesWithoutSeparators",
"(",
"$",
"password",
")",
"+",
... | Match occurences of dates in a password.
@copydoc Match::match()
@param $password
@param array $userInputs
@return array | [
"Match",
"occurences",
"of",
"dates",
"in",
"a",
"password",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/DateMatch.php#L62-L71 | train |
bjeavons/zxcvbn-php | src/Matchers/DateMatch.php | DateMatch.getEntropy | public function getEntropy()
{
if ($this->year < 100) {
// two-digit year
$entropy = $this->log(self::NUM_DAYS * self::NUM_MONTHS * 100);
} else {
// four-digit year
$entropy = $this->log(self::NUM_DAYS * self::NUM_MONTHS * self::NUM_YEARS);
}
// add two bits for separator selection [/,-,.,etc]
if (!empty($this->separator)) {
$entropy += 2;
}
return $entropy;
} | php | public function getEntropy()
{
if ($this->year < 100) {
// two-digit year
$entropy = $this->log(self::NUM_DAYS * self::NUM_MONTHS * 100);
} else {
// four-digit year
$entropy = $this->log(self::NUM_DAYS * self::NUM_MONTHS * self::NUM_YEARS);
}
// add two bits for separator selection [/,-,.,etc]
if (!empty($this->separator)) {
$entropy += 2;
}
return $entropy;
} | [
"public",
"function",
"getEntropy",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"year",
"<",
"100",
")",
"{",
"// two-digit year",
"$",
"entropy",
"=",
"$",
"this",
"->",
"log",
"(",
"self",
"::",
"NUM_DAYS",
"*",
"self",
"::",
"NUM_MONTHS",
"*",
"1... | Get match entropy.
@return float | [
"Get",
"match",
"entropy",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/DateMatch.php#L78-L93 | train |
bjeavons/zxcvbn-php | src/Matchers/DateMatch.php | DateMatch.datesWithSeparators | protected static function datesWithSeparators($password)
{
$dates = [];
foreach (static::findAll($password, static::DATE_RX_YEAR_SUFFIX) as $captures) {
$date = [
'day' => (int) $captures[1]['token'],
'month' => (int) $captures[3]['token'],
'year' => (int) $captures[4]['token'],
'sep' => $captures[2]['token'],
'begin' => $captures[0]['begin'],
'end' => $captures[0]['end'],
];
$dates[] = $date;
}
foreach (static::findAll($password, static::DATE_RX_YEAR_PREFIX) as $captures) {
$date = [
'day' => (int) $captures[4]['token'],
'month' => (int) $captures[3]['token'],
'year' => (int) $captures[1]['token'],
'sep' => $captures[2]['token'],
'begin' => $captures[0]['begin'],
'end' => $captures[0]['end'],
];
$dates[] = $date;
}
$results = [];
foreach ($dates as $candidate) {
$date = static::checkDate($candidate['day'], $candidate['month'], $candidate['year']);
if (false === $date) {
continue;
}
list($day, $month, $year) = $date;
$results[] = [
'pattern' => 'date',
'begin' => $candidate['begin'],
'end' => $candidate['end'],
'token' => substr($password, $candidate['begin'], $candidate['begin'] + $candidate['end'] - 1),
'separator' => $candidate['sep'],
'day' => $day,
'month' => $month,
'year' => $year,
];
}
return $results;
} | php | protected static function datesWithSeparators($password)
{
$dates = [];
foreach (static::findAll($password, static::DATE_RX_YEAR_SUFFIX) as $captures) {
$date = [
'day' => (int) $captures[1]['token'],
'month' => (int) $captures[3]['token'],
'year' => (int) $captures[4]['token'],
'sep' => $captures[2]['token'],
'begin' => $captures[0]['begin'],
'end' => $captures[0]['end'],
];
$dates[] = $date;
}
foreach (static::findAll($password, static::DATE_RX_YEAR_PREFIX) as $captures) {
$date = [
'day' => (int) $captures[4]['token'],
'month' => (int) $captures[3]['token'],
'year' => (int) $captures[1]['token'],
'sep' => $captures[2]['token'],
'begin' => $captures[0]['begin'],
'end' => $captures[0]['end'],
];
$dates[] = $date;
}
$results = [];
foreach ($dates as $candidate) {
$date = static::checkDate($candidate['day'], $candidate['month'], $candidate['year']);
if (false === $date) {
continue;
}
list($day, $month, $year) = $date;
$results[] = [
'pattern' => 'date',
'begin' => $candidate['begin'],
'end' => $candidate['end'],
'token' => substr($password, $candidate['begin'], $candidate['begin'] + $candidate['end'] - 1),
'separator' => $candidate['sep'],
'day' => $day,
'month' => $month,
'year' => $year,
];
}
return $results;
} | [
"protected",
"static",
"function",
"datesWithSeparators",
"(",
"$",
"password",
")",
"{",
"$",
"dates",
"=",
"[",
"]",
";",
"foreach",
"(",
"static",
"::",
"findAll",
"(",
"$",
"password",
",",
"static",
"::",
"DATE_RX_YEAR_SUFFIX",
")",
"as",
"$",
"captur... | Find dates with separators in a password.
@param string $password
@return array | [
"Find",
"dates",
"with",
"separators",
"in",
"a",
"password",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/DateMatch.php#L102-L150 | train |
bjeavons/zxcvbn-php | src/Matchers/DateMatch.php | DateMatch.checkDate | protected static function checkDate($day, $month, $year)
{
// Tolerate both day-month and month-day order
if ((12 <= $month && $month <= 31) && $day <= 12) {
$m = $month;
$month = $day;
$day = $m;
}
if ($day > 31 || $month > 12) {
return false;
}
if (!(1900 <= $year && $year <= 2019)) {
return false;
}
return [$day, $month, $year];
} | php | protected static function checkDate($day, $month, $year)
{
// Tolerate both day-month and month-day order
if ((12 <= $month && $month <= 31) && $day <= 12) {
$m = $month;
$month = $day;
$day = $m;
}
if ($day > 31 || $month > 12) {
return false;
}
if (!(1900 <= $year && $year <= 2019)) {
return false;
}
return [$day, $month, $year];
} | [
"protected",
"static",
"function",
"checkDate",
"(",
"$",
"day",
",",
"$",
"month",
",",
"$",
"year",
")",
"{",
"// Tolerate both day-month and month-day order",
"if",
"(",
"(",
"12",
"<=",
"$",
"month",
"&&",
"$",
"month",
"<=",
"31",
")",
"&&",
"$",
"d... | Validate date.
@param int $day
@param int $month
@param int $year
@return array|false | [
"Validate",
"date",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/DateMatch.php#L285-L301 | train |
bjeavons/zxcvbn-php | src/Matchers/YearMatch.php | YearMatch.match | public static function match($password, array $userInputs = [])
{
$matches = [];
$groups = static::findAll($password, '/(19\\d\\d|200\\d|201\\d)/');
foreach ($groups as $captures) {
$matches[] = new static($password, $captures[1]['begin'], $captures[1]['end'], $captures[1]['token']);
}
return $matches;
} | php | public static function match($password, array $userInputs = [])
{
$matches = [];
$groups = static::findAll($password, '/(19\\d\\d|200\\d|201\\d)/');
foreach ($groups as $captures) {
$matches[] = new static($password, $captures[1]['begin'], $captures[1]['end'], $captures[1]['token']);
}
return $matches;
} | [
"public",
"static",
"function",
"match",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"$",
"matches",
"=",
"[",
"]",
";",
"$",
"groups",
"=",
"static",
"::",
"findAll",
"(",
"$",
"password",
",",
"'/(19\\\\d\\\\d|200\... | Match occurences of years in a password.
@copydoc Match::match()
@param $password
@param array $userInputs
@return array | [
"Match",
"occurences",
"of",
"years",
"in",
"a",
"password",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/YearMatch.php#L31-L40 | train |
bjeavons/zxcvbn-php | src/Searcher.php | Searcher.getMinimumEntropy | public function getMinimumEntropy($password, $matches)
{
$passwordLength = strlen($password);
$entropyStack = [];
// for the optimal sequence of matches up to k, holds the final match (match.end == k).
// null means the sequence ends without a brute-force character.
$backpointers = [];
$bruteforceMatch = new Bruteforce($password, 0, $passwordLength - 1, $password);
$charEntropy = log($bruteforceMatch->getCardinality(), 2);
foreach (range(0, $passwordLength - 1) as $k) {
// starting scenario to try and beat: adding a brute-force character to the minimum entropy sequence at k-1.
$entropyStack[$k] = $this->prevValue($entropyStack, $k) + $charEntropy;
$backpointers[$k] = null;
foreach ($matches as $match) {
if (!isset($match->begin) || $match->end !== $k) {
continue;
}
// See if entropy prior to match + entropy of this match is less than
// the current minimum top of the stack.
$candidateEntropy = $this->prevValue($entropyStack, $match->begin) + $match->getEntropy();
if ($candidateEntropy <= $entropyStack[$k]) {
$entropyStack[$k] = $candidateEntropy;
$backpointers[$k] = $match;
}
}
}
// Walk backwards and decode the best sequence
$matchSequence = [];
$k = $passwordLength - 1;
while ($k >= 0) {
$match = $backpointers[$k];
if ($match) {
$matchSequence[] = $match;
$k = $match->begin - 1;
} else {
--$k;
}
}
$matchSequence = array_reverse($matchSequence);
$s = 0;
$matchSequenceCopy = [];
// Handle subtrings that weren't matched as bruteforce match.
foreach ($matchSequence as $match) {
if ($match->begin - $s > 0) {
$matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $match->begin - 1, $bruteforceMatch->getCardinality());
}
$s = $match->end + 1;
$matchSequenceCopy[] = $match;
}
if ($s < $passwordLength) {
$matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $passwordLength - 1, $bruteforceMatch->getCardinality());
}
$this->matchSequence = $matchSequenceCopy;
return $entropyStack[$passwordLength - 1];
} | php | public function getMinimumEntropy($password, $matches)
{
$passwordLength = strlen($password);
$entropyStack = [];
// for the optimal sequence of matches up to k, holds the final match (match.end == k).
// null means the sequence ends without a brute-force character.
$backpointers = [];
$bruteforceMatch = new Bruteforce($password, 0, $passwordLength - 1, $password);
$charEntropy = log($bruteforceMatch->getCardinality(), 2);
foreach (range(0, $passwordLength - 1) as $k) {
// starting scenario to try and beat: adding a brute-force character to the minimum entropy sequence at k-1.
$entropyStack[$k] = $this->prevValue($entropyStack, $k) + $charEntropy;
$backpointers[$k] = null;
foreach ($matches as $match) {
if (!isset($match->begin) || $match->end !== $k) {
continue;
}
// See if entropy prior to match + entropy of this match is less than
// the current minimum top of the stack.
$candidateEntropy = $this->prevValue($entropyStack, $match->begin) + $match->getEntropy();
if ($candidateEntropy <= $entropyStack[$k]) {
$entropyStack[$k] = $candidateEntropy;
$backpointers[$k] = $match;
}
}
}
// Walk backwards and decode the best sequence
$matchSequence = [];
$k = $passwordLength - 1;
while ($k >= 0) {
$match = $backpointers[$k];
if ($match) {
$matchSequence[] = $match;
$k = $match->begin - 1;
} else {
--$k;
}
}
$matchSequence = array_reverse($matchSequence);
$s = 0;
$matchSequenceCopy = [];
// Handle subtrings that weren't matched as bruteforce match.
foreach ($matchSequence as $match) {
if ($match->begin - $s > 0) {
$matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $match->begin - 1, $bruteforceMatch->getCardinality());
}
$s = $match->end + 1;
$matchSequenceCopy[] = $match;
}
if ($s < $passwordLength) {
$matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $passwordLength - 1, $bruteforceMatch->getCardinality());
}
$this->matchSequence = $matchSequenceCopy;
return $entropyStack[$passwordLength - 1];
} | [
"public",
"function",
"getMinimumEntropy",
"(",
"$",
"password",
",",
"$",
"matches",
")",
"{",
"$",
"passwordLength",
"=",
"strlen",
"(",
"$",
"password",
")",
";",
"$",
"entropyStack",
"=",
"[",
"]",
";",
"// for the optimal sequence of matches up to k, holds th... | Calculate the minimum entropy for a password and its matches.
@param string $password Password
@param array $matches Array of Match objects on the password
@return float Minimum entropy for non-overlapping best matches of a password | [
"Calculate",
"the",
"minimum",
"entropy",
"for",
"a",
"password",
"and",
"its",
"matches",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Searcher.php#L22-L86 | train |
bjeavons/zxcvbn-php | src/Searcher.php | Searcher.makeBruteforceMatch | protected function makeBruteforceMatch($password, $begin, $end, $cardinality = null)
{
$match = new Bruteforce($password, $begin, $end, substr($password, $begin, $end + 1), $cardinality);
// Set entropy in match.
$match->getEntropy();
return $match;
} | php | protected function makeBruteforceMatch($password, $begin, $end, $cardinality = null)
{
$match = new Bruteforce($password, $begin, $end, substr($password, $begin, $end + 1), $cardinality);
// Set entropy in match.
$match->getEntropy();
return $match;
} | [
"protected",
"function",
"makeBruteforceMatch",
"(",
"$",
"password",
",",
"$",
"begin",
",",
"$",
"end",
",",
"$",
"cardinality",
"=",
"null",
")",
"{",
"$",
"match",
"=",
"new",
"Bruteforce",
"(",
"$",
"password",
",",
"$",
"begin",
",",
"$",
"end",
... | Make a bruteforce match object for substring of password.
@param string $password
@param int $begin
@param int $end
@param int $cardinality optional
@return Bruteforce match | [
"Make",
"a",
"bruteforce",
"match",
"object",
"for",
"substring",
"of",
"password",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Searcher.php#L113-L120 | train |
bjeavons/zxcvbn-php | src/Matchers/RepeatMatch.php | RepeatMatch.match | public static function match($password, array $userInputs = [])
{
$groups = static::group($password);
$matches = [];
$k = 0;
foreach ($groups as $group) {
$char = $group[0];
$length = strlen($group);
if ($length > 2) {
$end = $k + $length - 1;
$token = substr($password, $k, $end + 1);
$matches[] = new static($password, $k, $end, $token, $char);
}
$k += $length;
}
return $matches;
} | php | public static function match($password, array $userInputs = [])
{
$groups = static::group($password);
$matches = [];
$k = 0;
foreach ($groups as $group) {
$char = $group[0];
$length = strlen($group);
if ($length > 2) {
$end = $k + $length - 1;
$token = substr($password, $k, $end + 1);
$matches[] = new static($password, $k, $end, $token, $char);
}
$k += $length;
}
return $matches;
} | [
"public",
"static",
"function",
"match",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"$",
"groups",
"=",
"static",
"::",
"group",
"(",
"$",
"password",
")",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"$",
"k",
"=... | Match 3 or more repeated characters.
@copydoc Match::match()
@param $password
@param array $userInputs
@return array | [
"Match",
"3",
"or",
"more",
"repeated",
"characters",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/RepeatMatch.php#L36-L55 | train |
bjeavons/zxcvbn-php | src/Matchers/RepeatMatch.php | RepeatMatch.group | protected static function group($string)
{
$grouped = [];
$chars = str_split($string);
$prevChar = null;
$i = 0;
foreach ($chars as $char) {
if ($prevChar === $char) {
$grouped[$i - 1] .= $char;
} else {
$grouped[$i] = $char;
++$i;
$prevChar = $char;
}
}
return $grouped;
} | php | protected static function group($string)
{
$grouped = [];
$chars = str_split($string);
$prevChar = null;
$i = 0;
foreach ($chars as $char) {
if ($prevChar === $char) {
$grouped[$i - 1] .= $char;
} else {
$grouped[$i] = $char;
++$i;
$prevChar = $char;
}
}
return $grouped;
} | [
"protected",
"static",
"function",
"group",
"(",
"$",
"string",
")",
"{",
"$",
"grouped",
"=",
"[",
"]",
";",
"$",
"chars",
"=",
"str_split",
"(",
"$",
"string",
")",
";",
"$",
"prevChar",
"=",
"null",
";",
"$",
"i",
"=",
"0",
";",
"foreach",
"("... | Group input by repeated characters.
@param string $string
@return array | [
"Group",
"input",
"by",
"repeated",
"characters",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/RepeatMatch.php#L76-L94 | train |
bjeavons/zxcvbn-php | src/Matchers/SpatialMatch.php | SpatialMatch.getEntropy | public function getEntropy()
{
if ('qwerty' === $this->graph || 'dvorak' === $this->graph) {
$startingPos = $this->keyboardStartingPos;
$avgDegree = $this->keyboardAvgDegree;
} else {
$startingPos = $this->keypadStartingPos;
$avgDegree = $this->keypadAvgDegree;
}
$possibilities = 0;
// estimate the number of possible patterns w/ token length or less with match turns or less.
$tokenLength = strlen($this->token);
for ($i = 2; $i <= $tokenLength; ++$i) {
$possibleTurns = min($this->turns, $i - 1);
for ($j = 1; $j <= $possibleTurns; ++$j) {
$possibilities += $this->binom($i - 1, $j - 1) * $startingPos * ($avgDegree ** $j);
}
}
$entropy = $this->log($possibilities);
// add extra entropy for shifted keys. (% instead of 5, A instead of a.)
if (!empty($this->shiftedCount)) {
$possibilities = 0;
$unshiftedCount = strlen($this->token) - $this->shiftedCount;
$len = min($this->shiftedCount, $unshiftedCount);
for ($i = 0; $i <= $len; ++$i) {
$possibilities += $this->binom($this->shiftedCount + $unshiftedCount, $i);
}
$entropy += $this->log($possibilities);
}
return $entropy;
} | php | public function getEntropy()
{
if ('qwerty' === $this->graph || 'dvorak' === $this->graph) {
$startingPos = $this->keyboardStartingPos;
$avgDegree = $this->keyboardAvgDegree;
} else {
$startingPos = $this->keypadStartingPos;
$avgDegree = $this->keypadAvgDegree;
}
$possibilities = 0;
// estimate the number of possible patterns w/ token length or less with match turns or less.
$tokenLength = strlen($this->token);
for ($i = 2; $i <= $tokenLength; ++$i) {
$possibleTurns = min($this->turns, $i - 1);
for ($j = 1; $j <= $possibleTurns; ++$j) {
$possibilities += $this->binom($i - 1, $j - 1) * $startingPos * ($avgDegree ** $j);
}
}
$entropy = $this->log($possibilities);
// add extra entropy for shifted keys. (% instead of 5, A instead of a.)
if (!empty($this->shiftedCount)) {
$possibilities = 0;
$unshiftedCount = strlen($this->token) - $this->shiftedCount;
$len = min($this->shiftedCount, $unshiftedCount);
for ($i = 0; $i <= $len; ++$i) {
$possibilities += $this->binom($this->shiftedCount + $unshiftedCount, $i);
}
$entropy += $this->log($possibilities);
}
return $entropy;
} | [
"public",
"function",
"getEntropy",
"(",
")",
"{",
"if",
"(",
"'qwerty'",
"===",
"$",
"this",
"->",
"graph",
"||",
"'dvorak'",
"===",
"$",
"this",
"->",
"graph",
")",
"{",
"$",
"startingPos",
"=",
"$",
"this",
"->",
"keyboardStartingPos",
";",
"$",
"av... | Get entropy.
@return float | [
"Get",
"entropy",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/SpatialMatch.php#L98-L133 | train |
bjeavons/zxcvbn-php | src/Matchers/SpatialMatch.php | SpatialMatch.graphMatch | protected static function graphMatch($password, $graph)
{
$result = [];
$i = 0;
$passwordLength = strlen($password);
while ($i < $passwordLength - 1) {
$j = $i + 1;
$lastDirection = null;
$turns = 0;
$shiftedCount = 0;
while (true) {
$prevChar = $password[$j - 1];
$found = false;
$curDirection = -1;
$adjacents = isset($graph[$prevChar]) ? $graph[$prevChar] : [];
// Consider growing pattern by one character if j hasn't gone over the edge.
if ($j < $passwordLength) {
$curChar = $password[$j];
foreach ($adjacents as $adj) {
++$curDirection;
$curCharPos = static::indexOf($adj, $curChar);
if ($adj && $curCharPos !== -1) {
$found = true;
$foundDirection = $curDirection;
if (1 === $curCharPos) {
// index 1 in the adjacency means the key is shifted, 0 means unshifted: A vs a, % vs 5, etc.
// for example, 'q' is adjacent to the entry '2@'. @ is shifted w/ index 1, 2 is unshifted.
++$shiftedCount;
}
if ($lastDirection !== $foundDirection) {
// adding a turn is correct even in the initial case when last_direction is null:
// every spatial pattern starts with a turn.
++$turns;
$lastDirection = $foundDirection;
}
break;
}
}
}
// if the current pattern continued, extend j and try to grow again
if ($found) {
++$j;
}
// otherwise push the pattern discovered so far, if any...
else {
// Ignore length 1 or 2 chains.
if ($j - $i > 2) {
$result[] = [
'begin' => $i,
'end' => $j - 1,
'token' => substr($password, $i, $j - $i),
'turns' => $turns,
'shifted_count' => $shiftedCount,
];
}
// ...and then start a new search for the rest of the password.
$i = $j;
break;
}
}
}
return $result;
} | php | protected static function graphMatch($password, $graph)
{
$result = [];
$i = 0;
$passwordLength = strlen($password);
while ($i < $passwordLength - 1) {
$j = $i + 1;
$lastDirection = null;
$turns = 0;
$shiftedCount = 0;
while (true) {
$prevChar = $password[$j - 1];
$found = false;
$curDirection = -1;
$adjacents = isset($graph[$prevChar]) ? $graph[$prevChar] : [];
// Consider growing pattern by one character if j hasn't gone over the edge.
if ($j < $passwordLength) {
$curChar = $password[$j];
foreach ($adjacents as $adj) {
++$curDirection;
$curCharPos = static::indexOf($adj, $curChar);
if ($adj && $curCharPos !== -1) {
$found = true;
$foundDirection = $curDirection;
if (1 === $curCharPos) {
// index 1 in the adjacency means the key is shifted, 0 means unshifted: A vs a, % vs 5, etc.
// for example, 'q' is adjacent to the entry '2@'. @ is shifted w/ index 1, 2 is unshifted.
++$shiftedCount;
}
if ($lastDirection !== $foundDirection) {
// adding a turn is correct even in the initial case when last_direction is null:
// every spatial pattern starts with a turn.
++$turns;
$lastDirection = $foundDirection;
}
break;
}
}
}
// if the current pattern continued, extend j and try to grow again
if ($found) {
++$j;
}
// otherwise push the pattern discovered so far, if any...
else {
// Ignore length 1 or 2 chains.
if ($j - $i > 2) {
$result[] = [
'begin' => $i,
'end' => $j - 1,
'token' => substr($password, $i, $j - $i),
'turns' => $turns,
'shifted_count' => $shiftedCount,
];
}
// ...and then start a new search for the rest of the password.
$i = $j;
break;
}
}
}
return $result;
} | [
"protected",
"static",
"function",
"graphMatch",
"(",
"$",
"password",
",",
"$",
"graph",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"i",
"=",
"0",
";",
"$",
"passwordLength",
"=",
"strlen",
"(",
"$",
"password",
")",
";",
"while",
"(",
"$",... | Match spatial patterns in a adjacency graph.
@param string $password
@param array $graph
@return array | [
"Match",
"spatial",
"patterns",
"in",
"a",
"adjacency",
"graph",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/SpatialMatch.php#L143-L213 | train |
bjeavons/zxcvbn-php | src/Matchers/SpatialMatch.php | SpatialMatch.indexOf | protected static function indexOf($string, $char)
{
$pos = @strpos($string, $char);
return false === $pos ? -1 : $pos;
} | php | protected static function indexOf($string, $char)
{
$pos = @strpos($string, $char);
return false === $pos ? -1 : $pos;
} | [
"protected",
"static",
"function",
"indexOf",
"(",
"$",
"string",
",",
"$",
"char",
")",
"{",
"$",
"pos",
"=",
"@",
"strpos",
"(",
"$",
"string",
",",
"$",
"char",
")",
";",
"return",
"false",
"===",
"$",
"pos",
"?",
"-",
"1",
":",
"$",
"pos",
... | Get the index of a string a character first.
@param string $string
@param string $char
@return int | [
"Get",
"the",
"index",
"of",
"a",
"string",
"a",
"character",
"first",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/SpatialMatch.php#L223-L228 | train |
bjeavons/zxcvbn-php | src/Matchers/SpatialMatch.php | SpatialMatch.calcAverageDegree | protected static function calcAverageDegree($graph)
{
$sum = 0;
foreach ($graph as $neighbors) {
foreach ($neighbors as $neighbor) {
// Ignore empty neighbors.
if (null !== $neighbor) {
++$sum;
}
}
}
return $sum / count(array_keys($graph));
} | php | protected static function calcAverageDegree($graph)
{
$sum = 0;
foreach ($graph as $neighbors) {
foreach ($neighbors as $neighbor) {
// Ignore empty neighbors.
if (null !== $neighbor) {
++$sum;
}
}
}
return $sum / count(array_keys($graph));
} | [
"protected",
"static",
"function",
"calcAverageDegree",
"(",
"$",
"graph",
")",
"{",
"$",
"sum",
"=",
"0",
";",
"foreach",
"(",
"$",
"graph",
"as",
"$",
"neighbors",
")",
"{",
"foreach",
"(",
"$",
"neighbors",
"as",
"$",
"neighbor",
")",
"{",
"// Ignor... | Calculate the average degree for all keys in a adjancency graph.
@param array $graph
@return float | [
"Calculate",
"the",
"average",
"degree",
"for",
"all",
"keys",
"in",
"a",
"adjancency",
"graph",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/SpatialMatch.php#L237-L250 | train |
bjeavons/zxcvbn-php | src/Matchers/DictionaryMatch.php | DictionaryMatch.match | public static function match($password, array $userInputs = [])
{
$matches = [];
$dicts = static::getRankedDictionaries();
if (!empty($userInputs)) {
$dicts['user_inputs'] = [];
foreach ($userInputs as $rank => $input) {
$input_lower = strtolower($input);
$rank = is_numeric($rank) ? $rank : count($dicts['user_inputs']);
$dicts['user_inputs'][$input_lower] = max(1, $rank);
}
}
foreach ($dicts as $name => $dict) {
$results = static::dictionaryMatch($password, $dict);
foreach ($results as $result) {
$result['dictionary_name'] = $name;
$matches[] = new static($password, $result['begin'], $result['end'], $result['token'], $result);
}
}
return $matches;
} | php | public static function match($password, array $userInputs = [])
{
$matches = [];
$dicts = static::getRankedDictionaries();
if (!empty($userInputs)) {
$dicts['user_inputs'] = [];
foreach ($userInputs as $rank => $input) {
$input_lower = strtolower($input);
$rank = is_numeric($rank) ? $rank : count($dicts['user_inputs']);
$dicts['user_inputs'][$input_lower] = max(1, $rank);
}
}
foreach ($dicts as $name => $dict) {
$results = static::dictionaryMatch($password, $dict);
foreach ($results as $result) {
$result['dictionary_name'] = $name;
$matches[] = new static($password, $result['begin'], $result['end'], $result['token'], $result);
}
}
return $matches;
} | [
"public",
"static",
"function",
"match",
"(",
"$",
"password",
",",
"array",
"$",
"userInputs",
"=",
"[",
"]",
")",
"{",
"$",
"matches",
"=",
"[",
"]",
";",
"$",
"dicts",
"=",
"static",
"::",
"getRankedDictionaries",
"(",
")",
";",
"if",
"(",
"!",
... | Match occurences of dictionary words in password.
@copydoc Match::match()
@param $password
@param array $userInputs
@return array | [
"Match",
"occurences",
"of",
"dictionary",
"words",
"in",
"password",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/DictionaryMatch.php#L50-L71 | train |
bjeavons/zxcvbn-php | src/Matchers/DictionaryMatch.php | DictionaryMatch.dictionaryMatch | protected static function dictionaryMatch($password, $dict)
{
$result = [];
$length = strlen($password);
$pw_lower = strtolower($password);
foreach (range(0, $length - 1) as $i) {
foreach (range($i, $length - 1) as $j) {
$word = substr($pw_lower, $i, $j - $i + 1);
if (isset($dict[$word])) {
$result[] = [
'begin' => $i,
'end' => $j,
'token' => substr($password, $i, $j - $i + 1),
'matched_word' => $word,
'rank' => $dict[$word],
];
}
}
}
return $result;
} | php | protected static function dictionaryMatch($password, $dict)
{
$result = [];
$length = strlen($password);
$pw_lower = strtolower($password);
foreach (range(0, $length - 1) as $i) {
foreach (range($i, $length - 1) as $j) {
$word = substr($pw_lower, $i, $j - $i + 1);
if (isset($dict[$word])) {
$result[] = [
'begin' => $i,
'end' => $j,
'token' => substr($password, $i, $j - $i + 1),
'matched_word' => $word,
'rank' => $dict[$word],
];
}
}
}
return $result;
} | [
"protected",
"static",
"function",
"dictionaryMatch",
"(",
"$",
"password",
",",
"$",
"dict",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"length",
"=",
"strlen",
"(",
"$",
"password",
")",
";",
"$",
"pw_lower",
"=",
"strtolower",
"(",
"$",
"pa... | Match password in a dictionary.
@param string $password
@param array $dict
@return array | [
"Match",
"password",
"in",
"a",
"dictionary",
"."
] | 3d581d1c8a0f6a2830b23d0e0438fb1effe26486 | https://github.com/bjeavons/zxcvbn-php/blob/3d581d1c8a0f6a2830b23d0e0438fb1effe26486/src/Matchers/DictionaryMatch.php#L137-L161 | train |
Symplify/CodingStandard | src/Fixer/AbstractSymplifyFixer.php | AbstractSymplifyFixer.getPriorityBefore | protected function getPriorityBefore(string $fixerClass): int
{
if (! is_a($fixerClass, FixerInterface::class, true)) {
return 0;
}
/** @var FixerInterface $fixer */
$fixer = (new ReflectionClass($fixerClass))->newInstanceWithoutConstructor();
return $fixer->getPriority() + 5;
} | php | protected function getPriorityBefore(string $fixerClass): int
{
if (! is_a($fixerClass, FixerInterface::class, true)) {
return 0;
}
/** @var FixerInterface $fixer */
$fixer = (new ReflectionClass($fixerClass))->newInstanceWithoutConstructor();
return $fixer->getPriority() + 5;
} | [
"protected",
"function",
"getPriorityBefore",
"(",
"string",
"$",
"fixerClass",
")",
":",
"int",
"{",
"if",
"(",
"!",
"is_a",
"(",
"$",
"fixerClass",
",",
"FixerInterface",
"::",
"class",
",",
"true",
")",
")",
"{",
"return",
"0",
";",
"}",
"/** @var Fix... | Helper method to run this before specified fixer,
works even in case of change. | [
"Helper",
"method",
"to",
"run",
"this",
"before",
"specified",
"fixer",
"works",
"even",
"in",
"case",
"of",
"change",
"."
] | 378e64dc8cc6e20684c520a938e77c458cfc0e9c | https://github.com/Symplify/CodingStandard/blob/378e64dc8cc6e20684c520a938e77c458cfc0e9c/src/Fixer/AbstractSymplifyFixer.php#L64-L74 | train |
Symplify/CodingStandard | src/Sniffs/Naming/ClassNameSuffixByParentSniff.php | ClassNameSuffixByParentSniff.resolveExpectedSuffix | private function resolveExpectedSuffix(string $parentType): string
{
if (Strings::endsWith($parentType, 'Interface')) {
$parentType = Strings::substring($parentType, 0, -strlen('Interface'));
}
if (Strings::endsWith($parentType, 'Abstract')) {
$parentType = Strings::substring($parentType, 0, -strlen('Abstract'));
}
if (Strings::startsWith($parentType, 'Abstract')) {
$parentType = Strings::substring($parentType, strlen('Abstract'));
}
return $parentType;
} | php | private function resolveExpectedSuffix(string $parentType): string
{
if (Strings::endsWith($parentType, 'Interface')) {
$parentType = Strings::substring($parentType, 0, -strlen('Interface'));
}
if (Strings::endsWith($parentType, 'Abstract')) {
$parentType = Strings::substring($parentType, 0, -strlen('Abstract'));
}
if (Strings::startsWith($parentType, 'Abstract')) {
$parentType = Strings::substring($parentType, strlen('Abstract'));
}
return $parentType;
} | [
"private",
"function",
"resolveExpectedSuffix",
"(",
"string",
"$",
"parentType",
")",
":",
"string",
"{",
"if",
"(",
"Strings",
"::",
"endsWith",
"(",
"$",
"parentType",
",",
"'Interface'",
")",
")",
"{",
"$",
"parentType",
"=",
"Strings",
"::",
"substring"... | - SomeInterface => Some
- SomeAbstract => Some
- AbstractSome => Some | [
"-",
"SomeInterface",
"=",
">",
"Some",
"-",
"SomeAbstract",
"=",
">",
"Some",
"-",
"AbstractSome",
"=",
">",
"Some"
] | 378e64dc8cc6e20684c520a938e77c458cfc0e9c | https://github.com/Symplify/CodingStandard/blob/378e64dc8cc6e20684c520a938e77c458cfc0e9c/src/Sniffs/Naming/ClassNameSuffixByParentSniff.php#L112-L127 | train |
Symplify/CodingStandard | packages/TokenRunner/src/Transformer/FixerTransformer/LineLengthTransformer.php | LineLengthTransformer.isLastItem | private function isLastItem(Tokens $tokens, int $i): bool
{
return Strings::contains($tokens[$i + 1]->getContent(), $this->whitespacesFixerConfig->getLineEnding());
} | php | private function isLastItem(Tokens $tokens, int $i): bool
{
return Strings::contains($tokens[$i + 1]->getContent(), $this->whitespacesFixerConfig->getLineEnding());
} | [
"private",
"function",
"isLastItem",
"(",
"Tokens",
"$",
"tokens",
",",
"int",
"$",
"i",
")",
":",
"bool",
"{",
"return",
"Strings",
"::",
"contains",
"(",
"$",
"tokens",
"[",
"$",
"i",
"+",
"1",
"]",
"->",
"getContent",
"(",
")",
",",
"$",
"this",... | Has already newline? usually the last line => skip to prevent double spacing | [
"Has",
"already",
"newline?",
"usually",
"the",
"last",
"line",
"=",
">",
"skip",
"to",
"prevent",
"double",
"spacing"
] | 378e64dc8cc6e20684c520a938e77c458cfc0e9c | https://github.com/Symplify/CodingStandard/blob/378e64dc8cc6e20684c520a938e77c458cfc0e9c/packages/TokenRunner/src/Transformer/FixerTransformer/LineLengthTransformer.php#L224-L227 | train |
Symplify/CodingStandard | src/Sniffs/DeadCode/UnusedPublicMethodSniff.php | UnusedPublicMethodSniff.shouldSkipFile | private function shouldSkipFile(File $file): bool
{
if (Strings::contains($file->getFilename(), '/tests/')
&& ! Strings::contains($file->getFilename(), 'CodingStandard/tests/')
) {
return true;
}
$classWrapper = $this->sniffClassWrapperFactory->createFromFirstClassInFile($file);
if ($classWrapper === null) {
return true;
}
return $classWrapper->implementsInterface() || $classWrapper->extends();
} | php | private function shouldSkipFile(File $file): bool
{
if (Strings::contains($file->getFilename(), '/tests/')
&& ! Strings::contains($file->getFilename(), 'CodingStandard/tests/')
) {
return true;
}
$classWrapper = $this->sniffClassWrapperFactory->createFromFirstClassInFile($file);
if ($classWrapper === null) {
return true;
}
return $classWrapper->implementsInterface() || $classWrapper->extends();
} | [
"private",
"function",
"shouldSkipFile",
"(",
"File",
"$",
"file",
")",
":",
"bool",
"{",
"if",
"(",
"Strings",
"::",
"contains",
"(",
"$",
"file",
"->",
"getFilename",
"(",
")",
",",
"'/tests/'",
")",
"&&",
"!",
"Strings",
"::",
"contains",
"(",
"$",
... | Skip tests as there might be many unused public methods
Skip anything that implements interface or extends class,
because methods can be enforced by them. | [
"Skip",
"tests",
"as",
"there",
"might",
"be",
"many",
"unused",
"public",
"methods"
] | 378e64dc8cc6e20684c520a938e77c458cfc0e9c | https://github.com/Symplify/CodingStandard/blob/378e64dc8cc6e20684c520a938e77c458cfc0e9c/src/Sniffs/DeadCode/UnusedPublicMethodSniff.php#L186-L200 | train |
Symplify/CodingStandard | packages/TokenRunner/src/DocBlock/MalformWorker/SuperfluousVarNameMalformWorker.php | SuperfluousVarNameMalformWorker.shouldSkip | private function shouldSkip(Tokens $tokens, int $position): bool
{
$nextMeaningfulTokenPosition = $tokens->getNextMeaningfulToken($position);
// nothing to change
if ($nextMeaningfulTokenPosition === null) {
return true;
}
$nextMeaningfulToken = $tokens[$nextMeaningfulTokenPosition];
// should be protected/private/public/static, to know we're property
return ! $nextMeaningfulToken->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC]);
} | php | private function shouldSkip(Tokens $tokens, int $position): bool
{
$nextMeaningfulTokenPosition = $tokens->getNextMeaningfulToken($position);
// nothing to change
if ($nextMeaningfulTokenPosition === null) {
return true;
}
$nextMeaningfulToken = $tokens[$nextMeaningfulTokenPosition];
// should be protected/private/public/static, to know we're property
return ! $nextMeaningfulToken->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC]);
} | [
"private",
"function",
"shouldSkip",
"(",
"Tokens",
"$",
"tokens",
",",
"int",
"$",
"position",
")",
":",
"bool",
"{",
"$",
"nextMeaningfulTokenPosition",
"=",
"$",
"tokens",
"->",
"getNextMeaningfulToken",
"(",
"$",
"position",
")",
";",
"// nothing to change",... | Is property doc block? | [
"Is",
"property",
"doc",
"block?"
] | 378e64dc8cc6e20684c520a938e77c458cfc0e9c | https://github.com/Symplify/CodingStandard/blob/378e64dc8cc6e20684c520a938e77c458cfc0e9c/packages/TokenRunner/src/DocBlock/MalformWorker/SuperfluousVarNameMalformWorker.php#L56-L69 | train |
Symplify/CodingStandard | src/Fixer/LineLength/LineLengthFixer.php | LineLengthFixer.matchNamePositionForEndOfFunctionCall | private function matchNamePositionForEndOfFunctionCall(Tokens $tokens, int $position): ?int
{
try {
$blockStart = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $position);
} catch (Throwable $throwable) {
// not a block start
return null;
}
$previousTokenPosition = $blockStart - 1;
$possibleMethodNameToken = $tokens[$previousTokenPosition];
// not a "methodCall()"
if (! $possibleMethodNameToken->isGivenKind(T_STRING)) {
return null;
}
// starts with small letter?
$methodOrFunctionName = $possibleMethodNameToken->getContent();
if (! ctype_lower($methodOrFunctionName[0])) {
return null;
}
// is "someCall()"? we don't care, there are no arguments
if ($tokens[$blockStart + 1]->equals(')')) {
return null;
}
return $previousTokenPosition;
} | php | private function matchNamePositionForEndOfFunctionCall(Tokens $tokens, int $position): ?int
{
try {
$blockStart = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $position);
} catch (Throwable $throwable) {
// not a block start
return null;
}
$previousTokenPosition = $blockStart - 1;
$possibleMethodNameToken = $tokens[$previousTokenPosition];
// not a "methodCall()"
if (! $possibleMethodNameToken->isGivenKind(T_STRING)) {
return null;
}
// starts with small letter?
$methodOrFunctionName = $possibleMethodNameToken->getContent();
if (! ctype_lower($methodOrFunctionName[0])) {
return null;
}
// is "someCall()"? we don't care, there are no arguments
if ($tokens[$blockStart + 1]->equals(')')) {
return null;
}
return $previousTokenPosition;
} | [
"private",
"function",
"matchNamePositionForEndOfFunctionCall",
"(",
"Tokens",
"$",
"tokens",
",",
"int",
"$",
"position",
")",
":",
"?",
"int",
"{",
"try",
"{",
"$",
"blockStart",
"=",
"$",
"tokens",
"->",
"findBlockStart",
"(",
"Tokens",
"::",
"BLOCK_TYPE_PA... | We go through tokens from down to up,
so we need to find ")" and then the start of function | [
"We",
"go",
"through",
"tokens",
"from",
"down",
"to",
"up",
"so",
"we",
"need",
"to",
"find",
")",
"and",
"then",
"the",
"start",
"of",
"function"
] | 378e64dc8cc6e20684c520a938e77c458cfc0e9c | https://github.com/Symplify/CodingStandard/blob/378e64dc8cc6e20684c520a938e77c458cfc0e9c/src/Fixer/LineLength/LineLengthFixer.php#L172-L201 | train |
Symplify/CodingStandard | packages/TokenRunner/src/Naming/Name/NameFactory.php | NameFactory.createFromTokensAndStart | public function createFromTokensAndStart(Tokens $tokens, int $start): Name
{
$nameTokens = [];
$nextTokenPointer = $start;
$prependNamespace = $this->shouldPrependNamespace($tokens, $nextTokenPointer);
while ($tokens[$nextTokenPointer]->isGivenKind([T_NS_SEPARATOR, T_STRING])) {
$nameTokens[] = $tokens[$nextTokenPointer];
++$nextTokenPointer;
}
/** @var Token[] $nameTokens */
if ($nameTokens[0]->isGivenKind(T_NS_SEPARATOR)) {
unset($nameTokens[0]);
// reset array keys
$nameTokens = array_values($nameTokens);
// move start pointer after "\"
--$nextTokenPointer;
}
if (! $tokens[$nextTokenPointer]->isGivenKind([T_STRING, T_NS_SEPARATOR])) {
--$nextTokenPointer;
}
$name = '';
foreach ($nameTokens as $nameToken) {
$name .= $nameToken->getContent();
}
// resolve fully qualified name - as argument?
$name = $this->resolveForName($tokens, $name, $prependNamespace);
return new Name($nextTokenPointer, $start, $name, $tokens);
} | php | public function createFromTokensAndStart(Tokens $tokens, int $start): Name
{
$nameTokens = [];
$nextTokenPointer = $start;
$prependNamespace = $this->shouldPrependNamespace($tokens, $nextTokenPointer);
while ($tokens[$nextTokenPointer]->isGivenKind([T_NS_SEPARATOR, T_STRING])) {
$nameTokens[] = $tokens[$nextTokenPointer];
++$nextTokenPointer;
}
/** @var Token[] $nameTokens */
if ($nameTokens[0]->isGivenKind(T_NS_SEPARATOR)) {
unset($nameTokens[0]);
// reset array keys
$nameTokens = array_values($nameTokens);
// move start pointer after "\"
--$nextTokenPointer;
}
if (! $tokens[$nextTokenPointer]->isGivenKind([T_STRING, T_NS_SEPARATOR])) {
--$nextTokenPointer;
}
$name = '';
foreach ($nameTokens as $nameToken) {
$name .= $nameToken->getContent();
}
// resolve fully qualified name - as argument?
$name = $this->resolveForName($tokens, $name, $prependNamespace);
return new Name($nextTokenPointer, $start, $name, $tokens);
} | [
"public",
"function",
"createFromTokensAndStart",
"(",
"Tokens",
"$",
"tokens",
",",
"int",
"$",
"start",
")",
":",
"Name",
"{",
"$",
"nameTokens",
"=",
"[",
"]",
";",
"$",
"nextTokenPointer",
"=",
"$",
"start",
";",
"$",
"prependNamespace",
"=",
"$",
"t... | Inverse direction to @see createFromTokensAndEnd() | [
"Inverse",
"direction",
"to"
] | 378e64dc8cc6e20684c520a938e77c458cfc0e9c | https://github.com/Symplify/CodingStandard/blob/378e64dc8cc6e20684c520a938e77c458cfc0e9c/packages/TokenRunner/src/Naming/Name/NameFactory.php#L52-L88 | train |
FriendsOfCake/CakePdf | src/Pdf/Engine/TexToPdfEngine.php | TexToPdfEngine._writeTexFile | protected function _writeTexFile()
{
$output = $this->_Pdf->html();
$file = sha1($output);
$texFile = $this->getConfig('options.output-directory') . DS . $file;
file_put_contents($texFile, $output);
return $texFile;
} | php | protected function _writeTexFile()
{
$output = $this->_Pdf->html();
$file = sha1($output);
$texFile = $this->getConfig('options.output-directory') . DS . $file;
file_put_contents($texFile, $output);
return $texFile;
} | [
"protected",
"function",
"_writeTexFile",
"(",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"_Pdf",
"->",
"html",
"(",
")",
";",
"$",
"file",
"=",
"sha1",
"(",
"$",
"output",
")",
";",
"$",
"texFile",
"=",
"$",
"this",
"->",
"getConfig",
"(",
... | Write the tex file.
@return string Returns the file name of the written tex file. | [
"Write",
"the",
"tex",
"file",
"."
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Engine/TexToPdfEngine.php#L34-L42 | train |
FriendsOfCake/CakePdf | src/Pdf/Engine/TexToPdfEngine.php | TexToPdfEngine._cleanUpTexFiles | protected function _cleanUpTexFiles($texFile)
{
$extensions = ['aux', 'log', 'pdf'];
foreach ($extensions as $extension) {
$texFile = $texFile . '.' . $extension;
if (file_exists($texFile)) {
unlink($texFile);
}
}
} | php | protected function _cleanUpTexFiles($texFile)
{
$extensions = ['aux', 'log', 'pdf'];
foreach ($extensions as $extension) {
$texFile = $texFile . '.' . $extension;
if (file_exists($texFile)) {
unlink($texFile);
}
}
} | [
"protected",
"function",
"_cleanUpTexFiles",
"(",
"$",
"texFile",
")",
"{",
"$",
"extensions",
"=",
"[",
"'aux'",
",",
"'log'",
",",
"'pdf'",
"]",
";",
"foreach",
"(",
"$",
"extensions",
"as",
"$",
"extension",
")",
"{",
"$",
"texFile",
"=",
"$",
"texF... | Clean up the files generated by tex.
@param string $texFile Tex file name.
@return void | [
"Clean",
"up",
"the",
"files",
"generated",
"by",
"tex",
"."
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Engine/TexToPdfEngine.php#L50-L59 | train |
FriendsOfCake/CakePdf | src/Pdf/Engine/TexToPdfEngine.php | TexToPdfEngine._buildCommand | protected function _buildCommand()
{
$command = $this->_binary;
$options = (array)$this->getConfig('options');
foreach ($options as $key => $value) {
if (empty($value)) {
continue;
} elseif ($value === true) {
$command .= ' --' . $key;
} else {
$command .= sprintf(' --%s %s', $key, escapeshellarg($value));
}
}
return $command;
} | php | protected function _buildCommand()
{
$command = $this->_binary;
$options = (array)$this->getConfig('options');
foreach ($options as $key => $value) {
if (empty($value)) {
continue;
} elseif ($value === true) {
$command .= ' --' . $key;
} else {
$command .= sprintf(' --%s %s', $key, escapeshellarg($value));
}
}
return $command;
} | [
"protected",
"function",
"_buildCommand",
"(",
")",
"{",
"$",
"command",
"=",
"$",
"this",
"->",
"_binary",
";",
"$",
"options",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"getConfig",
"(",
"'options'",
")",
";",
"foreach",
"(",
"$",
"options",
"as",
... | Builds the command.
@return string The command with params and options. | [
"Builds",
"the",
"command",
"."
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Engine/TexToPdfEngine.php#L123-L138 | train |
FriendsOfCake/CakePdf | src/Pdf/Engine/DomPdfEngine.php | DomPdfEngine._render | protected function _render($Pdf, $DomPDF)
{
$DomPDF->loadHtml($Pdf->html());
$DomPDF->render();
return $DomPDF;
} | php | protected function _render($Pdf, $DomPDF)
{
$DomPDF->loadHtml($Pdf->html());
$DomPDF->render();
return $DomPDF;
} | [
"protected",
"function",
"_render",
"(",
"$",
"Pdf",
",",
"$",
"DomPDF",
")",
"{",
"$",
"DomPDF",
"->",
"loadHtml",
"(",
"$",
"Pdf",
"->",
"html",
"(",
")",
")",
";",
"$",
"DomPDF",
"->",
"render",
"(",
")",
";",
"return",
"$",
"DomPDF",
";",
"}"... | Renders the Dompdf instance.
@param \CakePdf\Pdf\CakePdf $Pdf The CakePdf instance that supplies the content to render.
@param \Dompdf\Dompdf $DomPDF The Dompdf instance to render.
@return \Dompdf\Dompdf | [
"Renders",
"the",
"Dompdf",
"instance",
"."
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Engine/DomPdfEngine.php#L47-L53 | train |
FriendsOfCake/CakePdf | src/Pdf/CakePdf.php | CakePdf.output | public function output($html = null)
{
$Engine = $this->engine();
if (!$Engine) {
throw new Exception(__d('cake_pdf', 'Engine is not loaded'));
}
if ($html === null) {
$html = $this->_render();
}
$this->html($html);
$cacheKey = null;
$cache = $this->cache();
if ($cache) {
$cacheKey = md5(serialize($this));
$cached = Cache::read($cacheKey, $cache);
if ($cached) {
return $cached;
}
}
$output = $Engine->output();
if ($this->protect()) {
$output = $this->crypto()->encrypt($output);
}
if ($cache) {
Cache::write($cacheKey, $output, $cache);
}
return $output;
} | php | public function output($html = null)
{
$Engine = $this->engine();
if (!$Engine) {
throw new Exception(__d('cake_pdf', 'Engine is not loaded'));
}
if ($html === null) {
$html = $this->_render();
}
$this->html($html);
$cacheKey = null;
$cache = $this->cache();
if ($cache) {
$cacheKey = md5(serialize($this));
$cached = Cache::read($cacheKey, $cache);
if ($cached) {
return $cached;
}
}
$output = $Engine->output();
if ($this->protect()) {
$output = $this->crypto()->encrypt($output);
}
if ($cache) {
Cache::write($cacheKey, $output, $cache);
}
return $output;
} | [
"public",
"function",
"output",
"(",
"$",
"html",
"=",
"null",
")",
"{",
"$",
"Engine",
"=",
"$",
"this",
"->",
"engine",
"(",
")",
";",
"if",
"(",
"!",
"$",
"Engine",
")",
"{",
"throw",
"new",
"Exception",
"(",
"__d",
"(",
"'cake_pdf'",
",",
"'E... | Create pdf content from html. Can be used to write to file or with PdfView to display
@param null|string $html Html content to render. If omitted, the template will be rendered with viewVars and layout that have been set.
@throws \Cake\Core\Exception\Exception
@return string | [
"Create",
"pdf",
"content",
"from",
"html",
".",
"Can",
"be",
"used",
"to",
"write",
"to",
"file",
"or",
"with",
"PdfView",
"to",
"display"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/CakePdf.php#L278-L311 | train |
FriendsOfCake/CakePdf | src/Pdf/CakePdf.php | CakePdf.write | public function write($destination, $create = true, $html = null)
{
$output = $this->output($html);
$File = new File($destination, $create);
return $File->write($output) && $File->close();
} | php | public function write($destination, $create = true, $html = null)
{
$output = $this->output($html);
$File = new File($destination, $create);
return $File->write($output) && $File->close();
} | [
"public",
"function",
"write",
"(",
"$",
"destination",
",",
"$",
"create",
"=",
"true",
",",
"$",
"html",
"=",
"null",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"output",
"(",
"$",
"html",
")",
";",
"$",
"File",
"=",
"new",
"File",
"(",
... | Writes output to file
@param string $destination Absolute file path to write to
@param bool $create Create file if it does not exist (if true)
@param string $html Html to write
@return bool | [
"Writes",
"output",
"to",
"file"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/CakePdf.php#L337-L343 | train |
FriendsOfCake/CakePdf | src/Pdf/CakePdf.php | CakePdf._render | protected function _render()
{
$viewClass = $this->viewRender();
$viewClass = App::className($viewClass, 'View', $viewClass == 'View' ? '' : 'View');
$viewVars = [
'theme',
'layoutPath',
'templatePath',
'template',
'layout',
'helpers',
'viewVars',
];
$viewOptions = [];
foreach ($viewVars as $var) {
$prop = '_' . $var;
$viewOptions[$var] = $this->{$prop};
}
$request = Router::getRequest(true);
if (!$request) {
$request = ServerRequestFactory::fromGlobals();
}
$View = new $viewClass(
$request,
null,
null,
$viewOptions
);
return $View->render();
} | php | protected function _render()
{
$viewClass = $this->viewRender();
$viewClass = App::className($viewClass, 'View', $viewClass == 'View' ? '' : 'View');
$viewVars = [
'theme',
'layoutPath',
'templatePath',
'template',
'layout',
'helpers',
'viewVars',
];
$viewOptions = [];
foreach ($viewVars as $var) {
$prop = '_' . $var;
$viewOptions[$var] = $this->{$prop};
}
$request = Router::getRequest(true);
if (!$request) {
$request = ServerRequestFactory::fromGlobals();
}
$View = new $viewClass(
$request,
null,
null,
$viewOptions
);
return $View->render();
} | [
"protected",
"function",
"_render",
"(",
")",
"{",
"$",
"viewClass",
"=",
"$",
"this",
"->",
"viewRender",
"(",
")",
";",
"$",
"viewClass",
"=",
"App",
"::",
"className",
"(",
"$",
"viewClass",
",",
"'View'",
",",
"$",
"viewClass",
"==",
"'View'",
"?",... | Build and set all the view properties needed to render the layout and template.
@return array The rendered template wrapped in layout. | [
"Build",
"and",
"set",
"all",
"the",
"view",
"properties",
"needed",
"to",
"render",
"the",
"layout",
"and",
"template",
"."
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/CakePdf.php#L937-L970 | train |
FriendsOfCake/CakePdf | src/Pdf/Engine/WkHtmlToPdfEngine.php | WkHtmlToPdfEngine._exec | protected function _exec($cmd, $input)
{
$result = ['stdout' => '', 'stderr' => '', 'return' => ''];
$cwd = $this->getConfig('cwd');
$proc = proc_open($cmd, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $cwd);
fwrite($pipes[0], $input);
fclose($pipes[0]);
$result['stdout'] = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$result['stderr'] = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$result['return'] = proc_close($proc);
return $result;
} | php | protected function _exec($cmd, $input)
{
$result = ['stdout' => '', 'stderr' => '', 'return' => ''];
$cwd = $this->getConfig('cwd');
$proc = proc_open($cmd, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $cwd);
fwrite($pipes[0], $input);
fclose($pipes[0]);
$result['stdout'] = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$result['stderr'] = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$result['return'] = proc_close($proc);
return $result;
} | [
"protected",
"function",
"_exec",
"(",
"$",
"cmd",
",",
"$",
"input",
")",
"{",
"$",
"result",
"=",
"[",
"'stdout'",
"=>",
"''",
",",
"'stderr'",
"=>",
"''",
",",
"'return'",
"=>",
"''",
"]",
";",
"$",
"cwd",
"=",
"$",
"this",
"->",
"getConfig",
... | Execute the WkHtmlToPdf commands for rendering pdfs
@param string $cmd the command to execute
@param string $input Html to pass to wkhtmltopdf
@return array the result of running the command to generate the pdf | [
"Execute",
"the",
"WkHtmlToPdf",
"commands",
"for",
"rendering",
"pdfs"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Engine/WkHtmlToPdfEngine.php#L75-L94 | train |
FriendsOfCake/CakePdf | src/View/PdfView.php | PdfView.renderer | public function renderer($config = null)
{
if ($config !== null) {
$this->_renderer = new CakePdf($config);
}
return $this->_renderer;
} | php | public function renderer($config = null)
{
if ($config !== null) {
$this->_renderer = new CakePdf($config);
}
return $this->_renderer;
} | [
"public",
"function",
"renderer",
"(",
"$",
"config",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"config",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"_renderer",
"=",
"new",
"CakePdf",
"(",
"$",
"config",
")",
";",
"}",
"return",
"$",
"this",
"->",
... | Return CakePdf instance, optionally set engine to be used
@param array $config Array of pdf configs. When empty CakePdf instance will be returned.
@return \CakePdf\Pdf\CakePdf | [
"Return",
"CakePdf",
"instance",
"optionally",
"set",
"engine",
"to",
"be",
"used"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/View/PdfView.php#L89-L96 | train |
FriendsOfCake/CakePdf | src/View/PdfView.php | PdfView.render | public function render($view = null, $layout = null)
{
$content = parent::render($view, $layout);
if (version_compare(Configure::version(), '3.6.0', '<')) {
$type = $this->response->type();
} else {
$type = $this->response->getType();
}
if ($type === 'text/html') {
return $content;
}
if ($this->renderer() === null) {
$this->response = $this->response->withType('html');
return $content;
}
if (!empty($this->pdfConfig['filename']) || !empty($this->pdfConfig['download'])) {
$this->response = $this->response->withDownload($this->getFilename());
}
$this->Blocks->set('content', $this->renderer()->output($content));
return $this->Blocks->get('content');
} | php | public function render($view = null, $layout = null)
{
$content = parent::render($view, $layout);
if (version_compare(Configure::version(), '3.6.0', '<')) {
$type = $this->response->type();
} else {
$type = $this->response->getType();
}
if ($type === 'text/html') {
return $content;
}
if ($this->renderer() === null) {
$this->response = $this->response->withType('html');
return $content;
}
if (!empty($this->pdfConfig['filename']) || !empty($this->pdfConfig['download'])) {
$this->response = $this->response->withDownload($this->getFilename());
}
$this->Blocks->set('content', $this->renderer()->output($content));
return $this->Blocks->get('content');
} | [
"public",
"function",
"render",
"(",
"$",
"view",
"=",
"null",
",",
"$",
"layout",
"=",
"null",
")",
"{",
"$",
"content",
"=",
"parent",
"::",
"render",
"(",
"$",
"view",
",",
"$",
"layout",
")",
";",
"if",
"(",
"version_compare",
"(",
"Configure",
... | Render a Pdf view.
@param string $view The view being rendered.
@param string $layout The layout being rendered.
@return string The rendered view. | [
"Render",
"a",
"Pdf",
"view",
"."
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/View/PdfView.php#L105-L131 | train |
FriendsOfCake/CakePdf | src/View/PdfView.php | PdfView.getFilename | public function getFilename()
{
if (isset($this->pdfConfig['filename'])) {
return $this->pdfConfig['filename'];
}
$id = current($this->request->getParam('pass'));
return strtolower($this->getTemplatePath()) . $id . '.pdf';
} | php | public function getFilename()
{
if (isset($this->pdfConfig['filename'])) {
return $this->pdfConfig['filename'];
}
$id = current($this->request->getParam('pass'));
return strtolower($this->getTemplatePath()) . $id . '.pdf';
} | [
"public",
"function",
"getFilename",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"pdfConfig",
"[",
"'filename'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"pdfConfig",
"[",
"'filename'",
"]",
";",
"}",
"$",
"id",
"=",
"current",... | Get or build a filename for forced download
@return string The filename | [
"Get",
"or",
"build",
"a",
"filename",
"for",
"forced",
"download"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/View/PdfView.php#L138-L147 | train |
FriendsOfCake/CakePdf | src/Pdf/Crypto/PdftkCrypto.php | PdftkCrypto.encrypt | public function encrypt($data)
{
/** @var string $binary */
$binary = $this->config('binary');
if ($binary) {
$this->_binary = $binary;
}
if (!is_executable($this->_binary)) {
throw new Exception(sprintf('pdftk binary is not found or not executable: %s', $this->_binary));
}
$arguments = [];
$ownerPassword = $this->_Pdf->ownerPassword();
if ($ownerPassword !== null) {
$arguments['owner_pw'] = escapeshellarg($ownerPassword);
}
$userPassword = $this->_Pdf->userPassword();
if ($userPassword !== null) {
$arguments['user_pw'] = escapeshellarg($userPassword);
}
$allowed = $this->_buildPermissionsArgument();
if ($allowed) {
$arguments['allow'] = $allowed;
}
if (!$ownerPassword && !$userPassword) {
throw new Exception('Crypto: Required to configure atleast an ownerPassword or userPassword');
}
if ($ownerPassword == $userPassword) {
throw new Exception('Crypto: ownerPassword and userPassword cannot be the same');
}
$command = sprintf('%s - output - %s', $this->_binary, $this->_buildArguments($arguments));
$descriptorspec = [
0 => ['pipe', 'r'], // feed stdin of process from this file descriptor
1 => ['pipe', 'w'], // Note you can also grab stdout from a pipe, no need for temp file
2 => ['pipe', 'w'], // stderr
];
$prochandle = proc_open($command, $descriptorspec, $pipes);
fwrite($pipes[0], $data);
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$exitcode = proc_close($prochandle);
if ($exitcode !== 0) {
throw new Exception(sprintf('Crypto: Unknown error (exit code %d)', $exitcode));
}
return $stdout;
} | php | public function encrypt($data)
{
/** @var string $binary */
$binary = $this->config('binary');
if ($binary) {
$this->_binary = $binary;
}
if (!is_executable($this->_binary)) {
throw new Exception(sprintf('pdftk binary is not found or not executable: %s', $this->_binary));
}
$arguments = [];
$ownerPassword = $this->_Pdf->ownerPassword();
if ($ownerPassword !== null) {
$arguments['owner_pw'] = escapeshellarg($ownerPassword);
}
$userPassword = $this->_Pdf->userPassword();
if ($userPassword !== null) {
$arguments['user_pw'] = escapeshellarg($userPassword);
}
$allowed = $this->_buildPermissionsArgument();
if ($allowed) {
$arguments['allow'] = $allowed;
}
if (!$ownerPassword && !$userPassword) {
throw new Exception('Crypto: Required to configure atleast an ownerPassword or userPassword');
}
if ($ownerPassword == $userPassword) {
throw new Exception('Crypto: ownerPassword and userPassword cannot be the same');
}
$command = sprintf('%s - output - %s', $this->_binary, $this->_buildArguments($arguments));
$descriptorspec = [
0 => ['pipe', 'r'], // feed stdin of process from this file descriptor
1 => ['pipe', 'w'], // Note you can also grab stdout from a pipe, no need for temp file
2 => ['pipe', 'w'], // stderr
];
$prochandle = proc_open($command, $descriptorspec, $pipes);
fwrite($pipes[0], $data);
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$exitcode = proc_close($prochandle);
if ($exitcode !== 0) {
throw new Exception(sprintf('Crypto: Unknown error (exit code %d)', $exitcode));
}
return $stdout;
} | [
"public",
"function",
"encrypt",
"(",
"$",
"data",
")",
"{",
"/** @var string $binary */",
"$",
"binary",
"=",
"$",
"this",
"->",
"config",
"(",
"'binary'",
")",
";",
"if",
"(",
"$",
"binary",
")",
"{",
"$",
"this",
"->",
"_binary",
"=",
"$",
"binary",... | Encrypt a pdf file
@param string $data raw pdf data
@throws \Cake\Core\Exception\Exception
@return string raw pdf data | [
"Encrypt",
"a",
"pdf",
"file"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Crypto/PdftkCrypto.php#L39-L102 | train |
FriendsOfCake/CakePdf | src/Pdf/Crypto/PdftkCrypto.php | PdftkCrypto._buildArguments | protected function _buildArguments($arguments)
{
$output = [];
foreach ($arguments as $argument => $value) {
$output[] = $argument . ' ' . $value;
}
return implode(' ', $output);
} | php | protected function _buildArguments($arguments)
{
$output = [];
foreach ($arguments as $argument => $value) {
$output[] = $argument . ' ' . $value;
}
return implode(' ', $output);
} | [
"protected",
"function",
"_buildArguments",
"(",
"$",
"arguments",
")",
"{",
"$",
"output",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"arguments",
"as",
"$",
"argument",
"=>",
"$",
"value",
")",
"{",
"$",
"output",
"[",
"]",
"=",
"$",
"argument",
".",... | Builds a shell safe argument list
@param array $arguments arguments to pass to pdftk
@return string list of arguments | [
"Builds",
"a",
"shell",
"safe",
"argument",
"list"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Crypto/PdftkCrypto.php#L121-L130 | train |
FriendsOfCake/CakePdf | src/Pdf/Crypto/PdftkCrypto.php | PdftkCrypto._buildPermissionsArgument | protected function _buildPermissionsArgument()
{
$permissions = $this->_Pdf->permissions();
if ($permissions === false) {
return false;
}
$allowed = [];
if ($permissions === true) {
$allowed[] = 'AllFeatures';
}
if (is_array($permissions)) {
foreach ($permissions as $permission) {
$allowed[] = $this->_permissionsMap[$permission];
}
}
return implode(' ', $allowed);
} | php | protected function _buildPermissionsArgument()
{
$permissions = $this->_Pdf->permissions();
if ($permissions === false) {
return false;
}
$allowed = [];
if ($permissions === true) {
$allowed[] = 'AllFeatures';
}
if (is_array($permissions)) {
foreach ($permissions as $permission) {
$allowed[] = $this->_permissionsMap[$permission];
}
}
return implode(' ', $allowed);
} | [
"protected",
"function",
"_buildPermissionsArgument",
"(",
")",
"{",
"$",
"permissions",
"=",
"$",
"this",
"->",
"_Pdf",
"->",
"permissions",
"(",
")",
";",
"if",
"(",
"$",
"permissions",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"$",
"allow... | Generate the permissions argument
@return string|false list of arguments or false if no permission set | [
"Generate",
"the",
"permissions",
"argument"
] | c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49 | https://github.com/FriendsOfCake/CakePdf/blob/c59ac6b8a916aa6d0e174c1abe72e70f5bab9b49/src/Pdf/Crypto/PdftkCrypto.php#L137-L158 | train |
staudenmeir/eloquent-has-many-deep | src/HasManyDeep.php | HasManyDeep.joinThroughParent | protected function joinThroughParent(Builder $query, Model $throughParent, Model $predecessor, $foreignKey, $localKey, $prefix)
{
if (is_array($localKey)) {
$query->where($throughParent->qualifyColumn($localKey[0]), '=', $predecessor->getMorphClass());
$localKey = $localKey[1];
}
$first = $throughParent->qualifyColumn($localKey);
if (is_array($foreignKey)) {
$query->where($predecessor->qualifyColumn($foreignKey[0]), '=', $throughParent->getMorphClass());
$foreignKey = $foreignKey[1];
}
$second = $predecessor->qualifyColumn($prefix.$foreignKey);
$query->join($throughParent->getTable(), $first, '=', $second);
if ($this->throughParentInstanceSoftDeletes($throughParent)) {
$query->whereNull($throughParent->getQualifiedDeletedAtColumn());
}
} | php | protected function joinThroughParent(Builder $query, Model $throughParent, Model $predecessor, $foreignKey, $localKey, $prefix)
{
if (is_array($localKey)) {
$query->where($throughParent->qualifyColumn($localKey[0]), '=', $predecessor->getMorphClass());
$localKey = $localKey[1];
}
$first = $throughParent->qualifyColumn($localKey);
if (is_array($foreignKey)) {
$query->where($predecessor->qualifyColumn($foreignKey[0]), '=', $throughParent->getMorphClass());
$foreignKey = $foreignKey[1];
}
$second = $predecessor->qualifyColumn($prefix.$foreignKey);
$query->join($throughParent->getTable(), $first, '=', $second);
if ($this->throughParentInstanceSoftDeletes($throughParent)) {
$query->whereNull($throughParent->getQualifiedDeletedAtColumn());
}
} | [
"protected",
"function",
"joinThroughParent",
"(",
"Builder",
"$",
"query",
",",
"Model",
"$",
"throughParent",
",",
"Model",
"$",
"predecessor",
",",
"$",
"foreignKey",
",",
"$",
"localKey",
",",
"$",
"prefix",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
... | Join a through parent table.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $throughParent
@param \Illuminate\Database\Eloquent\Model $predecessor
@param array|string $foreignKey
@param array|string $localKey
@param string $prefix
@return void | [
"Join",
"a",
"through",
"parent",
"table",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasManyDeep.php#L114-L137 | train |
staudenmeir/eloquent-has-many-deep | src/HasManyDeep.php | HasManyDeep.withTrashed | public function withTrashed(...$columns)
{
if (empty($columns)) {
$this->query->withTrashed();
return $this;
}
if (is_array($columns[0])) {
$columns = $columns[0];
}
$this->query->getQuery()->wheres = collect($this->query->getQuery()->wheres)
->reject(function ($where) use ($columns) {
return $where['type'] === 'Null' && in_array($where['column'], $columns);
})->values()->all();
return $this;
} | php | public function withTrashed(...$columns)
{
if (empty($columns)) {
$this->query->withTrashed();
return $this;
}
if (is_array($columns[0])) {
$columns = $columns[0];
}
$this->query->getQuery()->wheres = collect($this->query->getQuery()->wheres)
->reject(function ($where) use ($columns) {
return $where['type'] === 'Null' && in_array($where['column'], $columns);
})->values()->all();
return $this;
} | [
"public",
"function",
"withTrashed",
"(",
"...",
"$",
"columns",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"columns",
")",
")",
"{",
"$",
"this",
"->",
"query",
"->",
"withTrashed",
"(",
")",
";",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"is_array... | Restore soft-deleted models.
@param string ...$columns
@return $this | [
"Restore",
"soft",
"-",
"deleted",
"models",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasManyDeep.php#L301-L319 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.hasManyDeep | public function hasManyDeep($related, array $through, array $foreignKeys = [], array $localKeys = [])
{
return $this->newHasManyDeep(...$this->hasOneOrManyDeep($related, $through, $foreignKeys, $localKeys));
} | php | public function hasManyDeep($related, array $through, array $foreignKeys = [], array $localKeys = [])
{
return $this->newHasManyDeep(...$this->hasOneOrManyDeep($related, $through, $foreignKeys, $localKeys));
} | [
"public",
"function",
"hasManyDeep",
"(",
"$",
"related",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
"=",
"[",
"]",
",",
"array",
"$",
"localKeys",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"newHasManyDeep",
"(",
"...",... | Define a has-many-deep relationship.
@param string $related
@param array $through
@param array $foreignKeys
@param array $localKeys
@return \Staudenmeir\EloquentHasManyDeep\HasManyDeep | [
"Define",
"a",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L23-L26 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.hasOneDeep | public function hasOneDeep($related, array $through, array $foreignKeys = [], array $localKeys = [])
{
return $this->newHasOneDeep(...$this->hasOneOrManyDeep($related, $through, $foreignKeys, $localKeys));
} | php | public function hasOneDeep($related, array $through, array $foreignKeys = [], array $localKeys = [])
{
return $this->newHasOneDeep(...$this->hasOneOrManyDeep($related, $through, $foreignKeys, $localKeys));
} | [
"public",
"function",
"hasOneDeep",
"(",
"$",
"related",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
"=",
"[",
"]",
",",
"array",
"$",
"localKeys",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"newHasOneDeep",
"(",
"...",
... | Define a has-one-deep relationship.
@param string $related
@param array $through
@param array $foreignKeys
@param array $localKeys
@return \Staudenmeir\EloquentHasManyDeep\HasOneDeep | [
"Define",
"a",
"has",
"-",
"one",
"-",
"deep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L48-L51 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.hasOneOrManyDeep | protected function hasOneOrManyDeep($related, array $through, array $foreignKeys, array $localKeys)
{
/** @var \Illuminate\Database\Eloquent\Model $relatedInstance */
$relatedInstance = $this->newRelatedInstance($related);
$throughParents = $this->hasOneOrManyDeepThroughParents($through);
$foreignKeys = $this->hasOneOrManyDeepForeignKeys($relatedInstance, $throughParents, $foreignKeys);
$localKeys = $this->hasOneOrManyDeepLocalKeys($relatedInstance, $throughParents, $localKeys);
return [$relatedInstance->newQuery(), $this, $throughParents, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeep($related, array $through, array $foreignKeys, array $localKeys)
{
/** @var \Illuminate\Database\Eloquent\Model $relatedInstance */
$relatedInstance = $this->newRelatedInstance($related);
$throughParents = $this->hasOneOrManyDeepThroughParents($through);
$foreignKeys = $this->hasOneOrManyDeepForeignKeys($relatedInstance, $throughParents, $foreignKeys);
$localKeys = $this->hasOneOrManyDeepLocalKeys($relatedInstance, $throughParents, $localKeys);
return [$relatedInstance->newQuery(), $this, $throughParents, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeep",
"(",
"$",
"related",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"/** @var \\Illuminate\\Database\\Eloquent\\Model $relatedInstance */",
"$",
"relatedInstance",
"=... | Prepare a has-one-deep or has-many-deep relationship.
@param string $related
@param array $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L73-L85 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.hasOneOrManyDeepThroughParents | protected function hasOneOrManyDeepThroughParents(array $through)
{
return array_map(function ($class) {
$segments = preg_split('/\s+as\s+/i', $class);
$instance = Str::contains($segments[0], '\\')
? new $segments[0]
: (new Pivot)->setTable($segments[0]);
if (isset($segments[1])) {
$instance->setTable($instance->getTable().' as '.$segments[1]);
}
return $instance;
}, $through);
} | php | protected function hasOneOrManyDeepThroughParents(array $through)
{
return array_map(function ($class) {
$segments = preg_split('/\s+as\s+/i', $class);
$instance = Str::contains($segments[0], '\\')
? new $segments[0]
: (new Pivot)->setTable($segments[0]);
if (isset($segments[1])) {
$instance->setTable($instance->getTable().' as '.$segments[1]);
}
return $instance;
}, $through);
} | [
"protected",
"function",
"hasOneOrManyDeepThroughParents",
"(",
"array",
"$",
"through",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"class",
")",
"{",
"$",
"segments",
"=",
"preg_split",
"(",
"'/\\s+as\\s+/i'",
",",
"$",
"class",
")",
";",
"... | Prepare the through parents for a has-one-deep or has-many-deep relationship.
@param array $through
@return array | [
"Prepare",
"the",
"through",
"parents",
"for",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L93-L108 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.hasOneOrManyDeepForeignKeys | protected function hasOneOrManyDeepForeignKeys(Model $related, array $throughParents, array $foreignKeys)
{
foreach (array_merge([$this], $throughParents) as $i => $instance) {
/** @var \Illuminate\Database\Eloquent\Model $instance */
if (! isset($foreignKeys[$i])) {
if ($instance instanceof Pivot) {
$foreignKeys[$i] = ($throughParents[$i] ?? $related)->getKeyName();
} else {
$foreignKeys[$i] = $instance->getForeignKey();
}
}
}
return $foreignKeys;
} | php | protected function hasOneOrManyDeepForeignKeys(Model $related, array $throughParents, array $foreignKeys)
{
foreach (array_merge([$this], $throughParents) as $i => $instance) {
/** @var \Illuminate\Database\Eloquent\Model $instance */
if (! isset($foreignKeys[$i])) {
if ($instance instanceof Pivot) {
$foreignKeys[$i] = ($throughParents[$i] ?? $related)->getKeyName();
} else {
$foreignKeys[$i] = $instance->getForeignKey();
}
}
}
return $foreignKeys;
} | [
"protected",
"function",
"hasOneOrManyDeepForeignKeys",
"(",
"Model",
"$",
"related",
",",
"array",
"$",
"throughParents",
",",
"array",
"$",
"foreignKeys",
")",
"{",
"foreach",
"(",
"array_merge",
"(",
"[",
"$",
"this",
"]",
",",
"$",
"throughParents",
")",
... | Prepare the foreign keys for a has-one-deep or has-many-deep relationship.
@param \Illuminate\Database\Eloquent\Model $related
@param \Illuminate\Database\Eloquent\Model[] $throughParents
@param array $foreignKeys
@return array | [
"Prepare",
"the",
"foreign",
"keys",
"for",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L118-L132 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.hasOneOrManyDeepLocalKeys | protected function hasOneOrManyDeepLocalKeys(Model $related, array $throughParents, array $localKeys)
{
foreach (array_merge([$this], $throughParents) as $i => $instance) {
/** @var \Illuminate\Database\Eloquent\Model $instance */
if (! isset($localKeys[$i])) {
if ($instance instanceof Pivot) {
$localKeys[$i] = ($throughParents[$i] ?? $related)->getForeignKey();
} else {
$localKeys[$i] = $instance->getKeyName();
}
}
}
return $localKeys;
} | php | protected function hasOneOrManyDeepLocalKeys(Model $related, array $throughParents, array $localKeys)
{
foreach (array_merge([$this], $throughParents) as $i => $instance) {
/** @var \Illuminate\Database\Eloquent\Model $instance */
if (! isset($localKeys[$i])) {
if ($instance instanceof Pivot) {
$localKeys[$i] = ($throughParents[$i] ?? $related)->getForeignKey();
} else {
$localKeys[$i] = $instance->getKeyName();
}
}
}
return $localKeys;
} | [
"protected",
"function",
"hasOneOrManyDeepLocalKeys",
"(",
"Model",
"$",
"related",
",",
"array",
"$",
"throughParents",
",",
"array",
"$",
"localKeys",
")",
"{",
"foreach",
"(",
"array_merge",
"(",
"[",
"$",
"this",
"]",
",",
"$",
"throughParents",
")",
"as... | Prepare the local keys for a has-one-deep or has-many-deep relationship.
@param \Illuminate\Database\Eloquent\Model $related
@param \Illuminate\Database\Eloquent\Model[] $throughParents
@param array $localKeys
@return array | [
"Prepare",
"the",
"local",
"keys",
"for",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L142-L156 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.newHasManyDeep | protected function newHasManyDeep(Builder $query, Model $farParent, array $throughParents, array $foreignKeys, array $localKeys)
{
return new HasManyDeep($query, $farParent, $throughParents, $foreignKeys, $localKeys);
} | php | protected function newHasManyDeep(Builder $query, Model $farParent, array $throughParents, array $foreignKeys, array $localKeys)
{
return new HasManyDeep($query, $farParent, $throughParents, $foreignKeys, $localKeys);
} | [
"protected",
"function",
"newHasManyDeep",
"(",
"Builder",
"$",
"query",
",",
"Model",
"$",
"farParent",
",",
"array",
"$",
"throughParents",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"return",
"new",
"HasManyDeep",
"(",
"$"... | Instantiate a new HasManyDeep relationship.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $farParent
@param \Illuminate\Database\Eloquent\Model[] $throughParents
@param array $foreignKeys
@param array $localKeys
@return \Staudenmeir\EloquentHasManyDeep\HasManyDeep | [
"Instantiate",
"a",
"new",
"HasManyDeep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L168-L171 | train |
staudenmeir/eloquent-has-many-deep | src/HasRelationships.php | HasRelationships.newHasOneDeep | protected function newHasOneDeep(Builder $query, Model $farParent, array $throughParents, array $foreignKeys, array $localKeys)
{
return new HasOneDeep($query, $farParent, $throughParents, $foreignKeys, $localKeys);
} | php | protected function newHasOneDeep(Builder $query, Model $farParent, array $throughParents, array $foreignKeys, array $localKeys)
{
return new HasOneDeep($query, $farParent, $throughParents, $foreignKeys, $localKeys);
} | [
"protected",
"function",
"newHasOneDeep",
"(",
"Builder",
"$",
"query",
",",
"Model",
"$",
"farParent",
",",
"array",
"$",
"throughParents",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"return",
"new",
"HasOneDeep",
"(",
"$",
... | Instantiate a new HasOneDeep relationship.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $farParent
@param \Illuminate\Database\Eloquent\Model[] $throughParents
@param array $foreignKeys
@param array $localKeys
@return \Staudenmeir\EloquentHasManyDeep\HasOneDeep | [
"Instantiate",
"a",
"new",
"HasOneDeep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasRelationships.php#L183-L186 | train |
staudenmeir/eloquent-has-many-deep | src/RetrievesIntermediateTables.php | RetrievesIntermediateTables.withIntermediate | public function withIntermediate($class, array $columns = ['*'], $accessor = null)
{
/** @var \Illuminate\Database\Eloquent\Model $instance */
$instance = new $class;
$accessor = $accessor ?: Str::snake(class_basename($class));
return $this->withPivot($instance->getTable(), $columns, $class, $accessor);
} | php | public function withIntermediate($class, array $columns = ['*'], $accessor = null)
{
/** @var \Illuminate\Database\Eloquent\Model $instance */
$instance = new $class;
$accessor = $accessor ?: Str::snake(class_basename($class));
return $this->withPivot($instance->getTable(), $columns, $class, $accessor);
} | [
"public",
"function",
"withIntermediate",
"(",
"$",
"class",
",",
"array",
"$",
"columns",
"=",
"[",
"'*'",
"]",
",",
"$",
"accessor",
"=",
"null",
")",
"{",
"/** @var \\Illuminate\\Database\\Eloquent\\Model $instance */",
"$",
"instance",
"=",
"new",
"$",
"clas... | Set the columns on an intermediate table to retrieve.
@param string $class
@param array $columns
@param string|null $accessor
@return $this | [
"Set",
"the",
"columns",
"on",
"an",
"intermediate",
"table",
"to",
"retrieve",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/RetrievesIntermediateTables.php#L26-L34 | train |
staudenmeir/eloquent-has-many-deep | src/RetrievesIntermediateTables.php | RetrievesIntermediateTables.withPivot | public function withPivot($table, array $columns = ['*'], $class = Pivot::class, $accessor = null)
{
if ($columns === ['*']) {
$columns = $this->query->getConnection()->getSchemaBuilder()->getColumnListing($table);
}
$accessor = $accessor ?: $table;
if (isset($this->intermediateTables[$accessor])) {
$columns = array_merge($columns, $this->intermediateTables[$accessor]['columns']);
}
$this->intermediateTables[$accessor] = compact('table', 'columns', 'class');
return $this;
} | php | public function withPivot($table, array $columns = ['*'], $class = Pivot::class, $accessor = null)
{
if ($columns === ['*']) {
$columns = $this->query->getConnection()->getSchemaBuilder()->getColumnListing($table);
}
$accessor = $accessor ?: $table;
if (isset($this->intermediateTables[$accessor])) {
$columns = array_merge($columns, $this->intermediateTables[$accessor]['columns']);
}
$this->intermediateTables[$accessor] = compact('table', 'columns', 'class');
return $this;
} | [
"public",
"function",
"withPivot",
"(",
"$",
"table",
",",
"array",
"$",
"columns",
"=",
"[",
"'*'",
"]",
",",
"$",
"class",
"=",
"Pivot",
"::",
"class",
",",
"$",
"accessor",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"columns",
"===",
"[",
"'*'",
"... | Set the columns on a pivot table to retrieve.
@param string $table
@param array $columns
@param string $class
@param string|null $accessor
@return $this | [
"Set",
"the",
"columns",
"on",
"a",
"pivot",
"table",
"to",
"retrieve",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/RetrievesIntermediateTables.php#L45-L60 | train |
staudenmeir/eloquent-has-many-deep | src/RetrievesIntermediateTables.php | RetrievesIntermediateTables.intermediateColumns | protected function intermediateColumns()
{
$columns = [];
foreach ($this->intermediateTables as $accessor => $intermediateTable) {
$prefix = $this->prefix($accessor);
foreach ($intermediateTable['columns'] as $column) {
$columns[] = $intermediateTable['table'].'.'.$column.' as '.$prefix.$column;
}
}
return array_unique($columns);
} | php | protected function intermediateColumns()
{
$columns = [];
foreach ($this->intermediateTables as $accessor => $intermediateTable) {
$prefix = $this->prefix($accessor);
foreach ($intermediateTable['columns'] as $column) {
$columns[] = $intermediateTable['table'].'.'.$column.' as '.$prefix.$column;
}
}
return array_unique($columns);
} | [
"protected",
"function",
"intermediateColumns",
"(",
")",
"{",
"$",
"columns",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"intermediateTables",
"as",
"$",
"accessor",
"=>",
"$",
"intermediateTable",
")",
"{",
"$",
"prefix",
"=",
"$",
"this",
... | Get the intermediate columns for the relation.
@return array | [
"Get",
"the",
"intermediate",
"columns",
"for",
"the",
"relation",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/RetrievesIntermediateTables.php#L67-L80 | train |
staudenmeir/eloquent-has-many-deep | src/RetrievesIntermediateTables.php | RetrievesIntermediateTables.hydrateIntermediateRelations | protected function hydrateIntermediateRelations(array $models)
{
$intermediateTables = $this->intermediateTables;
ksort($intermediateTables);
foreach ($intermediateTables as $accessor => $intermediateTable) {
$prefix = $this->prefix($accessor);
if (Str::contains($accessor, '.')) {
[$path, $key] = preg_split('/\.(?=[^.]*$)/', $accessor);
} else {
[$path, $key] = [null, $accessor];
}
foreach ($models as $model) {
$relation = $this->intermediateRelation($model, $intermediateTable, $prefix);
data_get($model, $path)->setRelation($key, $relation);
}
}
} | php | protected function hydrateIntermediateRelations(array $models)
{
$intermediateTables = $this->intermediateTables;
ksort($intermediateTables);
foreach ($intermediateTables as $accessor => $intermediateTable) {
$prefix = $this->prefix($accessor);
if (Str::contains($accessor, '.')) {
[$path, $key] = preg_split('/\.(?=[^.]*$)/', $accessor);
} else {
[$path, $key] = [null, $accessor];
}
foreach ($models as $model) {
$relation = $this->intermediateRelation($model, $intermediateTable, $prefix);
data_get($model, $path)->setRelation($key, $relation);
}
}
} | [
"protected",
"function",
"hydrateIntermediateRelations",
"(",
"array",
"$",
"models",
")",
"{",
"$",
"intermediateTables",
"=",
"$",
"this",
"->",
"intermediateTables",
";",
"ksort",
"(",
"$",
"intermediateTables",
")",
";",
"foreach",
"(",
"$",
"intermediateTable... | Hydrate the intermediate table relationship on the models.
@param array $models
@return void | [
"Hydrate",
"the",
"intermediate",
"table",
"relationship",
"on",
"the",
"models",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/RetrievesIntermediateTables.php#L88-L109 | train |
staudenmeir/eloquent-has-many-deep | src/RetrievesIntermediateTables.php | RetrievesIntermediateTables.intermediateRelation | protected function intermediateRelation(Model $model, array $intermediateTable, $prefix)
{
$attributes = $this->intermediateAttributes($model, $prefix);
$class = $intermediateTable['class'];
if ($class === Pivot::class) {
return $class::fromAttributes($model, $attributes, $intermediateTable['table'], true);
}
if (is_subclass_of($class, Pivot::class)) {
return $class::fromRawAttributes($model, $attributes, $intermediateTable['table'], true);
}
/** @var \Illuminate\Database\Eloquent\Model $instance */
$instance = new $class;
return $instance->newFromBuilder($attributes);
} | php | protected function intermediateRelation(Model $model, array $intermediateTable, $prefix)
{
$attributes = $this->intermediateAttributes($model, $prefix);
$class = $intermediateTable['class'];
if ($class === Pivot::class) {
return $class::fromAttributes($model, $attributes, $intermediateTable['table'], true);
}
if (is_subclass_of($class, Pivot::class)) {
return $class::fromRawAttributes($model, $attributes, $intermediateTable['table'], true);
}
/** @var \Illuminate\Database\Eloquent\Model $instance */
$instance = new $class;
return $instance->newFromBuilder($attributes);
} | [
"protected",
"function",
"intermediateRelation",
"(",
"Model",
"$",
"model",
",",
"array",
"$",
"intermediateTable",
",",
"$",
"prefix",
")",
"{",
"$",
"attributes",
"=",
"$",
"this",
"->",
"intermediateAttributes",
"(",
"$",
"model",
",",
"$",
"prefix",
")"... | Get the intermediate relationship from the query.
@param \Illuminate\Database\Eloquent\Model $model
@param array $intermediateTable
@param string $prefix
@return \Illuminate\Database\Eloquent\Model | [
"Get",
"the",
"intermediate",
"relationship",
"from",
"the",
"query",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/RetrievesIntermediateTables.php#L119-L137 | train |
staudenmeir/eloquent-has-many-deep | src/RetrievesIntermediateTables.php | RetrievesIntermediateTables.intermediateAttributes | protected function intermediateAttributes(Model $model, $prefix)
{
$attributes = [];
foreach ($model->getAttributes() as $key => $value) {
if (strpos($key, $prefix) === 0) {
$attributes[substr($key, strlen($prefix))] = $value;
unset($model->$key);
}
}
return $attributes;
} | php | protected function intermediateAttributes(Model $model, $prefix)
{
$attributes = [];
foreach ($model->getAttributes() as $key => $value) {
if (strpos($key, $prefix) === 0) {
$attributes[substr($key, strlen($prefix))] = $value;
unset($model->$key);
}
}
return $attributes;
} | [
"protected",
"function",
"intermediateAttributes",
"(",
"Model",
"$",
"model",
",",
"$",
"prefix",
")",
"{",
"$",
"attributes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"model",
"->",
"getAttributes",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")"... | Get the intermediate attributes from a model.
@param \Illuminate\Database\Eloquent\Model $model
@param string $prefix
@return array | [
"Get",
"the",
"intermediate",
"attributes",
"from",
"a",
"model",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/RetrievesIntermediateTables.php#L146-L159 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromRelations | protected function hasOneOrManyDeepFromRelations(array $relations)
{
if (is_array($relations[0])) {
$relations = $relations[0];
}
$related = null;
$through = [];
$foreignKeys = [];
$localKeys = [];
foreach ($relations as $i => $relation) {
$method = $this->hasOneOrManyDeepRelationMethod($relation);
[$through, $foreignKeys, $localKeys] = $this->$method($relation, $through, $foreignKeys, $localKeys);
if ($i === count($relations) - 1) {
$related = get_class($relation->getRelated());
} else {
$through[] = get_class($relation->getRelated());
}
}
return [$related, $through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromRelations(array $relations)
{
if (is_array($relations[0])) {
$relations = $relations[0];
}
$related = null;
$through = [];
$foreignKeys = [];
$localKeys = [];
foreach ($relations as $i => $relation) {
$method = $this->hasOneOrManyDeepRelationMethod($relation);
[$through, $foreignKeys, $localKeys] = $this->$method($relation, $through, $foreignKeys, $localKeys);
if ($i === count($relations) - 1) {
$related = get_class($relation->getRelated());
} else {
$through[] = get_class($relation->getRelated());
}
}
return [$related, $through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromRelations",
"(",
"array",
"$",
"relations",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"relations",
"[",
"0",
"]",
")",
")",
"{",
"$",
"relations",
"=",
"$",
"relations",
"[",
"0",
"]",
";",
"}",
"$",
"rela... | Prepare a has-one-deep or has-many-deep relationship from existing relationships.
@param \Illuminate\Database\Eloquent\Relations\Relation[] $relations
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"existing",
"relationships",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L23-L47 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromBelongsTo | protected function hasOneOrManyDeepFromBelongsTo(BelongsTo $relation, array $through, array $foreignKeys, array $localKeys)
{
$foreignKeys[] = $relation->getOwnerKeyName();
$localKeys[] = $relation->getForeignKeyName();
return [$through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromBelongsTo(BelongsTo $relation, array $through, array $foreignKeys, array $localKeys)
{
$foreignKeys[] = $relation->getOwnerKeyName();
$localKeys[] = $relation->getForeignKeyName();
return [$through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromBelongsTo",
"(",
"BelongsTo",
"$",
"relation",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"$",
"foreignKeys",
"[",
"]",
"=",
"$",
"relation",
"->",
"... | Prepare a has-one-deep or has-many-deep relationship from an existing belongs-to relationship.
@param \Illuminate\Database\Eloquent\Relations\BelongsTo $relation
@param \Illuminate\Database\Eloquent\Model[] $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"an",
"existing",
"belongs",
"-",
"to",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L58-L65 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromBelongsToMany | protected function hasOneOrManyDeepFromBelongsToMany(BelongsToMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$through[] = $relation->getTable();
$foreignKeys[] = $relation->getForeignPivotKeyName();
$foreignKeys[] = $relation->getRelatedKeyName();
$localKeys[] = $relation->getParentKeyName();
$localKeys[] = $relation->getRelatedPivotKeyName();
return [$through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromBelongsToMany(BelongsToMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$through[] = $relation->getTable();
$foreignKeys[] = $relation->getForeignPivotKeyName();
$foreignKeys[] = $relation->getRelatedKeyName();
$localKeys[] = $relation->getParentKeyName();
$localKeys[] = $relation->getRelatedPivotKeyName();
return [$through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromBelongsToMany",
"(",
"BelongsToMany",
"$",
"relation",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"$",
"through",
"[",
"]",
"=",
"$",
"relation",
"->",... | Prepare a has-one-deep or has-many-deep relationship from an existing belongs-to-many relationship.
@param \Illuminate\Database\Eloquent\Relations\BelongsToMany $relation
@param \Illuminate\Database\Eloquent\Model[] $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"an",
"existing",
"belongs",
"-",
"to",
"-",
"many",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L76-L87 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromHasOneOrMany | protected function hasOneOrManyDeepFromHasOneOrMany(HasOneOrMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$foreignKeys[] = $relation->getQualifiedForeignKeyName();
$localKeys[] = $relation->getLocalKeyName();
return [$through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromHasOneOrMany(HasOneOrMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$foreignKeys[] = $relation->getQualifiedForeignKeyName();
$localKeys[] = $relation->getLocalKeyName();
return [$through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromHasOneOrMany",
"(",
"HasOneOrMany",
"$",
"relation",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"$",
"foreignKeys",
"[",
"]",
"=",
"$",
"relation",
"->... | Prepare a has-one-deep or has-many-deep relationship from an existing has-one or has-many relationship.
@param \Illuminate\Database\Eloquent\Relations\HasOneOrMany $relation
@param \Illuminate\Database\Eloquent\Model[] $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"an",
"existing",
"has",
"-",
"one",
"or",
"has",
"-",
"many",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L98-L105 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromHasManyThrough | protected function hasOneOrManyDeepFromHasManyThrough(HasManyThrough $relation, array $through, array $foreignKeys, array $localKeys)
{
$through[] = get_class($relation->getParent());
$foreignKeys[] = $relation->getFirstKeyName();
$foreignKeys[] = $relation->getForeignKeyName();
$localKeys[] = $relation->getLocalKeyName();
$localKeys[] = $relation->getSecondLocalKeyName();
return [$through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromHasManyThrough(HasManyThrough $relation, array $through, array $foreignKeys, array $localKeys)
{
$through[] = get_class($relation->getParent());
$foreignKeys[] = $relation->getFirstKeyName();
$foreignKeys[] = $relation->getForeignKeyName();
$localKeys[] = $relation->getLocalKeyName();
$localKeys[] = $relation->getSecondLocalKeyName();
return [$through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromHasManyThrough",
"(",
"HasManyThrough",
"$",
"relation",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"$",
"through",
"[",
"]",
"=",
"get_class",
"(",
"$... | Prepare a has-one-deep or has-many-deep relationship from an existing has-many-through relationship.
@param \Illuminate\Database\Eloquent\Relations\HasManyThrough $relation
@param \Illuminate\Database\Eloquent\Model[] $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"an",
"existing",
"has",
"-",
"many",
"-",
"through",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L116-L127 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromHasManyDeep | protected function hasOneOrManyDeepFromHasManyDeep(HasManyDeep $relation, array $through, array $foreignKeys, array $localKeys)
{
foreach ($relation->getThroughParents() as $throughParent) {
$segments = explode(' as ', $throughParent->getTable());
$class = get_class($throughParent);
if (isset($segments[1])) {
$class .= ' as '.$segments[1];
} elseif ($throughParent instanceof Pivot) {
$class = $throughParent->getTable();
}
$through[] = $class;
}
$foreignKeys = array_merge($foreignKeys, $relation->getForeignKeys());
$localKeys = array_merge($localKeys, $relation->getLocalKeys());
return [$through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromHasManyDeep(HasManyDeep $relation, array $through, array $foreignKeys, array $localKeys)
{
foreach ($relation->getThroughParents() as $throughParent) {
$segments = explode(' as ', $throughParent->getTable());
$class = get_class($throughParent);
if (isset($segments[1])) {
$class .= ' as '.$segments[1];
} elseif ($throughParent instanceof Pivot) {
$class = $throughParent->getTable();
}
$through[] = $class;
}
$foreignKeys = array_merge($foreignKeys, $relation->getForeignKeys());
$localKeys = array_merge($localKeys, $relation->getLocalKeys());
return [$through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromHasManyDeep",
"(",
"HasManyDeep",
"$",
"relation",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"foreach",
"(",
"$",
"relation",
"->",
"getThroughParents",
... | Prepare a has-one-deep or has-many-deep relationship from an existing has-many-deep relationship.
@param \Staudenmeir\EloquentHasManyDeep\HasManyDeep $relation
@param \Illuminate\Database\Eloquent\Model[] $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"an",
"existing",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L138-L159 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromMorphOneOrMany | protected function hasOneOrManyDeepFromMorphOneOrMany(MorphOneOrMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$foreignKeys[] = [$relation->getQualifiedMorphType(), $relation->getQualifiedForeignKeyName()];
$localKeys[] = $relation->getLocalKeyName();
return [$through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromMorphOneOrMany(MorphOneOrMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$foreignKeys[] = [$relation->getQualifiedMorphType(), $relation->getQualifiedForeignKeyName()];
$localKeys[] = $relation->getLocalKeyName();
return [$through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromMorphOneOrMany",
"(",
"MorphOneOrMany",
"$",
"relation",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"$",
"foreignKeys",
"[",
"]",
"=",
"[",
"$",
"relat... | Prepare a has-one-deep or has-many-deep relationship from an existing morph-one or morph-many relationship.
@param \Illuminate\Database\Eloquent\Relations\MorphOneOrMany $relation
@param \Illuminate\Database\Eloquent\Model[] $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"an",
"existing",
"morph",
"-",
"one",
"or",
"morph",
"-",
"many",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L170-L177 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepFromMorphToMany | protected function hasOneOrManyDeepFromMorphToMany(MorphToMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$through[] = $relation->getTable();
if ($relation->getInverse()) {
$foreignKeys[] = $relation->getForeignPivotKeyName();
$foreignKeys[] = $relation->getRelatedKeyName();
$localKeys[] = $relation->getParentKeyName();
$localKeys[] = [$relation->getMorphType(), $relation->getRelatedPivotKeyName()];
} else {
$foreignKeys[] = [$relation->getMorphType(), $relation->getForeignPivotKeyName()];
$foreignKeys[] = $relation->getRelatedKeyName();
$localKeys[] = $relation->getParentKeyName();
$localKeys[] = $relation->getRelatedPivotKeyName();
}
return [$through, $foreignKeys, $localKeys];
} | php | protected function hasOneOrManyDeepFromMorphToMany(MorphToMany $relation, array $through, array $foreignKeys, array $localKeys)
{
$through[] = $relation->getTable();
if ($relation->getInverse()) {
$foreignKeys[] = $relation->getForeignPivotKeyName();
$foreignKeys[] = $relation->getRelatedKeyName();
$localKeys[] = $relation->getParentKeyName();
$localKeys[] = [$relation->getMorphType(), $relation->getRelatedPivotKeyName()];
} else {
$foreignKeys[] = [$relation->getMorphType(), $relation->getForeignPivotKeyName()];
$foreignKeys[] = $relation->getRelatedKeyName();
$localKeys[] = $relation->getParentKeyName();
$localKeys[] = $relation->getRelatedPivotKeyName();
}
return [$through, $foreignKeys, $localKeys];
} | [
"protected",
"function",
"hasOneOrManyDeepFromMorphToMany",
"(",
"MorphToMany",
"$",
"relation",
",",
"array",
"$",
"through",
",",
"array",
"$",
"foreignKeys",
",",
"array",
"$",
"localKeys",
")",
"{",
"$",
"through",
"[",
"]",
"=",
"$",
"relation",
"->",
"... | Prepare a has-one-deep or has-many-deep relationship from an existing morph-to-many relationship.
@param \Illuminate\Database\Eloquent\Relations\MorphToMany $relation
@param \Illuminate\Database\Eloquent\Model[] $through
@param array $foreignKeys
@param array $localKeys
@return array | [
"Prepare",
"a",
"has",
"-",
"one",
"-",
"deep",
"or",
"has",
"-",
"many",
"-",
"deep",
"relationship",
"from",
"an",
"existing",
"morph",
"-",
"to",
"-",
"many",
"relationship",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L188-L207 | train |
staudenmeir/eloquent-has-many-deep | src/ConcatenatesRelationships.php | ConcatenatesRelationships.hasOneOrManyDeepRelationMethod | protected function hasOneOrManyDeepRelationMethod(Relation $relation)
{
$classes = [
BelongsTo::class,
HasManyDeep::class,
HasManyThrough::class,
MorphOneOrMany::class,
HasOneOrMany::class,
MorphToMany::class,
BelongsToMany::class,
];
foreach ($classes as $class) {
if ($relation instanceof $class) {
return 'hasOneOrManyDeepFrom'.class_basename($class);
}
}
throw new RuntimeException('This relationship is not supported.'); // @codeCoverageIgnore
} | php | protected function hasOneOrManyDeepRelationMethod(Relation $relation)
{
$classes = [
BelongsTo::class,
HasManyDeep::class,
HasManyThrough::class,
MorphOneOrMany::class,
HasOneOrMany::class,
MorphToMany::class,
BelongsToMany::class,
];
foreach ($classes as $class) {
if ($relation instanceof $class) {
return 'hasOneOrManyDeepFrom'.class_basename($class);
}
}
throw new RuntimeException('This relationship is not supported.'); // @codeCoverageIgnore
} | [
"protected",
"function",
"hasOneOrManyDeepRelationMethod",
"(",
"Relation",
"$",
"relation",
")",
"{",
"$",
"classes",
"=",
"[",
"BelongsTo",
"::",
"class",
",",
"HasManyDeep",
"::",
"class",
",",
"HasManyThrough",
"::",
"class",
",",
"MorphOneOrMany",
"::",
"cl... | Get the relationship method name.
@param \Illuminate\Database\Eloquent\Relations\Relation $relation
@return string | [
"Get",
"the",
"relationship",
"method",
"name",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/ConcatenatesRelationships.php#L215-L234 | train |
staudenmeir/eloquent-has-many-deep | src/HasTableAlias.php | HasTableAlias.qualifyColumn | public function qualifyColumn($column)
{
if (Str::contains($column, '.')) {
return $column;
}
$table = $this->getTable();
if (Str::contains($table, ' as ')) {
$table = explode(' as ', $table)[1];
}
return $table.'.'.$column;
} | php | public function qualifyColumn($column)
{
if (Str::contains($column, '.')) {
return $column;
}
$table = $this->getTable();
if (Str::contains($table, ' as ')) {
$table = explode(' as ', $table)[1];
}
return $table.'.'.$column;
} | [
"public",
"function",
"qualifyColumn",
"(",
"$",
"column",
")",
"{",
"if",
"(",
"Str",
"::",
"contains",
"(",
"$",
"column",
",",
"'.'",
")",
")",
"{",
"return",
"$",
"column",
";",
"}",
"$",
"table",
"=",
"$",
"this",
"->",
"getTable",
"(",
")",
... | Qualify the given column name by the model's table.
@param string $column
@return string | [
"Qualify",
"the",
"given",
"column",
"name",
"by",
"the",
"model",
"s",
"table",
"."
] | 48e5a70eeddbae87eea21dcc576eeb5d7377057f | https://github.com/staudenmeir/eloquent-has-many-deep/blob/48e5a70eeddbae87eea21dcc576eeb5d7377057f/src/HasTableAlias.php#L15-L28 | train |
jakubkulhan/chrome-devtools-protocol | src/ChromeDevtoolsProtocol/Instance/Launcher.php | Launcher.launch | public function launch(ContextInterface $ctx, ...$args): ProcessInstance
{
if ($this->executable) {
$executable = $this->executable;
} else if (PHP_OS === "Linux") {
$finder = new ExecutableFinder();
$executable = $finder->find(static::DEFAULT_LINUX_EXECUTABLE);
if ($executable === null) {
throw new RuntimeException(sprintf("Executable [%s] not found.", static::DEFAULT_LINUX_EXECUTABLE));
}
} else if (strncasecmp(PHP_OS, "Win", 3) === 0) {
$finder = new ExecutableFinder();
$executable = $finder->find(static::DEFAULT_WINDOWS_EXECUTABLE);
if ($executable === null) {
throw new RuntimeException(sprintf("Executable [%s] not found.", static::DEFAULT_WINDOWS_EXECUTABLE));
}
} else if (PHP_OS === "Darwin") {
$candidateExecutables = [
// Chrome Canary
"/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
// Chrome Stable
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
];
$executable = null;
foreach ($candidateExecutables as $candidateExecutable) {
if (is_executable($candidateExecutable)) {
$executable = $candidateExecutable;
break;
}
}
if ($executable === null) {
throw new RuntimeException(sprintf("No OS X executable found."));
}
} else {
throw new LogicException(sprintf("Operating system [%s] not supported.", PHP_OS));
}
return $this->launchWithExecutable($ctx, $executable, ...$args);
} | php | public function launch(ContextInterface $ctx, ...$args): ProcessInstance
{
if ($this->executable) {
$executable = $this->executable;
} else if (PHP_OS === "Linux") {
$finder = new ExecutableFinder();
$executable = $finder->find(static::DEFAULT_LINUX_EXECUTABLE);
if ($executable === null) {
throw new RuntimeException(sprintf("Executable [%s] not found.", static::DEFAULT_LINUX_EXECUTABLE));
}
} else if (strncasecmp(PHP_OS, "Win", 3) === 0) {
$finder = new ExecutableFinder();
$executable = $finder->find(static::DEFAULT_WINDOWS_EXECUTABLE);
if ($executable === null) {
throw new RuntimeException(sprintf("Executable [%s] not found.", static::DEFAULT_WINDOWS_EXECUTABLE));
}
} else if (PHP_OS === "Darwin") {
$candidateExecutables = [
// Chrome Canary
"/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
// Chrome Stable
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
];
$executable = null;
foreach ($candidateExecutables as $candidateExecutable) {
if (is_executable($candidateExecutable)) {
$executable = $candidateExecutable;
break;
}
}
if ($executable === null) {
throw new RuntimeException(sprintf("No OS X executable found."));
}
} else {
throw new LogicException(sprintf("Operating system [%s] not supported.", PHP_OS));
}
return $this->launchWithExecutable($ctx, $executable, ...$args);
} | [
"public",
"function",
"launch",
"(",
"ContextInterface",
"$",
"ctx",
",",
"...",
"$",
"args",
")",
":",
"ProcessInstance",
"{",
"if",
"(",
"$",
"this",
"->",
"executable",
")",
"{",
"$",
"executable",
"=",
"$",
"this",
"->",
"executable",
";",
"}",
"el... | Start new Chrome process.
@param ContextInterface $ctx
@param array ...$args
@return ProcessInstance
@throws \Exception | [
"Start",
"new",
"Chrome",
"process",
"."
] | 6c04886b36263f108f5cdf7c255f71ee92c80f0c | https://github.com/jakubkulhan/chrome-devtools-protocol/blob/6c04886b36263f108f5cdf7c255f71ee92c80f0c/src/ChromeDevtoolsProtocol/Instance/Launcher.php#L123-L167 | train |
jakubkulhan/chrome-devtools-protocol | src/ChromeDevtoolsProtocol/Instance/Tab.php | Tab.activate | public function activate(ContextInterface $ctx): void
{
$this->internalInstance->activateTabById($ctx, $this->id);
} | php | public function activate(ContextInterface $ctx): void
{
$this->internalInstance->activateTabById($ctx, $this->id);
} | [
"public",
"function",
"activate",
"(",
"ContextInterface",
"$",
"ctx",
")",
":",
"void",
"{",
"$",
"this",
"->",
"internalInstance",
"->",
"activateTabById",
"(",
"$",
"ctx",
",",
"$",
"this",
"->",
"id",
")",
";",
"}"
] | Activate this tab.
@param ContextInterface $ctx | [
"Activate",
"this",
"tab",
"."
] | 6c04886b36263f108f5cdf7c255f71ee92c80f0c | https://github.com/jakubkulhan/chrome-devtools-protocol/blob/6c04886b36263f108f5cdf7c255f71ee92c80f0c/src/ChromeDevtoolsProtocol/Instance/Tab.php#L71-L74 | train |
jakubkulhan/chrome-devtools-protocol | src/ChromeDevtoolsProtocol/Instance/Tab.php | Tab.close | public function close(ContextInterface $ctx): void
{
$this->internalInstance->closeTabById($ctx, $this->id);
} | php | public function close(ContextInterface $ctx): void
{
$this->internalInstance->closeTabById($ctx, $this->id);
} | [
"public",
"function",
"close",
"(",
"ContextInterface",
"$",
"ctx",
")",
":",
"void",
"{",
"$",
"this",
"->",
"internalInstance",
"->",
"closeTabById",
"(",
"$",
"ctx",
",",
"$",
"this",
"->",
"id",
")",
";",
"}"
] | Close this tab.
@param ContextInterface $ctx | [
"Close",
"this",
"tab",
"."
] | 6c04886b36263f108f5cdf7c255f71ee92c80f0c | https://github.com/jakubkulhan/chrome-devtools-protocol/blob/6c04886b36263f108f5cdf7c255f71ee92c80f0c/src/ChromeDevtoolsProtocol/Instance/Tab.php#L81-L84 | train |
markuspoerschke/iCal | src/PropertyBag.php | PropertyBag.add | public function add(Property $property)
{
$name = $property->getName();
if (isset($this->elements[$name])) {
throw new \Exception("Property with name '{$name}' already exists");
}
$this->elements[$name] = $property;
return $this;
} | php | public function add(Property $property)
{
$name = $property->getName();
if (isset($this->elements[$name])) {
throw new \Exception("Property with name '{$name}' already exists");
}
$this->elements[$name] = $property;
return $this;
} | [
"public",
"function",
"add",
"(",
"Property",
"$",
"property",
")",
"{",
"$",
"name",
"=",
"$",
"property",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"ne... | Adds a Property. If Property already exists an Exception will be thrown.
@param Property $property
@return $this
@throws \Exception | [
"Adds",
"a",
"Property",
".",
"If",
"Property",
"already",
"exists",
"an",
"Exception",
"will",
"be",
"thrown",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/PropertyBag.php#L60-L71 | train |
markuspoerschke/iCal | src/ParameterBag.php | ParameterBag.escapeParamValue | private function escapeParamValue($value)
{
$count = 0;
$value = str_replace('\\', '\\\\', $value);
$value = str_replace('"', '\"', $value, $count);
$value = str_replace("\n", '\\n', $value);
if (false !== strpos($value, ';') || false !== strpos($value, ',') || false !== strpos($value, ':') || $count) {
$value = '"' . $value . '"';
}
return $value;
} | php | private function escapeParamValue($value)
{
$count = 0;
$value = str_replace('\\', '\\\\', $value);
$value = str_replace('"', '\"', $value, $count);
$value = str_replace("\n", '\\n', $value);
if (false !== strpos($value, ';') || false !== strpos($value, ',') || false !== strpos($value, ':') || $count) {
$value = '"' . $value . '"';
}
return $value;
} | [
"private",
"function",
"escapeParamValue",
"(",
"$",
"value",
")",
"{",
"$",
"count",
"=",
"0",
";",
"$",
"value",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
",",
"$",
"value",
")",
";",
"$",
"value",
"=",
"str_replace",
"(",
"'\"'",
",",
... | Returns an escaped string for a param value.
@param string $value
@return string | [
"Returns",
"an",
"escaped",
"string",
"for",
"a",
"param",
"value",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/ParameterBag.php#L92-L103 | train |
markuspoerschke/iCal | src/Util/ComponentUtil.php | ComponentUtil.fold | public static function fold($string)
{
$lines = [];
if (function_exists('mb_strcut')) {
while (strlen($string) > 0) {
if (strlen($string) > 75) {
$lines[] = mb_strcut($string, 0, 75, 'utf-8');
$string = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8');
} else {
$lines[] = $string;
$string = '';
break;
}
}
} else {
$array = preg_split('/(?<!^)(?!$)/u', $string);
$line = '';
$lineNo = 0;
foreach ($array as $char) {
$charLen = strlen($char);
$lineLen = strlen($line);
if ($lineLen + $charLen > 75) {
$line = ' ' . $char;
++$lineNo;
} else {
$line .= $char;
}
$lines[$lineNo] = $line;
}
}
return $lines;
} | php | public static function fold($string)
{
$lines = [];
if (function_exists('mb_strcut')) {
while (strlen($string) > 0) {
if (strlen($string) > 75) {
$lines[] = mb_strcut($string, 0, 75, 'utf-8');
$string = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8');
} else {
$lines[] = $string;
$string = '';
break;
}
}
} else {
$array = preg_split('/(?<!^)(?!$)/u', $string);
$line = '';
$lineNo = 0;
foreach ($array as $char) {
$charLen = strlen($char);
$lineLen = strlen($line);
if ($lineLen + $charLen > 75) {
$line = ' ' . $char;
++$lineNo;
} else {
$line .= $char;
}
$lines[$lineNo] = $line;
}
}
return $lines;
} | [
"public",
"static",
"function",
"fold",
"(",
"$",
"string",
")",
"{",
"$",
"lines",
"=",
"[",
"]",
";",
"if",
"(",
"function_exists",
"(",
"'mb_strcut'",
")",
")",
"{",
"while",
"(",
"strlen",
"(",
"$",
"string",
")",
">",
"0",
")",
"{",
"if",
"(... | Folds a single line.
According to RFC 5545, all lines longer than 75 characters should be folded
@see https://tools.ietf.org/html/rfc5545#section-5
@see https://tools.ietf.org/html/rfc5545#section-3.1
@param string $string
@return array | [
"Folds",
"a",
"single",
"line",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Util/ComponentUtil.php#L28-L61 | train |
markuspoerschke/iCal | src/Property/Event/Geo.php | Geo.getGeoLocationAsString | public function getGeoLocationAsString(string $separator = ';'): string
{
return number_format($this->latitude, 6) . $separator . number_format($this->longitude, 6);
} | php | public function getGeoLocationAsString(string $separator = ';'): string
{
return number_format($this->latitude, 6) . $separator . number_format($this->longitude, 6);
} | [
"public",
"function",
"getGeoLocationAsString",
"(",
"string",
"$",
"separator",
"=",
"';'",
")",
":",
"string",
"{",
"return",
"number_format",
"(",
"$",
"this",
"->",
"latitude",
",",
"6",
")",
".",
"$",
"separator",
".",
"number_format",
"(",
"$",
"this... | Returns the coordinates as a string.
@example 37.386013;-122.082932
@param string $separator
@return string | [
"Returns",
"the",
"coordinates",
"as",
"a",
"string",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/Geo.php#L78-L81 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setFreq | public function setFreq($freq)
{
if (@constant('static::FREQ_' . $freq) !== null) {
$this->freq = $freq;
} else {
throw new \InvalidArgumentException("The Frequency {$freq} is not supported.");
}
return $this;
} | php | public function setFreq($freq)
{
if (@constant('static::FREQ_' . $freq) !== null) {
$this->freq = $freq;
} else {
throw new \InvalidArgumentException("The Frequency {$freq} is not supported.");
}
return $this;
} | [
"public",
"function",
"setFreq",
"(",
"$",
"freq",
")",
"{",
"if",
"(",
"@",
"constant",
"(",
"'static::FREQ_'",
".",
"$",
"freq",
")",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"freq",
"=",
"$",
"freq",
";",
"}",
"else",
"{",
"throw",
"new",
"... | The FREQ rule part identifies the type of recurrence rule. This
rule part MUST be specified in the recurrence rule. Valid values
include.
SECONDLY, to specify repeating events based on an interval of a second or more;
MINUTELY, to specify repeating events based on an interval of a minute or more;
HOURLY, to specify repeating events based on an interval of an hour or more;
DAILY, to specify repeating events based on an interval of a day or more;
WEEKLY, to specify repeating events based on an interval of a week or more;
MONTHLY, to specify repeating events based on an interval of a month or more;
YEARLY, to specify repeating events based on an interval of a year or more.
@param string $freq
@return $this
@throws \InvalidArgumentException | [
"The",
"FREQ",
"rule",
"part",
"identifies",
"the",
"type",
"of",
"recurrence",
"rule",
".",
"This",
"rule",
"part",
"MUST",
"be",
"specified",
"in",
"the",
"recurrence",
"rule",
".",
"Valid",
"values",
"include",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L248-L257 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setBySetPos | public function setBySetPos($value)
{
if (null === $value) {
$this->bySetPos = $value;
return $this;
}
if (!(is_string($value) || is_array($value) || is_int($value))) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$list = $value;
if (is_int($value)) {
if ($value === 0 || $value < -366 || $value > 366) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$this->bySetPos = [$value];
return $this;
}
if (is_string($value)) {
$list = explode(',', $value);
}
$output = [];
foreach ($list as $item) {
if (is_string($item)) {
if (!preg_match('/^ *-?[0-9]* *$/', $item)) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$item = intval($item);
}
if (!is_int($item) || $item === 0 || $item < -366 || $item > 366) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$output[] = $item;
}
$this->bySetPos = $output;
return $this;
} | php | public function setBySetPos($value)
{
if (null === $value) {
$this->bySetPos = $value;
return $this;
}
if (!(is_string($value) || is_array($value) || is_int($value))) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$list = $value;
if (is_int($value)) {
if ($value === 0 || $value < -366 || $value > 366) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$this->bySetPos = [$value];
return $this;
}
if (is_string($value)) {
$list = explode(',', $value);
}
$output = [];
foreach ($list as $item) {
if (is_string($item)) {
if (!preg_match('/^ *-?[0-9]* *$/', $item)) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$item = intval($item);
}
if (!is_int($item) || $item === 0 || $item < -366 || $item > 366) {
throw new InvalidArgumentException('Invalid value for BYSETPOS');
}
$output[] = $item;
}
$this->bySetPos = $output;
return $this;
} | [
"public",
"function",
"setBySetPos",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"bySetPos",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"!",
"(",
"is_string",
"(",
"$"... | The BYSETPOS filters one interval of events by the specified position.
A positive position will start from the beginning and go forward while
a negative position will start at the end and move backward.
Valid values are a comma separated string or an array of integers
from 1 to 366 or negative integers from -1 to -366.
@param int|string|array|null $value
@throws InvalidArgumentException
@return $this | [
"The",
"BYSETPOS",
"filters",
"one",
"interval",
"of",
"events",
"by",
"the",
"specified",
"position",
".",
"A",
"positive",
"position",
"will",
"start",
"from",
"the",
"beginning",
"and",
"go",
"forward",
"while",
"a",
"negative",
"position",
"will",
"start",... | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L319-L366 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setByMonth | public function setByMonth($month)
{
if (!is_integer($month) || $month <= 0 || $month > 12) {
throw new InvalidArgumentException('Invalid value for BYMONTH');
}
$this->byMonth = $month;
$this->canUseBySetPos = true;
return $this;
} | php | public function setByMonth($month)
{
if (!is_integer($month) || $month <= 0 || $month > 12) {
throw new InvalidArgumentException('Invalid value for BYMONTH');
}
$this->byMonth = $month;
$this->canUseBySetPos = true;
return $this;
} | [
"public",
"function",
"setByMonth",
"(",
"$",
"month",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"month",
")",
"||",
"$",
"month",
"<=",
"0",
"||",
"$",
"month",
">",
"12",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Invalid va... | The BYMONTH rule part specifies a COMMA-separated list of months of the year.
Valid values are 1 to 12.
@param int $month
@throws \InvalidArgumentException
@return $this | [
"The",
"BYMONTH",
"rule",
"part",
"specifies",
"a",
"COMMA",
"-",
"separated",
"list",
"of",
"months",
"of",
"the",
"year",
".",
"Valid",
"values",
"are",
"1",
"to",
"12",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L378-L389 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setByWeekNo | public function setByWeekNo($value)
{
if (!is_integer($value) || $value > 53 || $value < -53 || $value === 0) {
throw new InvalidArgumentException('Invalid value for BYWEEKNO');
}
$this->byWeekNo = $value;
$this->canUseBySetPos = true;
return $this;
} | php | public function setByWeekNo($value)
{
if (!is_integer($value) || $value > 53 || $value < -53 || $value === 0) {
throw new InvalidArgumentException('Invalid value for BYWEEKNO');
}
$this->byWeekNo = $value;
$this->canUseBySetPos = true;
return $this;
} | [
"public",
"function",
"setByWeekNo",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"value",
")",
"||",
"$",
"value",
">",
"53",
"||",
"$",
"value",
"<",
"-",
"53",
"||",
"$",
"value",
"===",
"0",
")",
"{",
"throw",
"new",
... | The BYWEEKNO rule part specifies a COMMA-separated list of ordinals specifying weeks of the year.
Valid values are 1 to 53 or -53 to -1.
@param int $value
@throws \InvalidArgumentException
@return $this | [
"The",
"BYWEEKNO",
"rule",
"part",
"specifies",
"a",
"COMMA",
"-",
"separated",
"list",
"of",
"ordinals",
"specifying",
"weeks",
"of",
"the",
"year",
".",
"Valid",
"values",
"are",
"1",
"to",
"53",
"or",
"-",
"53",
"to",
"-",
"1",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L401-L412 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setByYearDay | public function setByYearDay($day)
{
if (!is_integer($day) || $day > 366 || $day < -366 || $day === 0) {
throw new InvalidArgumentException('Invalid value for BYYEARDAY');
}
$this->byYearDay = $day;
$this->canUseBySetPos = true;
return $this;
} | php | public function setByYearDay($day)
{
if (!is_integer($day) || $day > 366 || $day < -366 || $day === 0) {
throw new InvalidArgumentException('Invalid value for BYYEARDAY');
}
$this->byYearDay = $day;
$this->canUseBySetPos = true;
return $this;
} | [
"public",
"function",
"setByYearDay",
"(",
"$",
"day",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"day",
")",
"||",
"$",
"day",
">",
"366",
"||",
"$",
"day",
"<",
"-",
"366",
"||",
"$",
"day",
"===",
"0",
")",
"{",
"throw",
"new",
"Inval... | The BYYEARDAY rule part specifies a COMMA-separated list of days of the year.
Valid values are 1 to 366 or -366 to -1.
@param int $day
@throws \InvalidArgumentException
@return $this | [
"The",
"BYYEARDAY",
"rule",
"part",
"specifies",
"a",
"COMMA",
"-",
"separated",
"list",
"of",
"days",
"of",
"the",
"year",
".",
"Valid",
"values",
"are",
"1",
"to",
"366",
"or",
"-",
"366",
"to",
"-",
"1",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L424-L435 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setByMonthDay | public function setByMonthDay($day)
{
if (!is_integer($day) || $day > 31 || $day < -31 || $day === 0) {
throw new InvalidArgumentException('Invalid value for BYMONTHDAY');
}
$this->byMonthDay = $day;
$this->canUseBySetPos = true;
return $this;
} | php | public function setByMonthDay($day)
{
if (!is_integer($day) || $day > 31 || $day < -31 || $day === 0) {
throw new InvalidArgumentException('Invalid value for BYMONTHDAY');
}
$this->byMonthDay = $day;
$this->canUseBySetPos = true;
return $this;
} | [
"public",
"function",
"setByMonthDay",
"(",
"$",
"day",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"day",
")",
"||",
"$",
"day",
">",
"31",
"||",
"$",
"day",
"<",
"-",
"31",
"||",
"$",
"day",
"===",
"0",
")",
"{",
"throw",
"new",
"Invali... | The BYMONTHDAY rule part specifies a COMMA-separated list of days of the month.
Valid values are 1 to 31 or -31 to -1.
@param int $day
@return $this
@throws \InvalidArgumentException | [
"The",
"BYMONTHDAY",
"rule",
"part",
"specifies",
"a",
"COMMA",
"-",
"separated",
"list",
"of",
"days",
"of",
"the",
"month",
".",
"Valid",
"values",
"are",
"1",
"to",
"31",
"or",
"-",
"31",
"to",
"-",
"1",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L447-L458 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setByDay | public function setByDay(string $day)
{
$this->byDay = $day;
$this->canUseBySetPos = true;
return $this;
} | php | public function setByDay(string $day)
{
$this->byDay = $day;
$this->canUseBySetPos = true;
return $this;
} | [
"public",
"function",
"setByDay",
"(",
"string",
"$",
"day",
")",
"{",
"$",
"this",
"->",
"byDay",
"=",
"$",
"day",
";",
"$",
"this",
"->",
"canUseBySetPos",
"=",
"true",
";",
"return",
"$",
"this",
";",
"}"
] | The BYDAY rule part specifies a COMMA-separated list of days of the week;.
SU indicates Sunday; MO indicates Monday; TU indicates Tuesday;
WE indicates Wednesday; TH indicates Thursday; FR indicates Friday; and SA indicates Saturday.
Each BYDAY value can also be preceded by a positive (+n) or negative (-n) integer.
If present, this indicates the nth occurrence of a specific day within the MONTHLY or YEARLY "RRULE".
@param string $day
@return $this | [
"The",
"BYDAY",
"rule",
"part",
"specifies",
"a",
"COMMA",
"-",
"separated",
"list",
"of",
"days",
"of",
"the",
"week",
";",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L473-L480 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setByHour | public function setByHour($value)
{
if (!is_integer($value) || $value < 0 || $value > 23) {
throw new \InvalidArgumentException('Invalid value for BYHOUR');
}
$this->byHour = $value;
$this->canUseBySetPos = true;
return $this;
} | php | public function setByHour($value)
{
if (!is_integer($value) || $value < 0 || $value > 23) {
throw new \InvalidArgumentException('Invalid value for BYHOUR');
}
$this->byHour = $value;
$this->canUseBySetPos = true;
return $this;
} | [
"public",
"function",
"setByHour",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"value",
")",
"||",
"$",
"value",
"<",
"0",
"||",
"$",
"value",
">",
"23",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Inva... | The BYHOUR rule part specifies a COMMA-separated list of hours of the day.
Valid values are 0 to 23.
@param int $value
@return $this
@throws \InvalidArgumentException | [
"The",
"BYHOUR",
"rule",
"part",
"specifies",
"a",
"COMMA",
"-",
"separated",
"list",
"of",
"hours",
"of",
"the",
"day",
".",
"Valid",
"values",
"are",
"0",
"to",
"23",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L492-L503 | train |
markuspoerschke/iCal | src/Property/Event/RecurrenceRule.php | RecurrenceRule.setByMinute | public function setByMinute($value)
{
if (!is_integer($value) || $value < 0 || $value > 59) {
throw new \InvalidArgumentException('Invalid value for BYMINUTE');
}
$this->byMinute = $value;
$this->canUseBySetPos = true;
return $this;
} | php | public function setByMinute($value)
{
if (!is_integer($value) || $value < 0 || $value > 59) {
throw new \InvalidArgumentException('Invalid value for BYMINUTE');
}
$this->byMinute = $value;
$this->canUseBySetPos = true;
return $this;
} | [
"public",
"function",
"setByMinute",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"value",
")",
"||",
"$",
"value",
"<",
"0",
"||",
"$",
"value",
">",
"59",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'In... | The BYMINUTE rule part specifies a COMMA-separated list of minutes within an hour.
Valid values are 0 to 59.
@param int $value
@return $this
@throws \InvalidArgumentException | [
"The",
"BYMINUTE",
"rule",
"part",
"specifies",
"a",
"COMMA",
"-",
"separated",
"list",
"of",
"minutes",
"within",
"an",
"hour",
".",
"Valid",
"values",
"are",
"0",
"to",
"59",
"."
] | 42155dc800a9bb5058fbad3ecf208401efb454dc | https://github.com/markuspoerschke/iCal/blob/42155dc800a9bb5058fbad3ecf208401efb454dc/src/Property/Event/RecurrenceRule.php#L515-L526 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.