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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
mosbth/cimage | CImage.php | CImage.reCalculateDimensions | public function reCalculateDimensions()
{
$this->log("Re-calculate image dimensions, newWidth x newHeigh was: " . $this->newWidth . " x " . $this->newHeight);
$this->newWidth = $this->newWidthOrig;
$this->newHeight = $this->newHeightOrig;
$this->crop = $this->cropOrig;
$this->initDimensions()
->calculateNewWidthAndHeight();
return $this;
} | php | public function reCalculateDimensions()
{
$this->log("Re-calculate image dimensions, newWidth x newHeigh was: " . $this->newWidth . " x " . $this->newHeight);
$this->newWidth = $this->newWidthOrig;
$this->newHeight = $this->newHeightOrig;
$this->crop = $this->cropOrig;
$this->initDimensions()
->calculateNewWidthAndHeight();
return $this;
} | [
"public",
"function",
"reCalculateDimensions",
"(",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Re-calculate image dimensions, newWidth x newHeigh was: \"",
".",
"$",
"this",
"->",
"newWidth",
".",
"\" x \"",
".",
"$",
"this",
"->",
"newHeight",
")",
";",
"$",
"... | Re-calculate image dimensions when original image dimension has changed.
@return $this | [
"Re",
"-",
"calculate",
"image",
"dimensions",
"when",
"original",
"image",
"dimension",
"has",
"changed",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1245-L1257 | train |
mosbth/cimage | CImage.php | CImage.setSaveAsExtension | public function setSaveAsExtension($saveAs = null)
{
if (isset($saveAs)) {
$saveAs = strtolower($saveAs);
$this->checkFileExtension($saveAs);
$this->saveAs = $saveAs;
$this->extension = $saveAs;
}
$this->log("Prepare to save image as: " . $this->extension);
return $this;
} | php | public function setSaveAsExtension($saveAs = null)
{
if (isset($saveAs)) {
$saveAs = strtolower($saveAs);
$this->checkFileExtension($saveAs);
$this->saveAs = $saveAs;
$this->extension = $saveAs;
}
$this->log("Prepare to save image as: " . $this->extension);
return $this;
} | [
"public",
"function",
"setSaveAsExtension",
"(",
"$",
"saveAs",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"saveAs",
")",
")",
"{",
"$",
"saveAs",
"=",
"strtolower",
"(",
"$",
"saveAs",
")",
";",
"$",
"this",
"->",
"checkFileExtension",
"(",
... | Set extension for filename to save as.
@param string $saveas extension to save image as
@return $this | [
"Set",
"extension",
"for",
"filename",
"to",
"save",
"as",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1268-L1280 | train |
mosbth/cimage | CImage.php | CImage.setJpegQuality | public function setJpegQuality($quality = null)
{
if ($quality) {
$this->useQuality = true;
}
$this->quality = isset($quality)
? $quality
: self::JPEG_QUALITY_DEFAULT;
(is_numeric($this->quality) and $this->quality > 0 and $this->quality <= 100)
or $this->raiseError('Quality not in range.');
$this->log("Setting JPEG quality to {$this->quality}.");
return $this;
} | php | public function setJpegQuality($quality = null)
{
if ($quality) {
$this->useQuality = true;
}
$this->quality = isset($quality)
? $quality
: self::JPEG_QUALITY_DEFAULT;
(is_numeric($this->quality) and $this->quality > 0 and $this->quality <= 100)
or $this->raiseError('Quality not in range.');
$this->log("Setting JPEG quality to {$this->quality}.");
return $this;
} | [
"public",
"function",
"setJpegQuality",
"(",
"$",
"quality",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"quality",
")",
"{",
"$",
"this",
"->",
"useQuality",
"=",
"true",
";",
"}",
"$",
"this",
"->",
"quality",
"=",
"isset",
"(",
"$",
"quality",
")",
"... | Set JPEG quality to use when saving image
@param int $quality as the quality to set.
@return $this | [
"Set",
"JPEG",
"quality",
"to",
"use",
"when",
"saving",
"image"
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1291-L1307 | train |
mosbth/cimage | CImage.php | CImage.setPngCompression | public function setPngCompression($compress = null)
{
if ($compress) {
$this->useCompress = true;
}
$this->compress = isset($compress)
? $compress
: self::PNG_COMPRESSION_DEFAULT;
(is_numeric($this->compress) and $this->compress >= -1 and $this->compress <= 9)
or $this->raiseError('Quality not in range.');
$this->log("Setting PNG compression level to {$this->compress}.");
return $this;
} | php | public function setPngCompression($compress = null)
{
if ($compress) {
$this->useCompress = true;
}
$this->compress = isset($compress)
? $compress
: self::PNG_COMPRESSION_DEFAULT;
(is_numeric($this->compress) and $this->compress >= -1 and $this->compress <= 9)
or $this->raiseError('Quality not in range.');
$this->log("Setting PNG compression level to {$this->compress}.");
return $this;
} | [
"public",
"function",
"setPngCompression",
"(",
"$",
"compress",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"compress",
")",
"{",
"$",
"this",
"->",
"useCompress",
"=",
"true",
";",
"}",
"$",
"this",
"->",
"compress",
"=",
"isset",
"(",
"$",
"compress",
... | Set PNG compressen algorithm to use when saving image
@param int $compress as the algorithm to use.
@return $this | [
"Set",
"PNG",
"compressen",
"algorithm",
"to",
"use",
"when",
"saving",
"image"
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1318-L1334 | train |
mosbth/cimage | CImage.php | CImage.useOriginalIfPossible | public function useOriginalIfPossible($useOrig = true)
{
if ($useOrig
&& ($this->newWidth == $this->width)
&& ($this->newHeight == $this->height)
&& !$this->area
&& !$this->crop
&& !$this->cropToFit
&& !$this->fillToFit
&& !$this->filters
&& !$this->sharpen
&& !$this->emboss
&& !$this->blur
&& !$this->convolve
&& !$this->palette
&& !$this->useQuality
&& !$this->useCompress
&& !$this->saveAs
&& !$this->rotateBefore
&& !$this->rotateAfter
&& !$this->autoRotate
&& !$this->bgColor
&& ($this->upscale === self::UPSCALE_DEFAULT)
&& !$this->lossy
) {
$this->log("Using original image.");
$this->output($this->pathToImage);
}
return $this;
} | php | public function useOriginalIfPossible($useOrig = true)
{
if ($useOrig
&& ($this->newWidth == $this->width)
&& ($this->newHeight == $this->height)
&& !$this->area
&& !$this->crop
&& !$this->cropToFit
&& !$this->fillToFit
&& !$this->filters
&& !$this->sharpen
&& !$this->emboss
&& !$this->blur
&& !$this->convolve
&& !$this->palette
&& !$this->useQuality
&& !$this->useCompress
&& !$this->saveAs
&& !$this->rotateBefore
&& !$this->rotateAfter
&& !$this->autoRotate
&& !$this->bgColor
&& ($this->upscale === self::UPSCALE_DEFAULT)
&& !$this->lossy
) {
$this->log("Using original image.");
$this->output($this->pathToImage);
}
return $this;
} | [
"public",
"function",
"useOriginalIfPossible",
"(",
"$",
"useOrig",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"useOrig",
"&&",
"(",
"$",
"this",
"->",
"newWidth",
"==",
"$",
"this",
"->",
"width",
")",
"&&",
"(",
"$",
"this",
"->",
"newHeight",
"==",
"$... | Use original image if possible, check options which affects image processing.
@param boolean $useOrig default is to use original if possible, else set to false.
@return $this | [
"Use",
"original",
"image",
"if",
"possible",
"check",
"options",
"which",
"affects",
"image",
"processing",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1345-L1375 | train |
mosbth/cimage | CImage.php | CImage.useCacheIfPossible | public function useCacheIfPossible($useCache = true)
{
if ($useCache && is_readable($this->cacheFileName)) {
$fileTime = filemtime($this->pathToImage);
$cacheTime = filemtime($this->cacheFileName);
if ($fileTime <= $cacheTime) {
if ($this->useCache) {
if ($this->verbose) {
$this->log("Use cached file.");
$this->log("Cached image filesize: " . filesize($this->cacheFileName) . " bytes.");
}
$this->output($this->cacheFileName, $this->outputFormat);
} else {
$this->log("Cache is valid but ignoring it by intention.");
}
} else {
$this->log("Original file is modified, ignoring cache.");
}
} else {
$this->log("Cachefile does not exists or ignoring it.");
}
return $this;
} | php | public function useCacheIfPossible($useCache = true)
{
if ($useCache && is_readable($this->cacheFileName)) {
$fileTime = filemtime($this->pathToImage);
$cacheTime = filemtime($this->cacheFileName);
if ($fileTime <= $cacheTime) {
if ($this->useCache) {
if ($this->verbose) {
$this->log("Use cached file.");
$this->log("Cached image filesize: " . filesize($this->cacheFileName) . " bytes.");
}
$this->output($this->cacheFileName, $this->outputFormat);
} else {
$this->log("Cache is valid but ignoring it by intention.");
}
} else {
$this->log("Original file is modified, ignoring cache.");
}
} else {
$this->log("Cachefile does not exists or ignoring it.");
}
return $this;
} | [
"public",
"function",
"useCacheIfPossible",
"(",
"$",
"useCache",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"useCache",
"&&",
"is_readable",
"(",
"$",
"this",
"->",
"cacheFileName",
")",
")",
"{",
"$",
"fileTime",
"=",
"filemtime",
"(",
"$",
"this",
"->",
... | Use cached version of image, if possible.
@param boolean $useCache is default true, set to false to avoid using cached object.
@return $this | [
"Use",
"cached",
"version",
"of",
"image",
"if",
"possible",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1483-L1507 | train |
mosbth/cimage | CImage.php | CImage.load | public function load($src = null, $dir = null)
{
if (isset($src)) {
$this->setSource($src, $dir);
}
$this->loadImageDetails();
if ($this->fileType === IMG_WEBP) {
$this->image = imagecreatefromwebp($this->pathToImage);
} else {
$imageAsString = file_get_contents($this->pathToImage);
$this->image = imagecreatefromstring($imageAsString);
}
if ($this->image === false) {
throw new Exception("Could not load image.");
}
/* Removed v0.7.7
if (image_type_to_mime_type($this->fileType) == 'image/png') {
$type = $this->getPngType();
$hasFewColors = imagecolorstotal($this->image);
if ($type == self::PNG_RGB_PALETTE || ($hasFewColors > 0 && $hasFewColors <= 256)) {
if ($this->verbose) {
$this->log("Handle this image as a palette image.");
}
$this->palette = true;
}
}
*/
if ($this->verbose) {
$this->log("### Image successfully loaded from file.");
$this->log(" imageistruecolor() : " . (imageistruecolor($this->image) ? 'true' : 'false'));
$this->log(" imagecolorstotal() : " . imagecolorstotal($this->image));
$this->log(" Number of colors in image = " . $this->colorsTotal($this->image));
$index = imagecolortransparent($this->image);
$this->log(" Detected transparent color = " . ($index >= 0 ? implode(", ", imagecolorsforindex($this->image, $index)) : "NONE") . " at index = $index");
}
return $this;
} | php | public function load($src = null, $dir = null)
{
if (isset($src)) {
$this->setSource($src, $dir);
}
$this->loadImageDetails();
if ($this->fileType === IMG_WEBP) {
$this->image = imagecreatefromwebp($this->pathToImage);
} else {
$imageAsString = file_get_contents($this->pathToImage);
$this->image = imagecreatefromstring($imageAsString);
}
if ($this->image === false) {
throw new Exception("Could not load image.");
}
/* Removed v0.7.7
if (image_type_to_mime_type($this->fileType) == 'image/png') {
$type = $this->getPngType();
$hasFewColors = imagecolorstotal($this->image);
if ($type == self::PNG_RGB_PALETTE || ($hasFewColors > 0 && $hasFewColors <= 256)) {
if ($this->verbose) {
$this->log("Handle this image as a palette image.");
}
$this->palette = true;
}
}
*/
if ($this->verbose) {
$this->log("### Image successfully loaded from file.");
$this->log(" imageistruecolor() : " . (imageistruecolor($this->image) ? 'true' : 'false'));
$this->log(" imagecolorstotal() : " . imagecolorstotal($this->image));
$this->log(" Number of colors in image = " . $this->colorsTotal($this->image));
$index = imagecolortransparent($this->image);
$this->log(" Detected transparent color = " . ($index >= 0 ? implode(", ", imagecolorsforindex($this->image, $index)) : "NONE") . " at index = $index");
}
return $this;
} | [
"public",
"function",
"load",
"(",
"$",
"src",
"=",
"null",
",",
"$",
"dir",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"src",
")",
")",
"{",
"$",
"this",
"->",
"setSource",
"(",
"$",
"src",
",",
"$",
"dir",
")",
";",
"}",
"$",
"t... | Load image from disk. Try to load image without verbose error message,
if fail, load again and display error messages.
@param string $src of image.
@param string $dir as base directory where images are.
@return $this | [
"Load",
"image",
"from",
"disk",
".",
"Try",
"to",
"load",
"image",
"without",
"verbose",
"error",
"message",
"if",
"fail",
"load",
"again",
"and",
"display",
"error",
"messages",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1521-L1563 | train |
mosbth/cimage | CImage.php | CImage.getPngType | public function getPngType($filename = null)
{
$filename = $filename ? $filename : $this->pathToImage;
$pngType = ord(file_get_contents($filename, false, null, 25, 1));
if ($this->verbose) {
$this->log("Checking png type of: " . $filename);
$this->log($this->getPngTypeAsString($pngType));
}
return $pngType;
} | php | public function getPngType($filename = null)
{
$filename = $filename ? $filename : $this->pathToImage;
$pngType = ord(file_get_contents($filename, false, null, 25, 1));
if ($this->verbose) {
$this->log("Checking png type of: " . $filename);
$this->log($this->getPngTypeAsString($pngType));
}
return $pngType;
} | [
"public",
"function",
"getPngType",
"(",
"$",
"filename",
"=",
"null",
")",
"{",
"$",
"filename",
"=",
"$",
"filename",
"?",
"$",
"filename",
":",
"$",
"this",
"->",
"pathToImage",
";",
"$",
"pngType",
"=",
"ord",
"(",
"file_get_contents",
"(",
"$",
"f... | Get the type of PNG image.
@param string $filename to use instead of default.
@return int as the type of the png-image | [
"Get",
"the",
"type",
"of",
"PNG",
"image",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1575-L1587 | train |
mosbth/cimage | CImage.php | CImage.getPngTypeAsString | private function getPngTypeAsString($pngType = null, $filename = null)
{
if ($filename || !$pngType) {
$pngType = $this->getPngType($filename);
}
$index = imagecolortransparent($this->image);
$transparent = null;
if ($index != -1) {
$transparent = " (transparent)";
}
switch ($pngType) {
case self::PNG_GREYSCALE:
$text = "PNG is type 0, Greyscale$transparent";
break;
case self::PNG_RGB:
$text = "PNG is type 2, RGB$transparent";
break;
case self::PNG_RGB_PALETTE:
$text = "PNG is type 3, RGB with palette$transparent";
break;
case self::PNG_GREYSCALE_ALPHA:
$text = "PNG is type 4, Greyscale with alpha channel";
break;
case self::PNG_RGB_ALPHA:
$text = "PNG is type 6, RGB with alpha channel (PNG 32-bit)";
break;
default:
$text = "PNG is UNKNOWN type, is it really a PNG image?";
}
return $text;
} | php | private function getPngTypeAsString($pngType = null, $filename = null)
{
if ($filename || !$pngType) {
$pngType = $this->getPngType($filename);
}
$index = imagecolortransparent($this->image);
$transparent = null;
if ($index != -1) {
$transparent = " (transparent)";
}
switch ($pngType) {
case self::PNG_GREYSCALE:
$text = "PNG is type 0, Greyscale$transparent";
break;
case self::PNG_RGB:
$text = "PNG is type 2, RGB$transparent";
break;
case self::PNG_RGB_PALETTE:
$text = "PNG is type 3, RGB with palette$transparent";
break;
case self::PNG_GREYSCALE_ALPHA:
$text = "PNG is type 4, Greyscale with alpha channel";
break;
case self::PNG_RGB_ALPHA:
$text = "PNG is type 6, RGB with alpha channel (PNG 32-bit)";
break;
default:
$text = "PNG is UNKNOWN type, is it really a PNG image?";
}
return $text;
} | [
"private",
"function",
"getPngTypeAsString",
"(",
"$",
"pngType",
"=",
"null",
",",
"$",
"filename",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"filename",
"||",
"!",
"$",
"pngType",
")",
"{",
"$",
"pngType",
"=",
"$",
"this",
"->",
"getPngType",
"(",
"$... | Get the type of PNG image as a verbose string.
@param integer $type to use, default is to check the type.
@param string $filename to use instead of default.
@return int as the type of the png-image | [
"Get",
"the",
"type",
"of",
"PNG",
"image",
"as",
"a",
"verbose",
"string",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1600-L1639 | train |
mosbth/cimage | CImage.php | CImage.colorsTotal | private function colorsTotal($im)
{
if (imageistruecolor($im)) {
$this->log("Colors as true color.");
$h = imagesy($im);
$w = imagesx($im);
$c = array();
for ($x=0; $x < $w; $x++) {
for ($y=0; $y < $h; $y++) {
@$c['c'.imagecolorat($im, $x, $y)]++;
}
}
return count($c);
} else {
$this->log("Colors as palette.");
return imagecolorstotal($im);
}
} | php | private function colorsTotal($im)
{
if (imageistruecolor($im)) {
$this->log("Colors as true color.");
$h = imagesy($im);
$w = imagesx($im);
$c = array();
for ($x=0; $x < $w; $x++) {
for ($y=0; $y < $h; $y++) {
@$c['c'.imagecolorat($im, $x, $y)]++;
}
}
return count($c);
} else {
$this->log("Colors as palette.");
return imagecolorstotal($im);
}
} | [
"private",
"function",
"colorsTotal",
"(",
"$",
"im",
")",
"{",
"if",
"(",
"imageistruecolor",
"(",
"$",
"im",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Colors as true color.\"",
")",
";",
"$",
"h",
"=",
"imagesy",
"(",
"$",
"im",
")",
";",
... | Calculate number of colors in an image.
@param resource $im the image.
@return int | [
"Calculate",
"number",
"of",
"colors",
"in",
"an",
"image",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1651-L1668 | train |
mosbth/cimage | CImage.php | CImage.imageCopyResampled | public function imageCopyResampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
if($this->copyStrategy == self::RESIZE) {
$this->log("Copy by resize");
imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
} else {
$this->log("Copy by resample");
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
}
} | php | public function imageCopyResampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
if($this->copyStrategy == self::RESIZE) {
$this->log("Copy by resize");
imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
} else {
$this->log("Copy by resample");
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
}
} | [
"public",
"function",
"imageCopyResampled",
"(",
"$",
"dst_image",
",",
"$",
"src_image",
",",
"$",
"dst_x",
",",
"$",
"dst_y",
",",
"$",
"src_x",
",",
"$",
"src_y",
",",
"$",
"dst_w",
",",
"$",
"dst_h",
",",
"$",
"src_w",
",",
"$",
"src_h",
")",
"... | Resize and or crop the image.
@return void | [
"Resize",
"and",
"or",
"crop",
"the",
"image",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L1732-L1741 | train |
mosbth/cimage | CImage.php | CImage.rotate | public function rotate($angle, $bgColor)
{
$this->log("Rotate image " . $angle . " degrees with filler color.");
$color = $this->getBackgroundColor();
$this->image = imagerotate($this->image, $angle, $color);
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
$this->log("New image dimension width x height: " . $this->width . " x " . $this->height);
return $this;
} | php | public function rotate($angle, $bgColor)
{
$this->log("Rotate image " . $angle . " degrees with filler color.");
$color = $this->getBackgroundColor();
$this->image = imagerotate($this->image, $angle, $color);
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
$this->log("New image dimension width x height: " . $this->width . " x " . $this->height);
return $this;
} | [
"public",
"function",
"rotate",
"(",
"$",
"angle",
",",
"$",
"bgColor",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Rotate image \"",
".",
"$",
"angle",
".",
"\" degrees with filler color.\"",
")",
";",
"$",
"color",
"=",
"$",
"this",
"->",
"getBackgroundC... | Rotate image using angle.
@param float $angle to rotate image.
@param int $anglebgColor to fill image with if needed.
@return $this | [
"Rotate",
"image",
"using",
"angle",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2014-L2027 | train |
mosbth/cimage | CImage.php | CImage.rotateExif | public function rotateExif()
{
if (!in_array($this->fileType, array(IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM))) {
$this->log("Autorotate ignored, EXIF not supported by this filetype.");
return $this;
}
$exif = exif_read_data($this->pathToImage);
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$this->log("Autorotate 180.");
$this->rotate(180, $this->bgColor);
break;
case 6:
$this->log("Autorotate -90.");
$this->rotate(-90, $this->bgColor);
break;
case 8:
$this->log("Autorotate 90.");
$this->rotate(90, $this->bgColor);
break;
default:
$this->log("Autorotate ignored, unknown value as orientation.");
}
} else {
$this->log("Autorotate ignored, no orientation in EXIF.");
}
return $this;
} | php | public function rotateExif()
{
if (!in_array($this->fileType, array(IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM))) {
$this->log("Autorotate ignored, EXIF not supported by this filetype.");
return $this;
}
$exif = exif_read_data($this->pathToImage);
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$this->log("Autorotate 180.");
$this->rotate(180, $this->bgColor);
break;
case 6:
$this->log("Autorotate -90.");
$this->rotate(-90, $this->bgColor);
break;
case 8:
$this->log("Autorotate 90.");
$this->rotate(90, $this->bgColor);
break;
default:
$this->log("Autorotate ignored, unknown value as orientation.");
}
} else {
$this->log("Autorotate ignored, no orientation in EXIF.");
}
return $this;
} | [
"public",
"function",
"rotateExif",
"(",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"this",
"->",
"fileType",
",",
"array",
"(",
"IMAGETYPE_JPEG",
",",
"IMAGETYPE_TIFF_II",
",",
"IMAGETYPE_TIFF_MM",
")",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",... | Rotate image using information in EXIF.
@return $this | [
"Rotate",
"image",
"using",
"information",
"in",
"EXIF",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2036-L2070 | train |
mosbth/cimage | CImage.php | CImage.setDefaultBackgroundColor | public function setDefaultBackgroundColor($color)
{
$this->log("Setting default background color to '$color'.");
if (!(strlen($color) == 6 || strlen($color) == 8)) {
throw new Exception(
"Background color needs a hex value of 6 or 8
digits. 000000-FFFFFF or 00000000-FFFFFF7F.
Current value was: '$color'."
);
}
$red = hexdec(substr($color, 0, 2));
$green = hexdec(substr($color, 2, 2));
$blue = hexdec(substr($color, 4, 2));
$alpha = (strlen($color) == 8)
? hexdec(substr($color, 6, 2))
: null;
if (($red < 0 || $red > 255)
|| ($green < 0 || $green > 255)
|| ($blue < 0 || $blue > 255)
|| ($alpha < 0 || $alpha > 127)
) {
throw new Exception(
"Background color out of range. Red, green blue
should be 00-FF and alpha should be 00-7F.
Current value was: '$color'."
);
}
$this->bgColor = strtolower($color);
$this->bgColorDefault = array(
'red' => $red,
'green' => $green,
'blue' => $blue,
'alpha' => $alpha
);
return $this;
} | php | public function setDefaultBackgroundColor($color)
{
$this->log("Setting default background color to '$color'.");
if (!(strlen($color) == 6 || strlen($color) == 8)) {
throw new Exception(
"Background color needs a hex value of 6 or 8
digits. 000000-FFFFFF or 00000000-FFFFFF7F.
Current value was: '$color'."
);
}
$red = hexdec(substr($color, 0, 2));
$green = hexdec(substr($color, 2, 2));
$blue = hexdec(substr($color, 4, 2));
$alpha = (strlen($color) == 8)
? hexdec(substr($color, 6, 2))
: null;
if (($red < 0 || $red > 255)
|| ($green < 0 || $green > 255)
|| ($blue < 0 || $blue > 255)
|| ($alpha < 0 || $alpha > 127)
) {
throw new Exception(
"Background color out of range. Red, green blue
should be 00-FF and alpha should be 00-7F.
Current value was: '$color'."
);
}
$this->bgColor = strtolower($color);
$this->bgColorDefault = array(
'red' => $red,
'green' => $green,
'blue' => $blue,
'alpha' => $alpha
);
return $this;
} | [
"public",
"function",
"setDefaultBackgroundColor",
"(",
"$",
"color",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Setting default background color to '$color'.\"",
")",
";",
"if",
"(",
"!",
"(",
"strlen",
"(",
"$",
"color",
")",
"==",
"6",
"||",
"strlen",
"(... | Set default background color between 000000-FFFFFF or if using
alpha 00000000-FFFFFF7F.
@param string $color as hex value.
@return $this | [
"Set",
"default",
"background",
"color",
"between",
"000000",
"-",
"FFFFFF",
"or",
"if",
"using",
"alpha",
"00000000",
"-",
"FFFFFF7F",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2235-L2276 | train |
mosbth/cimage | CImage.php | CImage.getBackgroundColor | private function getBackgroundColor($img = null)
{
$img = isset($img) ? $img : $this->image;
if ($this->bgColorDefault) {
$red = $this->bgColorDefault['red'];
$green = $this->bgColorDefault['green'];
$blue = $this->bgColorDefault['blue'];
$alpha = $this->bgColorDefault['alpha'];
if ($alpha) {
$color = imagecolorallocatealpha($img, $red, $green, $blue, $alpha);
} else {
$color = imagecolorallocate($img, $red, $green, $blue);
}
return $color;
} else {
return 0;
}
} | php | private function getBackgroundColor($img = null)
{
$img = isset($img) ? $img : $this->image;
if ($this->bgColorDefault) {
$red = $this->bgColorDefault['red'];
$green = $this->bgColorDefault['green'];
$blue = $this->bgColorDefault['blue'];
$alpha = $this->bgColorDefault['alpha'];
if ($alpha) {
$color = imagecolorallocatealpha($img, $red, $green, $blue, $alpha);
} else {
$color = imagecolorallocate($img, $red, $green, $blue);
}
return $color;
} else {
return 0;
}
} | [
"private",
"function",
"getBackgroundColor",
"(",
"$",
"img",
"=",
"null",
")",
"{",
"$",
"img",
"=",
"isset",
"(",
"$",
"img",
")",
"?",
"$",
"img",
":",
"$",
"this",
"->",
"image",
";",
"if",
"(",
"$",
"this",
"->",
"bgColorDefault",
")",
"{",
... | Get the background color.
@param resource $img the image to work with or null if using $this->image.
@return color value or null if no background color is set. | [
"Get",
"the",
"background",
"color",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2287-L2309 | train |
mosbth/cimage | CImage.php | CImage.createImageKeepTransparency | private function createImageKeepTransparency($width, $height)
{
$this->log("Creating a new working image width={$width}px, height={$height}px.");
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagesavealpha($img, true);
$index = $this->image
? imagecolortransparent($this->image)
: -1;
if ($index != -1) {
imagealphablending($img, true);
$transparent = imagecolorsforindex($this->image, $index);
$color = imagecolorallocatealpha($img, $transparent['red'], $transparent['green'], $transparent['blue'], $transparent['alpha']);
imagefill($img, 0, 0, $color);
$index = imagecolortransparent($img, $color);
$this->Log("Detected transparent color = " . implode(", ", $transparent) . " at index = $index");
} elseif ($this->bgColorDefault) {
$color = $this->getBackgroundColor($img);
imagefill($img, 0, 0, $color);
$this->Log("Filling image with background color.");
}
return $img;
} | php | private function createImageKeepTransparency($width, $height)
{
$this->log("Creating a new working image width={$width}px, height={$height}px.");
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagesavealpha($img, true);
$index = $this->image
? imagecolortransparent($this->image)
: -1;
if ($index != -1) {
imagealphablending($img, true);
$transparent = imagecolorsforindex($this->image, $index);
$color = imagecolorallocatealpha($img, $transparent['red'], $transparent['green'], $transparent['blue'], $transparent['alpha']);
imagefill($img, 0, 0, $color);
$index = imagecolortransparent($img, $color);
$this->Log("Detected transparent color = " . implode(", ", $transparent) . " at index = $index");
} elseif ($this->bgColorDefault) {
$color = $this->getBackgroundColor($img);
imagefill($img, 0, 0, $color);
$this->Log("Filling image with background color.");
}
return $img;
} | [
"private",
"function",
"createImageKeepTransparency",
"(",
"$",
"width",
",",
"$",
"height",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Creating a new working image width={$width}px, height={$height}px.\"",
")",
";",
"$",
"img",
"=",
"imagecreatetruecolor",
"(",
"$",... | Create a image and keep transparency for png and gifs.
@param int $width of the new image.
@param int $height of the new image.
@return image resource. | [
"Create",
"a",
"image",
"and",
"keep",
"transparency",
"for",
"png",
"and",
"gifs",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2321-L2349 | train |
mosbth/cimage | CImage.php | CImage.setPostProcessingOptions | public function setPostProcessingOptions($options)
{
if (isset($options['jpeg_optimize']) && $options['jpeg_optimize']) {
$this->jpegOptimizeCmd = $options['jpeg_optimize_cmd'];
} else {
$this->jpegOptimizeCmd = null;
}
if (array_key_exists("png_lossy", $options)
&& $options['png_lossy'] !== false) {
$this->pngLossy = $options['png_lossy'];
$this->pngLossyCmd = $options['png_lossy_cmd'];
} else {
$this->pngLossyCmd = null;
}
if (isset($options['png_filter']) && $options['png_filter']) {
$this->pngFilterCmd = $options['png_filter_cmd'];
} else {
$this->pngFilterCmd = null;
}
if (isset($options['png_deflate']) && $options['png_deflate']) {
$this->pngDeflateCmd = $options['png_deflate_cmd'];
} else {
$this->pngDeflateCmd = null;
}
return $this;
} | php | public function setPostProcessingOptions($options)
{
if (isset($options['jpeg_optimize']) && $options['jpeg_optimize']) {
$this->jpegOptimizeCmd = $options['jpeg_optimize_cmd'];
} else {
$this->jpegOptimizeCmd = null;
}
if (array_key_exists("png_lossy", $options)
&& $options['png_lossy'] !== false) {
$this->pngLossy = $options['png_lossy'];
$this->pngLossyCmd = $options['png_lossy_cmd'];
} else {
$this->pngLossyCmd = null;
}
if (isset($options['png_filter']) && $options['png_filter']) {
$this->pngFilterCmd = $options['png_filter_cmd'];
} else {
$this->pngFilterCmd = null;
}
if (isset($options['png_deflate']) && $options['png_deflate']) {
$this->pngDeflateCmd = $options['png_deflate_cmd'];
} else {
$this->pngDeflateCmd = null;
}
return $this;
} | [
"public",
"function",
"setPostProcessingOptions",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'jpeg_optimize'",
"]",
")",
"&&",
"$",
"options",
"[",
"'jpeg_optimize'",
"]",
")",
"{",
"$",
"this",
"->",
"jpegOptimizeCmd",
"... | Set optimizing and post-processing options.
@param array $options with config for postprocessing with external tools.
@return $this | [
"Set",
"optimizing",
"and",
"post",
"-",
"processing",
"options",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2360-L2389 | train |
mosbth/cimage | CImage.php | CImage.linkToCacheFile | public function linkToCacheFile($alias)
{
if ($alias === null) {
$this->log("Ignore creating alias.");
return $this;
}
if (is_readable($alias)) {
unlink($alias);
}
$res = link($this->cacheFileName, $alias);
if ($res) {
$this->log("Created an alias as: $alias");
} else {
$this->log("Failed to create the alias: $alias");
}
return $this;
} | php | public function linkToCacheFile($alias)
{
if ($alias === null) {
$this->log("Ignore creating alias.");
return $this;
}
if (is_readable($alias)) {
unlink($alias);
}
$res = link($this->cacheFileName, $alias);
if ($res) {
$this->log("Created an alias as: $alias");
} else {
$this->log("Failed to create the alias: $alias");
}
return $this;
} | [
"public",
"function",
"linkToCacheFile",
"(",
"$",
"alias",
")",
"{",
"if",
"(",
"$",
"alias",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"\"Ignore creating alias.\"",
")",
";",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"is_readable",
"(... | Create a hard link, as an alias, to the cached file.
@param string $alias where to store the link,
filename without extension.
@return $this | [
"Create",
"a",
"hard",
"link",
"as",
"an",
"alias",
"to",
"the",
"cached",
"file",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2615-L2635 | train |
mosbth/cimage | CImage.php | CImage.json | public function json($file = null)
{
$file = $file ? $file : $this->cacheFileName;
$details = array();
clearstatcache();
$details['src'] = $this->imageSrc;
$lastModified = filemtime($this->pathToImage);
$details['srcGmdate'] = gmdate("D, d M Y H:i:s", $lastModified);
$details['cache'] = basename($this->cacheFileName);
$lastModified = filemtime($this->cacheFileName);
$details['cacheGmdate'] = gmdate("D, d M Y H:i:s", $lastModified);
$this->load($file);
$details['filename'] = basename($file);
$details['mimeType'] = $this->getMimeType($this->fileType);
$details['width'] = $this->width;
$details['height'] = $this->height;
$details['aspectRatio'] = round($this->width / $this->height, 3);
$details['size'] = filesize($file);
$details['colors'] = $this->colorsTotal($this->image);
$details['includedFiles'] = count(get_included_files());
$details['memoryPeek'] = round(memory_get_peak_usage()/1024/1024, 3) . " MB" ;
$details['memoryCurrent'] = round(memory_get_usage()/1024/1024, 3) . " MB";
$details['memoryLimit'] = ini_get('memory_limit');
if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
$details['loadTime'] = (string) round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']), 3) . "s";
}
if ($details['mimeType'] == 'image/png') {
$details['pngType'] = $this->getPngTypeAsString(null, $file);
}
$options = null;
if (defined("JSON_PRETTY_PRINT") && defined("JSON_UNESCAPED_SLASHES")) {
$options = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES;
}
return json_encode($details, $options);
} | php | public function json($file = null)
{
$file = $file ? $file : $this->cacheFileName;
$details = array();
clearstatcache();
$details['src'] = $this->imageSrc;
$lastModified = filemtime($this->pathToImage);
$details['srcGmdate'] = gmdate("D, d M Y H:i:s", $lastModified);
$details['cache'] = basename($this->cacheFileName);
$lastModified = filemtime($this->cacheFileName);
$details['cacheGmdate'] = gmdate("D, d M Y H:i:s", $lastModified);
$this->load($file);
$details['filename'] = basename($file);
$details['mimeType'] = $this->getMimeType($this->fileType);
$details['width'] = $this->width;
$details['height'] = $this->height;
$details['aspectRatio'] = round($this->width / $this->height, 3);
$details['size'] = filesize($file);
$details['colors'] = $this->colorsTotal($this->image);
$details['includedFiles'] = count(get_included_files());
$details['memoryPeek'] = round(memory_get_peak_usage()/1024/1024, 3) . " MB" ;
$details['memoryCurrent'] = round(memory_get_usage()/1024/1024, 3) . " MB";
$details['memoryLimit'] = ini_get('memory_limit');
if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
$details['loadTime'] = (string) round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']), 3) . "s";
}
if ($details['mimeType'] == 'image/png') {
$details['pngType'] = $this->getPngTypeAsString(null, $file);
}
$options = null;
if (defined("JSON_PRETTY_PRINT") && defined("JSON_UNESCAPED_SLASHES")) {
$options = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES;
}
return json_encode($details, $options);
} | [
"public",
"function",
"json",
"(",
"$",
"file",
"=",
"null",
")",
"{",
"$",
"file",
"=",
"$",
"file",
"?",
"$",
"file",
":",
"$",
"this",
"->",
"cacheFileName",
";",
"$",
"details",
"=",
"array",
"(",
")",
";",
"clearstatcache",
"(",
")",
";",
"$... | Create a JSON object from the image details.
@param string $file the file to output.
@return string json-encoded representation of the image. | [
"Create",
"a",
"JSON",
"object",
"from",
"the",
"image",
"details",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2767-L2811 | train |
mosbth/cimage | CImage.php | CImage.ascii | public function ascii($file = null)
{
$file = $file ? $file : $this->cacheFileName;
$asciiArt = new CAsciiArt();
$asciiArt->setOptions($this->asciiOptions);
return $asciiArt->createFromFile($file);
} | php | public function ascii($file = null)
{
$file = $file ? $file : $this->cacheFileName;
$asciiArt = new CAsciiArt();
$asciiArt->setOptions($this->asciiOptions);
return $asciiArt->createFromFile($file);
} | [
"public",
"function",
"ascii",
"(",
"$",
"file",
"=",
"null",
")",
"{",
"$",
"file",
"=",
"$",
"file",
"?",
"$",
"file",
":",
"$",
"this",
"->",
"cacheFileName",
";",
"$",
"asciiArt",
"=",
"new",
"CAsciiArt",
"(",
")",
";",
"$",
"asciiArt",
"->",
... | Create an ASCII version from the image details.
@param string $file the file to output.
@return string ASCII representation of the image. | [
"Create",
"an",
"ASCII",
"version",
"from",
"the",
"image",
"details",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2836-L2843 | train |
mosbth/cimage | CImage.php | CImage.verboseOutput | private function verboseOutput()
{
$log = null;
$this->log("### Summary of verbose log");
$this->log("As JSON: \n" . $this->json());
$this->log("Memory peak: " . round(memory_get_peak_usage() /1024/1024) . "M");
$this->log("Memory limit: " . ini_get('memory_limit'));
$included = get_included_files();
$this->log("Included files: " . count($included));
foreach ($this->log as $val) {
if (is_array($val)) {
foreach ($val as $val1) {
$log .= htmlentities($val1) . '<br/>';
}
} else {
$log .= htmlentities($val) . '<br/>';
}
}
if (!is_null($this->verboseFileName)) {
file_put_contents(
$this->verboseFileName,
str_replace("<br/>", "\n", $log)
);
} else {
echo <<<EOD
<h1>CImage Verbose Output</h1>
<pre>{$log}</pre>
EOD;
}
} | php | private function verboseOutput()
{
$log = null;
$this->log("### Summary of verbose log");
$this->log("As JSON: \n" . $this->json());
$this->log("Memory peak: " . round(memory_get_peak_usage() /1024/1024) . "M");
$this->log("Memory limit: " . ini_get('memory_limit'));
$included = get_included_files();
$this->log("Included files: " . count($included));
foreach ($this->log as $val) {
if (is_array($val)) {
foreach ($val as $val1) {
$log .= htmlentities($val1) . '<br/>';
}
} else {
$log .= htmlentities($val) . '<br/>';
}
}
if (!is_null($this->verboseFileName)) {
file_put_contents(
$this->verboseFileName,
str_replace("<br/>", "\n", $log)
);
} else {
echo <<<EOD
<h1>CImage Verbose Output</h1>
<pre>{$log}</pre>
EOD;
}
} | [
"private",
"function",
"verboseOutput",
"(",
")",
"{",
"$",
"log",
"=",
"null",
";",
"$",
"this",
"->",
"log",
"(",
"\"### Summary of verbose log\"",
")",
";",
"$",
"this",
"->",
"log",
"(",
"\"As JSON: \\n\"",
".",
"$",
"this",
"->",
"json",
"(",
")",
... | Do verbose output and print out the log and the actual images.
@return void | [
"Do",
"verbose",
"output",
"and",
"print",
"out",
"the",
"log",
"and",
"the",
"actual",
"images",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CImage.php#L2885-L2917 | train |
mosbth/cimage | CRemoteImage.php | CRemoteImage.setHeaderFields | public function setHeaderFields()
{
$cimageVersion = "CImage";
if (defined("CIMAGE_USER_AGENT")) {
$cimageVersion = CIMAGE_USER_AGENT;
}
$this->http->setHeader("User-Agent", "$cimageVersion (PHP/". phpversion() . " cURL)");
$this->http->setHeader("Accept", "image/jpeg,image/png,image/gif");
if ($this->useCache) {
$this->http->setHeader("Cache-Control", "max-age=0");
} else {
$this->http->setHeader("Cache-Control", "no-cache");
$this->http->setHeader("Pragma", "no-cache");
}
} | php | public function setHeaderFields()
{
$cimageVersion = "CImage";
if (defined("CIMAGE_USER_AGENT")) {
$cimageVersion = CIMAGE_USER_AGENT;
}
$this->http->setHeader("User-Agent", "$cimageVersion (PHP/". phpversion() . " cURL)");
$this->http->setHeader("Accept", "image/jpeg,image/png,image/gif");
if ($this->useCache) {
$this->http->setHeader("Cache-Control", "max-age=0");
} else {
$this->http->setHeader("Cache-Control", "no-cache");
$this->http->setHeader("Pragma", "no-cache");
}
} | [
"public",
"function",
"setHeaderFields",
"(",
")",
"{",
"$",
"cimageVersion",
"=",
"\"CImage\"",
";",
"if",
"(",
"defined",
"(",
"\"CIMAGE_USER_AGENT\"",
")",
")",
"{",
"$",
"cimageVersion",
"=",
"CIMAGE_USER_AGENT",
";",
"}",
"$",
"this",
"->",
"http",
"->"... | Set header fields.
@return $this | [
"Set",
"header",
"fields",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CRemoteImage.php#L148-L164 | train |
mosbth/cimage | CRemoteImage.php | CRemoteImage.save | public function save()
{
$this->cache = array();
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$type = $this->http->getContentType();
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
$this->cache['Content-Type'] = $type;
$this->cache['Url'] = $this->url;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
// Save only if body is a valid image
$body = $this->http->getBody();
$img = imagecreatefromstring($body);
if ($img !== false) {
file_put_contents($this->fileName, $body);
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileName;
}
return false;
} | php | public function save()
{
$this->cache = array();
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$type = $this->http->getContentType();
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
$this->cache['Content-Type'] = $type;
$this->cache['Url'] = $this->url;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
// Save only if body is a valid image
$body = $this->http->getBody();
$img = imagecreatefromstring($body);
if ($img !== false) {
file_put_contents($this->fileName, $body);
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileName;
}
return false;
} | [
"public",
"function",
"save",
"(",
")",
"{",
"$",
"this",
"->",
"cache",
"=",
"array",
"(",
")",
";",
"$",
"date",
"=",
"$",
"this",
"->",
"http",
"->",
"getDate",
"(",
"time",
"(",
")",
")",
";",
"$",
"maxAge",
"=",
"$",
"this",
"->",
"http",
... | Save downloaded resource to cache.
@return string as path to saved file or false if not saved. | [
"Save",
"downloaded",
"resource",
"to",
"cache",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CRemoteImage.php#L173-L201 | train |
mosbth/cimage | CRemoteImage.php | CRemoteImage.updateCacheDetails | public function updateCacheDetails()
{
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileName;
} | php | public function updateCacheDetails()
{
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileName;
} | [
"public",
"function",
"updateCacheDetails",
"(",
")",
"{",
"$",
"date",
"=",
"$",
"this",
"->",
"http",
"->",
"getDate",
"(",
"time",
"(",
")",
")",
";",
"$",
"maxAge",
"=",
"$",
"this",
"->",
"http",
"->",
"getMaxAge",
"(",
"$",
"this",
"->",
"def... | Got a 304 and updates cache with new age.
@return string as path to cached file. | [
"Got",
"a",
"304",
"and",
"updates",
"cache",
"with",
"new",
"age",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CRemoteImage.php#L210-L225 | train |
mosbth/cimage | CRemoteImage.php | CRemoteImage.loadCacheDetails | public function loadCacheDetails()
{
$cacheFile = md5($this->url);
$this->fileName = $this->saveFolder . $cacheFile;
$this->fileJson = $this->fileName . ".json";
if (is_readable($this->fileJson)) {
$this->cache = json_decode(file_get_contents($this->fileJson), true);
}
} | php | public function loadCacheDetails()
{
$cacheFile = md5($this->url);
$this->fileName = $this->saveFolder . $cacheFile;
$this->fileJson = $this->fileName . ".json";
if (is_readable($this->fileJson)) {
$this->cache = json_decode(file_get_contents($this->fileJson), true);
}
} | [
"public",
"function",
"loadCacheDetails",
"(",
")",
"{",
"$",
"cacheFile",
"=",
"md5",
"(",
"$",
"this",
"->",
"url",
")",
";",
"$",
"this",
"->",
"fileName",
"=",
"$",
"this",
"->",
"saveFolder",
".",
"$",
"cacheFile",
";",
"$",
"this",
"->",
"fileJ... | Get the path to the cached image file if the cache is valid.
@return $this | [
"Get",
"the",
"path",
"to",
"the",
"cached",
"image",
"file",
"if",
"the",
"cache",
"is",
"valid",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CRemoteImage.php#L278-L286 | train |
mosbth/cimage | CWhitelist.php | CWhitelist.check | public function check($item, $whitelist = null)
{
if ($whitelist !== null) {
$this->set($whitelist);
}
if (empty($item) or empty($this->whitelist)) {
return false;
}
foreach ($this->whitelist as $regexp) {
if (preg_match("#$regexp#", $item)) {
return true;
}
}
return false;
} | php | public function check($item, $whitelist = null)
{
if ($whitelist !== null) {
$this->set($whitelist);
}
if (empty($item) or empty($this->whitelist)) {
return false;
}
foreach ($this->whitelist as $regexp) {
if (preg_match("#$regexp#", $item)) {
return true;
}
}
return false;
} | [
"public",
"function",
"check",
"(",
"$",
"item",
",",
"$",
"whitelist",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"whitelist",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"set",
"(",
"$",
"whitelist",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"... | Check if item exists in the whitelist.
@param string $item string to check.
@param array $whitelist optional with all valid options, default is null.
@return boolean true if item is in whitelist, else false. | [
"Check",
"if",
"item",
"exists",
"in",
"the",
"whitelist",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CWhitelist.php#L44-L61 | train |
mosbth/cimage | CFastTrackCache.php | CFastTrackCache.setFilename | public function setFilename($clear)
{
$query = $_GET;
// Remove parts from querystring that should not be part of filename
foreach ($clear as $value) {
unset($query[$value]);
}
arsort($query);
$queryAsString = http_build_query($query);
$this->filename = md5($queryAsString);
if (CIMAGE_DEBUG) {
$this->container["query-string"] = $queryAsString;
}
return $this->filename;
} | php | public function setFilename($clear)
{
$query = $_GET;
// Remove parts from querystring that should not be part of filename
foreach ($clear as $value) {
unset($query[$value]);
}
arsort($query);
$queryAsString = http_build_query($query);
$this->filename = md5($queryAsString);
if (CIMAGE_DEBUG) {
$this->container["query-string"] = $queryAsString;
}
return $this->filename;
} | [
"public",
"function",
"setFilename",
"(",
"$",
"clear",
")",
"{",
"$",
"query",
"=",
"$",
"_GET",
";",
"// Remove parts from querystring that should not be part of filename",
"foreach",
"(",
"$",
"clear",
"as",
"$",
"value",
")",
"{",
"unset",
"(",
"$",
"query",... | Set the filename to store in cache, use the querystring to create that
filename.
@param array $clear items to clear in $_GET when creating the filename.
@return string as filename created. | [
"Set",
"the",
"filename",
"to",
"store",
"in",
"cache",
"use",
"the",
"querystring",
"to",
"create",
"that",
"filename",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CFastTrackCache.php#L81-L100 | train |
mosbth/cimage | CHttpGet.php | CHttpGet.parseHeader | public function parseHeader()
{
//$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
$rawHeaders = rtrim($this->response['headerRaw'], "\r\n");
# Handle multiple responses e.g. with redirections (proxies too)
$headerGroups = explode("\r\n\r\n", $rawHeaders);
# We're only interested in the last one
$header = explode("\r\n", end($headerGroups));
$output = array();
if ('HTTP' === substr($header[0], 0, 4)) {
list($output['version'], $output['status']) = explode(' ', $header[0]);
unset($header[0]);
}
foreach ($header as $entry) {
$pos = strpos($entry, ':');
$output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1));
}
$this->response['header'] = $output;
return $this;
} | php | public function parseHeader()
{
//$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
$rawHeaders = rtrim($this->response['headerRaw'], "\r\n");
# Handle multiple responses e.g. with redirections (proxies too)
$headerGroups = explode("\r\n\r\n", $rawHeaders);
# We're only interested in the last one
$header = explode("\r\n", end($headerGroups));
$output = array();
if ('HTTP' === substr($header[0], 0, 4)) {
list($output['version'], $output['status']) = explode(' ', $header[0]);
unset($header[0]);
}
foreach ($header as $entry) {
$pos = strpos($entry, ':');
$output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1));
}
$this->response['header'] = $output;
return $this;
} | [
"public",
"function",
"parseHeader",
"(",
")",
"{",
"//$header = explode(\"\\r\\n\", rtrim($this->response['headerRaw'], \"\\r\\n\"));",
"$",
"rawHeaders",
"=",
"rtrim",
"(",
"$",
"this",
"->",
"response",
"[",
"'headerRaw'",
"]",
",",
"\"\\r\\n\"",
")",
";",
"# Handle ... | Set header fields for the request.
@param string $field
@param string $value
@return $this | [
"Set",
"header",
"fields",
"for",
"the",
"request",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CHttpGet.php#L102-L126 | train |
mosbth/cimage | CHttpGet.php | CHttpGet.getMaxAge | public function getMaxAge($default = false)
{
$cacheControl = isset($this->response['header']['Cache-Control'])
? $this->response['header']['Cache-Control']
: null;
$maxAge = null;
if ($cacheControl) {
// max-age=2592000
$part = explode('=', $cacheControl);
$maxAge = ($part[0] == "max-age")
? (int) $part[1]
: null;
}
if ($maxAge) {
return $maxAge;
}
$expire = isset($this->response['header']['Expires'])
? strtotime($this->response['header']['Expires'])
: null;
return $expire ? $expire : $default;
} | php | public function getMaxAge($default = false)
{
$cacheControl = isset($this->response['header']['Cache-Control'])
? $this->response['header']['Cache-Control']
: null;
$maxAge = null;
if ($cacheControl) {
// max-age=2592000
$part = explode('=', $cacheControl);
$maxAge = ($part[0] == "max-age")
? (int) $part[1]
: null;
}
if ($maxAge) {
return $maxAge;
}
$expire = isset($this->response['header']['Expires'])
? strtotime($this->response['header']['Expires'])
: null;
return $expire ? $expire : $default;
} | [
"public",
"function",
"getMaxAge",
"(",
"$",
"default",
"=",
"false",
")",
"{",
"$",
"cacheControl",
"=",
"isset",
"(",
"$",
"this",
"->",
"response",
"[",
"'header'",
"]",
"[",
"'Cache-Control'",
"]",
")",
"?",
"$",
"this",
"->",
"response",
"[",
"'he... | Get max age of cachable item.
@param mixed $default as default value if date is missing in response
header.
@return int as timestamp or false if not available. | [
"Get",
"max",
"age",
"of",
"cachable",
"item",
"."
] | 8fec09b195e79cbb8ad2ed3f997dd106132922a3 | https://github.com/mosbth/cimage/blob/8fec09b195e79cbb8ad2ed3f997dd106132922a3/CHttpGet.php#L253-L277 | train |
yajra/pdo-via-oci8 | src/Pdo/Oci8.php | Oci8.checkSequence | public function checkSequence($name)
{
try {
$stmt = $this->query(
"SELECT count(*) FROM ALL_SEQUENCES WHERE SEQUENCE_NAME=UPPER('{$name}') AND SEQUENCE_OWNER=UPPER(USER)",
PDO::FETCH_COLUMN
);
return $stmt->fetch();
} catch (\Exception $e) {
return false;
}
} | php | public function checkSequence($name)
{
try {
$stmt = $this->query(
"SELECT count(*) FROM ALL_SEQUENCES WHERE SEQUENCE_NAME=UPPER('{$name}') AND SEQUENCE_OWNER=UPPER(USER)",
PDO::FETCH_COLUMN
);
return $stmt->fetch();
} catch (\Exception $e) {
return false;
}
} | [
"public",
"function",
"checkSequence",
"(",
"$",
"name",
")",
"{",
"try",
"{",
"$",
"stmt",
"=",
"$",
"this",
"->",
"query",
"(",
"\"SELECT count(*) FROM ALL_SEQUENCES WHERE SEQUENCE_NAME=UPPER('{$name}') AND SEQUENCE_OWNER=UPPER(USER)\"",
",",
"PDO",
"::",
"FETCH_COLUMN"... | Special non PDO function to check if sequence exists.
@param string $name
@return bool | [
"Special",
"non",
"PDO",
"function",
"to",
"check",
"if",
"sequence",
"exists",
"."
] | 35ca9a2dbbaed0432f91f1b15507cadab614ed02 | https://github.com/yajra/pdo-via-oci8/blob/35ca9a2dbbaed0432f91f1b15507cadab614ed02/src/Pdo/Oci8.php#L412-L424 | train |
yajra/pdo-via-oci8 | src/Pdo/Oci8.php | Oci8.isNamedParameterable | private function isNamedParameterable($statement)
{
return ! preg_match('/^alter+ +table/', strtolower(trim($statement)))
and ! preg_match('/^create+ +table/', strtolower(trim($statement)));
} | php | private function isNamedParameterable($statement)
{
return ! preg_match('/^alter+ +table/', strtolower(trim($statement)))
and ! preg_match('/^create+ +table/', strtolower(trim($statement)));
} | [
"private",
"function",
"isNamedParameterable",
"(",
"$",
"statement",
")",
"{",
"return",
"!",
"preg_match",
"(",
"'/^alter+ +table/'",
",",
"strtolower",
"(",
"trim",
"(",
"$",
"statement",
")",
")",
")",
"and",
"!",
"preg_match",
"(",
"'/^create+ +table/'",
... | Check if statement can use pseudo named parameter.
@param string $statement
@return bool | [
"Check",
"if",
"statement",
"can",
"use",
"pseudo",
"named",
"parameter",
"."
] | 35ca9a2dbbaed0432f91f1b15507cadab614ed02 | https://github.com/yajra/pdo-via-oci8/blob/35ca9a2dbbaed0432f91f1b15507cadab614ed02/src/Pdo/Oci8.php#L432-L436 | train |
yajra/pdo-via-oci8 | src/Pdo/Oci8.php | Oci8._getCharset | private function _getCharset($charset=null)
{
if (! $charset) {
return;
}
$expr = '/^(charset=)(\w+)$/';
$tokens = array_filter(
$charset, function ($token) use ($expr) {
return preg_match($expr, $token, $matches);
}
);
if (count($tokens) > 0) {
preg_match($expr, array_shift($tokens), $matches);
$_charset = $matches[2];
} else {
$_charset = null;
}
return $_charset;
} | php | private function _getCharset($charset=null)
{
if (! $charset) {
return;
}
$expr = '/^(charset=)(\w+)$/';
$tokens = array_filter(
$charset, function ($token) use ($expr) {
return preg_match($expr, $token, $matches);
}
);
if (count($tokens) > 0) {
preg_match($expr, array_shift($tokens), $matches);
$_charset = $matches[2];
} else {
$_charset = null;
}
return $_charset;
} | [
"private",
"function",
"_getCharset",
"(",
"$",
"charset",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"charset",
")",
"{",
"return",
";",
"}",
"$",
"expr",
"=",
"'/^(charset=)(\\w+)$/'",
";",
"$",
"tokens",
"=",
"array_filter",
"(",
"$",
"charset",
",... | Find the charset.
@param string $charset charset
@return charset | [
"Find",
"the",
"charset",
"."
] | 35ca9a2dbbaed0432f91f1b15507cadab614ed02 | https://github.com/yajra/pdo-via-oci8/blob/35ca9a2dbbaed0432f91f1b15507cadab614ed02/src/Pdo/Oci8.php#L471-L491 | train |
yajra/pdo-via-oci8 | src/Pdo/Oci8.php | Oci8.configureCharset | private function configureCharset(array $options)
{
$charset = 'AL32UTF8';
// Get the character set from the options.
if (array_key_exists('charset', $options)) {
$charset = $options['charset'];
}
// Convert UTF8 charset to AL32UTF8
$charset = strtolower($charset) == 'utf8' ? 'AL32UTF8' : $charset;
return $charset;
} | php | private function configureCharset(array $options)
{
$charset = 'AL32UTF8';
// Get the character set from the options.
if (array_key_exists('charset', $options)) {
$charset = $options['charset'];
}
// Convert UTF8 charset to AL32UTF8
$charset = strtolower($charset) == 'utf8' ? 'AL32UTF8' : $charset;
return $charset;
} | [
"private",
"function",
"configureCharset",
"(",
"array",
"$",
"options",
")",
"{",
"$",
"charset",
"=",
"'AL32UTF8'",
";",
"// Get the character set from the options.",
"if",
"(",
"array_key_exists",
"(",
"'charset'",
",",
"$",
"options",
")",
")",
"{",
"$",
"ch... | Configure proper charset.
@param array $options
@return string | [
"Configure",
"proper",
"charset",
"."
] | 35ca9a2dbbaed0432f91f1b15507cadab614ed02 | https://github.com/yajra/pdo-via-oci8/blob/35ca9a2dbbaed0432f91f1b15507cadab614ed02/src/Pdo/Oci8.php#L499-L510 | train |
yajra/pdo-via-oci8 | src/Pdo/Oci8/Statement.php | Statement.bindArray | public function bindArray($parameter, &$variable, $maxTableLength, $maxItemLength = -1, $type = SQLT_CHR)
{
$this->bindings[] = $variable;
return oci_bind_array_by_name($this->sth, $parameter, $variable, $maxTableLength, $maxItemLength, $type);
} | php | public function bindArray($parameter, &$variable, $maxTableLength, $maxItemLength = -1, $type = SQLT_CHR)
{
$this->bindings[] = $variable;
return oci_bind_array_by_name($this->sth, $parameter, $variable, $maxTableLength, $maxItemLength, $type);
} | [
"public",
"function",
"bindArray",
"(",
"$",
"parameter",
",",
"&",
"$",
"variable",
",",
"$",
"maxTableLength",
",",
"$",
"maxItemLength",
"=",
"-",
"1",
",",
"$",
"type",
"=",
"SQLT_CHR",
")",
"{",
"$",
"this",
"->",
"bindings",
"[",
"]",
"=",
"$",... | Special non-PDO function that binds an array parameter to the specified variable name.
@see http://php.net/manual/en/function.oci-bind-array-by-name.php
@param string $parameter The Oracle placeholder.
@param array $variable An array.
@param int $maxTableLength Sets the maximum length both for incoming and result arrays.
@param int $maxItemLength Sets maximum length for array items.
If not specified or equals to -1, oci_bind_array_by_name() will find
the longest element in the incoming array and will use it as the maximum length.
@param int $type Explicit data type for the parameter using the
@return bool TRUE on success or FALSE on failure. | [
"Special",
"non",
"-",
"PDO",
"function",
"that",
"binds",
"an",
"array",
"parameter",
"to",
"the",
"specified",
"variable",
"name",
"."
] | 35ca9a2dbbaed0432f91f1b15507cadab614ed02 | https://github.com/yajra/pdo-via-oci8/blob/35ca9a2dbbaed0432f91f1b15507cadab614ed02/src/Pdo/Oci8/Statement.php#L507-L512 | train |
yajra/pdo-via-oci8 | src/Pdo/Oci8/Statement.php | Statement.errorInfo | public function errorInfo()
{
$e = oci_error($this->sth);
if (is_array($e)) {
return [
'HY000',
$e['code'],
$e['message'],
];
}
return ['00000', null, null];
} | php | public function errorInfo()
{
$e = oci_error($this->sth);
if (is_array($e)) {
return [
'HY000',
$e['code'],
$e['message'],
];
}
return ['00000', null, null];
} | [
"public",
"function",
"errorInfo",
"(",
")",
"{",
"$",
"e",
"=",
"oci_error",
"(",
"$",
"this",
"->",
"sth",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"e",
")",
")",
"{",
"return",
"[",
"'HY000'",
",",
"$",
"e",
"[",
"'code'",
"]",
",",
"$",
... | Fetch extended error information associated with the last operation on
the resource handle.
@return array Array of error information about the last operation
performed | [
"Fetch",
"extended",
"error",
"information",
"associated",
"with",
"the",
"last",
"operation",
"on",
"the",
"resource",
"handle",
"."
] | 35ca9a2dbbaed0432f91f1b15507cadab614ed02 | https://github.com/yajra/pdo-via-oci8/blob/35ca9a2dbbaed0432f91f1b15507cadab614ed02/src/Pdo/Oci8/Statement.php#L653-L666 | train |
adesigns/calendar-bundle | Controller/CalendarController.php | CalendarController.loadCalendarAction | public function loadCalendarAction(Request $request)
{
$startDatetime = new \DateTime();
$startDatetime->setTimestamp($request->get('start'));
$endDatetime = new \DateTime();
$endDatetime->setTimestamp($request->get('end'));
$events = $this->container->get('event_dispatcher')->dispatch(CalendarEvent::CONFIGURE, new CalendarEvent($startDatetime, $endDatetime, $request))->getEvents();
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-Type', 'application/json');
$return_events = array();
foreach($events as $event) {
$return_events[] = $event->toArray();
}
$response->setContent(json_encode($return_events));
return $response;
} | php | public function loadCalendarAction(Request $request)
{
$startDatetime = new \DateTime();
$startDatetime->setTimestamp($request->get('start'));
$endDatetime = new \DateTime();
$endDatetime->setTimestamp($request->get('end'));
$events = $this->container->get('event_dispatcher')->dispatch(CalendarEvent::CONFIGURE, new CalendarEvent($startDatetime, $endDatetime, $request))->getEvents();
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-Type', 'application/json');
$return_events = array();
foreach($events as $event) {
$return_events[] = $event->toArray();
}
$response->setContent(json_encode($return_events));
return $response;
} | [
"public",
"function",
"loadCalendarAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"startDatetime",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"$",
"startDatetime",
"->",
"setTimestamp",
"(",
"$",
"request",
"->",
"get",
"(",
"'start'",
")",
")",... | Dispatch a CalendarEvent and return a JSON Response of any events returned.
@param Request $request
@return Response | [
"Dispatch",
"a",
"CalendarEvent",
"and",
"return",
"a",
"JSON",
"Response",
"of",
"any",
"events",
"returned",
"."
] | 056861b042f4c70c7d929c3ad62d891fe4eb0e36 | https://github.com/adesigns/calendar-bundle/blob/056861b042f4c70c7d929c3ad62d891fe4eb0e36/Controller/CalendarController.php#L18-L40 | train |
adesigns/calendar-bundle | Event/CalendarEvent.php | CalendarEvent.addEvent | public function addEvent(EventEntity $event)
{
if (!$this->events->contains($event)) {
$this->events[] = $event;
}
return $this;
} | php | public function addEvent(EventEntity $event)
{
if (!$this->events->contains($event)) {
$this->events[] = $event;
}
return $this;
} | [
"public",
"function",
"addEvent",
"(",
"EventEntity",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"events",
"->",
"contains",
"(",
"$",
"event",
")",
")",
"{",
"$",
"this",
"->",
"events",
"[",
"]",
"=",
"$",
"event",
";",
"}",
"re... | If the event isn't already in the list, add it
@param EventEntity $event
@return CalendarEvent $this | [
"If",
"the",
"event",
"isn",
"t",
"already",
"in",
"the",
"list",
"add",
"it"
] | 056861b042f4c70c7d929c3ad62d891fe4eb0e36 | https://github.com/adesigns/calendar-bundle/blob/056861b042f4c70c7d929c3ad62d891fe4eb0e36/Event/CalendarEvent.php#L52-L59 | train |
adesigns/calendar-bundle | Entity/EventEntity.php | EventEntity.toArray | public function toArray()
{
$event = array();
if ($this->id !== null) {
$event['id'] = $this->id;
}
$event['title'] = $this->title;
$event['start'] = $this->startDatetime->format("Y-m-d\TH:i:sP");
if ($this->url !== null) {
$event['url'] = $this->url;
}
if ($this->bgColor !== null) {
$event['backgroundColor'] = $this->bgColor;
$event['borderColor'] = $this->bgColor;
}
if ($this->fgColor !== null) {
$event['textColor'] = $this->fgColor;
}
if ($this->cssClass !== null) {
$event['className'] = $this->cssClass;
}
if ($this->endDatetime !== null) {
$event['end'] = $this->endDatetime->format("Y-m-d\TH:i:sP");
}
$event['allDay'] = $this->allDay;
foreach ($this->otherFields as $field => $value) {
$event[$field] = $value;
}
return $event;
} | php | public function toArray()
{
$event = array();
if ($this->id !== null) {
$event['id'] = $this->id;
}
$event['title'] = $this->title;
$event['start'] = $this->startDatetime->format("Y-m-d\TH:i:sP");
if ($this->url !== null) {
$event['url'] = $this->url;
}
if ($this->bgColor !== null) {
$event['backgroundColor'] = $this->bgColor;
$event['borderColor'] = $this->bgColor;
}
if ($this->fgColor !== null) {
$event['textColor'] = $this->fgColor;
}
if ($this->cssClass !== null) {
$event['className'] = $this->cssClass;
}
if ($this->endDatetime !== null) {
$event['end'] = $this->endDatetime->format("Y-m-d\TH:i:sP");
}
$event['allDay'] = $this->allDay;
foreach ($this->otherFields as $field => $value) {
$event[$field] = $value;
}
return $event;
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"$",
"event",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"id",
"!==",
"null",
")",
"{",
"$",
"event",
"[",
"'id'",
"]",
"=",
"$",
"this",
"->",
"id",
";",
"}",
"$",
"event",
"[",... | Convert calendar event details to an array
@return array $event | [
"Convert",
"calendar",
"event",
"details",
"to",
"an",
"array"
] | 056861b042f4c70c7d929c3ad62d891fe4eb0e36 | https://github.com/adesigns/calendar-bundle/blob/056861b042f4c70c7d929c3ad62d891fe4eb0e36/Entity/EventEntity.php#L80-L119 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Message.php | Message.getJson | public function getJson()
{
// Get message and aps array to create JSON from
$message = array();
$aps = array();
// If we have a payload replace the message object by the payload
if (null !== $this->payload) {
$message = $this->payload;
}
// Add the alert if any
if (null !== $this->alert) {
$aps['alert'] = $this->alert;
}
// Add the badge if any
if (null !== $this->badge) {
$aps['badge'] = $this->badge;
}
// Add the sound if any
if (null !== $this->sound) {
$aps['sound'] = $this->sound;
}
// Add category identifier if any
if (null !== $this->category) {
$aps['category'] = $this->category;
}
// Add the content-available flag if set
if (true == $this->contentAvailable) {
$aps['content-available'] = 1;
}
// Check if APS data is set
if (count($aps) > 0) {
$message['aps'] = $aps;
}
// Encode as JSON object
$json = json_encode($message);
if (false == $json) {
throw new \RuntimeException('Failed to convert APNS\Message to JSON, are all strings UTF-8?', json_last_error());
}
return $json;
} | php | public function getJson()
{
// Get message and aps array to create JSON from
$message = array();
$aps = array();
// If we have a payload replace the message object by the payload
if (null !== $this->payload) {
$message = $this->payload;
}
// Add the alert if any
if (null !== $this->alert) {
$aps['alert'] = $this->alert;
}
// Add the badge if any
if (null !== $this->badge) {
$aps['badge'] = $this->badge;
}
// Add the sound if any
if (null !== $this->sound) {
$aps['sound'] = $this->sound;
}
// Add category identifier if any
if (null !== $this->category) {
$aps['category'] = $this->category;
}
// Add the content-available flag if set
if (true == $this->contentAvailable) {
$aps['content-available'] = 1;
}
// Check if APS data is set
if (count($aps) > 0) {
$message['aps'] = $aps;
}
// Encode as JSON object
$json = json_encode($message);
if (false == $json) {
throw new \RuntimeException('Failed to convert APNS\Message to JSON, are all strings UTF-8?', json_last_error());
}
return $json;
} | [
"public",
"function",
"getJson",
"(",
")",
"{",
"// Get message and aps array to create JSON from",
"$",
"message",
"=",
"array",
"(",
")",
";",
"$",
"aps",
"=",
"array",
"(",
")",
";",
"// If we have a payload replace the message object by the payload",
"if",
"(",
"n... | Get the JSON payload that should be send to the APNS
@return string
@throws \RuntimeException When unable to create JSON, for example because of non-UTF-8 characters | [
"Get",
"the",
"JSON",
"payload",
"that",
"should",
"be",
"send",
"to",
"the",
"APNS"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Message.php#L177-L225 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Message.php | Message.setDeviceToken | private function setDeviceToken($deviceToken)
{
// Check if a devicetoken is given
if (null == $deviceToken) {
throw new \InvalidArgumentException('No device token given.');
}
// Check if the devicetoken is a valid hexadecimal string
if (!ctype_xdigit($deviceToken)) {
throw new \InvalidArgumentException('Invalid device token given, no hexadecimal: ' . $deviceToken);
}
// Check if the length of the devicetoken is correct
if (64 != strlen($deviceToken)) {
throw new \InvalidArgumentException('Invalid device token given, incorrect length: ' . $deviceToken . ' (' . strlen($deviceToken) . ')');
}
// Set the devicetoken
$this->deviceToken = $deviceToken;
} | php | private function setDeviceToken($deviceToken)
{
// Check if a devicetoken is given
if (null == $deviceToken) {
throw new \InvalidArgumentException('No device token given.');
}
// Check if the devicetoken is a valid hexadecimal string
if (!ctype_xdigit($deviceToken)) {
throw new \InvalidArgumentException('Invalid device token given, no hexadecimal: ' . $deviceToken);
}
// Check if the length of the devicetoken is correct
if (64 != strlen($deviceToken)) {
throw new \InvalidArgumentException('Invalid device token given, incorrect length: ' . $deviceToken . ' (' . strlen($deviceToken) . ')');
}
// Set the devicetoken
$this->deviceToken = $deviceToken;
} | [
"private",
"function",
"setDeviceToken",
"(",
"$",
"deviceToken",
")",
"{",
"// Check if a devicetoken is given",
"if",
"(",
"null",
"==",
"$",
"deviceToken",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'No device token given.'",
")",
";",
"}",... | Set the receiver of the message
@param string Receiver of this message
@throws \InvalidArgumentException On invalid or missing arguments | [
"Set",
"the",
"receiver",
"of",
"the",
"message"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Message.php#L285-L304 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Message.php | Message.setBadge | private function setBadge($badge)
{
// Validate the badge int
if ((int)$badge < 0) {
throw new \InvalidArgumentException('Badge must be 0 or higher.');
}
// Cast to int or set to null
$this->badge = (null === $badge) ? null : (int)$badge;
} | php | private function setBadge($badge)
{
// Validate the badge int
if ((int)$badge < 0) {
throw new \InvalidArgumentException('Badge must be 0 or higher.');
}
// Cast to int or set to null
$this->badge = (null === $badge) ? null : (int)$badge;
} | [
"private",
"function",
"setBadge",
"(",
"$",
"badge",
")",
"{",
"// Validate the badge int",
"if",
"(",
"(",
"int",
")",
"$",
"badge",
"<",
"0",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Badge must be 0 or higher.'",
")",
";",
"}",
"... | Set the badge to display on the App icon
@param int|null The badge number to display, zero to remove badge
@throws \InvalidArgumentException On invalid or missing arguments | [
"Set",
"the",
"badge",
"to",
"display",
"on",
"the",
"App",
"icon"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Message.php#L351-L360 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Message.php | Message.setPayload | private function setPayload($payload)
{
if ( (is_string($payload) && empty($payload)) || (is_array($payload) && count($payload) == 0) )
{
// Empty strings or arrays are not allowed
throw new \InvalidArgumentException('Invalid payload for message. Payload was empty, but not null)');
}
else if (is_array($payload) || null === $payload)
{
if ( isset($payload['aps']) )
{
// Reserved key is used
throw new \InvalidArgumentException('Invalid payload for message. Custom payload may not contain the reserved "aps" key.');
}
else
{
// This is okay, set as payload
$this->payload = $payload;
}
}
else
{
// Try to decode JSON string payload
$payload = json_decode($payload, true);
// Check if decoding the payload worked
if (null === $payload) {
throw new \InvalidArgumentException('Invalid payload for message. Payload was invalid JSON.');
}
// Set as payload
$this->payload = $payload;
}
} | php | private function setPayload($payload)
{
if ( (is_string($payload) && empty($payload)) || (is_array($payload) && count($payload) == 0) )
{
// Empty strings or arrays are not allowed
throw new \InvalidArgumentException('Invalid payload for message. Payload was empty, but not null)');
}
else if (is_array($payload) || null === $payload)
{
if ( isset($payload['aps']) )
{
// Reserved key is used
throw new \InvalidArgumentException('Invalid payload for message. Custom payload may not contain the reserved "aps" key.');
}
else
{
// This is okay, set as payload
$this->payload = $payload;
}
}
else
{
// Try to decode JSON string payload
$payload = json_decode($payload, true);
// Check if decoding the payload worked
if (null === $payload) {
throw new \InvalidArgumentException('Invalid payload for message. Payload was invalid JSON.');
}
// Set as payload
$this->payload = $payload;
}
} | [
"private",
"function",
"setPayload",
"(",
"$",
"payload",
")",
"{",
"if",
"(",
"(",
"is_string",
"(",
"$",
"payload",
")",
"&&",
"empty",
"(",
"$",
"payload",
")",
")",
"||",
"(",
"is_array",
"(",
"$",
"payload",
")",
"&&",
"count",
"(",
"$",
"payl... | Set custom payload to go with the message
@param array|json|null The payload to send as array or JSON string
@throws \InvalidArgumentException On invalid or missing arguments | [
"Set",
"custom",
"payload",
"to",
"go",
"with",
"the",
"message"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Message.php#L368-L401 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/SslSocket.php | SslSocket.disconnect | protected function disconnect()
{
$this->logger->debug('Disconnecting Apns\SslSocket from the APNS service with certificate "' . $this->getCertificate()->getDescription() . '"');
// Check if there is a socket to disconnect
if (is_resource($this->connection))
{
// Disconnect and unset the connection variable
fclose($this->connection);
}
$this->connection = null;
} | php | protected function disconnect()
{
$this->logger->debug('Disconnecting Apns\SslSocket from the APNS service with certificate "' . $this->getCertificate()->getDescription() . '"');
// Check if there is a socket to disconnect
if (is_resource($this->connection))
{
// Disconnect and unset the connection variable
fclose($this->connection);
}
$this->connection = null;
} | [
"protected",
"function",
"disconnect",
"(",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Disconnecting Apns\\SslSocket from the APNS service with certificate \"'",
".",
"$",
"this",
"->",
"getCertificate",
"(",
")",
"->",
"getDescription",
"(",
")",
... | Disconnect from the endpoint | [
"Disconnect",
"from",
"the",
"endpoint"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/SslSocket.php#L120-L132 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Gateway.php | Gateway.queue | public function queue(Message $message)
{
// Bump the message ID
$this->lastMessageId++;
// Put the message in an envelope
$envelope = new MessageEnvelope($this->lastMessageId, $message);
// Save the message so we can update it later on
$this->storeMessageEnvelope($envelope);
// Queue and return the envelope
$this->logger->debug('Queuing Apns\Message #' . $this->lastMessageId . ' to device "' . $message->getDeviceToken() . '" on Apns\Gateway with certificate "' . $this->getCertificate()->getDescription() . '"');
$this->sendQueue->enqueue($envelope);
return $envelope;
} | php | public function queue(Message $message)
{
// Bump the message ID
$this->lastMessageId++;
// Put the message in an envelope
$envelope = new MessageEnvelope($this->lastMessageId, $message);
// Save the message so we can update it later on
$this->storeMessageEnvelope($envelope);
// Queue and return the envelope
$this->logger->debug('Queuing Apns\Message #' . $this->lastMessageId . ' to device "' . $message->getDeviceToken() . '" on Apns\Gateway with certificate "' . $this->getCertificate()->getDescription() . '"');
$this->sendQueue->enqueue($envelope);
return $envelope;
} | [
"public",
"function",
"queue",
"(",
"Message",
"$",
"message",
")",
"{",
"// Bump the message ID",
"$",
"this",
"->",
"lastMessageId",
"++",
";",
"// Put the message in an envelope",
"$",
"envelope",
"=",
"new",
"MessageEnvelope",
"(",
"$",
"this",
"->",
"lastMess... | Queue a message for sending
@param Message The message object to queue for sending
@return MessageEnvelope | [
"Queue",
"a",
"message",
"for",
"sending"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Gateway.php#L48-L64 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Gateway.php | Gateway.retrieveMessageEnvelope | protected function retrieveMessageEnvelope($identifier)
{
$envelope = null;
// Fetch the requested anvelope if we have any
if ( isset($this->messageEnvelopeStore[self::MESSAGE_ENVELOPE_STORE_PREFIX . $identifier]) ) {
$envelope = $this->messageEnvelopeStore[self::MESSAGE_ENVELOPE_STORE_PREFIX . $identifier];
}
return $envelope;
} | php | protected function retrieveMessageEnvelope($identifier)
{
$envelope = null;
// Fetch the requested anvelope if we have any
if ( isset($this->messageEnvelopeStore[self::MESSAGE_ENVELOPE_STORE_PREFIX . $identifier]) ) {
$envelope = $this->messageEnvelopeStore[self::MESSAGE_ENVELOPE_STORE_PREFIX . $identifier];
}
return $envelope;
} | [
"protected",
"function",
"retrieveMessageEnvelope",
"(",
"$",
"identifier",
")",
"{",
"$",
"envelope",
"=",
"null",
";",
"// Fetch the requested anvelope if we have any",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"messageEnvelopeStore",
"[",
"self",
"::",
"MESSAGE... | Retrieve a stored envelope
@return MessageEnvelope|null | [
"Retrieve",
"a",
"stored",
"envelope"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Gateway.php#L242-L252 | train |
mac-cain13/notificato | src/Wrep/Notificato/Notificato.php | Notificato.createCertificate | public function createCertificate($pemFile, $passphrase = null, $validate = true, $endpointEnv = null)
{
return $this->certificateFactory->createCertificate($pemFile, $passphrase, $validate, $endpointEnv);
} | php | public function createCertificate($pemFile, $passphrase = null, $validate = true, $endpointEnv = null)
{
return $this->certificateFactory->createCertificate($pemFile, $passphrase, $validate, $endpointEnv);
} | [
"public",
"function",
"createCertificate",
"(",
"$",
"pemFile",
",",
"$",
"passphrase",
"=",
"null",
",",
"$",
"validate",
"=",
"true",
",",
"$",
"endpointEnv",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"certificateFactory",
"->",
"createCertificat... | Create an APNS Certificate
@param string Path to the PEM certificate file
@param string|null Passphrase to use with the PEM file
@param boolean Set to false to skip the validation of the certificate, default true
@param string|null APNS environment this certificate is valid for, by default autodetects during validation
@return Apns\Certificate | [
"Create",
"an",
"APNS",
"Certificate"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Notificato.php#L46-L49 | train |
mac-cain13/notificato | src/Wrep/Notificato/Notificato.php | Notificato.messageBuilder | public function messageBuilder()
{
$builder = Apns\Message::builder();
if ($this->certificateFactory->getDefaultCertificate() != null) {
$builder->setCertificate( $this->certificateFactory->getDefaultCertificate() );
}
return $builder;
} | php | public function messageBuilder()
{
$builder = Apns\Message::builder();
if ($this->certificateFactory->getDefaultCertificate() != null) {
$builder->setCertificate( $this->certificateFactory->getDefaultCertificate() );
}
return $builder;
} | [
"public",
"function",
"messageBuilder",
"(",
")",
"{",
"$",
"builder",
"=",
"Apns",
"\\",
"Message",
"::",
"builder",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"certificateFactory",
"->",
"getDefaultCertificate",
"(",
")",
"!=",
"null",
")",
"{",
"$",... | Create a Message builder
@return Apns\MessageBuilder | [
"Create",
"a",
"Message",
"builder"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Notificato.php#L56-L65 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/CertificateFactory.php | CertificateFactory.createCertificate | public function createCertificate($pemFile, $passphrase = null, $validate = true, $endpointEnv = null)
{
return new Certificate($pemFile, $passphrase, $validate, $endpointEnv);
} | php | public function createCertificate($pemFile, $passphrase = null, $validate = true, $endpointEnv = null)
{
return new Certificate($pemFile, $passphrase, $validate, $endpointEnv);
} | [
"public",
"function",
"createCertificate",
"(",
"$",
"pemFile",
",",
"$",
"passphrase",
"=",
"null",
",",
"$",
"validate",
"=",
"true",
",",
"$",
"endpointEnv",
"=",
"null",
")",
"{",
"return",
"new",
"Certificate",
"(",
"$",
"pemFile",
",",
"$",
"passph... | Create a Certificate
@param string Path to the PEM certificate file
@param string|null Passphrase to use with the PEM file
@param boolean Set to false to skip the validation of the certificate, default true
@param string|null APNS environment this certificate is valid for, by default autodetects during validation
@return Certificate | [
"Create",
"a",
"Certificate"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/CertificateFactory.php#L56-L59 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/MessageEnvelope.php | MessageEnvelope.setStatus | public function setStatus($status, $envelope = null)
{
// Check if we're not in a final state yet
if ($this->status > 0) {
throw new \RuntimeException('Cannot change status from final state ' . $this->status . ' to state ' . $status . '.');
}
// Check if this is a valid state
if ( !in_array($status, array_keys(self::$statusDescriptionMapping)) ) {
throw new \InvalidArgumentException('Status ' . $status . ' is not a valid status.');
}
// Check if the retry envelope is not this envelope
if ($this === $envelope) {
throw new \InvalidArgumentException('Retry envelope cannot be set to this envelope.');
}
// Save it!
$this->status = $status;
$this->retryEnvelope = $envelope;
} | php | public function setStatus($status, $envelope = null)
{
// Check if we're not in a final state yet
if ($this->status > 0) {
throw new \RuntimeException('Cannot change status from final state ' . $this->status . ' to state ' . $status . '.');
}
// Check if this is a valid state
if ( !in_array($status, array_keys(self::$statusDescriptionMapping)) ) {
throw new \InvalidArgumentException('Status ' . $status . ' is not a valid status.');
}
// Check if the retry envelope is not this envelope
if ($this === $envelope) {
throw new \InvalidArgumentException('Retry envelope cannot be set to this envelope.');
}
// Save it!
$this->status = $status;
$this->retryEnvelope = $envelope;
} | [
"public",
"function",
"setStatus",
"(",
"$",
"status",
",",
"$",
"envelope",
"=",
"null",
")",
"{",
"// Check if we're not in a final state yet",
"if",
"(",
"$",
"this",
"->",
"status",
">",
"0",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Can... | Set the status of this message envelope
only possible if there is no final state set yet.
@param int One of the keys in self::$statusDescriptionMapping
@param MessageEnvelope|null Envelope for the retry of this MessageEnvelope | [
"Set",
"the",
"status",
"of",
"this",
"message",
"envelope",
"only",
"possible",
"if",
"there",
"is",
"no",
"final",
"state",
"set",
"yet",
"."
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/MessageEnvelope.php#L127-L147 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/MessageEnvelope.php | MessageEnvelope.getFinalStatus | public function getFinalStatus()
{
$currentEnvelope = $this;
while ( null != $currentEnvelope->getRetryEnvelope() ) {
$currentEnvelope = $currentEnvelope->getRetryEnvelope();
}
return $currentEnvelope->getStatus();
} | php | public function getFinalStatus()
{
$currentEnvelope = $this;
while ( null != $currentEnvelope->getRetryEnvelope() ) {
$currentEnvelope = $currentEnvelope->getRetryEnvelope();
}
return $currentEnvelope->getStatus();
} | [
"public",
"function",
"getFinalStatus",
"(",
")",
"{",
"$",
"currentEnvelope",
"=",
"$",
"this",
";",
"while",
"(",
"null",
"!=",
"$",
"currentEnvelope",
"->",
"getRetryEnvelope",
"(",
")",
")",
"{",
"$",
"currentEnvelope",
"=",
"$",
"currentEnvelope",
"->",... | Get the final status after all retries.
Use this method to know how the message ended up after all retries.
@return int | [
"Get",
"the",
"final",
"status",
"after",
"all",
"retries",
".",
"Use",
"this",
"method",
"to",
"know",
"how",
"the",
"message",
"ended",
"up",
"after",
"all",
"retries",
"."
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/MessageEnvelope.php#L175-L183 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/MessageEnvelope.php | MessageEnvelope.getBinaryMessage | public function getBinaryMessage()
{
$jsonMessage = $this->getMessage()->getJson();
$jsonMessageLength = strlen($jsonMessage);
$binaryMessage = pack('CNNnH*', self::BINARY_COMMAND, $this->getIdentifier(), $this->getMessage()->getExpiresAt(), self::BINARY_DEVICETOKEN_SIZE, $this->getMessage()->getDeviceToken()) . pack('n', $jsonMessageLength);
return $binaryMessage . $jsonMessage;
} | php | public function getBinaryMessage()
{
$jsonMessage = $this->getMessage()->getJson();
$jsonMessageLength = strlen($jsonMessage);
$binaryMessage = pack('CNNnH*', self::BINARY_COMMAND, $this->getIdentifier(), $this->getMessage()->getExpiresAt(), self::BINARY_DEVICETOKEN_SIZE, $this->getMessage()->getDeviceToken()) . pack('n', $jsonMessageLength);
return $binaryMessage . $jsonMessage;
} | [
"public",
"function",
"getBinaryMessage",
"(",
")",
"{",
"$",
"jsonMessage",
"=",
"$",
"this",
"->",
"getMessage",
"(",
")",
"->",
"getJson",
"(",
")",
";",
"$",
"jsonMessageLength",
"=",
"strlen",
"(",
"$",
"jsonMessage",
")",
";",
"$",
"binaryMessage",
... | Get the message that this envelope contains in binary APNS compatible format
@return string | [
"Get",
"the",
"message",
"that",
"this",
"envelope",
"contains",
"in",
"binary",
"APNS",
"compatible",
"format"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/MessageEnvelope.php#L201-L208 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Feedback/FeedbackFactory.php | FeedbackFactory.createFeedback | public function createFeedback(Certificate $certificate = null)
{
// Check if a certificate is given, if not use the default certificate
if (null == $certificate && $this->getCertificateFactory() != null) {
$certificate = $this->getCertificateFactory()->getDefaultCertificate();
}
// Check if there is a certificate to use after falling back on the default certificate
if (null == $certificate) {
throw new \RuntimeException('No certificate given for the creation of the feedback service and no default certificate available.');
}
return new Feedback($certificate);
} | php | public function createFeedback(Certificate $certificate = null)
{
// Check if a certificate is given, if not use the default certificate
if (null == $certificate && $this->getCertificateFactory() != null) {
$certificate = $this->getCertificateFactory()->getDefaultCertificate();
}
// Check if there is a certificate to use after falling back on the default certificate
if (null == $certificate) {
throw new \RuntimeException('No certificate given for the creation of the feedback service and no default certificate available.');
}
return new Feedback($certificate);
} | [
"public",
"function",
"createFeedback",
"(",
"Certificate",
"$",
"certificate",
"=",
"null",
")",
"{",
"// Check if a certificate is given, if not use the default certificate",
"if",
"(",
"null",
"==",
"$",
"certificate",
"&&",
"$",
"this",
"->",
"getCertificateFactory",
... | Create a Feedback object
@param Certificate|null The certificate to use or null to use the default certificate from the given certificate factory
@return Feedback | [
"Create",
"a",
"Feedback",
"object"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Feedback/FeedbackFactory.php#L48-L61 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Sender.php | Sender.queue | public function queue(Message $message)
{
// Get the gateway for the certificate
$gateway = $this->getGatewayForCertificate( $message->getCertificate() );
// Queue the message
return $gateway->queue($message);
} | php | public function queue(Message $message)
{
// Get the gateway for the certificate
$gateway = $this->getGatewayForCertificate( $message->getCertificate() );
// Queue the message
return $gateway->queue($message);
} | [
"public",
"function",
"queue",
"(",
"Message",
"$",
"message",
")",
"{",
"// Get the gateway for the certificate",
"$",
"gateway",
"=",
"$",
"this",
"->",
"getGatewayForCertificate",
"(",
"$",
"message",
"->",
"getCertificate",
"(",
")",
")",
";",
"// Queue the me... | Queue a message on the correct APNS gateway connection
@param Message The message to queue
@param int The times Notificato should retry to deliver the message on failure (deprecated and ignored)
@return MessageEnvelope | [
"Queue",
"a",
"message",
"on",
"the",
"correct",
"APNS",
"gateway",
"connection"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Sender.php#L84-L91 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Sender.php | Sender.getQueueLength | public function getQueueLength()
{
$queueLength = 0;
foreach ($this->gatewayPool as $gateway)
{
$queueLength += $gateway->getQueueLength();
}
return $queueLength;
} | php | public function getQueueLength()
{
$queueLength = 0;
foreach ($this->gatewayPool as $gateway)
{
$queueLength += $gateway->getQueueLength();
}
return $queueLength;
} | [
"public",
"function",
"getQueueLength",
"(",
")",
"{",
"$",
"queueLength",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"gatewayPool",
"as",
"$",
"gateway",
")",
"{",
"$",
"queueLength",
"+=",
"$",
"gateway",
"->",
"getQueueLength",
"(",
")",
";",
... | Count of all queued messages
@return int | [
"Count",
"of",
"all",
"queued",
"messages"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Sender.php#L98-L108 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Certificate.php | Certificate.getDescription | public function getDescription()
{
$description = $this->description;
if (null == $description) {
$description = $this->getFingerprint();
}
return $description;
} | php | public function getDescription()
{
$description = $this->description;
if (null == $description) {
$description = $this->getFingerprint();
}
return $description;
} | [
"public",
"function",
"getDescription",
"(",
")",
"{",
"$",
"description",
"=",
"$",
"this",
"->",
"description",
";",
"if",
"(",
"null",
"==",
"$",
"description",
")",
"{",
"$",
"description",
"=",
"$",
"this",
"->",
"getFingerprint",
"(",
")",
";",
"... | An as humanreadable as possible description of the certificate to identify the certificate
@return string | [
"An",
"as",
"humanreadable",
"as",
"possible",
"description",
"of",
"the",
"certificate",
"to",
"identify",
"the",
"certificate"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Certificate.php#L238-L247 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Certificate.php | Certificate.getEndpoint | public function getEndpoint($endpointType)
{
// Check if the endpoint type is valid
if (self::ENDPOINT_TYPE_GATEWAY !== $endpointType && self::ENDPOINT_TYPE_FEEDBACK !== $endpointType ) {
throw new \InvalidArgumentException($endpointType . ' is not a valid endpoint type.');
}
return self::$endpoints[$this->endpointEnv][$endpointType];
} | php | public function getEndpoint($endpointType)
{
// Check if the endpoint type is valid
if (self::ENDPOINT_TYPE_GATEWAY !== $endpointType && self::ENDPOINT_TYPE_FEEDBACK !== $endpointType ) {
throw new \InvalidArgumentException($endpointType . ' is not a valid endpoint type.');
}
return self::$endpoints[$this->endpointEnv][$endpointType];
} | [
"public",
"function",
"getEndpoint",
"(",
"$",
"endpointType",
")",
"{",
"// Check if the endpoint type is valid",
"if",
"(",
"self",
"::",
"ENDPOINT_TYPE_GATEWAY",
"!==",
"$",
"endpointType",
"&&",
"self",
"::",
"ENDPOINT_TYPE_FEEDBACK",
"!==",
"$",
"endpointType",
"... | Get the endpoint this certificate is valid for
@param string The type of endpoint you want
@return string
@throws \InvalidArgumentException | [
"Get",
"the",
"endpoint",
"this",
"certificate",
"is",
"valid",
"for"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Certificate.php#L279-L287 | train |
mac-cain13/notificato | src/Wrep/Notificato/Apns/Certificate.php | Certificate.getFingerprint | public function getFingerprint()
{
// Calculate fingerprint if unknown
if (null == $this->fingerprint) {
$this->fingerprint = sha1( $this->endpointEnv . sha1_file($this->getPemFile()) );
}
return $this->fingerprint;
} | php | public function getFingerprint()
{
// Calculate fingerprint if unknown
if (null == $this->fingerprint) {
$this->fingerprint = sha1( $this->endpointEnv . sha1_file($this->getPemFile()) );
}
return $this->fingerprint;
} | [
"public",
"function",
"getFingerprint",
"(",
")",
"{",
"// Calculate fingerprint if unknown",
"if",
"(",
"null",
"==",
"$",
"this",
"->",
"fingerprint",
")",
"{",
"$",
"this",
"->",
"fingerprint",
"=",
"sha1",
"(",
"$",
"this",
"->",
"endpointEnv",
".",
"sha... | Get a unique hash of the certificate
this can be used to check if two Apns\Certificate objects are the same
@return string | [
"Get",
"a",
"unique",
"hash",
"of",
"the",
"certificate",
"this",
"can",
"be",
"used",
"to",
"check",
"if",
"two",
"Apns",
"\\",
"Certificate",
"objects",
"are",
"the",
"same"
] | a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915 | https://github.com/mac-cain13/notificato/blob/a4b3c3edda1ffeb4ba154fad31dbda4a5a5cf915/src/Wrep/Notificato/Apns/Certificate.php#L295-L303 | train |
potievdev/slim-rbac | src/migrations/20171210103530_create_permission.php | CreatePermission.change | public function change()
{
$permissionTable = $this->table('permission', ['signed' => false]);
$permissionTable->addColumn('name', 'string', ['limit' => 100])
->addColumn('status', 'boolean', ['default' => 1])
->addColumn('created_at', 'datetime')
->addColumn('updated_at', 'datetime', ['null' => true])
->addIndex('name', ['name' => 'idx_role_name' ,'unique' => true])
->create();
} | php | public function change()
{
$permissionTable = $this->table('permission', ['signed' => false]);
$permissionTable->addColumn('name', 'string', ['limit' => 100])
->addColumn('status', 'boolean', ['default' => 1])
->addColumn('created_at', 'datetime')
->addColumn('updated_at', 'datetime', ['null' => true])
->addIndex('name', ['name' => 'idx_role_name' ,'unique' => true])
->create();
} | [
"public",
"function",
"change",
"(",
")",
"{",
"$",
"permissionTable",
"=",
"$",
"this",
"->",
"table",
"(",
"'permission'",
",",
"[",
"'signed'",
"=>",
"false",
"]",
")",
";",
"$",
"permissionTable",
"->",
"addColumn",
"(",
"'name'",
",",
"'string'",
",... | Create permission table in database.
Field 'name' is unique index. | [
"Create",
"permission",
"table",
"in",
"database",
".",
"Field",
"name",
"is",
"unique",
"index",
"."
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/migrations/20171210103530_create_permission.php#L14-L24 | train |
potievdev/slim-rbac | src/Models/Repository/RoleHierarchyRepository.php | RoleHierarchyRepository.getChildIds | private function getChildIds($parentIds)
{
$qb = $this->createQueryBuilder('roleHierarchy');
$qb->select('roleHierarchy.childRoleId')
->where($qb->expr()->in( 'roleHierarchy.parentRoleId', $parentIds))
->indexBy('roleHierarchy', 'roleHierarchy.childRoleId');
$childRoleIds = $qb->getQuery()->getArrayResult();
return array_keys($childRoleIds);
} | php | private function getChildIds($parentIds)
{
$qb = $this->createQueryBuilder('roleHierarchy');
$qb->select('roleHierarchy.childRoleId')
->where($qb->expr()->in( 'roleHierarchy.parentRoleId', $parentIds))
->indexBy('roleHierarchy', 'roleHierarchy.childRoleId');
$childRoleIds = $qb->getQuery()->getArrayResult();
return array_keys($childRoleIds);
} | [
"private",
"function",
"getChildIds",
"(",
"$",
"parentIds",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'roleHierarchy'",
")",
";",
"$",
"qb",
"->",
"select",
"(",
"'roleHierarchy.childRoleId'",
")",
"->",
"where",
"(",
"$",
"... | Returns array of child role ids for given parent role ids
@param integer[] $parentIds
@return integer[]
@throws \Doctrine\ORM\Query\QueryException | [
"Returns",
"array",
"of",
"child",
"role",
"ids",
"for",
"given",
"parent",
"role",
"ids"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Models/Repository/RoleHierarchyRepository.php#L22-L33 | train |
potievdev/slim-rbac | src/Models/Repository/RoleHierarchyRepository.php | RoleHierarchyRepository.getAllChildRoleIds | private function getAllChildRoleIds($parentIds)
{
$allChildIds = [];
while (count($parentIds) > 0) {
$parentIds = $this->getChildIds($parentIds);
$allChildIds = ArrayHelper::merge($allChildIds, $parentIds);
};
return $allChildIds;
} | php | private function getAllChildRoleIds($parentIds)
{
$allChildIds = [];
while (count($parentIds) > 0) {
$parentIds = $this->getChildIds($parentIds);
$allChildIds = ArrayHelper::merge($allChildIds, $parentIds);
};
return $allChildIds;
} | [
"private",
"function",
"getAllChildRoleIds",
"(",
"$",
"parentIds",
")",
"{",
"$",
"allChildIds",
"=",
"[",
"]",
";",
"while",
"(",
"count",
"(",
"$",
"parentIds",
")",
">",
"0",
")",
"{",
"$",
"parentIds",
"=",
"$",
"this",
"->",
"getChildIds",
"(",
... | Returns all child role ids for given parent role ids
@param integer[] $parentIds
@return integer[]
@throws \Doctrine\ORM\Query\QueryException | [
"Returns",
"all",
"child",
"role",
"ids",
"for",
"given",
"parent",
"role",
"ids"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Models/Repository/RoleHierarchyRepository.php#L69-L79 | train |
potievdev/slim-rbac | src/Console/Command/BaseDatabaseCommand.php | BaseDatabaseCommand.getCliPath | private function getCliPath(InputInterface $input)
{
$filePaths = [
__DIR__ . '/../../../config/sr-config.php',
__DIR__ . '/../../../../../../sr-config.php',
__DIR__ . '/../../../../../../config/sr-config.php',
];
if ($input->hasOption('config')) {
$filePaths[] = $input->getOption('config');
}
foreach ($filePaths as $path) {
if (is_file($path)) {
return $path;
}
}
throw new \Exception(
'There is not found config file.' . PHP_EOL .
'You can pass path to file as option: -c FILE_PATH'
);
} | php | private function getCliPath(InputInterface $input)
{
$filePaths = [
__DIR__ . '/../../../config/sr-config.php',
__DIR__ . '/../../../../../../sr-config.php',
__DIR__ . '/../../../../../../config/sr-config.php',
];
if ($input->hasOption('config')) {
$filePaths[] = $input->getOption('config');
}
foreach ($filePaths as $path) {
if (is_file($path)) {
return $path;
}
}
throw new \Exception(
'There is not found config file.' . PHP_EOL .
'You can pass path to file as option: -c FILE_PATH'
);
} | [
"private",
"function",
"getCliPath",
"(",
"InputInterface",
"$",
"input",
")",
"{",
"$",
"filePaths",
"=",
"[",
"__DIR__",
".",
"'/../../../config/sr-config.php'",
",",
"__DIR__",
".",
"'/../../../../../../sr-config.php'",
",",
"__DIR__",
".",
"'/../../../../../../confi... | Returns cli-config file path
@param InputInterface $input
@return string
@throws \Exception | [
"Returns",
"cli",
"-",
"config",
"file",
"path"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Console/Command/BaseDatabaseCommand.php#L37-L60 | train |
potievdev/slim-rbac | src/Component/BaseComponent.php | BaseComponent.saveEntity | protected function saveEntity($entity)
{
try {
$this->entityManager->persist($entity);
$this->entityManager->flush($entity);
return $entity;
} catch (OptimisticLockException $e) {
throw new DatabaseException($e->getMessage());
}
} | php | protected function saveEntity($entity)
{
try {
$this->entityManager->persist($entity);
$this->entityManager->flush($entity);
return $entity;
} catch (OptimisticLockException $e) {
throw new DatabaseException($e->getMessage());
}
} | [
"protected",
"function",
"saveEntity",
"(",
"$",
"entity",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"entityManager",
"->",
"persist",
"(",
"$",
"entity",
")",
";",
"$",
"this",
"->",
"entityManager",
"->",
"flush",
"(",
"$",
"entity",
")",
";",
"return... | Insert or update entity
@param object $entity
@return object
@throws DatabaseException | [
"Insert",
"or",
"update",
"entity"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/BaseComponent.php#L45-L54 | train |
potievdev/slim-rbac | src/Component/BaseComponent.php | BaseComponent.checkAccess | public function checkAccess($userId, $permissionName)
{
if (ValidatorHelper::isInteger($userId) == false) {
throw new InvalidArgumentException('User identifier must be number.');
}
/** @var integer $permissionId */
$permissionId = $this->repositoryRegistry
->getPermissionRepository()
->getPermissionIdByName($permissionName);
if (ValidatorHelper::isInteger($permissionId)) {
/** @var integer[] $rootRoleIds */
$rootRoleIds = $this->repositoryRegistry
->getUserRoleRepository()
->getUserRoleIds($userId);
if (count($rootRoleIds) > 0) {
/** @var integer[] $allRoleIds */
$allRoleIds = $this->repositoryRegistry
->getRoleHierarchyRepository()
->getAllRoleIdsHierarchy($rootRoleIds);
return $this->repositoryRegistry
->getRolePermissionRepository()
->isPermissionAssigned($permissionId, $allRoleIds);
}
}
return false;
} | php | public function checkAccess($userId, $permissionName)
{
if (ValidatorHelper::isInteger($userId) == false) {
throw new InvalidArgumentException('User identifier must be number.');
}
/** @var integer $permissionId */
$permissionId = $this->repositoryRegistry
->getPermissionRepository()
->getPermissionIdByName($permissionName);
if (ValidatorHelper::isInteger($permissionId)) {
/** @var integer[] $rootRoleIds */
$rootRoleIds = $this->repositoryRegistry
->getUserRoleRepository()
->getUserRoleIds($userId);
if (count($rootRoleIds) > 0) {
/** @var integer[] $allRoleIds */
$allRoleIds = $this->repositoryRegistry
->getRoleHierarchyRepository()
->getAllRoleIdsHierarchy($rootRoleIds);
return $this->repositoryRegistry
->getRolePermissionRepository()
->isPermissionAssigned($permissionId, $allRoleIds);
}
}
return false;
} | [
"public",
"function",
"checkAccess",
"(",
"$",
"userId",
",",
"$",
"permissionName",
")",
"{",
"if",
"(",
"ValidatorHelper",
"::",
"isInteger",
"(",
"$",
"userId",
")",
"==",
"false",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'User identifier... | Checks access status
@param integer $userId
@param string $permissionName
@return bool
@throws InvalidArgumentException
@throws \Doctrine\ORM\Query\QueryException | [
"Checks",
"access",
"status"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/BaseComponent.php#L64-L96 | train |
potievdev/slim-rbac | src/Models/Repository/RolePermissionRepository.php | RolePermissionRepository.isPermissionAssigned | public function isPermissionAssigned($permissionId, $roleIds)
{
$qb = $this->createQueryBuilder('rolePermission');
$result = $qb
->select('rolePermission.id')
->where(
$qb->expr()->andX(
$qb->expr()->eq('rolePermission.permissionId', $permissionId),
$qb->expr()->in('rolePermission.roleId', $roleIds)
)
)
->setMaxResults(1)
->getQuery()
->getArrayResult();
return count($result) > 0;
} | php | public function isPermissionAssigned($permissionId, $roleIds)
{
$qb = $this->createQueryBuilder('rolePermission');
$result = $qb
->select('rolePermission.id')
->where(
$qb->expr()->andX(
$qb->expr()->eq('rolePermission.permissionId', $permissionId),
$qb->expr()->in('rolePermission.roleId', $roleIds)
)
)
->setMaxResults(1)
->getQuery()
->getArrayResult();
return count($result) > 0;
} | [
"public",
"function",
"isPermissionAssigned",
"(",
"$",
"permissionId",
",",
"$",
"roleIds",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'rolePermission'",
")",
";",
"$",
"result",
"=",
"$",
"qb",
"->",
"select",
"(",
"'rolePer... | Search RolePermission record. If found return true else false
@param integer $permissionId
@param integer[] $roleIds
@return bool | [
"Search",
"RolePermission",
"record",
".",
"If",
"found",
"return",
"true",
"else",
"false"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Models/Repository/RolePermissionRepository.php#L36-L53 | train |
potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.checkForCyclicHierarchy | private function checkForCyclicHierarchy($parentRoleId, $childRoleId)
{
$result = $this->repositoryRegistry
->getRoleHierarchyRepository()
->hasChildRoleId($parentRoleId, $childRoleId);
if ($result === true) {
throw new CyclicException('There detected cyclic line. Role with id = ' . $parentRoleId . ' has child role whit id =' . $childRoleId);
}
} | php | private function checkForCyclicHierarchy($parentRoleId, $childRoleId)
{
$result = $this->repositoryRegistry
->getRoleHierarchyRepository()
->hasChildRoleId($parentRoleId, $childRoleId);
if ($result === true) {
throw new CyclicException('There detected cyclic line. Role with id = ' . $parentRoleId . ' has child role whit id =' . $childRoleId);
}
} | [
"private",
"function",
"checkForCyclicHierarchy",
"(",
"$",
"parentRoleId",
",",
"$",
"childRoleId",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"repositoryRegistry",
"->",
"getRoleHierarchyRepository",
"(",
")",
"->",
"hasChildRoleId",
"(",
"$",
"parentRoleI... | Checking hierarchy cyclic line
@param integer $parentRoleId
@param integer $childRoleId
@throws CyclicException
@throws \Doctrine\ORM\Query\QueryException | [
"Checking",
"hierarchy",
"cyclic",
"line"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L29-L38 | train |
potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.removeAll | public function removeAll()
{
$pdo = $this->entityManager->getConnection()->getWrappedConnection();
$pdo->beginTransaction();
try {
$pdo->exec('SET FOREIGN_KEY_CHECKS=0');
$pdo->exec('TRUNCATE role_permission');
$pdo->exec('TRUNCATE role_hierarchy');
$pdo->exec('TRUNCATE role');
$pdo->exec('TRUNCATE permission');
$pdo->exec('TRUNCATE user_role');
$pdo->exec('SET FOREIGN_KEY_CHECKS=1');
$pdo->commit();
} catch (\Exception $e) {
$pdo->rollBack();
throw new DatabaseException($e->getMessage());
}
} | php | public function removeAll()
{
$pdo = $this->entityManager->getConnection()->getWrappedConnection();
$pdo->beginTransaction();
try {
$pdo->exec('SET FOREIGN_KEY_CHECKS=0');
$pdo->exec('TRUNCATE role_permission');
$pdo->exec('TRUNCATE role_hierarchy');
$pdo->exec('TRUNCATE role');
$pdo->exec('TRUNCATE permission');
$pdo->exec('TRUNCATE user_role');
$pdo->exec('SET FOREIGN_KEY_CHECKS=1');
$pdo->commit();
} catch (\Exception $e) {
$pdo->rollBack();
throw new DatabaseException($e->getMessage());
}
} | [
"public",
"function",
"removeAll",
"(",
")",
"{",
"$",
"pdo",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getConnection",
"(",
")",
"->",
"getWrappedConnection",
"(",
")",
";",
"$",
"pdo",
"->",
"beginTransaction",
"(",
")",
";",
"try",
"{",
"$",
"... | Truncates all tables
@throws DatabaseException | [
"Truncates",
"all",
"tables"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L44-L65 | train |
potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addPermission | public function addPermission(Permission $permission)
{
try {
$this->saveEntity($permission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission with name ' . $permission->getName() . ' already created');
}
} | php | public function addPermission(Permission $permission)
{
try {
$this->saveEntity($permission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission with name ' . $permission->getName() . ' already created');
}
} | [
"public",
"function",
"addPermission",
"(",
"Permission",
"$",
"permission",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"saveEntity",
"(",
"$",
"permission",
")",
";",
"}",
"catch",
"(",
"UniqueConstraintViolationException",
"$",
"e",
")",
"{",
"throw",
"new",... | Save permission in database
@param Permission $permission
@throws NotUniqueException
@throws DatabaseException | [
"Save",
"permission",
"in",
"database"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L99-L106 | train |
potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addRole | public function addRole(Role $role)
{
try {
$this->saveEntity($role);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role with name ' . $role->getName() . ' already created');
}
} | php | public function addRole(Role $role)
{
try {
$this->saveEntity($role);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role with name ' . $role->getName() . ' already created');
}
} | [
"public",
"function",
"addRole",
"(",
"Role",
"$",
"role",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"saveEntity",
"(",
"$",
"role",
")",
";",
"}",
"catch",
"(",
"UniqueConstraintViolationException",
"$",
"e",
")",
"{",
"throw",
"new",
"NotUniqueException",... | Save role in database
@param Role $role
@throws NotUniqueException
@throws DatabaseException | [
"Save",
"role",
"in",
"database"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L114-L121 | train |
potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addChildPermission | public function addChildPermission(Role $role, Permission $permission)
{
$rolePermission = new RolePermission();
$rolePermission->setPermission($permission);
$rolePermission->setRole($role);
try {
$this->saveEntity($rolePermission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission ' . $permission->getName() . ' is already assigned to role ' . $role->getName());
}
} | php | public function addChildPermission(Role $role, Permission $permission)
{
$rolePermission = new RolePermission();
$rolePermission->setPermission($permission);
$rolePermission->setRole($role);
try {
$this->saveEntity($rolePermission);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Permission ' . $permission->getName() . ' is already assigned to role ' . $role->getName());
}
} | [
"public",
"function",
"addChildPermission",
"(",
"Role",
"$",
"role",
",",
"Permission",
"$",
"permission",
")",
"{",
"$",
"rolePermission",
"=",
"new",
"RolePermission",
"(",
")",
";",
"$",
"rolePermission",
"->",
"setPermission",
"(",
"$",
"permission",
")",... | Add permission to role
@param Role $role
@param Permission $permission
@throws DatabaseException
@throws NotUniqueException | [
"Add",
"permission",
"to",
"role"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L130-L142 | train |
potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.addChildRole | public function addChildRole(Role $parentRole, Role $childRole)
{
$roleHierarchy = new RoleHierarchy();
$roleHierarchy->setParentRole($parentRole);
$roleHierarchy->setChildRole($childRole);
$this->checkForCyclicHierarchy($childRole->getId(), $parentRole->getId());
try {
$this->saveEntity($roleHierarchy);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Child role ' . $childRole->getName() . ' is already has parent role ' . $parentRole->getName());
}
} | php | public function addChildRole(Role $parentRole, Role $childRole)
{
$roleHierarchy = new RoleHierarchy();
$roleHierarchy->setParentRole($parentRole);
$roleHierarchy->setChildRole($childRole);
$this->checkForCyclicHierarchy($childRole->getId(), $parentRole->getId());
try {
$this->saveEntity($roleHierarchy);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Child role ' . $childRole->getName() . ' is already has parent role ' . $parentRole->getName());
}
} | [
"public",
"function",
"addChildRole",
"(",
"Role",
"$",
"parentRole",
",",
"Role",
"$",
"childRole",
")",
"{",
"$",
"roleHierarchy",
"=",
"new",
"RoleHierarchy",
"(",
")",
";",
"$",
"roleHierarchy",
"->",
"setParentRole",
"(",
"$",
"parentRole",
")",
";",
... | Add child role to role
@param Role $parentRole
@param Role $childRole
@throws CyclicException
@throws DatabaseException
@throws NotUniqueException
@throws \Doctrine\ORM\Query\QueryException | [
"Add",
"child",
"role",
"to",
"role"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L153-L167 | train |
potievdev/slim-rbac | src/Component/AuthManager.php | AuthManager.assign | public function assign(Role $role, $userId)
{
$userRole = new UserRole();
$userRole->setUserId($userId);
$userRole->setRole($role);
try {
$this->saveEntity($userRole);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role ' . $role->getName() . 'is already assigned to user with identifier ' . $userId);
}
} | php | public function assign(Role $role, $userId)
{
$userRole = new UserRole();
$userRole->setUserId($userId);
$userRole->setRole($role);
try {
$this->saveEntity($userRole);
} catch (UniqueConstraintViolationException $e) {
throw new NotUniqueException('Role ' . $role->getName() . 'is already assigned to user with identifier ' . $userId);
}
} | [
"public",
"function",
"assign",
"(",
"Role",
"$",
"role",
",",
"$",
"userId",
")",
"{",
"$",
"userRole",
"=",
"new",
"UserRole",
"(",
")",
";",
"$",
"userRole",
"->",
"setUserId",
"(",
"$",
"userId",
")",
";",
"$",
"userRole",
"->",
"setRole",
"(",
... | Assign role to user
@param Role $role
@param integer $userId
@throws NotUniqueException
@throws DatabaseException | [
"Assign",
"role",
"to",
"user"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Component/AuthManager.php#L176-L188 | train |
potievdev/slim-rbac | src/Models/Repository/PermissionRepository.php | PermissionRepository.getPermissionIdByName | public function getPermissionIdByName($permissionName)
{
$qb = $this->createQueryBuilder('permission');
$result = $qb->select('permission.id')
->where($qb->expr()->eq('permission.name', $qb->expr()->literal($permissionName)))
->setMaxResults(1)
->getQuery()
->getArrayResult();
if (count($result) > 0) {
return $result[0]['id'];
}
return null;
} | php | public function getPermissionIdByName($permissionName)
{
$qb = $this->createQueryBuilder('permission');
$result = $qb->select('permission.id')
->where($qb->expr()->eq('permission.name', $qb->expr()->literal($permissionName)))
->setMaxResults(1)
->getQuery()
->getArrayResult();
if (count($result) > 0) {
return $result[0]['id'];
}
return null;
} | [
"public",
"function",
"getPermissionIdByName",
"(",
"$",
"permissionName",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'permission'",
")",
";",
"$",
"result",
"=",
"$",
"qb",
"->",
"select",
"(",
"'permission.id'",
")",
"->",
"... | Finds permission by name. If it founded returns permission id
@param string $permissionName
@return integer | [
"Finds",
"permission",
"by",
"name",
".",
"If",
"it",
"founded",
"returns",
"permission",
"id"
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/Models/Repository/PermissionRepository.php#L20-L35 | train |
potievdev/slim-rbac | src/migrations/20171210104049_create_role_permission.php | CreateRolePermission.change | public function change()
{
$rolePermissionTable = $this->table('role_permission', ['signed' => false]);
$rolePermissionTable->addColumn('role_id', 'integer', ['signed' => false])
->addColumn('permission_id', 'integer', ['signed' => false])
->addColumn('created_at', 'datetime')
->addIndex(['role_id', 'permission_id'], ['name' => 'idx_role_permission_unique', 'unique' => true])
->addForeignKey('role_id', 'role', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_role'])
->addForeignKey('permission_id', 'permission', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_permission'])
->create();
} | php | public function change()
{
$rolePermissionTable = $this->table('role_permission', ['signed' => false]);
$rolePermissionTable->addColumn('role_id', 'integer', ['signed' => false])
->addColumn('permission_id', 'integer', ['signed' => false])
->addColumn('created_at', 'datetime')
->addIndex(['role_id', 'permission_id'], ['name' => 'idx_role_permission_unique', 'unique' => true])
->addForeignKey('role_id', 'role', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_role'])
->addForeignKey('permission_id', 'permission', 'id', ['delete' => 'RESTRICT', 'constraint' => 'fk_role_permission_permission'])
->create();
} | [
"public",
"function",
"change",
"(",
")",
"{",
"$",
"rolePermissionTable",
"=",
"$",
"this",
"->",
"table",
"(",
"'role_permission'",
",",
"[",
"'signed'",
"=>",
"false",
"]",
")",
";",
"$",
"rolePermissionTable",
"->",
"addColumn",
"(",
"'role_id'",
",",
... | Create 'role_permission' table in database.
'role_id' with 'permission_id' creates unique index. | [
"Create",
"role_permission",
"table",
"in",
"database",
".",
"role_id",
"with",
"permission_id",
"creates",
"unique",
"index",
"."
] | 1c79649b7cc651d878c3dcfed73c7c858fd54345 | https://github.com/potievdev/slim-rbac/blob/1c79649b7cc651d878c3dcfed73c7c858fd54345/src/migrations/20171210104049_create_role_permission.php#L14-L25 | train |
azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.getRecipientVarsForNotificationsEmail | protected function getRecipientVarsForNotificationsEmail(RecipientInterface $recipient)
{
$recipientParams = array();
$recipientParams['recipient'] = $recipient;
$recipientParams['mode'] = $recipient->getNotificationMode();
return $recipientParams;
} | php | protected function getRecipientVarsForNotificationsEmail(RecipientInterface $recipient)
{
$recipientParams = array();
$recipientParams['recipient'] = $recipient;
$recipientParams['mode'] = $recipient->getNotificationMode();
return $recipientParams;
} | [
"protected",
"function",
"getRecipientVarsForNotificationsEmail",
"(",
"RecipientInterface",
"$",
"recipient",
")",
"{",
"$",
"recipientParams",
"=",
"array",
"(",
")",
";",
"$",
"recipientParams",
"[",
"'recipient'",
"]",
"=",
"$",
"recipient",
";",
"$",
"recipie... | Override this function to fill in any recipient-specific parameters that are required to
render the notifications-template or one of the notification-item-templates that
are rendered into the notifications-template.
@param RecipientInterface $recipient
@return array | [
"Override",
"this",
"function",
"to",
"fill",
"in",
"any",
"recipient",
"-",
"specific",
"parameters",
"that",
"are",
"required",
"to",
"render",
"the",
"notifications",
"-",
"template",
"or",
"one",
"of",
"the",
"notification",
"-",
"item",
"-",
"templates",
... | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L43-L50 | train |
azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.getRecipientSpecificNotificationsSubject | public function getRecipientSpecificNotificationsSubject($contentItems, RecipientInterface $recipient)
{
$count = sizeof($contentItems);
if (1 == $count) {
// get the content-item out of the boxed associative array => array(array('templateId' => contentItem))
$onlyItem = current(current($contentItems));
// get the title out of the notification in the contentItem
return $onlyItem['notification']->getTitle();
}
return $this->translatorService->transChoice('_az.email.notifications.subject.%count%', $count, array('%count%' => $count));
} | php | public function getRecipientSpecificNotificationsSubject($contentItems, RecipientInterface $recipient)
{
$count = sizeof($contentItems);
if (1 == $count) {
// get the content-item out of the boxed associative array => array(array('templateId' => contentItem))
$onlyItem = current(current($contentItems));
// get the title out of the notification in the contentItem
return $onlyItem['notification']->getTitle();
}
return $this->translatorService->transChoice('_az.email.notifications.subject.%count%', $count, array('%count%' => $count));
} | [
"public",
"function",
"getRecipientSpecificNotificationsSubject",
"(",
"$",
"contentItems",
",",
"RecipientInterface",
"$",
"recipient",
")",
"{",
"$",
"count",
"=",
"sizeof",
"(",
"$",
"contentItems",
")",
";",
"if",
"(",
"1",
"==",
"$",
"count",
")",
"{",
... | Get the subject for the notifications-email to send. Override this function to implement your custom subject-lines.
@param array of array $contentItems
@param RecipientInterface $recipient
@return string | [
"Get",
"the",
"subject",
"for",
"the",
"notifications",
"-",
"email",
"to",
"send",
".",
"Override",
"this",
"function",
"to",
"implement",
"your",
"custom",
"subject",
"-",
"lines",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L60-L72 | train |
azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.sendNotificationsFor | public function sendNotificationsFor($recipientId, $wrapperTemplateName, $params)
{
// get the recipient
$recipient = $this->recipientProvider->getRecipient($recipientId);
// get all Notification-Items for the recipient from the database
$notifications = $this->getNotificationsFor($recipient);
if (0 == sizeof($notifications)) {
return null;
}
// get the recipient specific parameters for the twig-templates
$recipientParams = $this->getRecipientVarsForNotificationsEmail($recipient);
$params = array_merge($recipientParams, $params);
// prepare the arrays with template and template-variables for each notification
$contentItems = array();
foreach ($notifications as $notification) {
// decode the $params from the json in the notification-entity
$itemVars = $notification->getVariables();
$itemVars = array_merge($params, $itemVars);
$itemVars['notification'] = $notification;
$itemVars['recipient'] = $recipient;
$itemTemplateName = $notification->getTemplate();
$contentItems[] = array($itemTemplateName => $itemVars);
}
// add the notifications to the params array so they will be rendered later
$params[self::CONTENT_ITEMS] = $contentItems;
$params['recipient'] = $recipient;
$params['_locale'] = $recipient->getPreferredLocale();
$subject = $this->getRecipientSpecificNotificationsSubject($contentItems, $recipient);
// send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $params, $wrapperTemplateName.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save the updated notifications
$this->setNotificationsAsSent($notifications);
return null;
}
return $recipient->getEmail();
} | php | public function sendNotificationsFor($recipientId, $wrapperTemplateName, $params)
{
// get the recipient
$recipient = $this->recipientProvider->getRecipient($recipientId);
// get all Notification-Items for the recipient from the database
$notifications = $this->getNotificationsFor($recipient);
if (0 == sizeof($notifications)) {
return null;
}
// get the recipient specific parameters for the twig-templates
$recipientParams = $this->getRecipientVarsForNotificationsEmail($recipient);
$params = array_merge($recipientParams, $params);
// prepare the arrays with template and template-variables for each notification
$contentItems = array();
foreach ($notifications as $notification) {
// decode the $params from the json in the notification-entity
$itemVars = $notification->getVariables();
$itemVars = array_merge($params, $itemVars);
$itemVars['notification'] = $notification;
$itemVars['recipient'] = $recipient;
$itemTemplateName = $notification->getTemplate();
$contentItems[] = array($itemTemplateName => $itemVars);
}
// add the notifications to the params array so they will be rendered later
$params[self::CONTENT_ITEMS] = $contentItems;
$params['recipient'] = $recipient;
$params['_locale'] = $recipient->getPreferredLocale();
$subject = $this->getRecipientSpecificNotificationsSubject($contentItems, $recipient);
// send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $params, $wrapperTemplateName.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save the updated notifications
$this->setNotificationsAsSent($notifications);
return null;
}
return $recipient->getEmail();
} | [
"public",
"function",
"sendNotificationsFor",
"(",
"$",
"recipientId",
",",
"$",
"wrapperTemplateName",
",",
"$",
"params",
")",
"{",
"// get the recipient",
"$",
"recipient",
"=",
"$",
"this",
"->",
"recipientProvider",
"->",
"getRecipient",
"(",
"$",
"recipientI... | Send the notifications-email for one recipient.
@param int $recipientId
@param string $wrapperTemplateName
@param array $params array of parameters for this recipient
@return string|null or the failed email addressess | [
"Send",
"the",
"notifications",
"-",
"email",
"for",
"one",
"recipient",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L315-L362 | train |
azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.sendNewsletterFor | public function sendNewsletterFor($recipientId, array $params, $wrapperTemplate)
{
$recipient = $this->recipientProvider->getRecipient($recipientId);
// create new array for each recipient.
$recipientParams = array_merge($params, $this->getRecipientSpecificNewsletterParams($recipient));
// get the recipient-specific contentItems of the newsletter
$recipientContentItems = $this->getRecipientSpecificNewsletterContentItems($recipient);
// merge the recipient-specific and the general content items. recipient-specific first/at the top!
$recipientParams[self::CONTENT_ITEMS] = $this->orderContentItems(array_merge($recipientContentItems, $params[self::CONTENT_ITEMS]));
$recipientParams['_locale'] = $recipient->getPreferredLocale();
if (0 == sizeof($recipientParams[self::CONTENT_ITEMS])) {
return $recipient->getEmail();
}
$subject = $this->getRecipientSpecificNewsletterSubject($params[self::CONTENT_ITEMS], $recipientContentItems, $params, $recipient, $recipient->getPreferredLocale());
// render and send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $recipientParams, $wrapperTemplate.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save that this recipient has recieved the newsletter
return null;
}
return $recipient->getEmail();
} | php | public function sendNewsletterFor($recipientId, array $params, $wrapperTemplate)
{
$recipient = $this->recipientProvider->getRecipient($recipientId);
// create new array for each recipient.
$recipientParams = array_merge($params, $this->getRecipientSpecificNewsletterParams($recipient));
// get the recipient-specific contentItems of the newsletter
$recipientContentItems = $this->getRecipientSpecificNewsletterContentItems($recipient);
// merge the recipient-specific and the general content items. recipient-specific first/at the top!
$recipientParams[self::CONTENT_ITEMS] = $this->orderContentItems(array_merge($recipientContentItems, $params[self::CONTENT_ITEMS]));
$recipientParams['_locale'] = $recipient->getPreferredLocale();
if (0 == sizeof($recipientParams[self::CONTENT_ITEMS])) {
return $recipient->getEmail();
}
$subject = $this->getRecipientSpecificNewsletterSubject($params[self::CONTENT_ITEMS], $recipientContentItems, $params, $recipient, $recipient->getPreferredLocale());
// render and send the email with the right wrapper-template
$sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $recipientParams, $wrapperTemplate.'.txt.twig', $recipient->getPreferredLocale());
if ($sent) {
// save that this recipient has recieved the newsletter
return null;
}
return $recipient->getEmail();
} | [
"public",
"function",
"sendNewsletterFor",
"(",
"$",
"recipientId",
",",
"array",
"$",
"params",
",",
"$",
"wrapperTemplate",
")",
"{",
"$",
"recipient",
"=",
"$",
"this",
"->",
"recipientProvider",
"->",
"getRecipient",
"(",
"$",
"recipientId",
")",
";",
"/... | Send the newsletter for one recipient.
@param int $recipientId
@param array $params params and contentItems that are the same for all recipients
@param string $wrapperTemplate
@return string|null or the failed email addressess | [
"Send",
"the",
"newsletter",
"for",
"one",
"recipient",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L405-L434 | train |
azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.getNotificationsFor | protected function getNotificationsFor(RecipientInterface $recipient)
{
// get the notification mode
$notificationMode = $recipient->getNotificationMode();
// get the date/time of the last notification
$lastNotificationDate = $this->getNotificationRepository()->getLastNotificationDate($recipient->getId());
$sendNotifications = false;
$timeDelta = time() - $lastNotificationDate->getTimestamp();
if (RecipientInterface::NOTIFICATION_MODE_IMMEDIATELY == $notificationMode) {
$sendNotifications = true;
} elseif (RecipientInterface::NOTIFICATION_MODE_HOURLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getHourInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_DAYLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getDayInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_NEVER == $notificationMode) {
$this->markAllNotificationsAsSentFarInThePast($recipient);
return array();
}
// regularly sent notifications now
if ($sendNotifications) {
$notifications = $this->getNotificationRepository()->getNotificationsToSend($recipient->getId());
// if notifications exist, that should be sent immediately, then send those now disregarding the users mailing-preferences.
} else {
$notifications = $this->getNotificationRepository()->getNotificationsToSendImmediately($recipient->getId());
}
return $notifications;
} | php | protected function getNotificationsFor(RecipientInterface $recipient)
{
// get the notification mode
$notificationMode = $recipient->getNotificationMode();
// get the date/time of the last notification
$lastNotificationDate = $this->getNotificationRepository()->getLastNotificationDate($recipient->getId());
$sendNotifications = false;
$timeDelta = time() - $lastNotificationDate->getTimestamp();
if (RecipientInterface::NOTIFICATION_MODE_IMMEDIATELY == $notificationMode) {
$sendNotifications = true;
} elseif (RecipientInterface::NOTIFICATION_MODE_HOURLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getHourInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_DAYLY == $notificationMode) {
$sendNotifications = ($timeDelta > $this->getDayInterval());
} elseif (RecipientInterface::NOTIFICATION_MODE_NEVER == $notificationMode) {
$this->markAllNotificationsAsSentFarInThePast($recipient);
return array();
}
// regularly sent notifications now
if ($sendNotifications) {
$notifications = $this->getNotificationRepository()->getNotificationsToSend($recipient->getId());
// if notifications exist, that should be sent immediately, then send those now disregarding the users mailing-preferences.
} else {
$notifications = $this->getNotificationRepository()->getNotificationsToSendImmediately($recipient->getId());
}
return $notifications;
} | [
"protected",
"function",
"getNotificationsFor",
"(",
"RecipientInterface",
"$",
"recipient",
")",
"{",
"// get the notification mode",
"$",
"notificationMode",
"=",
"$",
"recipient",
"->",
"getNotificationMode",
"(",
")",
";",
"// get the date/time of the last notification",
... | Get the Notifications that have not yet been sent yet.
Ordered by "template" and "title".
@param RecipientInterface $recipient
@return array of Notification | [
"Get",
"the",
"Notifications",
"that",
"have",
"not",
"yet",
"been",
"sent",
"yet",
".",
"Ordered",
"by",
"template",
"and",
"title",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L444-L477 | train |
azine/email-bundle | Services/AzineNotifierService.php | AzineNotifierService.addNotification | public function addNotification($recipientId, $title, $content, $template, $templateVars, $importance, $sendImmediately)
{
$notification = new Notification();
$notification->setRecipientId($recipientId);
$notification->setTitle($title);
$notification->setContent($content);
$notification->setTemplate($template);
$notification->setImportance($importance);
$notification->setSendImmediately($sendImmediately);
$notification->setVariables($templateVars);
$this->managerRegistry->getManager()->persist($notification);
$this->managerRegistry->getManager()->flush($notification);
return $notification;
} | php | public function addNotification($recipientId, $title, $content, $template, $templateVars, $importance, $sendImmediately)
{
$notification = new Notification();
$notification->setRecipientId($recipientId);
$notification->setTitle($title);
$notification->setContent($content);
$notification->setTemplate($template);
$notification->setImportance($importance);
$notification->setSendImmediately($sendImmediately);
$notification->setVariables($templateVars);
$this->managerRegistry->getManager()->persist($notification);
$this->managerRegistry->getManager()->flush($notification);
return $notification;
} | [
"public",
"function",
"addNotification",
"(",
"$",
"recipientId",
",",
"$",
"title",
",",
"$",
"content",
",",
"$",
"template",
",",
"$",
"templateVars",
",",
"$",
"importance",
",",
"$",
"sendImmediately",
")",
"{",
"$",
"notification",
"=",
"new",
"Notif... | Convenience-function to add and save a Notification-entity.
@param int $recipientId the ID of the recipient of this notification => see RecipientProvider.getRecipient($id)
@param string $title the title of the notification. depending on the recipients settings, multiple notifications are sent in one email.
@param string $content the content of the notification
@param string $template the twig-template to render the notification with
@param array $templateVars the parameters used in the twig-template, 'notification' => Notification and 'recipient' => RecipientInterface will be added to this array when rendering the twig-template
@param int $importance important messages are at the top of the notification-emails, un-important at the bottom
@param bool $sendImmediately whether or not to ignore the recipients mailing-preference and send the notification a.s.a.p.
@return Notification | [
"Convenience",
"-",
"function",
"to",
"add",
"and",
"save",
"a",
"Notification",
"-",
"entity",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineNotifierService.php#L564-L578 | train |
azine/email-bundle | Entity/Repositories/SentEmailRepository.php | SentEmailRepository.search | public function search($searchParams = array())
{
$queryBuilder = $this->createQueryBuilder('e');
if (!empty($searchParams)) {
$searchAttributes = array(
'recipients',
'template',
'sent',
'variables',
'token',
);
foreach ($searchAttributes as $attribute) {
if (empty($searchParams[$attribute])) {
continue;
}
$attributeValue = $searchParams[$attribute];
$queryBuilder->andWhere('e.'.$attribute.' LIKE :'.$attribute)
->setParameter($attribute, '%'.$attributeValue.'%');
}
}
return $queryBuilder->getQuery();
} | php | public function search($searchParams = array())
{
$queryBuilder = $this->createQueryBuilder('e');
if (!empty($searchParams)) {
$searchAttributes = array(
'recipients',
'template',
'sent',
'variables',
'token',
);
foreach ($searchAttributes as $attribute) {
if (empty($searchParams[$attribute])) {
continue;
}
$attributeValue = $searchParams[$attribute];
$queryBuilder->andWhere('e.'.$attribute.' LIKE :'.$attribute)
->setParameter($attribute, '%'.$attributeValue.'%');
}
}
return $queryBuilder->getQuery();
} | [
"public",
"function",
"search",
"(",
"$",
"searchParams",
"=",
"array",
"(",
")",
")",
"{",
"$",
"queryBuilder",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'e'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"searchParams",
")",
")",
"{",
"$"... | Search SentEmails by search params.
@param $searchParams
@return Query | [
"Search",
"SentEmails",
"by",
"search",
"params",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/SentEmailRepository.php#L23-L49 | train |
azine/email-bundle | Services/AzineTemplateProvider.php | AzineTemplateProvider.makeImagePathsWebRelative | public function makeImagePathsWebRelative(array $emailVars, $locale)
{
foreach ($emailVars as $key => $value) {
if (is_string($value) && is_file($value)) {
// check if the file is in an allowed_images_folder
$folderKey = $this->isFileAllowed($value);
if (false !== $folderKey) {
// replace the fs-path with the web-path
$fsPathToReplace = $this->getFolderFrom($folderKey);
$filename = substr($value, strlen($fsPathToReplace));
$newValue = $this->getRouter()->generate('azine_email_serve_template_image', array('folderKey' => $folderKey, 'filename' => urlencode($filename), '_locale' => $locale));
$emailVars[$key] = $newValue;
}
} elseif (is_array($value)) {
$emailVars[$key] = $this->makeImagePathsWebRelative($value, $locale);
}
}
return $emailVars;
} | php | public function makeImagePathsWebRelative(array $emailVars, $locale)
{
foreach ($emailVars as $key => $value) {
if (is_string($value) && is_file($value)) {
// check if the file is in an allowed_images_folder
$folderKey = $this->isFileAllowed($value);
if (false !== $folderKey) {
// replace the fs-path with the web-path
$fsPathToReplace = $this->getFolderFrom($folderKey);
$filename = substr($value, strlen($fsPathToReplace));
$newValue = $this->getRouter()->generate('azine_email_serve_template_image', array('folderKey' => $folderKey, 'filename' => urlencode($filename), '_locale' => $locale));
$emailVars[$key] = $newValue;
}
} elseif (is_array($value)) {
$emailVars[$key] = $this->makeImagePathsWebRelative($value, $locale);
}
}
return $emailVars;
} | [
"public",
"function",
"makeImagePathsWebRelative",
"(",
"array",
"$",
"emailVars",
",",
"$",
"locale",
")",
"{",
"foreach",
"(",
"$",
"emailVars",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
"&&",
"is... | Recursively replace all absolute image-file-paths with relative web-paths.
@param array $emailVars
@param string $locale
@return array | [
"Recursively",
"replace",
"all",
"absolute",
"image",
"-",
"file",
"-",
"paths",
"with",
"relative",
"web",
"-",
"paths",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTemplateProvider.php#L491-L510 | train |
azine/email-bundle | Services/AzineEmailTwigExtension.php | AzineEmailTwigExtension.addCampaignParamsToAllUrls | public function addCampaignParamsToAllUrls($html, $campaignParams)
{
$urlPattern = '/(href=[\'|"])(http[s]?\:\/\/\S*)([\'|"])/';
$filteredHtml = preg_replace_callback($urlPattern, function ($matches) use ($campaignParams) {
$start = $matches[1];
$url = $matches[2];
$end = $matches[3];
$domain = parse_url($url, PHP_URL_HOST);
// if the url is not in the list of domains to track then
if (false === array_search($domain, $this->domainsToTrack)) {
// don't append tracking parameters to the url
return $start.$url.$end;
}
// avoid duplicate params and don't replace existing params
$params = array();
foreach ($campaignParams as $nextKey => $nextValue) {
if (false === strpos($url, $nextKey)) {
$params[$nextKey] = $nextValue;
}
}
$urlParams = http_build_query($params);
if (false === strpos($url, '?')) {
$urlParams = '?'.$urlParams;
} else {
$urlParams = '&'.$urlParams;
}
$replacement = $start.$url.$urlParams.$end;
return $replacement;
}, $html);
return $filteredHtml;
} | php | public function addCampaignParamsToAllUrls($html, $campaignParams)
{
$urlPattern = '/(href=[\'|"])(http[s]?\:\/\/\S*)([\'|"])/';
$filteredHtml = preg_replace_callback($urlPattern, function ($matches) use ($campaignParams) {
$start = $matches[1];
$url = $matches[2];
$end = $matches[3];
$domain = parse_url($url, PHP_URL_HOST);
// if the url is not in the list of domains to track then
if (false === array_search($domain, $this->domainsToTrack)) {
// don't append tracking parameters to the url
return $start.$url.$end;
}
// avoid duplicate params and don't replace existing params
$params = array();
foreach ($campaignParams as $nextKey => $nextValue) {
if (false === strpos($url, $nextKey)) {
$params[$nextKey] = $nextValue;
}
}
$urlParams = http_build_query($params);
if (false === strpos($url, '?')) {
$urlParams = '?'.$urlParams;
} else {
$urlParams = '&'.$urlParams;
}
$replacement = $start.$url.$urlParams.$end;
return $replacement;
}, $html);
return $filteredHtml;
} | [
"public",
"function",
"addCampaignParamsToAllUrls",
"(",
"$",
"html",
",",
"$",
"campaignParams",
")",
"{",
"$",
"urlPattern",
"=",
"'/(href=[\\'|\"])(http[s]?\\:\\/\\/\\S*)([\\'|\"])/'",
";",
"$",
"filteredHtml",
"=",
"preg_replace_callback",
"(",
"$",
"urlPattern",
",... | Add the campaign-parameters to all URLs in the html.
@param string $html
@param array $campaignParams
@return string | [
"Add",
"the",
"campaign",
"-",
"parameters",
"to",
"all",
"URLs",
"in",
"the",
"html",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineEmailTwigExtension.php#L112-L150 | train |
azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.getNotificationsToSend | public function getNotificationsToSend($recipientId)
{
$qb = $this->createQueryBuilder('n')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->orderBy('n.importance', 'desc')
->orderBy('n.template', 'asc')
->orderBy('n.title', 'asc');
$notifications = $qb->getQuery()->execute();
return $notifications;
} | php | public function getNotificationsToSend($recipientId)
{
$qb = $this->createQueryBuilder('n')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->orderBy('n.importance', 'desc')
->orderBy('n.template', 'asc')
->orderBy('n.title', 'asc');
$notifications = $qb->getQuery()->execute();
return $notifications;
} | [
"public",
"function",
"getNotificationsToSend",
"(",
"$",
"recipientId",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'n'",
")",
"->",
"andWhere",
"(",
"'n.sent is null'",
")",
"->",
"andWhere",
"(",
"'n.recipient_id = :recipientId'",
... | Get all notifications that should be sent.
@param $recipientId
@return array of Notification | [
"Get",
"all",
"notifications",
"that",
"should",
"be",
"sent",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L22-L34 | train |
azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.getNotificationRecipientIds | public function getNotificationRecipientIds()
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('n.recipient_id')
->distinct()
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.sent is null');
$results = $qb->getQuery()->execute();
$ids = array();
foreach ($results as $next) {
$ids[] = $next['recipient_id'];
}
return $ids;
} | php | public function getNotificationRecipientIds()
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('n.recipient_id')
->distinct()
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.sent is null');
$results = $qb->getQuery()->execute();
$ids = array();
foreach ($results as $next) {
$ids[] = $next['recipient_id'];
}
return $ids;
} | [
"public",
"function",
"getNotificationRecipientIds",
"(",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
"->",
"select",
"(",
"'n.recipient_id'",
")",
"->",
"distinct",
"(",
")",
"->",
"from",... | Get all recipients with unsent Notifications.
@return array | [
"Get",
"all",
"recipients",
"with",
"unsent",
"Notifications",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L63-L78 | train |
azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.markAllNotificationsAsSentFarInThePast | public function markAllNotificationsAsSentFarInThePast($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->update("Azine\EmailBundle\Entity\Notification", 'n')
->set('n.sent', ':farInThePast')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->setParameter('farInThePast', new \DateTime('1900-01-01'));
$qb->getQuery()->execute();
} | php | public function markAllNotificationsAsSentFarInThePast($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->update("Azine\EmailBundle\Entity\Notification", 'n')
->set('n.sent', ':farInThePast')
->andWhere('n.sent is null')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId)
->setParameter('farInThePast', new \DateTime('1900-01-01'));
$qb->getQuery()->execute();
} | [
"public",
"function",
"markAllNotificationsAsSentFarInThePast",
"(",
"$",
"recipientId",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
"->",
"update",
"(",
"\"Azine\\EmailBundle\\Entity\\Notification\"... | Mark all notifications as sent "far in the past". This is used for users that don't want to receive any notifications.
@param $recipientId | [
"Mark",
"all",
"notifications",
"as",
"sent",
"far",
"in",
"the",
"past",
".",
"This",
"is",
"used",
"for",
"users",
"that",
"don",
"t",
"want",
"to",
"receive",
"any",
"notifications",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L85-L95 | train |
azine/email-bundle | Entity/Repositories/NotificationRepository.php | NotificationRepository.getLastNotificationDate | public function getLastNotificationDate($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('max(n.sent)')
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId);
$results = $qb->getQuery()->execute();
if (null === $results[0][1]) {
// the user has not received any notifications yet ever
$lastNotification = new \DateTime('@0');
} else {
$lastNotification = new \DateTime($results[0][1]);
}
return $lastNotification;
} | php | public function getLastNotificationDate($recipientId)
{
$qb = $this->getEntityManager()->createQueryBuilder()
->select('max(n.sent)')
->from("Azine\EmailBundle\Entity\Notification", 'n')
->andWhere('n.recipient_id = :recipientId')
->setParameter('recipientId', $recipientId);
$results = $qb->getQuery()->execute();
if (null === $results[0][1]) {
// the user has not received any notifications yet ever
$lastNotification = new \DateTime('@0');
} else {
$lastNotification = new \DateTime($results[0][1]);
}
return $lastNotification;
} | [
"public",
"function",
"getLastNotificationDate",
"(",
"$",
"recipientId",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
"->",
"select",
"(",
"'max(n.sent)'",
")",
"->",
"from",
"(",
"\"Azine\... | Get the \DateTime of the last Notification that has been sent.
@param $recipientId
@return \DateTime | [
"Get",
"the",
"\\",
"DateTime",
"of",
"the",
"last",
"Notification",
"that",
"has",
"been",
"sent",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Entity/Repositories/NotificationRepository.php#L104-L120 | train |
azine/email-bundle | Services/AzineEmailOpenTrackingCodeBuilder.php | AzineEmailOpenTrackingCodeBuilder.merge | protected function merge($to, $cc, $bcc)
{
if ($to && !is_array($to)) {
$to = array($to);
}
if (!is_array($cc)) {
$cc = array($cc);
}
if (!is_array($bcc)) {
$bcc = array($bcc);
}
$all = array_merge($to, $cc, $bcc);
return implode(';', $all);
} | php | protected function merge($to, $cc, $bcc)
{
if ($to && !is_array($to)) {
$to = array($to);
}
if (!is_array($cc)) {
$cc = array($cc);
}
if (!is_array($bcc)) {
$bcc = array($bcc);
}
$all = array_merge($to, $cc, $bcc);
return implode(';', $all);
} | [
"protected",
"function",
"merge",
"(",
"$",
"to",
",",
"$",
"cc",
",",
"$",
"bcc",
")",
"{",
"if",
"(",
"$",
"to",
"&&",
"!",
"is_array",
"(",
"$",
"to",
")",
")",
"{",
"$",
"to",
"=",
"array",
"(",
"$",
"to",
")",
";",
"}",
"if",
"(",
"!... | concatenate all recipients into an array and implode with ';' to a string.
@param string|array $to
@param string|array $cc
@param string|array $bcc
@return string | [
"concatenate",
"all",
"recipients",
"into",
"an",
"array",
"and",
"implode",
"with",
";",
"to",
"a",
"string",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineEmailOpenTrackingCodeBuilder.php#L107-L121 | train |
azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.indexAction | public function indexAction(Request $request)
{
$customEmail = $request->get('customEmail', 'custom@email.com');
$templates = $this->get('azine_email_web_view_service')->getTemplatesForWebPreView();
$emails = $this->get('azine_email_web_view_service')->getTestMailAccounts();
return $this->get('templating')
->renderResponse('AzineEmailBundle:Webview:index.html.twig',
array(
'customEmail' => $customEmail,
'templates' => $templates,
'emails' => $emails,
));
} | php | public function indexAction(Request $request)
{
$customEmail = $request->get('customEmail', 'custom@email.com');
$templates = $this->get('azine_email_web_view_service')->getTemplatesForWebPreView();
$emails = $this->get('azine_email_web_view_service')->getTestMailAccounts();
return $this->get('templating')
->renderResponse('AzineEmailBundle:Webview:index.html.twig',
array(
'customEmail' => $customEmail,
'templates' => $templates,
'emails' => $emails,
));
} | [
"public",
"function",
"indexAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"customEmail",
"=",
"$",
"request",
"->",
"get",
"(",
"'customEmail'",
",",
"'custom@email.com'",
")",
";",
"$",
"templates",
"=",
"$",
"this",
"->",
"get",
"(",
"'azine_em... | Show a set of options to view html- and text-versions of email in the browser and send them as emails to test-accounts. | [
"Show",
"a",
"set",
"of",
"options",
"to",
"view",
"html",
"-",
"and",
"text",
"-",
"versions",
"of",
"email",
"in",
"the",
"browser",
"and",
"send",
"them",
"as",
"emails",
"to",
"test",
"-",
"accounts",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L35-L48 | train |
azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.webPreViewAction | public function webPreViewAction(Request $request, $template, $format = null)
{
if ('txt' !== $format) {
$format = 'html';
}
$template = urldecode($template);
$locale = $request->getLocale();
// merge request vars with dummyVars, but make sure request vars remain as they are.
$emailVars = array_merge(array(), $request->query->all());
$emailVars = $this->get('azine_email_web_view_service')->getDummyVarsFor($template, $locale, $emailVars);
$emailVars = array_merge($emailVars, $request->query->all());
// add the styles
$emailVars = $this->getTemplateProviderService()->addTemplateVariablesFor($template, $emailVars);
// add the from-email for the footer-text
if (!array_key_exists('fromEmail', $emailVars)) {
$noReply = $this->getParameter('azine_email_no_reply');
$emailVars['fromEmail'] = $noReply['email'];
$emailVars['fromName'] = $noReply['name'];
}
// set the emailLocale for the templates
$emailVars['emailLocale'] = $locale;
// replace absolute image-paths with relative ones.
$emailVars = $this->getTemplateProviderService()->makeImagePathsWebRelative($emailVars, $locale);
// add code-snippets
$emailVars = $this->getTemplateProviderService()->addTemplateSnippetsWithImagesFor($template, $emailVars, $locale);
// render & return email
$response = $this->renderResponse("$template.$format.twig", $emailVars);
// add campaign tracking params
$campaignParams = $this->getTemplateProviderService()->getCampaignParamsFor($template, $emailVars);
$campaignParams['utm_medium'] = 'webPreview';
if (sizeof($campaignParams) > 0) {
$htmlBody = $response->getContent();
$htmlBody = $this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($htmlBody, $campaignParams);
$emailOpenTrackingCodeBuilder = $this->get('azine_email_email_open_tracking_code_builder');
if ($emailOpenTrackingCodeBuilder) {
// add an image at the end of the html tag with the tracking-params to track email-opens
$imgTrackingCode = $emailOpenTrackingCodeBuilder->getTrackingImgCode($template, $campaignParams, $emailVars, 'dummy', 'dummy@from.email.com', null, null);
if ($imgTrackingCode && strlen($imgTrackingCode) > 0) {
// replace the tracking url, so no request is made to the real tracking system.
$imgTrackingCode = str_replace('://', '://webview-dummy-domain.', $imgTrackingCode);
$htmlCloseTagPosition = strpos($htmlBody, '</html>');
$htmlBody = substr_replace($htmlBody, $imgTrackingCode, $htmlCloseTagPosition, 0);
}
}
$response->setContent($htmlBody);
}
// if the requested format is txt, remove the html-part
if ('txt' == $format) {
// set the correct content-type
$response->headers->set('Content-Type', 'text/plain');
// cut away the html-part
$content = $response->getContent();
$textEnd = stripos($content, '<!doctype');
$response->setContent(substr($content, 0, $textEnd));
}
return $response;
} | php | public function webPreViewAction(Request $request, $template, $format = null)
{
if ('txt' !== $format) {
$format = 'html';
}
$template = urldecode($template);
$locale = $request->getLocale();
// merge request vars with dummyVars, but make sure request vars remain as they are.
$emailVars = array_merge(array(), $request->query->all());
$emailVars = $this->get('azine_email_web_view_service')->getDummyVarsFor($template, $locale, $emailVars);
$emailVars = array_merge($emailVars, $request->query->all());
// add the styles
$emailVars = $this->getTemplateProviderService()->addTemplateVariablesFor($template, $emailVars);
// add the from-email for the footer-text
if (!array_key_exists('fromEmail', $emailVars)) {
$noReply = $this->getParameter('azine_email_no_reply');
$emailVars['fromEmail'] = $noReply['email'];
$emailVars['fromName'] = $noReply['name'];
}
// set the emailLocale for the templates
$emailVars['emailLocale'] = $locale;
// replace absolute image-paths with relative ones.
$emailVars = $this->getTemplateProviderService()->makeImagePathsWebRelative($emailVars, $locale);
// add code-snippets
$emailVars = $this->getTemplateProviderService()->addTemplateSnippetsWithImagesFor($template, $emailVars, $locale);
// render & return email
$response = $this->renderResponse("$template.$format.twig", $emailVars);
// add campaign tracking params
$campaignParams = $this->getTemplateProviderService()->getCampaignParamsFor($template, $emailVars);
$campaignParams['utm_medium'] = 'webPreview';
if (sizeof($campaignParams) > 0) {
$htmlBody = $response->getContent();
$htmlBody = $this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($htmlBody, $campaignParams);
$emailOpenTrackingCodeBuilder = $this->get('azine_email_email_open_tracking_code_builder');
if ($emailOpenTrackingCodeBuilder) {
// add an image at the end of the html tag with the tracking-params to track email-opens
$imgTrackingCode = $emailOpenTrackingCodeBuilder->getTrackingImgCode($template, $campaignParams, $emailVars, 'dummy', 'dummy@from.email.com', null, null);
if ($imgTrackingCode && strlen($imgTrackingCode) > 0) {
// replace the tracking url, so no request is made to the real tracking system.
$imgTrackingCode = str_replace('://', '://webview-dummy-domain.', $imgTrackingCode);
$htmlCloseTagPosition = strpos($htmlBody, '</html>');
$htmlBody = substr_replace($htmlBody, $imgTrackingCode, $htmlCloseTagPosition, 0);
}
}
$response->setContent($htmlBody);
}
// if the requested format is txt, remove the html-part
if ('txt' == $format) {
// set the correct content-type
$response->headers->set('Content-Type', 'text/plain');
// cut away the html-part
$content = $response->getContent();
$textEnd = stripos($content, '<!doctype');
$response->setContent(substr($content, 0, $textEnd));
}
return $response;
} | [
"public",
"function",
"webPreViewAction",
"(",
"Request",
"$",
"request",
",",
"$",
"template",
",",
"$",
"format",
"=",
"null",
")",
"{",
"if",
"(",
"'txt'",
"!==",
"$",
"format",
")",
"{",
"$",
"format",
"=",
"'html'",
";",
"}",
"$",
"template",
"=... | Show a web-preview-version of an email-template, filled with dummy-content.
@param string $format
@return Response | [
"Show",
"a",
"web",
"-",
"preview",
"-",
"version",
"of",
"an",
"email",
"-",
"template",
"filled",
"with",
"dummy",
"-",
"content",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L57-L127 | train |
azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.webViewAction | public function webViewAction(Request $request, $token)
{
// find email recipients, template & params
$sentEmail = $this->getSentEmailForToken($token);
// check if the sent email is available
if (null !== $sentEmail) {
// check if the current user is allowed to see the email
if ($this->userIsAllowedToSeeThisMail($sentEmail)) {
$template = $sentEmail->getTemplate();
$emailVars = $sentEmail->getVariables();
// re-attach all entities to the EntityManager.
$this->reAttachAllEntities($emailVars);
// remove the web-view-token from the param-array
$templateProvider = $this->getTemplateProviderService();
unset($emailVars[$templateProvider->getWebViewTokenId()]);
// render & return email
$response = $this->renderResponse("$template.html.twig", $emailVars);
$campaignParams = $templateProvider->getCampaignParamsFor($template, $emailVars);
if (null != $campaignParams && sizeof($campaignParams) > 0) {
$response->setContent($this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($response->getContent(), $campaignParams));
}
return $response;
// if the user is not allowed to see this mail
}
$msg = $this->get('translator')->trans('web.pre.view.test.mail.access.denied');
throw new AccessDeniedException($msg);
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->renderResponse('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | php | public function webViewAction(Request $request, $token)
{
// find email recipients, template & params
$sentEmail = $this->getSentEmailForToken($token);
// check if the sent email is available
if (null !== $sentEmail) {
// check if the current user is allowed to see the email
if ($this->userIsAllowedToSeeThisMail($sentEmail)) {
$template = $sentEmail->getTemplate();
$emailVars = $sentEmail->getVariables();
// re-attach all entities to the EntityManager.
$this->reAttachAllEntities($emailVars);
// remove the web-view-token from the param-array
$templateProvider = $this->getTemplateProviderService();
unset($emailVars[$templateProvider->getWebViewTokenId()]);
// render & return email
$response = $this->renderResponse("$template.html.twig", $emailVars);
$campaignParams = $templateProvider->getCampaignParamsFor($template, $emailVars);
if (null != $campaignParams && sizeof($campaignParams) > 0) {
$response->setContent($this->get('azine.email.bundle.twig.filters')->addCampaignParamsToAllUrls($response->getContent(), $campaignParams));
}
return $response;
// if the user is not allowed to see this mail
}
$msg = $this->get('translator')->trans('web.pre.view.test.mail.access.denied');
throw new AccessDeniedException($msg);
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->renderResponse('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | [
"public",
"function",
"webViewAction",
"(",
"Request",
"$",
"request",
",",
"$",
"token",
")",
"{",
"// find email recipients, template & params",
"$",
"sentEmail",
"=",
"$",
"this",
"->",
"getSentEmailForToken",
"(",
"$",
"token",
")",
";",
"// check if the sent em... | Show a web-version of an email that has been sent to recipients and has been stored in the database.
@param Request $request
@param string $token
@return Response | [
"Show",
"a",
"web",
"-",
"version",
"of",
"an",
"email",
"that",
"has",
"been",
"sent",
"to",
"recipients",
"and",
"has",
"been",
"stored",
"in",
"the",
"database",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L137-L179 | train |
azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.userIsAllowedToSeeThisMail | private function userIsAllowedToSeeThisMail(SentEmail $mail)
{
$recipients = $mail->getRecipients();
// it is a public email
if (null === $recipients) {
return true;
}
// get the current user
$currentUser = null;
if (!$this->has('security.token_storage')) {
// @codeCoverageIgnoreStart
throw new \LogicException('The SecurityBundle is not registered in your application.');
// @codeCoverageIgnoreEnd
}
$token = $this->get('security.token_storage')->getToken();
// check if the token is not null and the user in the token an object
if ($token instanceof TokenInterface && is_object($token->getUser())) {
$currentUser = $token->getUser();
}
// it is not a public email, and a user is logged in
if (null !== $currentUser) {
// the user is among the recipients
if (false !== array_search($currentUser->getEmail(), $recipients)) {
return true;
}
// the user is admin
if ($currentUser->hasRole('ROLE_ADMIN')) {
return true;
}
}
// not public email, but
// - there is no user, or
// - the user is not among the recipients and
// - the user not an admin-user either
return false;
} | php | private function userIsAllowedToSeeThisMail(SentEmail $mail)
{
$recipients = $mail->getRecipients();
// it is a public email
if (null === $recipients) {
return true;
}
// get the current user
$currentUser = null;
if (!$this->has('security.token_storage')) {
// @codeCoverageIgnoreStart
throw new \LogicException('The SecurityBundle is not registered in your application.');
// @codeCoverageIgnoreEnd
}
$token = $this->get('security.token_storage')->getToken();
// check if the token is not null and the user in the token an object
if ($token instanceof TokenInterface && is_object($token->getUser())) {
$currentUser = $token->getUser();
}
// it is not a public email, and a user is logged in
if (null !== $currentUser) {
// the user is among the recipients
if (false !== array_search($currentUser->getEmail(), $recipients)) {
return true;
}
// the user is admin
if ($currentUser->hasRole('ROLE_ADMIN')) {
return true;
}
}
// not public email, but
// - there is no user, or
// - the user is not among the recipients and
// - the user not an admin-user either
return false;
} | [
"private",
"function",
"userIsAllowedToSeeThisMail",
"(",
"SentEmail",
"$",
"mail",
")",
"{",
"$",
"recipients",
"=",
"$",
"mail",
"->",
"getRecipients",
"(",
")",
";",
"// it is a public email",
"if",
"(",
"null",
"===",
"$",
"recipients",
")",
"{",
"return",... | Check if the user is allowed to see the email.
=> the mail is public or the user is among the recipients or the user is an admin.
@param SentEmail $mail
@return bool | [
"Check",
"if",
"the",
"user",
"is",
"allowed",
"to",
"see",
"the",
"email",
".",
"=",
">",
"the",
"mail",
"is",
"public",
"or",
"the",
"user",
"is",
"among",
"the",
"recipients",
"or",
"the",
"user",
"is",
"an",
"admin",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L189-L230 | train |
azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.serveImageAction | public function serveImageAction(Request $request, $folderKey, $filename)
{
$folder = $this->getTemplateProviderService()->getFolderFrom($folderKey);
if (false !== $folder) {
$fullPath = $folder.urldecode($filename);
$response = BinaryFileResponse::create($fullPath);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
$response->headers->set('Content-Type', 'image');
return $response;
}
throw new FileNotFoundException($filename);
} | php | public function serveImageAction(Request $request, $folderKey, $filename)
{
$folder = $this->getTemplateProviderService()->getFolderFrom($folderKey);
if (false !== $folder) {
$fullPath = $folder.urldecode($filename);
$response = BinaryFileResponse::create($fullPath);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
$response->headers->set('Content-Type', 'image');
return $response;
}
throw new FileNotFoundException($filename);
} | [
"public",
"function",
"serveImageAction",
"(",
"Request",
"$",
"request",
",",
"$",
"folderKey",
",",
"$",
"filename",
")",
"{",
"$",
"folder",
"=",
"$",
"this",
"->",
"getTemplateProviderService",
"(",
")",
"->",
"getFolderFrom",
"(",
"$",
"folderKey",
")",... | Serve the image from the templates-folder.
@param Request $request
@param string $folderKey
@param string $filename
@return BinaryFileResponse | [
"Serve",
"the",
"image",
"from",
"the",
"templates",
"-",
"folder",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L273-L286 | train |
azine/email-bundle | Controller/AzineEmailTemplateController.php | AzineEmailTemplateController.checkSpamScoreOfSentEmailAction | public function checkSpamScoreOfSentEmailAction(Request $request)
{
$msgString = $request->get('emailSource');
$spamReport = $this->getSpamIndexReport($msgString);
$spamInfo = '';
if (is_array($spamReport)) {
if (array_key_exists('curlHttpCode', $spamReport) && 200 == $spamReport['curlHttpCode'] && $spamReport['success'] && array_key_exists('score', $spamReport)) {
$spamScore = $spamReport['score'];
$spamInfo = "SpamScore: $spamScore! \n".$spamReport['report'];
//@codeCoverageIgnoreStart
// this only happens if the spam-check-server has a problem / is not responding
} else {
if (array_key_exists('curlHttpCode', $spamReport) && array_key_exists('curlError', $spamReport) && array_key_exists('message', $spamReport)) {
$spamInfo = 'Getting the spam-info failed.
HttpCode: '.$spamReport['curlHttpCode'].'
cURL-Error: '.$spamReport['curlError'].'
SpamReportMsg: '.$spamReport['message'];
} elseif (null !== $spamReport && is_array($spamReport)) {
$spamInfo = 'Getting the spam-info failed. This was returned:
---Start----------------------------------------------
'.implode(";\n", $spamReport).'
---End------------------------------------------------';
}
//@codeCoverageIgnoreEnd
}
}
return new JsonResponse(array('result' => $spamInfo));
} | php | public function checkSpamScoreOfSentEmailAction(Request $request)
{
$msgString = $request->get('emailSource');
$spamReport = $this->getSpamIndexReport($msgString);
$spamInfo = '';
if (is_array($spamReport)) {
if (array_key_exists('curlHttpCode', $spamReport) && 200 == $spamReport['curlHttpCode'] && $spamReport['success'] && array_key_exists('score', $spamReport)) {
$spamScore = $spamReport['score'];
$spamInfo = "SpamScore: $spamScore! \n".$spamReport['report'];
//@codeCoverageIgnoreStart
// this only happens if the spam-check-server has a problem / is not responding
} else {
if (array_key_exists('curlHttpCode', $spamReport) && array_key_exists('curlError', $spamReport) && array_key_exists('message', $spamReport)) {
$spamInfo = 'Getting the spam-info failed.
HttpCode: '.$spamReport['curlHttpCode'].'
cURL-Error: '.$spamReport['curlError'].'
SpamReportMsg: '.$spamReport['message'];
} elseif (null !== $spamReport && is_array($spamReport)) {
$spamInfo = 'Getting the spam-info failed. This was returned:
---Start----------------------------------------------
'.implode(";\n", $spamReport).'
---End------------------------------------------------';
}
//@codeCoverageIgnoreEnd
}
}
return new JsonResponse(array('result' => $spamInfo));
} | [
"public",
"function",
"checkSpamScoreOfSentEmailAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"msgString",
"=",
"$",
"request",
"->",
"get",
"(",
"'emailSource'",
")",
";",
"$",
"spamReport",
"=",
"$",
"this",
"->",
"getSpamIndexReport",
"(",
"$",
... | Ajax action to check the spam-score for the pasted email-source. | [
"Ajax",
"action",
"to",
"check",
"the",
"spam",
"-",
"score",
"for",
"the",
"pasted",
"email",
"-",
"source",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailTemplateController.php#L455-L483 | train |
azine/email-bundle | Controller/AzineEmailController.php | AzineEmailController.emailsDashboardAction | public function emailsDashboardAction(Request $request)
{
$form = $this->createForm(SentEmailType::class);
$form->handleRequest($request);
$searchParams = $form->getData();
/** @var SentEmailRepository $repository */
$repository = $this->getDoctrine()->getManager()->getRepository(SentEmail::class);
$query = $repository->search($searchParams);
$pagination = $this->get('knp_paginator')->paginate($query, $request->query->getInt('page', 1));
return $this->render('AzineEmailBundle::emailsDashboard.html.twig',
array('form' => $form->createView(), 'pagination' => $pagination));
} | php | public function emailsDashboardAction(Request $request)
{
$form = $this->createForm(SentEmailType::class);
$form->handleRequest($request);
$searchParams = $form->getData();
/** @var SentEmailRepository $repository */
$repository = $this->getDoctrine()->getManager()->getRepository(SentEmail::class);
$query = $repository->search($searchParams);
$pagination = $this->get('knp_paginator')->paginate($query, $request->query->getInt('page', 1));
return $this->render('AzineEmailBundle::emailsDashboard.html.twig',
array('form' => $form->createView(), 'pagination' => $pagination));
} | [
"public",
"function",
"emailsDashboardAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"createForm",
"(",
"SentEmailType",
"::",
"class",
")",
";",
"$",
"form",
"->",
"handleRequest",
"(",
"$",
"request",
")",
";",
... | Displays an Emails-Dashboard with filters for each property of SentEmails entity and links to
emailDetailsByToken & webView actions for each email.
@param Request $request
@return Response | [
"Displays",
"an",
"Emails",
"-",
"Dashboard",
"with",
"filters",
"for",
"each",
"property",
"of",
"SentEmails",
"entity",
"and",
"links",
"to",
"emailDetailsByToken",
"&",
"webView",
"actions",
"for",
"each",
"email",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailController.php#L25-L37 | train |
azine/email-bundle | Controller/AzineEmailController.php | AzineEmailController.emailDetailsByTokenAction | public function emailDetailsByTokenAction(Request $request, $token)
{
$email = $this->getDoctrine()->getManager()->getRepository(SentEmail::class)
->findOneByToken($token);
if ($email instanceof SentEmail) {
$recipients = implode(', ', $email->getRecipients());
$variables = implode(', ', array_keys($email->getVariables()));
return $this->render('AzineEmailBundle::sentEmailDetails.html.twig',
array('email' => $email, 'recipients' => $recipients, 'variables' => $variables));
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->render('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | php | public function emailDetailsByTokenAction(Request $request, $token)
{
$email = $this->getDoctrine()->getManager()->getRepository(SentEmail::class)
->findOneByToken($token);
if ($email instanceof SentEmail) {
$recipients = implode(', ', $email->getRecipients());
$variables = implode(', ', array_keys($email->getVariables()));
return $this->render('AzineEmailBundle::sentEmailDetails.html.twig',
array('email' => $email, 'recipients' => $recipients, 'variables' => $variables));
}
// the parameters-array is null => the email is not available in webView
$days = $this->getParameter('azine_email_web_view_retention');
$response = $this->render('AzineEmailBundle:Webview:mail.not.available.html.twig', array('days' => $days));
$response->setStatusCode(404);
return $response;
} | [
"public",
"function",
"emailDetailsByTokenAction",
"(",
"Request",
"$",
"request",
",",
"$",
"token",
")",
"{",
"$",
"email",
"=",
"$",
"this",
"->",
"getDoctrine",
"(",
")",
"->",
"getManager",
"(",
")",
"->",
"getRepository",
"(",
"SentEmail",
"::",
"cla... | Displays an extended view of SentEmail entity searched by a token property.
@param string $token
@return Response | [
"Displays",
"an",
"extended",
"view",
"of",
"SentEmail",
"entity",
"searched",
"by",
"a",
"token",
"property",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Controller/AzineEmailController.php#L46-L65 | train |
azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.removeUnreferecedEmbededItemsFromMessage | private function removeUnreferecedEmbededItemsFromMessage(\Swift_Message $message, $params, $htmlBody)
{
foreach ($params as $key => $value) {
// remove unreferenced attachments from contentItems too.
if ('contentItems' === $key) {
foreach ($value as $contentItemParams) {
$message = $this->removeUnreferecedEmbededItemsFromMessage($message, $contentItemParams, $htmlBody);
}
} else {
// check if the embeded items are referenced in the templates
$isEmbededItem = is_string($value) && 1 == preg_match($this->encodedItemIdPattern, $value);
if ($isEmbededItem && false === stripos($htmlBody, $value)) {
// remove unreferenced items
$children = array();
foreach ($message->getChildren() as $attachment) {
if ('cid:'.$attachment->getId() != $value) {
$children[] = $attachment;
}
}
$message->setChildren($children);
}
}
}
return $message;
} | php | private function removeUnreferecedEmbededItemsFromMessage(\Swift_Message $message, $params, $htmlBody)
{
foreach ($params as $key => $value) {
// remove unreferenced attachments from contentItems too.
if ('contentItems' === $key) {
foreach ($value as $contentItemParams) {
$message = $this->removeUnreferecedEmbededItemsFromMessage($message, $contentItemParams, $htmlBody);
}
} else {
// check if the embeded items are referenced in the templates
$isEmbededItem = is_string($value) && 1 == preg_match($this->encodedItemIdPattern, $value);
if ($isEmbededItem && false === stripos($htmlBody, $value)) {
// remove unreferenced items
$children = array();
foreach ($message->getChildren() as $attachment) {
if ('cid:'.$attachment->getId() != $value) {
$children[] = $attachment;
}
}
$message->setChildren($children);
}
}
}
return $message;
} | [
"private",
"function",
"removeUnreferecedEmbededItemsFromMessage",
"(",
"\\",
"Swift_Message",
"$",
"message",
",",
"$",
"params",
",",
"$",
"htmlBody",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"// remove unrefer... | Remove all Embeded Attachments that are not referenced in the html-body from the message
to avoid using unneccary bandwidth.
@param \Swift_Message $message
@param array $params the parameters used to render the html
@param string $htmlBody
@return \Swift_Message | [
"Remove",
"all",
"Embeded",
"Attachments",
"that",
"are",
"not",
"referenced",
"in",
"the",
"html",
"-",
"body",
"from",
"the",
"message",
"to",
"avoid",
"using",
"unneccary",
"bandwidth",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L327-L355 | train |
azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.loadTemplate | private function loadTemplate($template)
{
if (!array_key_exists($template, $this->templateCache)) {
$this->templateCache[$template] = $this->twig->loadTemplate($template);
}
return $this->templateCache[$template];
} | php | private function loadTemplate($template)
{
if (!array_key_exists($template, $this->templateCache)) {
$this->templateCache[$template] = $this->twig->loadTemplate($template);
}
return $this->templateCache[$template];
} | [
"private",
"function",
"loadTemplate",
"(",
"$",
"template",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"template",
",",
"$",
"this",
"->",
"templateCache",
")",
")",
"{",
"$",
"this",
"->",
"templateCache",
"[",
"$",
"template",
"]",
"=",
... | Get the template from the cache if it was loaded already.
@param string $template
@return \Twig_Template | [
"Get",
"the",
"template",
"from",
"the",
"cache",
"if",
"it",
"was",
"loaded",
"already",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L364-L371 | train |
azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.embedImages | private function embedImages(&$message, &$params)
{
// loop through the array
foreach ($params as $key => $value) {
// if the current value is an array
if (is_array($value)) {
// search for more images deeper in the arrays
$value = $this->embedImages($message, $value);
$params[$key] = $value;
// if the current value is an existing file from the image-folder, embed it
} elseif (is_string($value)) {
if (is_file($value)) {
// check if the file is from an allowed folder
if (false !== $this->templateProvider->isFileAllowed($value)) {
$encodedImage = $this->cachedEmbedImage($value);
if (null !== $encodedImage) {
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
}
// the $filePath isn't a regular file
} else {
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$value] = null;
}
//if the current value is a generated image
} elseif (is_resource($value) && 0 == stripos(get_resource_type($value), 'gd')) {
// get the image-data as string
ob_start();
imagepng($value);
$imageData = ob_get_clean();
// encode the image
$encodedImage = new \Swift_Image($imageData, 'generatedImage'.md5($imageData));
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
// don't do anything
}
// remove duplicate-attachments
$message->setChildren(array_unique($message->getChildren()));
return $params;
} | php | private function embedImages(&$message, &$params)
{
// loop through the array
foreach ($params as $key => $value) {
// if the current value is an array
if (is_array($value)) {
// search for more images deeper in the arrays
$value = $this->embedImages($message, $value);
$params[$key] = $value;
// if the current value is an existing file from the image-folder, embed it
} elseif (is_string($value)) {
if (is_file($value)) {
// check if the file is from an allowed folder
if (false !== $this->templateProvider->isFileAllowed($value)) {
$encodedImage = $this->cachedEmbedImage($value);
if (null !== $encodedImage) {
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
}
// the $filePath isn't a regular file
} else {
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$value] = null;
}
//if the current value is a generated image
} elseif (is_resource($value) && 0 == stripos(get_resource_type($value), 'gd')) {
// get the image-data as string
ob_start();
imagepng($value);
$imageData = ob_get_clean();
// encode the image
$encodedImage = new \Swift_Image($imageData, 'generatedImage'.md5($imageData));
$id = $message->embed($encodedImage);
$params[$key] = $id;
}
// don't do anything
}
// remove duplicate-attachments
$message->setChildren(array_unique($message->getChildren()));
return $params;
} | [
"private",
"function",
"embedImages",
"(",
"&",
"$",
"message",
",",
"&",
"$",
"params",
")",
"{",
"// loop through the array",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"// if the current value is an array",
"if",
"(",
"... | Recursively embed all images in the array into the message.
@param \Swift_Message $message
@param array $params
@return array $params | [
"Recursively",
"embed",
"all",
"images",
"in",
"the",
"array",
"into",
"the",
"message",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L381-L428 | train |
azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.cachedEmbedImage | private function cachedEmbedImage($filePath)
{
$filePath = realpath($filePath);
if (!array_key_exists($filePath, $this->imageCache)) {
if (is_file($filePath)) {
$image = \Swift_Image::fromPath($filePath);
$id = $image->getId();
// $id and $value must not be the same => this happens if the file cannot be found/read
if ($id == $filePath) {
// @codeCoverageIgnoreStart
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$filePath] = null;
} else {
// @codeCoverageIgnoreEnd
// add the image to the cache
$this->imageCache[$filePath] = $image;
}
}
}
return $this->imageCache[$filePath];
} | php | private function cachedEmbedImage($filePath)
{
$filePath = realpath($filePath);
if (!array_key_exists($filePath, $this->imageCache)) {
if (is_file($filePath)) {
$image = \Swift_Image::fromPath($filePath);
$id = $image->getId();
// $id and $value must not be the same => this happens if the file cannot be found/read
if ($id == $filePath) {
// @codeCoverageIgnoreStart
// add a null-value to the cache for this path, so we don't try again.
$this->imageCache[$filePath] = null;
} else {
// @codeCoverageIgnoreEnd
// add the image to the cache
$this->imageCache[$filePath] = $image;
}
}
}
return $this->imageCache[$filePath];
} | [
"private",
"function",
"cachedEmbedImage",
"(",
"$",
"filePath",
")",
"{",
"$",
"filePath",
"=",
"realpath",
"(",
"$",
"filePath",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"filePath",
",",
"$",
"this",
"->",
"imageCache",
")",
")",
"{",
... | Get the Swift_Image for the file.
@param string $filePath
@return \Swift_Image|null | [
"Get",
"the",
"Swift_Image",
"for",
"the",
"file",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L437-L459 | train |
azine/email-bundle | Services/AzineTwigSwiftMailer.php | AzineTwigSwiftMailer.sendMessage | protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
{
// get the subject from the template
// => make sure the subject block exists in your fos-templates (FOSUserBundle:Registration:email.txt.twig & FOSUserBundle:Resetting:email.txt.twig)
$twigTemplate = $this->loadTemplate($templateName);
$subject = $twigTemplate->renderBlock('subject', $context);
return $this->sendSingleEmail($toEmail, null, $subject, $context, $templateName, $this->translator->getLocale(), $fromEmail);
} | php | protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
{
// get the subject from the template
// => make sure the subject block exists in your fos-templates (FOSUserBundle:Registration:email.txt.twig & FOSUserBundle:Resetting:email.txt.twig)
$twigTemplate = $this->loadTemplate($templateName);
$subject = $twigTemplate->renderBlock('subject', $context);
return $this->sendSingleEmail($toEmail, null, $subject, $context, $templateName, $this->translator->getLocale(), $fromEmail);
} | [
"protected",
"function",
"sendMessage",
"(",
"$",
"templateName",
",",
"$",
"context",
",",
"$",
"fromEmail",
",",
"$",
"toEmail",
")",
"{",
"// get the subject from the template",
"// => make sure the subject block exists in your fos-templates (FOSUserBundle:Registration:email.t... | Override the fosuserbundles original sendMessage, to embed template variables etc. into html-emails.
@param string $templateName
@param array $context
@param string $fromEmail
@param string $toEmail
@return bool true if the mail was sent successfully, else false | [
"Override",
"the",
"fosuserbundles",
"original",
"sendMessage",
"to",
"embed",
"template",
"variables",
"etc",
".",
"into",
"html",
"-",
"emails",
"."
] | e1d25da6600a5a068709074cb4d7ece15ceaaae6 | https://github.com/azine/email-bundle/blob/e1d25da6600a5a068709074cb4d7ece15ceaaae6/Services/AzineTwigSwiftMailer.php#L496-L504 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.