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 |
---|---|---|---|---|---|---|---|---|---|---|---|
heimrichhannot/contao-utils-bundle
|
src/Cache/UtilCacheWarmer.php
|
UtilCacheWarmer.generateTemplateMapper
|
private function generateTemplateMapper($cacheDir)
{
$files = $this->templateUtil->getAllTemplates();
if (empty($files)) {
return;
}
$this->filesystem->dumpFile(
$cacheDir.'/contao/config/twig-templates.php',
sprintf("<?php\n\nreturn %s;\n", var_export($files, true))
);
}
|
php
|
private function generateTemplateMapper($cacheDir)
{
$files = $this->templateUtil->getAllTemplates();
if (empty($files)) {
return;
}
$this->filesystem->dumpFile(
$cacheDir.'/contao/config/twig-templates.php',
sprintf("<?php\n\nreturn %s;\n", var_export($files, true))
);
}
|
[
"private",
"function",
"generateTemplateMapper",
"(",
"$",
"cacheDir",
")",
"{",
"$",
"files",
"=",
"$",
"this",
"->",
"templateUtil",
"->",
"getAllTemplates",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"files",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"filesystem",
"->",
"dumpFile",
"(",
"$",
"cacheDir",
".",
"'/contao/config/twig-templates.php'",
",",
"sprintf",
"(",
"\"<?php\\n\\nreturn %s;\\n\"",
",",
"var_export",
"(",
"$",
"files",
",",
"true",
")",
")",
")",
";",
"}"
] |
Generates the template mapper array.
@param string $cacheDir The cache directory
|
[
"Generates",
"the",
"template",
"mapper",
"array",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/UtilCacheWarmer.php#L123-L135
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pdf/PdfPreview.php
|
PdfPreview.generatePdfPreview
|
public function generatePdfPreview(string $pdfPath, string $imagePath, array $options = [])
{
if (!isset($options['absolutePdfPath']) || true !== $options['absolutePdfPath']) {
$pdfPath = $this->webDir.'/'.$pdfPath;
}
if (!isset($options['absoluteImagePath']) || true !== $options['absoluteImagePath']) {
$imagePath = $this->webDir.'/'.$imagePath;
}
$pdfTranscoder = isset($options['pdfTranscoder']) ? $options['pdfTranscoder'] : '';
switch ($pdfTranscoder) {
case 'alchemy':
return $this->alchemyPdf($pdfPath, $imagePath, $options);
case 'spatie':
default:
return $this->spatiePdf($pdfPath, $imagePath, $options);
}
}
|
php
|
public function generatePdfPreview(string $pdfPath, string $imagePath, array $options = [])
{
if (!isset($options['absolutePdfPath']) || true !== $options['absolutePdfPath']) {
$pdfPath = $this->webDir.'/'.$pdfPath;
}
if (!isset($options['absoluteImagePath']) || true !== $options['absoluteImagePath']) {
$imagePath = $this->webDir.'/'.$imagePath;
}
$pdfTranscoder = isset($options['pdfTranscoder']) ? $options['pdfTranscoder'] : '';
switch ($pdfTranscoder) {
case 'alchemy':
return $this->alchemyPdf($pdfPath, $imagePath, $options);
case 'spatie':
default:
return $this->spatiePdf($pdfPath, $imagePath, $options);
}
}
|
[
"public",
"function",
"generatePdfPreview",
"(",
"string",
"$",
"pdfPath",
",",
"string",
"$",
"imagePath",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'absolutePdfPath'",
"]",
")",
"||",
"true",
"!==",
"$",
"options",
"[",
"'absolutePdfPath'",
"]",
")",
"{",
"$",
"pdfPath",
"=",
"$",
"this",
"->",
"webDir",
".",
"'/'",
".",
"$",
"pdfPath",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'absoluteImagePath'",
"]",
")",
"||",
"true",
"!==",
"$",
"options",
"[",
"'absoluteImagePath'",
"]",
")",
"{",
"$",
"imagePath",
"=",
"$",
"this",
"->",
"webDir",
".",
"'/'",
".",
"$",
"imagePath",
";",
"}",
"$",
"pdfTranscoder",
"=",
"isset",
"(",
"$",
"options",
"[",
"'pdfTranscoder'",
"]",
")",
"?",
"$",
"options",
"[",
"'pdfTranscoder'",
"]",
":",
"''",
";",
"switch",
"(",
"$",
"pdfTranscoder",
")",
"{",
"case",
"'alchemy'",
":",
"return",
"$",
"this",
"->",
"alchemyPdf",
"(",
"$",
"pdfPath",
",",
"$",
"imagePath",
",",
"$",
"options",
")",
";",
"case",
"'spatie'",
":",
"default",
":",
"return",
"$",
"this",
"->",
"spatiePdf",
"(",
"$",
"pdfPath",
",",
"$",
"imagePath",
",",
"$",
"options",
")",
";",
"}",
"}"
] |
Generate a image preview of the given pdf.
Possible PdfTranscoder: spatie (spatie/pdf-to-image), alchemy (alchemy/ghostscript)
Possible file extensions: jpg, jpeg, png
Additional options:
- string pdfTranscoder The pdf transcoder to use (default: spatie)
- int page The page to render (default: 1)
- int compressionQuality Pdf compression quality (default: null) (spatie only)
- int resolution Raster resolution (default: 144)(spatie only)
- bool absolutePdfPath Set true if pdf path is absolute (default: false)
- bool absoluteImagePath Set true if image path is absolute (default: false)
@param string $pdfPath the relative path to the pdf file
@param string $imagePath the relative path where the image file should be saved (including file name and extension)
@param array $options Additional rendering options
@throws \Exception
@return bool
|
[
"Generate",
"a",
"image",
"preview",
"of",
"the",
"given",
"pdf",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pdf/PdfPreview.php#L80-L99
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pagination/TextualPagination.php
|
TextualPagination.getItemsAsArray
|
public function getItemsAsArray()
{
$items = [];
foreach ($this->teasers as $page => $teaser) {
if ($page == $this->intPage) {
$items[] = [
'page' => $page,
'href' => null,
'title' => null,
'text' => $teaser,
];
} else {
$items[] = [
'page' => $page,
'href' => $this->linkToPage($page),
'title' => StringUtil::specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['goToPage'], $page)),
'text' => $teaser,
];
}
}
if ($this->singlePageUrl) {
$items[] = [
'page' => 'singlePage',
'href' => $this->singlePageUrl,
'title' => null,
'text' => $GLOBALS['TL_LANG']['MSC']['readOnSinglePage'],
];
}
return $items;
}
|
php
|
public function getItemsAsArray()
{
$items = [];
foreach ($this->teasers as $page => $teaser) {
if ($page == $this->intPage) {
$items[] = [
'page' => $page,
'href' => null,
'title' => null,
'text' => $teaser,
];
} else {
$items[] = [
'page' => $page,
'href' => $this->linkToPage($page),
'title' => StringUtil::specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['goToPage'], $page)),
'text' => $teaser,
];
}
}
if ($this->singlePageUrl) {
$items[] = [
'page' => 'singlePage',
'href' => $this->singlePageUrl,
'title' => null,
'text' => $GLOBALS['TL_LANG']['MSC']['readOnSinglePage'],
];
}
return $items;
}
|
[
"public",
"function",
"getItemsAsArray",
"(",
")",
"{",
"$",
"items",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"teasers",
"as",
"$",
"page",
"=>",
"$",
"teaser",
")",
"{",
"if",
"(",
"$",
"page",
"==",
"$",
"this",
"->",
"intPage",
")",
"{",
"$",
"items",
"[",
"]",
"=",
"[",
"'page'",
"=>",
"$",
"page",
",",
"'href'",
"=>",
"null",
",",
"'title'",
"=>",
"null",
",",
"'text'",
"=>",
"$",
"teaser",
",",
"]",
";",
"}",
"else",
"{",
"$",
"items",
"[",
"]",
"=",
"[",
"'page'",
"=>",
"$",
"page",
",",
"'href'",
"=>",
"$",
"this",
"->",
"linkToPage",
"(",
"$",
"page",
")",
",",
"'title'",
"=>",
"StringUtil",
"::",
"specialchars",
"(",
"sprintf",
"(",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"'MSC'",
"]",
"[",
"'goToPage'",
"]",
",",
"$",
"page",
")",
")",
",",
"'text'",
"=>",
"$",
"teaser",
",",
"]",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"singlePageUrl",
")",
"{",
"$",
"items",
"[",
"]",
"=",
"[",
"'page'",
"=>",
"'singlePage'",
",",
"'href'",
"=>",
"$",
"this",
"->",
"singlePageUrl",
",",
"'title'",
"=>",
"null",
",",
"'text'",
"=>",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"'MSC'",
"]",
"[",
"'readOnSinglePage'",
"]",
",",
"]",
";",
"}",
"return",
"$",
"items",
";",
"}"
] |
Generate all page links and return them as array.
@return array The page links as array
|
[
"Generate",
"all",
"page",
"links",
"and",
"return",
"them",
"as",
"array",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pagination/TextualPagination.php#L60-L92
|
train
|
heimrichhannot/contao-utils-bundle
|
src/EventListener/InsertTagsListener.php
|
InsertTagsListener.onReplaceInsertTags
|
public function onReplaceInsertTags(string $tag)
{
$elements = explode('::', $tag);
$key = strtolower($elements[0]);
$attributes = \array_slice($elements, 1);
if (\in_array($key, $this->supportedTags)) {
return $this->replaceSupportedTags($key, $attributes);
}
return false;
}
|
php
|
public function onReplaceInsertTags(string $tag)
{
$elements = explode('::', $tag);
$key = strtolower($elements[0]);
$attributes = \array_slice($elements, 1);
if (\in_array($key, $this->supportedTags)) {
return $this->replaceSupportedTags($key, $attributes);
}
return false;
}
|
[
"public",
"function",
"onReplaceInsertTags",
"(",
"string",
"$",
"tag",
")",
"{",
"$",
"elements",
"=",
"explode",
"(",
"'::'",
",",
"$",
"tag",
")",
";",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"elements",
"[",
"0",
"]",
")",
";",
"$",
"attributes",
"=",
"\\",
"array_slice",
"(",
"$",
"elements",
",",
"1",
")",
";",
"if",
"(",
"\\",
"in_array",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"supportedTags",
")",
")",
"{",
"return",
"$",
"this",
"->",
"replaceSupportedTags",
"(",
"$",
"key",
",",
"$",
"attributes",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Replaces calendar insert tags.
@param string $tag
@return string|false
|
[
"Replaces",
"calendar",
"insert",
"tags",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/EventListener/InsertTagsListener.php#L47-L58
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pdf/PdfWriter.php
|
PdfWriter.setTemplate
|
public function setTemplate(string $template): self
{
$projectDir = System::getContainer()->get('huh.utils.container')->getProjectDir();
$this->template = $projectDir.\DIRECTORY_SEPARATOR.ltrim(preg_replace('#^'.$projectDir.'#', '', $template), \DIRECTORY_SEPARATOR);
return $this;
}
|
php
|
public function setTemplate(string $template): self
{
$projectDir = System::getContainer()->get('huh.utils.container')->getProjectDir();
$this->template = $projectDir.\DIRECTORY_SEPARATOR.ltrim(preg_replace('#^'.$projectDir.'#', '', $template), \DIRECTORY_SEPARATOR);
return $this;
}
|
[
"public",
"function",
"setTemplate",
"(",
"string",
"$",
"template",
")",
":",
"self",
"{",
"$",
"projectDir",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.container'",
")",
"->",
"getProjectDir",
"(",
")",
";",
"$",
"this",
"->",
"template",
"=",
"$",
"projectDir",
".",
"\\",
"DIRECTORY_SEPARATOR",
".",
"ltrim",
"(",
"preg_replace",
"(",
"'#^'",
".",
"$",
"projectDir",
".",
"'#'",
",",
"''",
",",
"$",
"template",
")",
",",
"\\",
"DIRECTORY_SEPARATOR",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
Set the master template path.
@param string $template
@return PdfWriter Current pdf writer instance
|
[
"Set",
"the",
"master",
"template",
"path",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pdf/PdfWriter.php#L98-L105
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pdf/PdfWriter.php
|
PdfWriter.prepare
|
public function prepare(): Mpdf
{
$this->pdf = $this->getPdf();
// set the custom pdf template
if (null !== $this->getTemplate() && file_exists($this->getTemplate())) {
$this->pdf->SetImportUse();
$pageCount = $this->pdf->SetSourceFile($this->getTemplate());
$tplIdx = $this->pdf->ImportPage($pageCount);
$this->pdf->UseTemplate($tplIdx);
$this->pdf->UseTemplate($tplIdx);
}
$this->pdf->WriteHTML($this->html);
$this->isPrepared = true;
return $this->pdf;
}
|
php
|
public function prepare(): Mpdf
{
$this->pdf = $this->getPdf();
// set the custom pdf template
if (null !== $this->getTemplate() && file_exists($this->getTemplate())) {
$this->pdf->SetImportUse();
$pageCount = $this->pdf->SetSourceFile($this->getTemplate());
$tplIdx = $this->pdf->ImportPage($pageCount);
$this->pdf->UseTemplate($tplIdx);
$this->pdf->UseTemplate($tplIdx);
}
$this->pdf->WriteHTML($this->html);
$this->isPrepared = true;
return $this->pdf;
}
|
[
"public",
"function",
"prepare",
"(",
")",
":",
"Mpdf",
"{",
"$",
"this",
"->",
"pdf",
"=",
"$",
"this",
"->",
"getPdf",
"(",
")",
";",
"// set the custom pdf template",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"getTemplate",
"(",
")",
"&&",
"file_exists",
"(",
"$",
"this",
"->",
"getTemplate",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"pdf",
"->",
"SetImportUse",
"(",
")",
";",
"$",
"pageCount",
"=",
"$",
"this",
"->",
"pdf",
"->",
"SetSourceFile",
"(",
"$",
"this",
"->",
"getTemplate",
"(",
")",
")",
";",
"$",
"tplIdx",
"=",
"$",
"this",
"->",
"pdf",
"->",
"ImportPage",
"(",
"$",
"pageCount",
")",
";",
"$",
"this",
"->",
"pdf",
"->",
"UseTemplate",
"(",
"$",
"tplIdx",
")",
";",
"$",
"this",
"->",
"pdf",
"->",
"UseTemplate",
"(",
"$",
"tplIdx",
")",
";",
"}",
"$",
"this",
"->",
"pdf",
"->",
"WriteHTML",
"(",
"$",
"this",
"->",
"html",
")",
";",
"$",
"this",
"->",
"isPrepared",
"=",
"true",
";",
"return",
"$",
"this",
"->",
"pdf",
";",
"}"
] |
Prepare the current mpdf object.
@return Mpdf
|
[
"Prepare",
"the",
"current",
"mpdf",
"object",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pdf/PdfWriter.php#L112-L131
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pdf/PdfWriter.php
|
PdfWriter.addFontDirectories
|
public function addFontDirectories(array $paths): self
{
$projectDir = System::getContainer()->get('huh.utils.container')->getProjectDir();
$defaultConfig = (new ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
foreach ($paths as $path) {
$fontDir = $projectDir.\DIRECTORY_SEPARATOR.ltrim($path, \DIRECTORY_SEPARATOR);
if (!file_exists($fontDir) || !file_exists($fontDir.\DIRECTORY_SEPARATOR.'mpdf-config.php')) {
continue;
}
$configPath = $fontDir.\DIRECTORY_SEPARATOR.'mpdf-config.php';
$fontConfig = require_once $configPath;
if (!\is_array($fontConfig)) {
continue;
}
if (!isset($fontConfig['fontDir'])) {
$fontConfig['fontDir'] = array_merge($fontDirs, [
$fontDir,
]);
}
$this->config = array_merge($this->config, $fontConfig);
}
return $this;
}
|
php
|
public function addFontDirectories(array $paths): self
{
$projectDir = System::getContainer()->get('huh.utils.container')->getProjectDir();
$defaultConfig = (new ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
foreach ($paths as $path) {
$fontDir = $projectDir.\DIRECTORY_SEPARATOR.ltrim($path, \DIRECTORY_SEPARATOR);
if (!file_exists($fontDir) || !file_exists($fontDir.\DIRECTORY_SEPARATOR.'mpdf-config.php')) {
continue;
}
$configPath = $fontDir.\DIRECTORY_SEPARATOR.'mpdf-config.php';
$fontConfig = require_once $configPath;
if (!\is_array($fontConfig)) {
continue;
}
if (!isset($fontConfig['fontDir'])) {
$fontConfig['fontDir'] = array_merge($fontDirs, [
$fontDir,
]);
}
$this->config = array_merge($this->config, $fontConfig);
}
return $this;
}
|
[
"public",
"function",
"addFontDirectories",
"(",
"array",
"$",
"paths",
")",
":",
"self",
"{",
"$",
"projectDir",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.container'",
")",
"->",
"getProjectDir",
"(",
")",
";",
"$",
"defaultConfig",
"=",
"(",
"new",
"ConfigVariables",
"(",
")",
")",
"->",
"getDefaults",
"(",
")",
";",
"$",
"fontDirs",
"=",
"$",
"defaultConfig",
"[",
"'fontDir'",
"]",
";",
"foreach",
"(",
"$",
"paths",
"as",
"$",
"path",
")",
"{",
"$",
"fontDir",
"=",
"$",
"projectDir",
".",
"\\",
"DIRECTORY_SEPARATOR",
".",
"ltrim",
"(",
"$",
"path",
",",
"\\",
"DIRECTORY_SEPARATOR",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"fontDir",
")",
"||",
"!",
"file_exists",
"(",
"$",
"fontDir",
".",
"\\",
"DIRECTORY_SEPARATOR",
".",
"'mpdf-config.php'",
")",
")",
"{",
"continue",
";",
"}",
"$",
"configPath",
"=",
"$",
"fontDir",
".",
"\\",
"DIRECTORY_SEPARATOR",
".",
"'mpdf-config.php'",
";",
"$",
"fontConfig",
"=",
"require_once",
"$",
"configPath",
";",
"if",
"(",
"!",
"\\",
"is_array",
"(",
"$",
"fontConfig",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"fontConfig",
"[",
"'fontDir'",
"]",
")",
")",
"{",
"$",
"fontConfig",
"[",
"'fontDir'",
"]",
"=",
"array_merge",
"(",
"$",
"fontDirs",
",",
"[",
"$",
"fontDir",
",",
"]",
")",
";",
"}",
"$",
"this",
"->",
"config",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"config",
",",
"$",
"fontConfig",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Add font directories to the config.
@param array $paths Directory pathseader
@return PdfWriter Current pdf writer instance
|
[
"Add",
"font",
"directories",
"to",
"the",
"config",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pdf/PdfWriter.php#L154-L185
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pdf/PdfWriter.php
|
PdfWriter.getPdf
|
public function getPdf(bool $init = false): Mpdf
{
$this->pdf = (null === $this->pdf || true === $init) ? new Mpdf($this->config) : $this->pdf;
return $this->pdf;
}
|
php
|
public function getPdf(bool $init = false): Mpdf
{
$this->pdf = (null === $this->pdf || true === $init) ? new Mpdf($this->config) : $this->pdf;
return $this->pdf;
}
|
[
"public",
"function",
"getPdf",
"(",
"bool",
"$",
"init",
"=",
"false",
")",
":",
"Mpdf",
"{",
"$",
"this",
"->",
"pdf",
"=",
"(",
"null",
"===",
"$",
"this",
"->",
"pdf",
"||",
"true",
"===",
"$",
"init",
")",
"?",
"new",
"Mpdf",
"(",
"$",
"this",
"->",
"config",
")",
":",
"$",
"this",
"->",
"pdf",
";",
"return",
"$",
"this",
"->",
"pdf",
";",
"}"
] |
Get current pdf object.
@param bool $init Set true if you want to create a new pdf regardless there is always an existing pdf
@return Mpdf
|
[
"Get",
"current",
"pdf",
"object",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pdf/PdfWriter.php#L218-L223
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pdf/PdfWriter.php
|
PdfWriter.setFileName
|
public function setFileName(string $fileName): self
{
if (!preg_match('#.pdf$#i', $fileName)) {
$fileName .= '.pdf';
}
$this->fileName = System::getContainer()->get('huh.utils.file')->sanitizeFileName($fileName);
return $this;
}
|
php
|
public function setFileName(string $fileName): self
{
if (!preg_match('#.pdf$#i', $fileName)) {
$fileName .= '.pdf';
}
$this->fileName = System::getContainer()->get('huh.utils.file')->sanitizeFileName($fileName);
return $this;
}
|
[
"public",
"function",
"setFileName",
"(",
"string",
"$",
"fileName",
")",
":",
"self",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'#.pdf$#i'",
",",
"$",
"fileName",
")",
")",
"{",
"$",
"fileName",
".=",
"'.pdf'",
";",
"}",
"$",
"this",
"->",
"fileName",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.file'",
")",
"->",
"sanitizeFileName",
"(",
"$",
"fileName",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
Set the pdf filename.
@param string $fileName
@return PdfWriter Current pdf writer instance
|
[
"Set",
"the",
"pdf",
"filename",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pdf/PdfWriter.php#L242-L251
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Pdf/PdfWriter.php
|
PdfWriter.mergeConfig
|
public function mergeConfig(array $config): self
{
$this->config = array_merge($this->config, $config);
return $this;
}
|
php
|
public function mergeConfig(array $config): self
{
$this->config = array_merge($this->config, $config);
return $this;
}
|
[
"public",
"function",
"mergeConfig",
"(",
"array",
"$",
"config",
")",
":",
"self",
"{",
"$",
"this",
"->",
"config",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"config",
",",
"$",
"config",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
Merge current pdf config with given.
@param array $config
@return PdfWriter Current pdf writer instance
|
[
"Merge",
"current",
"pdf",
"config",
"with",
"given",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Pdf/PdfWriter.php#L284-L289
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Arrays/ArrayUtil.php
|
ArrayUtil.filterByPrefixes
|
public function filterByPrefixes(array $data = [], $prefixes = [])
{
$extract = [];
if (!\is_array($prefixes) || empty($prefixes)) {
return $data;
}
foreach ($data as $key => $value) {
foreach ($prefixes as $prefix) {
if ($this->container->get('huh.utils.string')->startsWith($key, $prefix)) {
$extract[$key] = $value;
}
}
}
return $extract;
}
|
php
|
public function filterByPrefixes(array $data = [], $prefixes = [])
{
$extract = [];
if (!\is_array($prefixes) || empty($prefixes)) {
return $data;
}
foreach ($data as $key => $value) {
foreach ($prefixes as $prefix) {
if ($this->container->get('huh.utils.string')->startsWith($key, $prefix)) {
$extract[$key] = $value;
}
}
}
return $extract;
}
|
[
"public",
"function",
"filterByPrefixes",
"(",
"array",
"$",
"data",
"=",
"[",
"]",
",",
"$",
"prefixes",
"=",
"[",
"]",
")",
"{",
"$",
"extract",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"\\",
"is_array",
"(",
"$",
"prefixes",
")",
"||",
"empty",
"(",
"$",
"prefixes",
")",
")",
"{",
"return",
"$",
"data",
";",
"}",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"prefixes",
"as",
"$",
"prefix",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.string'",
")",
"->",
"startsWith",
"(",
"$",
"key",
",",
"$",
"prefix",
")",
")",
"{",
"$",
"extract",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"}",
"return",
"$",
"extract",
";",
"}"
] |
Filter an Array by given prefixes.
@param array $data
@param array $prefixes
@return array the filtered array or $arrData if $prefix is empty
|
[
"Filter",
"an",
"Array",
"by",
"given",
"prefixes",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Arrays/ArrayUtil.php#L39-L56
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Arrays/ArrayUtil.php
|
ArrayUtil.removeValue
|
public function removeValue($value, array &$array): bool
{
if (false !== ($intPosition = array_search($value, $array))) {
unset($array[$intPosition]);
return true;
}
return false;
}
|
php
|
public function removeValue($value, array &$array): bool
{
if (false !== ($intPosition = array_search($value, $array))) {
unset($array[$intPosition]);
return true;
}
return false;
}
|
[
"public",
"function",
"removeValue",
"(",
"$",
"value",
",",
"array",
"&",
"$",
"array",
")",
":",
"bool",
"{",
"if",
"(",
"false",
"!==",
"(",
"$",
"intPosition",
"=",
"array_search",
"(",
"$",
"value",
",",
"$",
"array",
")",
")",
")",
"{",
"unset",
"(",
"$",
"array",
"[",
"$",
"intPosition",
"]",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Removes a value in an array.
@param $value
@param array $array
@return bool Returns true if the value has been found and removed, false in other cases
|
[
"Removes",
"a",
"value",
"in",
"an",
"array",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Arrays/ArrayUtil.php#L90-L99
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Arrays/ArrayUtil.php
|
ArrayUtil.insertInArrayByName
|
public function insertInArrayByName(array &$current, string $key, $value, int $offset = 0, bool $strict = false)
{
if (false !== ($intIndex = array_search($key, array_keys($current), $strict))) {
array_insert($current, $intIndex + $offset, $value);
}
}
|
php
|
public function insertInArrayByName(array &$current, string $key, $value, int $offset = 0, bool $strict = false)
{
if (false !== ($intIndex = array_search($key, array_keys($current), $strict))) {
array_insert($current, $intIndex + $offset, $value);
}
}
|
[
"public",
"function",
"insertInArrayByName",
"(",
"array",
"&",
"$",
"current",
",",
"string",
"$",
"key",
",",
"$",
"value",
",",
"int",
"$",
"offset",
"=",
"0",
",",
"bool",
"$",
"strict",
"=",
"false",
")",
"{",
"if",
"(",
"false",
"!==",
"(",
"$",
"intIndex",
"=",
"array_search",
"(",
"$",
"key",
",",
"array_keys",
"(",
"$",
"current",
")",
",",
"$",
"strict",
")",
")",
")",
"{",
"array_insert",
"(",
"$",
"current",
",",
"$",
"intIndex",
"+",
"$",
"offset",
",",
"$",
"value",
")",
";",
"}",
"}"
] |
Insert a value into an existing array by key name.
@param array $current The target array
@param string $key the existing target key in the array
@param mixed $value the new value to be inserted
@param int $offset offset for inserting the new value
@param bool $strict use strict behavior for array search
|
[
"Insert",
"a",
"value",
"into",
"an",
"existing",
"array",
"by",
"key",
"name",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Arrays/ArrayUtil.php#L121-L126
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Arrays/ArrayUtil.php
|
ArrayUtil.arrayToObject
|
public function arrayToObject(array $array): \stdClass
{
$objResult = new \stdClass();
foreach ($array as $varKey => $varValue) {
$objResult->{$varKey} = $varValue;
}
return $objResult;
}
|
php
|
public function arrayToObject(array $array): \stdClass
{
$objResult = new \stdClass();
foreach ($array as $varKey => $varValue) {
$objResult->{$varKey} = $varValue;
}
return $objResult;
}
|
[
"public",
"function",
"arrayToObject",
"(",
"array",
"$",
"array",
")",
":",
"\\",
"stdClass",
"{",
"$",
"objResult",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"varKey",
"=>",
"$",
"varValue",
")",
"{",
"$",
"objResult",
"->",
"{",
"$",
"varKey",
"}",
"=",
"$",
"varValue",
";",
"}",
"return",
"$",
"objResult",
";",
"}"
] |
Creates a stdClass from array.
@param $array
@return \stdClass
|
[
"Creates",
"a",
"stdClass",
"from",
"array",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Arrays/ArrayUtil.php#L135-L144
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Arrays/ArrayUtil.php
|
ArrayUtil.getArrayRowByFieldValue
|
public function getArrayRowByFieldValue($key, $value, array $haystack, bool $strictType = false)
{
foreach ($haystack as $row) {
if (!\is_array($row)) {
continue;
}
if (!isset($row[$key])) {
continue;
}
if (true === $strictType) {
if ($value === $row[$key]) {
return $row;
}
} else {
if ($row[$key] == $value) {
return $row;
}
}
}
return false;
}
|
php
|
public function getArrayRowByFieldValue($key, $value, array $haystack, bool $strictType = false)
{
foreach ($haystack as $row) {
if (!\is_array($row)) {
continue;
}
if (!isset($row[$key])) {
continue;
}
if (true === $strictType) {
if ($value === $row[$key]) {
return $row;
}
} else {
if ($row[$key] == $value) {
return $row;
}
}
}
return false;
}
|
[
"public",
"function",
"getArrayRowByFieldValue",
"(",
"$",
"key",
",",
"$",
"value",
",",
"array",
"$",
"haystack",
",",
"bool",
"$",
"strictType",
"=",
"false",
")",
"{",
"foreach",
"(",
"$",
"haystack",
"as",
"$",
"row",
")",
"{",
"if",
"(",
"!",
"\\",
"is_array",
"(",
"$",
"row",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"row",
"[",
"$",
"key",
"]",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"true",
"===",
"$",
"strictType",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"$",
"row",
"[",
"$",
"key",
"]",
")",
"{",
"return",
"$",
"row",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"row",
"[",
"$",
"key",
"]",
"==",
"$",
"value",
")",
"{",
"return",
"$",
"row",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] |
Returns a row of an multidimensional array by field value. Returns false, if no row found.
@param string|int $key The array key (fieldname)
@param mixed $value
@param array $haystack a multidimensional array
@param bool $strictType Specifiy if type comparison should be strict (type-safe)
@return mixed
|
[
"Returns",
"a",
"row",
"of",
"an",
"multidimensional",
"array",
"by",
"field",
"value",
".",
"Returns",
"false",
"if",
"no",
"row",
"found",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Arrays/ArrayUtil.php#L156-L179
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Arrays/ArrayUtil.php
|
ArrayUtil.insertBeforeKey
|
public static function insertBeforeKey(array &$array, string $key, string $newKey, $newValue)
{
if (\array_key_exists($key, $array)) {
$new = [];
foreach ($array as $k => $value) {
if ($k === $key) {
$new[$newKey] = $newValue;
}
$new[$k] = $value;
}
$array = $new;
} else {
$array[$newKey] = $newValue;
}
}
|
php
|
public static function insertBeforeKey(array &$array, string $key, string $newKey, $newValue)
{
if (\array_key_exists($key, $array)) {
$new = [];
foreach ($array as $k => $value) {
if ($k === $key) {
$new[$newKey] = $newValue;
}
$new[$k] = $value;
}
$array = $new;
} else {
$array[$newKey] = $newValue;
}
}
|
[
"public",
"static",
"function",
"insertBeforeKey",
"(",
"array",
"&",
"$",
"array",
",",
"string",
"$",
"key",
",",
"string",
"$",
"newKey",
",",
"$",
"newValue",
")",
"{",
"if",
"(",
"\\",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"array",
")",
")",
"{",
"$",
"new",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"k",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"k",
"===",
"$",
"key",
")",
"{",
"$",
"new",
"[",
"$",
"newKey",
"]",
"=",
"$",
"newValue",
";",
"}",
"$",
"new",
"[",
"$",
"k",
"]",
"=",
"$",
"value",
";",
"}",
"$",
"array",
"=",
"$",
"new",
";",
"}",
"else",
"{",
"$",
"array",
"[",
"$",
"newKey",
"]",
"=",
"$",
"newValue",
";",
"}",
"}"
] |
Insert a new entry before an specific key in array.
If key not exist, the new entry is added to the end of the array.
Array is passed as reference.
Usage example: contao config.php to make your hook entry run before another.
@param array $array Array the new entry should inserted to
@param string $key The key where the new entry should be added before
@param string $newKey The key of the entry that should be added
@param mixed $newValue The value of the entry that should be added
|
[
"Insert",
"a",
"new",
"entry",
"before",
"an",
"specific",
"key",
"in",
"array",
".",
"If",
"key",
"not",
"exist",
"the",
"new",
"entry",
"is",
"added",
"to",
"the",
"end",
"of",
"the",
"array",
".",
"Array",
"is",
"passed",
"as",
"reference",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Arrays/ArrayUtil.php#L213-L228
|
train
|
heimrichhannot/contao-utils-bundle
|
src/ContaoManager/Plugin.php
|
Plugin.registerContainerConfiguration
|
public function registerContainerConfiguration(LoaderInterface $loader, array $managerConfig)
{
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/services.yml');
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/listener.yml');
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/parameters.yml');
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/utils.yml');
}
|
php
|
public function registerContainerConfiguration(LoaderInterface $loader, array $managerConfig)
{
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/services.yml');
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/listener.yml');
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/parameters.yml');
$loader->load('@HeimrichHannotContaoUtilsBundle/Resources/config/utils.yml');
}
|
[
"public",
"function",
"registerContainerConfiguration",
"(",
"LoaderInterface",
"$",
"loader",
",",
"array",
"$",
"managerConfig",
")",
"{",
"$",
"loader",
"->",
"load",
"(",
"'@HeimrichHannotContaoUtilsBundle/Resources/config/services.yml'",
")",
";",
"$",
"loader",
"->",
"load",
"(",
"'@HeimrichHannotContaoUtilsBundle/Resources/config/listener.yml'",
")",
";",
"$",
"loader",
"->",
"load",
"(",
"'@HeimrichHannotContaoUtilsBundle/Resources/config/parameters.yml'",
")",
";",
"$",
"loader",
"->",
"load",
"(",
"'@HeimrichHannotContaoUtilsBundle/Resources/config/utils.yml'",
")",
";",
"}"
] |
Allows a plugin to load container configuration.
|
[
"Allows",
"a",
"plugin",
"to",
"load",
"container",
"configuration",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/ContaoManager/Plugin.php#L48-L54
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Module/ModuleUtil.php
|
ModuleUtil.getClassByModule
|
public function getClassByModule($module): ?string
{
if ($module instanceof Module || $module instanceof ModuleModel) {
return Module::findClass($module->type);
}
if (\is_string($module)) {
return Module::findClass($module);
}
return null;
}
|
php
|
public function getClassByModule($module): ?string
{
if ($module instanceof Module || $module instanceof ModuleModel) {
return Module::findClass($module->type);
}
if (\is_string($module)) {
return Module::findClass($module);
}
return null;
}
|
[
"public",
"function",
"getClassByModule",
"(",
"$",
"module",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"module",
"instanceof",
"Module",
"||",
"$",
"module",
"instanceof",
"ModuleModel",
")",
"{",
"return",
"Module",
"::",
"findClass",
"(",
"$",
"module",
"->",
"type",
")",
";",
"}",
"if",
"(",
"\\",
"is_string",
"(",
"$",
"module",
")",
")",
"{",
"return",
"Module",
"::",
"findClass",
"(",
"$",
"module",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Get the class name of a given module.
@param mixed $module Module as module type string, module model object or module object
@return bool
|
[
"Get",
"the",
"class",
"name",
"of",
"a",
"given",
"module",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Module/ModuleUtil.php#L25-L36
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Module/ModuleUtil.php
|
ModuleUtil.isSubModuleOf
|
public function isSubModuleOf($module1, $module2): bool
{
if (!\is_string($module1) || false === strpos($module1, '\\')) {
$module1 = $this->getClassByModule($module1);
}
if (!$module1 || !class_exists($module1)) {
return false;
}
if (\is_string($module2) || false === strpos($module2, '\\')) {
$module2 = $this->getClassByModule($module2);
}
if (!$module2 || !class_exists($module2)) {
return false;
}
return is_subclass_of($module1, $module2);
}
|
php
|
public function isSubModuleOf($module1, $module2): bool
{
if (!\is_string($module1) || false === strpos($module1, '\\')) {
$module1 = $this->getClassByModule($module1);
}
if (!$module1 || !class_exists($module1)) {
return false;
}
if (\is_string($module2) || false === strpos($module2, '\\')) {
$module2 = $this->getClassByModule($module2);
}
if (!$module2 || !class_exists($module2)) {
return false;
}
return is_subclass_of($module1, $module2);
}
|
[
"public",
"function",
"isSubModuleOf",
"(",
"$",
"module1",
",",
"$",
"module2",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"\\",
"is_string",
"(",
"$",
"module1",
")",
"||",
"false",
"===",
"strpos",
"(",
"$",
"module1",
",",
"'\\\\'",
")",
")",
"{",
"$",
"module1",
"=",
"$",
"this",
"->",
"getClassByModule",
"(",
"$",
"module1",
")",
";",
"}",
"if",
"(",
"!",
"$",
"module1",
"||",
"!",
"class_exists",
"(",
"$",
"module1",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"\\",
"is_string",
"(",
"$",
"module2",
")",
"||",
"false",
"===",
"strpos",
"(",
"$",
"module2",
",",
"'\\\\'",
")",
")",
"{",
"$",
"module2",
"=",
"$",
"this",
"->",
"getClassByModule",
"(",
"$",
"module2",
")",
";",
"}",
"if",
"(",
"!",
"$",
"module2",
"||",
"!",
"class_exists",
"(",
"$",
"module2",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"is_subclass_of",
"(",
"$",
"module1",
",",
"$",
"module2",
")",
";",
"}"
] |
Check whether a module is a sub module of another.
@param mixed $module1 First module as class string, module type string, module model object or module object
@param mixed $module2 Second module as class string, module type string, module model object or module object
@return bool
|
[
"Check",
"whether",
"a",
"module",
"is",
"a",
"sub",
"module",
"of",
"another",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Module/ModuleUtil.php#L46-L65
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.getTimeStamp
|
public function getTimeStamp($date = null, $replaceInsertTags = true, $timezone = null)
{
if (null === $date) {
return 0;
}
if ($date instanceof \DateTime) {
$timezone ? $date->setTimezone(new \DateTimeZone($timezone)) : null;
return $date->getTimestamp();
}
if (true === $replaceInsertTags) {
$date = Controller::replaceInsertTags($date, false);
}
if (is_numeric($date)) {
$dateTime = new \DateTime(null, $timezone ? new \DateTimeZone($timezone) : null);
$dateTime->setTimestamp($date);
return $dateTime->getTimestamp();
}
if (false !== ($dateTime = strtotime($date))) {
$dateTime = new \DateTime($date, $timezone ? new \DateTimeZone($timezone) : null);
return $dateTime->getTimestamp();
}
return 0;
}
|
php
|
public function getTimeStamp($date = null, $replaceInsertTags = true, $timezone = null)
{
if (null === $date) {
return 0;
}
if ($date instanceof \DateTime) {
$timezone ? $date->setTimezone(new \DateTimeZone($timezone)) : null;
return $date->getTimestamp();
}
if (true === $replaceInsertTags) {
$date = Controller::replaceInsertTags($date, false);
}
if (is_numeric($date)) {
$dateTime = new \DateTime(null, $timezone ? new \DateTimeZone($timezone) : null);
$dateTime->setTimestamp($date);
return $dateTime->getTimestamp();
}
if (false !== ($dateTime = strtotime($date))) {
$dateTime = new \DateTime($date, $timezone ? new \DateTimeZone($timezone) : null);
return $dateTime->getTimestamp();
}
return 0;
}
|
[
"public",
"function",
"getTimeStamp",
"(",
"$",
"date",
"=",
"null",
",",
"$",
"replaceInsertTags",
"=",
"true",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"date",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"$",
"date",
"instanceof",
"\\",
"DateTime",
")",
"{",
"$",
"timezone",
"?",
"$",
"date",
"->",
"setTimezone",
"(",
"new",
"\\",
"DateTimeZone",
"(",
"$",
"timezone",
")",
")",
":",
"null",
";",
"return",
"$",
"date",
"->",
"getTimestamp",
"(",
")",
";",
"}",
"if",
"(",
"true",
"===",
"$",
"replaceInsertTags",
")",
"{",
"$",
"date",
"=",
"Controller",
"::",
"replaceInsertTags",
"(",
"$",
"date",
",",
"false",
")",
";",
"}",
"if",
"(",
"is_numeric",
"(",
"$",
"date",
")",
")",
"{",
"$",
"dateTime",
"=",
"new",
"\\",
"DateTime",
"(",
"null",
",",
"$",
"timezone",
"?",
"new",
"\\",
"DateTimeZone",
"(",
"$",
"timezone",
")",
":",
"null",
")",
";",
"$",
"dateTime",
"->",
"setTimestamp",
"(",
"$",
"date",
")",
";",
"return",
"$",
"dateTime",
"->",
"getTimestamp",
"(",
")",
";",
"}",
"if",
"(",
"false",
"!==",
"(",
"$",
"dateTime",
"=",
"strtotime",
"(",
"$",
"date",
")",
")",
")",
"{",
"$",
"dateTime",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"date",
",",
"$",
"timezone",
"?",
"new",
"\\",
"DateTimeZone",
"(",
"$",
"timezone",
")",
":",
"null",
")",
";",
"return",
"$",
"dateTime",
"->",
"getTimestamp",
"(",
")",
";",
"}",
"return",
"0",
";",
"}"
] |
Get the timestamp based on input date, no matter input is timestamp or string date.
@param string|int|\DateTime|null $date The input date/timestamp/insertTag
@param bool $replaceInsertTags Disable/enable {{date::}} insertTag support
@param string|null $timezone A valid timezone from DateTimeZone::ALL, if provided the timezone offset will be added to the timestamp
@throws \Exception Throws error in case of an error when creating new DateTime instances
@return int The integer timestamp presentation of the input date with added timezone offset
|
[
"Get",
"the",
"timestamp",
"based",
"on",
"input",
"date",
"no",
"matter",
"input",
"is",
"timestamp",
"or",
"string",
"date",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L45-L75
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.getTimePeriodInSeconds
|
public function getTimePeriodInSeconds($timePeriod)
{
$timePeriod = StringUtil::deserialize($timePeriod, true);
if (!isset($timePeriod['unit']) || !isset($timePeriod['value'])) {
return null;
}
$factor = 1;
switch ($timePeriod['unit']) {
case 'm':
$factor = 60;
break;
case 'h':
$factor = 60 * 60;
break;
case 'd':
$factor = 24 * 60 * 60;
break;
}
return $timePeriod['value'] * $factor;
}
|
php
|
public function getTimePeriodInSeconds($timePeriod)
{
$timePeriod = StringUtil::deserialize($timePeriod, true);
if (!isset($timePeriod['unit']) || !isset($timePeriod['value'])) {
return null;
}
$factor = 1;
switch ($timePeriod['unit']) {
case 'm':
$factor = 60;
break;
case 'h':
$factor = 60 * 60;
break;
case 'd':
$factor = 24 * 60 * 60;
break;
}
return $timePeriod['value'] * $factor;
}
|
[
"public",
"function",
"getTimePeriodInSeconds",
"(",
"$",
"timePeriod",
")",
"{",
"$",
"timePeriod",
"=",
"StringUtil",
"::",
"deserialize",
"(",
"$",
"timePeriod",
",",
"true",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"timePeriod",
"[",
"'unit'",
"]",
")",
"||",
"!",
"isset",
"(",
"$",
"timePeriod",
"[",
"'value'",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"factor",
"=",
"1",
";",
"switch",
"(",
"$",
"timePeriod",
"[",
"'unit'",
"]",
")",
"{",
"case",
"'m'",
":",
"$",
"factor",
"=",
"60",
";",
"break",
";",
"case",
"'h'",
":",
"$",
"factor",
"=",
"60",
"*",
"60",
";",
"break",
";",
"case",
"'d'",
":",
"$",
"factor",
"=",
"24",
"*",
"60",
"*",
"60",
";",
"break",
";",
"}",
"return",
"$",
"timePeriod",
"[",
"'value'",
"]",
"*",
"$",
"factor",
";",
"}"
] |
Returns the time in seconds of an given time period.
@param string|array $timePeriod Array or serialized string containing an value and an unit key
@return float|int|null
|
[
"Returns",
"the",
"time",
"in",
"seconds",
"of",
"an",
"given",
"time",
"period",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L84-L112
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.transformPhpDateFormatToRFC3339
|
public function transformPhpDateFormatToRFC3339(string $format): string
{
$mapping = [
'd' => 'dd', //Day of the month, 2 digits with leading zeros (01 to 31)
'D' => 'E', // A textual representation of a day, three letters (Mon through Sun)
'j' => 'd', // Day of the month without leading zeros (1 to 31)
'l' => 'EEEE', // A full textual representation of the day of the week (Sunday through Saturday)
'N' => 'd', // ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) (1 (for Monday) through 7 (for Sunday))
'S' => '', // Not supported yet: English ordinal suffix for the day of the month, 2 characters (st, nd, rd or th. Works well with j)
'w' => 'e', // Numeric representation of the day of the week (0 (for Sunday) through 6 (for Saturday))
'z' => 'D', // The day of the year (starting from 0) (0 through 365)
'W' => 'w', // ISO-8601 week number of year, weeks starting on Monday (Example: 42 (the 42nd week in the year))
'F' => 'MMMM', // A full textual representation of a month, such as January or March (January through December)
'm' => 'MM', // Numeric representation of a month, with leading zeros (01 through 12)
'M' => 'MMM', // A short textual representation of a month, three letters (Jan through Dec)
'n' => 'M', // Numeric representation of a month, without leading zeros (1 through 12)
't' => '', // Not supported yet: Number of days in the given month (28 through 31)
'L' => '', // Not supported yet: Whether it's a leap year (1 if it is a leap year, 0 otherwise.)
'o' => 'Y', // ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) (Examples: 1999 or 2003)
'Y' => 'yyyy', // A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)
'y' => 'yy', // A two digit representation of a year (Examples: 99 or 03)
'a' => '', // Not supported yet: Lowercase Ante meridiem and Post meridiem (am or pm)
'A' => 'a', // Uppercase Ante meridiem and Post meridiem (AM or PM)
'B' => '', // Not supported yet: Swatch Internet time (000 through 999)
'g' => 'h', // 12-hour format of an hour without leading zeros (1 through 12)
'G' => 'H', // 24-hour format of an hour without leading zeros (0 through 23)
'h' => 'hh', // 12-hour format of an hour with leading zeros (01 through 12)
'H' => 'HH', // 24-hour format of an hour with leading zeros (00 through 23)
'i' => 'mm', // Minutes with leading zeros (00 to 59)
's' => 'ss', // Seconds, with leading zeros (00 to 59)
'u' => '', // Not supported yet: Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. (Example: 654321)
'v' => '', // Not supported yet: Milliseconds (added in PHP 7.0.0). Same note applies as for u. (Example: 654)
'e' => 'VV', // Timezone identifier (added in PHP 5.1.0) (Examples: UTC, GMT, Atlantic/Azores)
'I' => '', // Not supported yet: Whether or not the date is in daylight saving time (1 if Daylight Saving Time, 0 otherwise.)
'O' => 'xx', // Difference to Greenwich time (GMT) in hours (Example: +0200)
'P' => 'xxx', // Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) (Example: +02:00)
'T' => '', // Not supported yet: Timezone abbreviation (Examples: EST, MDT)
'Z' => '', // Not supported yet: Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. (-43200 through 50400)
'c' => "yyyy-MM-dd'T'HH:mm:ssxxx", // ISO 8601 date (added in PHP 5) (2004-02-12T15:19:21+00:00)
'r' => '', // Not supported yet: » RFC 2822 formatted date (Example: Thu, 21 Dec 2000 16:01:07 +0200)
'U' => '', // Not supported yet: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
];
$chunks = str_split($format);
foreach ($chunks as $k => $v) {
if (!isset($mapping[$v])) {
continue;
}
$chunks[$k] = $mapping[$v];
}
return preg_replace('/([a-zA-Z])/', '$1', implode('', $chunks));
}
|
php
|
public function transformPhpDateFormatToRFC3339(string $format): string
{
$mapping = [
'd' => 'dd', //Day of the month, 2 digits with leading zeros (01 to 31)
'D' => 'E', // A textual representation of a day, three letters (Mon through Sun)
'j' => 'd', // Day of the month without leading zeros (1 to 31)
'l' => 'EEEE', // A full textual representation of the day of the week (Sunday through Saturday)
'N' => 'd', // ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) (1 (for Monday) through 7 (for Sunday))
'S' => '', // Not supported yet: English ordinal suffix for the day of the month, 2 characters (st, nd, rd or th. Works well with j)
'w' => 'e', // Numeric representation of the day of the week (0 (for Sunday) through 6 (for Saturday))
'z' => 'D', // The day of the year (starting from 0) (0 through 365)
'W' => 'w', // ISO-8601 week number of year, weeks starting on Monday (Example: 42 (the 42nd week in the year))
'F' => 'MMMM', // A full textual representation of a month, such as January or March (January through December)
'm' => 'MM', // Numeric representation of a month, with leading zeros (01 through 12)
'M' => 'MMM', // A short textual representation of a month, three letters (Jan through Dec)
'n' => 'M', // Numeric representation of a month, without leading zeros (1 through 12)
't' => '', // Not supported yet: Number of days in the given month (28 through 31)
'L' => '', // Not supported yet: Whether it's a leap year (1 if it is a leap year, 0 otherwise.)
'o' => 'Y', // ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) (Examples: 1999 or 2003)
'Y' => 'yyyy', // A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)
'y' => 'yy', // A two digit representation of a year (Examples: 99 or 03)
'a' => '', // Not supported yet: Lowercase Ante meridiem and Post meridiem (am or pm)
'A' => 'a', // Uppercase Ante meridiem and Post meridiem (AM or PM)
'B' => '', // Not supported yet: Swatch Internet time (000 through 999)
'g' => 'h', // 12-hour format of an hour without leading zeros (1 through 12)
'G' => 'H', // 24-hour format of an hour without leading zeros (0 through 23)
'h' => 'hh', // 12-hour format of an hour with leading zeros (01 through 12)
'H' => 'HH', // 24-hour format of an hour with leading zeros (00 through 23)
'i' => 'mm', // Minutes with leading zeros (00 to 59)
's' => 'ss', // Seconds, with leading zeros (00 to 59)
'u' => '', // Not supported yet: Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. (Example: 654321)
'v' => '', // Not supported yet: Milliseconds (added in PHP 7.0.0). Same note applies as for u. (Example: 654)
'e' => 'VV', // Timezone identifier (added in PHP 5.1.0) (Examples: UTC, GMT, Atlantic/Azores)
'I' => '', // Not supported yet: Whether or not the date is in daylight saving time (1 if Daylight Saving Time, 0 otherwise.)
'O' => 'xx', // Difference to Greenwich time (GMT) in hours (Example: +0200)
'P' => 'xxx', // Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) (Example: +02:00)
'T' => '', // Not supported yet: Timezone abbreviation (Examples: EST, MDT)
'Z' => '', // Not supported yet: Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. (-43200 through 50400)
'c' => "yyyy-MM-dd'T'HH:mm:ssxxx", // ISO 8601 date (added in PHP 5) (2004-02-12T15:19:21+00:00)
'r' => '', // Not supported yet: » RFC 2822 formatted date (Example: Thu, 21 Dec 2000 16:01:07 +0200)
'U' => '', // Not supported yet: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
];
$chunks = str_split($format);
foreach ($chunks as $k => $v) {
if (!isset($mapping[$v])) {
continue;
}
$chunks[$k] = $mapping[$v];
}
return preg_replace('/([a-zA-Z])/', '$1', implode('', $chunks));
}
|
[
"public",
"function",
"transformPhpDateFormatToRFC3339",
"(",
"string",
"$",
"format",
")",
":",
"string",
"{",
"$",
"mapping",
"=",
"[",
"'d'",
"=>",
"'dd'",
",",
"//Day of the month, 2 digits with leading zeros (01 to 31)",
"'D'",
"=>",
"'E'",
",",
"// A textual representation of a day, three letters (Mon through Sun)",
"'j'",
"=>",
"'d'",
",",
"// Day of the month without leading zeros (1 to 31)",
"'l'",
"=>",
"'EEEE'",
",",
"// A full textual representation of the day of the week (Sunday through Saturday)",
"'N'",
"=>",
"'d'",
",",
"// ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) (1 (for Monday) through 7 (for Sunday))",
"'S'",
"=>",
"''",
",",
"// Not supported yet: English ordinal suffix for the day of the month, 2 characters (st, nd, rd or th. Works well with j)",
"'w'",
"=>",
"'e'",
",",
"// Numeric representation of the day of the week (0 (for Sunday) through 6 (for Saturday))",
"'z'",
"=>",
"'D'",
",",
"// The day of the year (starting from 0) (0 through 365)",
"'W'",
"=>",
"'w'",
",",
"// ISO-8601 week number of year, weeks starting on Monday (Example: 42 (the 42nd week in the year))",
"'F'",
"=>",
"'MMMM'",
",",
"// A full textual representation of a month, such as January or March (January through December)",
"'m'",
"=>",
"'MM'",
",",
"// Numeric representation of a month, with leading zeros (01 through 12)",
"'M'",
"=>",
"'MMM'",
",",
"// A short textual representation of a month, three letters (Jan through Dec)",
"'n'",
"=>",
"'M'",
",",
"// Numeric representation of a month, without leading zeros (1 through 12)",
"'t'",
"=>",
"''",
",",
"// Not supported yet: Number of days in the given month (28 through 31)",
"'L'",
"=>",
"''",
",",
"// Not supported yet: Whether it's a leap year (1 if it is a leap year, 0 otherwise.)",
"'o'",
"=>",
"'Y'",
",",
"// ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) (Examples: 1999 or 2003)",
"'Y'",
"=>",
"'yyyy'",
",",
"// A full numeric representation of a year, 4 digits (Examples: 1999 or 2003)",
"'y'",
"=>",
"'yy'",
",",
"// A two digit representation of a year (Examples: 99 or 03)",
"'a'",
"=>",
"''",
",",
"// Not supported yet: Lowercase Ante meridiem and Post meridiem (am or pm)",
"'A'",
"=>",
"'a'",
",",
"// Uppercase Ante meridiem and Post meridiem (AM or PM)",
"'B'",
"=>",
"''",
",",
"// Not supported yet: Swatch Internet time (000 through 999)",
"'g'",
"=>",
"'h'",
",",
"// 12-hour format of an hour without leading zeros (1 through 12)",
"'G'",
"=>",
"'H'",
",",
"// 24-hour format of an hour without leading zeros (0 through 23)",
"'h'",
"=>",
"'hh'",
",",
"// 12-hour format of an hour with leading zeros (01 through 12)",
"'H'",
"=>",
"'HH'",
",",
"// 24-hour format of an hour with leading zeros (00 through 23)",
"'i'",
"=>",
"'mm'",
",",
"// Minutes with leading zeros (00 to 59)",
"'s'",
"=>",
"'ss'",
",",
"// Seconds, with leading zeros (00 to 59)",
"'u'",
"=>",
"''",
",",
"// Not supported yet: Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. (Example: 654321)",
"'v'",
"=>",
"''",
",",
"// Not supported yet: Milliseconds (added in PHP 7.0.0). Same note applies as for u. (Example: 654)",
"'e'",
"=>",
"'VV'",
",",
"// Timezone identifier (added in PHP 5.1.0) (Examples: UTC, GMT, Atlantic/Azores)",
"'I'",
"=>",
"''",
",",
"// Not supported yet: Whether or not the date is in daylight saving time (1 if Daylight Saving Time, 0 otherwise.)",
"'O'",
"=>",
"'xx'",
",",
"// Difference to Greenwich time (GMT) in hours (Example: +0200)",
"'P'",
"=>",
"'xxx'",
",",
"// Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) (Example: +02:00)",
"'T'",
"=>",
"''",
",",
"// Not supported yet: Timezone abbreviation\t(Examples: EST, MDT)",
"'Z'",
"=>",
"''",
",",
"// Not supported yet: Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. (-43200 through 50400)",
"'c'",
"=>",
"\"yyyy-MM-dd'T'HH:mm:ssxxx\"",
",",
"// ISO 8601 date (added in PHP 5) (2004-02-12T15:19:21+00:00)",
"'r'",
"=>",
"''",
",",
"// Not supported yet: » RFC 2822 formatted date (Example: Thu, 21 Dec 2000 16:01:07 +0200)",
"'U'",
"=>",
"''",
",",
"// Not supported yet: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)",
"]",
";",
"$",
"chunks",
"=",
"str_split",
"(",
"$",
"format",
")",
";",
"foreach",
"(",
"$",
"chunks",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"mapping",
"[",
"$",
"v",
"]",
")",
")",
"{",
"continue",
";",
"}",
"$",
"chunks",
"[",
"$",
"k",
"]",
"=",
"$",
"mapping",
"[",
"$",
"v",
"]",
";",
"}",
"return",
"preg_replace",
"(",
"'/([a-zA-Z])/'",
",",
"'$1'",
",",
"implode",
"(",
"''",
",",
"$",
"chunks",
")",
")",
";",
"}"
] |
Format a php date formate pattern to an RFC3339 compliant format.
@param string $format The php date format (see: http://php.net/manual/de/function.date.php#refsect1-function.date-parameters)
@return string The RFC3339 compliant format (see: http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax or http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table)
|
[
"Format",
"a",
"php",
"date",
"formate",
"pattern",
"to",
"an",
"RFC3339",
"compliant",
"format",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L121-L175
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.getGMTMidnightTstamp
|
public function getGMTMidnightTstamp(int $tstamp)
{
$date = new \DateTime(date('Y-m-d', $tstamp));
$date->setTimezone(new \DateTimeZone('GMT'));
$date->setTime(0, 0, 0);
return $date->getTimestamp();
}
|
php
|
public function getGMTMidnightTstamp(int $tstamp)
{
$date = new \DateTime(date('Y-m-d', $tstamp));
$date->setTimezone(new \DateTimeZone('GMT'));
$date->setTime(0, 0, 0);
return $date->getTimestamp();
}
|
[
"public",
"function",
"getGMTMidnightTstamp",
"(",
"int",
"$",
"tstamp",
")",
"{",
"$",
"date",
"=",
"new",
"\\",
"DateTime",
"(",
"date",
"(",
"'Y-m-d'",
",",
"$",
"tstamp",
")",
")",
";",
"$",
"date",
"->",
"setTimezone",
"(",
"new",
"\\",
"DateTimeZone",
"(",
"'GMT'",
")",
")",
";",
"$",
"date",
"->",
"setTime",
"(",
"0",
",",
"0",
",",
"0",
")",
";",
"return",
"$",
"date",
"->",
"getTimestamp",
"(",
")",
";",
"}"
] |
transfer a given timestamp to a gmt timestamp at midnight.
@param int $tstamp
@return int
|
[
"transfer",
"a",
"given",
"timestamp",
"to",
"a",
"gmt",
"timestamp",
"at",
"midnight",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L247-L254
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.isMonthInDateFormat
|
public function isMonthInDateFormat(string $dateFormat)
{
return false !== strpos($dateFormat, 'F') ||
false !== strpos($dateFormat, 'M') ||
false !== strpos($dateFormat, 'm') ||
false !== strpos($dateFormat, 'n');
}
|
php
|
public function isMonthInDateFormat(string $dateFormat)
{
return false !== strpos($dateFormat, 'F') ||
false !== strpos($dateFormat, 'M') ||
false !== strpos($dateFormat, 'm') ||
false !== strpos($dateFormat, 'n');
}
|
[
"public",
"function",
"isMonthInDateFormat",
"(",
"string",
"$",
"dateFormat",
")",
"{",
"return",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'F'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'M'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'m'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'n'",
")",
";",
"}"
] |
Checks if a form of month is available in the date format.
@param string $dateFormat
@return bool
|
[
"Checks",
"if",
"a",
"form",
"of",
"month",
"is",
"available",
"in",
"the",
"date",
"format",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L263-L269
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.isDayInDateFormat
|
public function isDayInDateFormat(string $dateFormat)
{
return false !== strpos($dateFormat, 'd') ||
false !== strpos($dateFormat, 'D') ||
false !== strpos($dateFormat, 'j') ||
false !== strpos($dateFormat, 'l') ||
false !== strpos($dateFormat, 'N') ||
false !== strpos($dateFormat, 'z');
}
|
php
|
public function isDayInDateFormat(string $dateFormat)
{
return false !== strpos($dateFormat, 'd') ||
false !== strpos($dateFormat, 'D') ||
false !== strpos($dateFormat, 'j') ||
false !== strpos($dateFormat, 'l') ||
false !== strpos($dateFormat, 'N') ||
false !== strpos($dateFormat, 'z');
}
|
[
"public",
"function",
"isDayInDateFormat",
"(",
"string",
"$",
"dateFormat",
")",
"{",
"return",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'d'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'D'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'j'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'l'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'N'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'z'",
")",
";",
"}"
] |
Checks if a form of day is available in the date format.
@param string $dateFormat
@return bool
|
[
"Checks",
"if",
"a",
"form",
"of",
"day",
"is",
"available",
"in",
"the",
"date",
"format",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L278-L286
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.isYearInDateFormat
|
public function isYearInDateFormat(string $dateFormat)
{
return false !== strpos($dateFormat, 'o') ||
false !== strpos($dateFormat, 'Y') ||
false !== strpos($dateFormat, 'y');
}
|
php
|
public function isYearInDateFormat(string $dateFormat)
{
return false !== strpos($dateFormat, 'o') ||
false !== strpos($dateFormat, 'Y') ||
false !== strpos($dateFormat, 'y');
}
|
[
"public",
"function",
"isYearInDateFormat",
"(",
"string",
"$",
"dateFormat",
")",
"{",
"return",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'o'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'Y'",
")",
"||",
"false",
"!==",
"strpos",
"(",
"$",
"dateFormat",
",",
"'y'",
")",
";",
"}"
] |
Checks if a form of year is available in the date format.
@param string $dateFormat
@return bool
|
[
"Checks",
"if",
"a",
"form",
"of",
"year",
"is",
"available",
"in",
"the",
"date",
"format",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L295-L300
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.translateMonthsToEnglish
|
public function translateMonthsToEnglish(string $date)
{
foreach ($this->getMonthTranslationMap() as $english => $translated) {
if (false !== strpos($date, $translated)) {
$date = str_replace($translated, $english, $date);
}
}
foreach ($this->getShortMonthTranslationMap() as $english => $translated) {
if (false !== strpos($date, $translated)) {
$date = str_replace($translated, $english, $date);
}
}
return $date;
}
|
php
|
public function translateMonthsToEnglish(string $date)
{
foreach ($this->getMonthTranslationMap() as $english => $translated) {
if (false !== strpos($date, $translated)) {
$date = str_replace($translated, $english, $date);
}
}
foreach ($this->getShortMonthTranslationMap() as $english => $translated) {
if (false !== strpos($date, $translated)) {
$date = str_replace($translated, $english, $date);
}
}
return $date;
}
|
[
"public",
"function",
"translateMonthsToEnglish",
"(",
"string",
"$",
"date",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getMonthTranslationMap",
"(",
")",
"as",
"$",
"english",
"=>",
"$",
"translated",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"date",
",",
"$",
"translated",
")",
")",
"{",
"$",
"date",
"=",
"str_replace",
"(",
"$",
"translated",
",",
"$",
"english",
",",
"$",
"date",
")",
";",
"}",
"}",
"foreach",
"(",
"$",
"this",
"->",
"getShortMonthTranslationMap",
"(",
")",
"as",
"$",
"english",
"=>",
"$",
"translated",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"date",
",",
"$",
"translated",
")",
")",
"{",
"$",
"date",
"=",
"str_replace",
"(",
"$",
"translated",
",",
"$",
"english",
",",
"$",
"date",
")",
";",
"}",
"}",
"return",
"$",
"date",
";",
"}"
] |
Translates available months inside a given string into their English representations taking into account the current language.
@param string $date
@return mixed|string
|
[
"Translates",
"available",
"months",
"inside",
"a",
"given",
"string",
"into",
"their",
"English",
"representations",
"taking",
"into",
"account",
"the",
"current",
"language",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L365-L380
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Date/DateUtil.php
|
DateUtil.translateMonths
|
public function translateMonths(string $date)
{
foreach (array_flip($this->getMonthTranslationMap()) as $translated => $english) {
if (false !== strpos($date, $english)) {
$date = str_replace($english, $translated, $date);
}
}
foreach (array_flip($this->getShortMonthTranslationMap()) as $translated => $english) {
if (false !== strpos($date, $english)) {
$date = str_replace($english, $translated, $date);
}
}
return $date;
}
|
php
|
public function translateMonths(string $date)
{
foreach (array_flip($this->getMonthTranslationMap()) as $translated => $english) {
if (false !== strpos($date, $english)) {
$date = str_replace($english, $translated, $date);
}
}
foreach (array_flip($this->getShortMonthTranslationMap()) as $translated => $english) {
if (false !== strpos($date, $english)) {
$date = str_replace($english, $translated, $date);
}
}
return $date;
}
|
[
"public",
"function",
"translateMonths",
"(",
"string",
"$",
"date",
")",
"{",
"foreach",
"(",
"array_flip",
"(",
"$",
"this",
"->",
"getMonthTranslationMap",
"(",
")",
")",
"as",
"$",
"translated",
"=>",
"$",
"english",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"date",
",",
"$",
"english",
")",
")",
"{",
"$",
"date",
"=",
"str_replace",
"(",
"$",
"english",
",",
"$",
"translated",
",",
"$",
"date",
")",
";",
"}",
"}",
"foreach",
"(",
"array_flip",
"(",
"$",
"this",
"->",
"getShortMonthTranslationMap",
"(",
")",
")",
"as",
"$",
"translated",
"=>",
"$",
"english",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"date",
",",
"$",
"english",
")",
")",
"{",
"$",
"date",
"=",
"str_replace",
"(",
"$",
"english",
",",
"$",
"translated",
",",
"$",
"date",
")",
";",
"}",
"}",
"return",
"$",
"date",
";",
"}"
] |
Translates available months inside a given string from English to the current language.
@param string $date
@return mixed|string
|
[
"Translates",
"available",
"months",
"inside",
"a",
"given",
"string",
"from",
"English",
"to",
"the",
"current",
"language",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Date/DateUtil.php#L389-L404
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/RemoteImageCache.php
|
RemoteImageCache.get
|
public function get(string $identifier, $folder, $remoteUrl, $returnUuid = false)
{
$strFilename = $identifier.'.jpg';
if (Validator::isUuid($folder)) {
$objFolder = $this->container->get('huh.utils.file')->getFolderFromUuid($folder);
if (false === $objFolder) {
return false;
}
$folder = $objFolder->value;
}
$objFile = new File(rtrim($folder, '/').'/'.$strFilename);
if ($objFile->exists() && $objFile->size > 0) {
return $returnUuid ? $objFile->getModel()->uuid : $objFile->path;
}
$strContent = $this->container->get('huh.utils.request.curl')->request($remoteUrl);
if (!$strContent || !\is_string($strContent)) {
return false;
}
$objFile->write($strContent);
$objFile->close();
return $returnUuid ? $objFile->getModel()->uuid : $objFile->path;
}
|
php
|
public function get(string $identifier, $folder, $remoteUrl, $returnUuid = false)
{
$strFilename = $identifier.'.jpg';
if (Validator::isUuid($folder)) {
$objFolder = $this->container->get('huh.utils.file')->getFolderFromUuid($folder);
if (false === $objFolder) {
return false;
}
$folder = $objFolder->value;
}
$objFile = new File(rtrim($folder, '/').'/'.$strFilename);
if ($objFile->exists() && $objFile->size > 0) {
return $returnUuid ? $objFile->getModel()->uuid : $objFile->path;
}
$strContent = $this->container->get('huh.utils.request.curl')->request($remoteUrl);
if (!$strContent || !\is_string($strContent)) {
return false;
}
$objFile->write($strContent);
$objFile->close();
return $returnUuid ? $objFile->getModel()->uuid : $objFile->path;
}
|
[
"public",
"function",
"get",
"(",
"string",
"$",
"identifier",
",",
"$",
"folder",
",",
"$",
"remoteUrl",
",",
"$",
"returnUuid",
"=",
"false",
")",
"{",
"$",
"strFilename",
"=",
"$",
"identifier",
".",
"'.jpg'",
";",
"if",
"(",
"Validator",
"::",
"isUuid",
"(",
"$",
"folder",
")",
")",
"{",
"$",
"objFolder",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.file'",
")",
"->",
"getFolderFromUuid",
"(",
"$",
"folder",
")",
";",
"if",
"(",
"false",
"===",
"$",
"objFolder",
")",
"{",
"return",
"false",
";",
"}",
"$",
"folder",
"=",
"$",
"objFolder",
"->",
"value",
";",
"}",
"$",
"objFile",
"=",
"new",
"File",
"(",
"rtrim",
"(",
"$",
"folder",
",",
"'/'",
")",
".",
"'/'",
".",
"$",
"strFilename",
")",
";",
"if",
"(",
"$",
"objFile",
"->",
"exists",
"(",
")",
"&&",
"$",
"objFile",
"->",
"size",
">",
"0",
")",
"{",
"return",
"$",
"returnUuid",
"?",
"$",
"objFile",
"->",
"getModel",
"(",
")",
"->",
"uuid",
":",
"$",
"objFile",
"->",
"path",
";",
"}",
"$",
"strContent",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.request.curl'",
")",
"->",
"request",
"(",
"$",
"remoteUrl",
")",
";",
"if",
"(",
"!",
"$",
"strContent",
"||",
"!",
"\\",
"is_string",
"(",
"$",
"strContent",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"objFile",
"->",
"write",
"(",
"$",
"strContent",
")",
";",
"$",
"objFile",
"->",
"close",
"(",
")",
";",
"return",
"$",
"returnUuid",
"?",
"$",
"objFile",
"->",
"getModel",
"(",
")",
"->",
"uuid",
":",
"$",
"objFile",
"->",
"path",
";",
"}"
] |
Get a remote file from cache and cache file, if not already in cache.
Returns false, if remote file could not be fetched or given uuid is not valid.
Else returns the url or, if $returnUuid is set true, the uuid of the image.
@param string $identifier Used as filename of the cached image. Should be unique within the folder scope
@param string $folder Folder path or uuid of the file
@param string $remoteUrl The url of the cached (or to cache) file
@param bool $returnUuid Return uuid instead of the path
@throws \Exception
@return bool|string
|
[
"Get",
"a",
"remote",
"file",
"from",
"cache",
"and",
"cache",
"file",
"if",
"not",
"already",
"in",
"cache",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/RemoteImageCache.php#L48-L77
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Classes/ClassUtil.php
|
ClassUtil.getClassesInNamespace
|
public function getClassesInNamespace(string $namespace)
{
$arrOptions = [];
foreach (get_declared_classes() as $strName) {
if ($this->container->get('huh.utils.string')->startsWith($strName, $namespace)) {
$arrOptions[$strName] = $strName;
}
}
asort($arrOptions);
return $arrOptions;
}
|
php
|
public function getClassesInNamespace(string $namespace)
{
$arrOptions = [];
foreach (get_declared_classes() as $strName) {
if ($this->container->get('huh.utils.string')->startsWith($strName, $namespace)) {
$arrOptions[$strName] = $strName;
}
}
asort($arrOptions);
return $arrOptions;
}
|
[
"public",
"function",
"getClassesInNamespace",
"(",
"string",
"$",
"namespace",
")",
"{",
"$",
"arrOptions",
"=",
"[",
"]",
";",
"foreach",
"(",
"get_declared_classes",
"(",
")",
"as",
"$",
"strName",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.string'",
")",
"->",
"startsWith",
"(",
"$",
"strName",
",",
"$",
"namespace",
")",
")",
"{",
"$",
"arrOptions",
"[",
"$",
"strName",
"]",
"=",
"$",
"strName",
";",
"}",
"}",
"asort",
"(",
"$",
"arrOptions",
")",
";",
"return",
"$",
"arrOptions",
";",
"}"
] |
Returns all classes in the given namespace.
@param string $namespace
@return array
|
[
"Returns",
"all",
"classes",
"in",
"the",
"given",
"namespace",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Classes/ClassUtil.php#L85-L98
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Classes/ClassUtil.php
|
ClassUtil.getChildClasses
|
public function getChildClasses(string $qualifiedClassName)
{
$arrOptions = [];
foreach (get_declared_classes() as $strName) {
if (\in_array($qualifiedClassName, $this->getParentClasses($strName))) {
$arrOptions[$strName] = $strName;
}
}
asort($arrOptions);
return $arrOptions;
}
|
php
|
public function getChildClasses(string $qualifiedClassName)
{
$arrOptions = [];
foreach (get_declared_classes() as $strName) {
if (\in_array($qualifiedClassName, $this->getParentClasses($strName))) {
$arrOptions[$strName] = $strName;
}
}
asort($arrOptions);
return $arrOptions;
}
|
[
"public",
"function",
"getChildClasses",
"(",
"string",
"$",
"qualifiedClassName",
")",
"{",
"$",
"arrOptions",
"=",
"[",
"]",
";",
"foreach",
"(",
"get_declared_classes",
"(",
")",
"as",
"$",
"strName",
")",
"{",
"if",
"(",
"\\",
"in_array",
"(",
"$",
"qualifiedClassName",
",",
"$",
"this",
"->",
"getParentClasses",
"(",
"$",
"strName",
")",
")",
")",
"{",
"$",
"arrOptions",
"[",
"$",
"strName",
"]",
"=",
"$",
"strName",
";",
"}",
"}",
"asort",
"(",
"$",
"arrOptions",
")",
";",
"return",
"$",
"arrOptions",
";",
"}"
] |
Returns all children of a given class.
@param string $strNamespace
@return array
|
[
"Returns",
"all",
"children",
"of",
"a",
"given",
"class",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Classes/ClassUtil.php#L107-L120
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Classes/ClassUtil.php
|
ClassUtil.callInaccessibleMethod
|
public function callInaccessibleMethod($entity, string $method)
{
$rc = new \ReflectionClass($entity);
if ($rc->hasMethod($method)) {
$method = $rc->getMethod($method);
$method->setAccessible(true);
return $method->invoke($entity);
}
return null;
}
|
php
|
public function callInaccessibleMethod($entity, string $method)
{
$rc = new \ReflectionClass($entity);
if ($rc->hasMethod($method)) {
$method = $rc->getMethod($method);
$method->setAccessible(true);
return $method->invoke($entity);
}
return null;
}
|
[
"public",
"function",
"callInaccessibleMethod",
"(",
"$",
"entity",
",",
"string",
"$",
"method",
")",
"{",
"$",
"rc",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"entity",
")",
";",
"if",
"(",
"$",
"rc",
"->",
"hasMethod",
"(",
"$",
"method",
")",
")",
"{",
"$",
"method",
"=",
"$",
"rc",
"->",
"getMethod",
"(",
"$",
"method",
")",
";",
"$",
"method",
"->",
"setAccessible",
"(",
"true",
")",
";",
"return",
"$",
"method",
"->",
"invoke",
"(",
"$",
"entity",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Calls an object's method which is inaccessible.
@param $entity
@param string $method
@throws \ReflectionException
@return mixed|null
|
[
"Calls",
"an",
"object",
"s",
"method",
"which",
"is",
"inaccessible",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Classes/ClassUtil.php#L229-L241
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._translateConfigMessages
|
protected function _translateConfigMessages() {
return [
'requestPassword' => [
'successMessage' => __d('burzum/user_tools', 'An email was send to your address, please check your inbox.'),
'errorMessage' => __d('burzum/user_tools', 'Invalid user.'),
],
'resetPassword' => [
'successMessage' => __d('burzum/user_tools', 'Your password has been reset, you can now login.'),
'errorMessage' => __d('burzum/user_tools', 'Please check your inputs.'),
'invalidErrorMessage' => __d('burzum/user_tools', 'Invalid token!'),
'expiredErrorMessage' => __d('burzum/user_tools', 'The token has expired!')
],
'changePassword' => [
'successMessage' => __d('burzum/user_tools', 'Your password has been updated.'),
'errorMessage' => __d('burzum/user_tools', 'Could not update your password, please check for errors and try again.'),
],
'registration' => [
'successMessage' => __d('burzum/user_tools', 'Thank you for signing up!'),
'errorMessage' => __d('burzum/user_tools', 'Please check your inputs'),
],
'login' => [
'successMessage' => __d('burzum/user_tools', 'You are logged in!'),
'errorMessage' => __d('burzum/user_tools', 'Invalid login credentials.'),
],
'logout' => [
'successMessage' => __d('burzum/user_tools', 'You are logged out!'),
],
'verifyEmailToken' => [
'successMessage' => __d('burzum/user_tools', 'Email verified, you can now login!'),
'errorMessage' => __d('burzum/user_tools', 'Invalid email token!'),
],
'verifyToken' => [
'successMessage' => __d('burzum/user_tools', 'Token verified!'),
]
];
}
|
php
|
protected function _translateConfigMessages() {
return [
'requestPassword' => [
'successMessage' => __d('burzum/user_tools', 'An email was send to your address, please check your inbox.'),
'errorMessage' => __d('burzum/user_tools', 'Invalid user.'),
],
'resetPassword' => [
'successMessage' => __d('burzum/user_tools', 'Your password has been reset, you can now login.'),
'errorMessage' => __d('burzum/user_tools', 'Please check your inputs.'),
'invalidErrorMessage' => __d('burzum/user_tools', 'Invalid token!'),
'expiredErrorMessage' => __d('burzum/user_tools', 'The token has expired!')
],
'changePassword' => [
'successMessage' => __d('burzum/user_tools', 'Your password has been updated.'),
'errorMessage' => __d('burzum/user_tools', 'Could not update your password, please check for errors and try again.'),
],
'registration' => [
'successMessage' => __d('burzum/user_tools', 'Thank you for signing up!'),
'errorMessage' => __d('burzum/user_tools', 'Please check your inputs'),
],
'login' => [
'successMessage' => __d('burzum/user_tools', 'You are logged in!'),
'errorMessage' => __d('burzum/user_tools', 'Invalid login credentials.'),
],
'logout' => [
'successMessage' => __d('burzum/user_tools', 'You are logged out!'),
],
'verifyEmailToken' => [
'successMessage' => __d('burzum/user_tools', 'Email verified, you can now login!'),
'errorMessage' => __d('burzum/user_tools', 'Invalid email token!'),
],
'verifyToken' => [
'successMessage' => __d('burzum/user_tools', 'Token verified!'),
]
];
}
|
[
"protected",
"function",
"_translateConfigMessages",
"(",
")",
"{",
"return",
"[",
"'requestPassword'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'An email was send to your address, please check your inbox.'",
")",
",",
"'errorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Invalid user.'",
")",
",",
"]",
",",
"'resetPassword'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Your password has been reset, you can now login.'",
")",
",",
"'errorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Please check your inputs.'",
")",
",",
"'invalidErrorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Invalid token!'",
")",
",",
"'expiredErrorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'The token has expired!'",
")",
"]",
",",
"'changePassword'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Your password has been updated.'",
")",
",",
"'errorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Could not update your password, please check for errors and try again.'",
")",
",",
"]",
",",
"'registration'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Thank you for signing up!'",
")",
",",
"'errorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Please check your inputs'",
")",
",",
"]",
",",
"'login'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'You are logged in!'",
")",
",",
"'errorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Invalid login credentials.'",
")",
",",
"]",
",",
"'logout'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'You are logged out!'",
")",
",",
"]",
",",
"'verifyEmailToken'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Email verified, you can now login!'",
")",
",",
"'errorMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Invalid email token!'",
")",
",",
"]",
",",
"'verifyToken'",
"=>",
"[",
"'successMessage'",
"=>",
"__d",
"(",
"'burzum/user_tools'",
",",
"'Token verified!'",
")",
",",
"]",
"]",
";",
"}"
] |
Translates the messages in the configuration array
@return array
|
[
"Translates",
"the",
"messages",
"in",
"the",
"configuration",
"array"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L252-L287
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.listing
|
public function listing($options = []) {
$this->getController()->set('users', $this->getController()->paginate($this->UserTable, $options));
$this->getController()->set('_serialize', ['users']);
}
|
php
|
public function listing($options = []) {
$this->getController()->set('users', $this->getController()->paginate($this->UserTable, $options));
$this->getController()->set('_serialize', ['users']);
}
|
[
"public",
"function",
"listing",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"set",
"(",
"'users'",
",",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"paginate",
"(",
"$",
"this",
"->",
"UserTable",
",",
"$",
"options",
")",
")",
";",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"set",
"(",
"'_serialize'",
",",
"[",
"'users'",
"]",
")",
";",
"}"
] |
User listing with pagination.
@param array $options Pagination options
@return void
|
[
"User",
"listing",
"with",
"pagination",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L306-L309
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.loadUserBehaviour
|
public function loadUserBehaviour() {
if ($this->getConfig('autoloadBehavior') && !$this->UserTable->hasBehavior('UserTools.User')) {
if (is_array($this->getConfig('autoloadBehavior'))) {
$this->UserTable->addBehavior('Burzum/UserTools.User', $this->getConfig('autoloadBehavior'));
} else {
$this->UserTable->addBehavior('Burzum/UserTools.User');
}
}
}
|
php
|
public function loadUserBehaviour() {
if ($this->getConfig('autoloadBehavior') && !$this->UserTable->hasBehavior('UserTools.User')) {
if (is_array($this->getConfig('autoloadBehavior'))) {
$this->UserTable->addBehavior('Burzum/UserTools.User', $this->getConfig('autoloadBehavior'));
} else {
$this->UserTable->addBehavior('Burzum/UserTools.User');
}
}
}
|
[
"public",
"function",
"loadUserBehaviour",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'autoloadBehavior'",
")",
"&&",
"!",
"$",
"this",
"->",
"UserTable",
"->",
"hasBehavior",
"(",
"'UserTools.User'",
")",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'autoloadBehavior'",
")",
")",
")",
"{",
"$",
"this",
"->",
"UserTable",
"->",
"addBehavior",
"(",
"'Burzum/UserTools.User'",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'autoloadBehavior'",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"UserTable",
"->",
"addBehavior",
"(",
"'Burzum/UserTools.User'",
")",
";",
"}",
"}",
"}"
] |
Loads the User behavior for the user model if it is not already loaded
@return void
|
[
"Loads",
"the",
"User",
"behavior",
"for",
"the",
"user",
"model",
"if",
"it",
"is",
"not",
"already",
"loaded"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L316-L324
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.setUserTable
|
public function setUserTable($table = null) {
if ($table === null) {
$this->UserTable = $this->getController()->{$this->getController()->modelClass};
} else {
if (is_object($table)) {
if (!is_a($table, Table::class)) {
throw new RuntimeException('Passed object is not of type \Cake\ORM\Table!');
}
$this->UserTable = $table->getAlias();
}
if (is_string($table)) {
$this->UserTable = TableRegistry::get($table);
}
}
$this->getController()->set('userTable', $this->UserTable->getAlias());
}
|
php
|
public function setUserTable($table = null) {
if ($table === null) {
$this->UserTable = $this->getController()->{$this->getController()->modelClass};
} else {
if (is_object($table)) {
if (!is_a($table, Table::class)) {
throw new RuntimeException('Passed object is not of type \Cake\ORM\Table!');
}
$this->UserTable = $table->getAlias();
}
if (is_string($table)) {
$this->UserTable = TableRegistry::get($table);
}
}
$this->getController()->set('userTable', $this->UserTable->getAlias());
}
|
[
"public",
"function",
"setUserTable",
"(",
"$",
"table",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"table",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"UserTable",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"{",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"modelClass",
"}",
";",
"}",
"else",
"{",
"if",
"(",
"is_object",
"(",
"$",
"table",
")",
")",
"{",
"if",
"(",
"!",
"is_a",
"(",
"$",
"table",
",",
"Table",
"::",
"class",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Passed object is not of type \\Cake\\ORM\\Table!'",
")",
";",
"}",
"$",
"this",
"->",
"UserTable",
"=",
"$",
"table",
"->",
"getAlias",
"(",
")",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"table",
")",
")",
"{",
"$",
"this",
"->",
"UserTable",
"=",
"TableRegistry",
"::",
"get",
"(",
"$",
"table",
")",
";",
"}",
"}",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"set",
"(",
"'userTable'",
",",
"$",
"this",
"->",
"UserTable",
"->",
"getAlias",
"(",
")",
")",
";",
"}"
] |
Sets or instantiates the user model class.
@param null|string|\Cake\ORM\Table $table Table name or a table object
@throws \RuntimeException
@return void
|
[
"Sets",
"or",
"instantiates",
"the",
"user",
"model",
"class",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L333-L349
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.mapAction
|
public function mapAction() {
$action = $this->_getRequest()->params['action'];
if ($this->getConfig('directMapping') === true) {
$this->_directMapping($action);
}
return $this->_mapAction($action);
}
|
php
|
public function mapAction() {
$action = $this->_getRequest()->params['action'];
if ($this->getConfig('directMapping') === true) {
$this->_directMapping($action);
}
return $this->_mapAction($action);
}
|
[
"public",
"function",
"mapAction",
"(",
")",
"{",
"$",
"action",
"=",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"params",
"[",
"'action'",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'directMapping'",
")",
"===",
"true",
")",
"{",
"$",
"this",
"->",
"_directMapping",
"(",
"$",
"action",
")",
";",
"}",
"return",
"$",
"this",
"->",
"_mapAction",
"(",
"$",
"action",
")",
";",
"}"
] |
Maps a called controller action to a component method
@return bool|\Cake\Http\Response
|
[
"Maps",
"a",
"called",
"controller",
"action",
"to",
"a",
"component",
"method"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L372-L379
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._mapAction
|
protected function _mapAction($action) {
$actionMap = $this->getConfig('actionMap');
if (isset($actionMap[$action]) && method_exists($this, $actionMap[$action]['method'])) {
$pass = (array)$this->_getRequest()->param('pass');
call_user_func_array([$this, $actionMap[$action]['method']], $pass);
if ($this->_redirectResponse instanceof Response) {
return $this->_redirectResponse;
}
if (is_string($actionMap[$action]['view'])) {
try {
return $this->getController()->render($this->getController()->request->param('action'));
} catch (MissingTemplateException $e) {
return $this->getController()->render($actionMap[$action]['view']);
}
}
return $this->_getResponse();
}
return false;
}
|
php
|
protected function _mapAction($action) {
$actionMap = $this->getConfig('actionMap');
if (isset($actionMap[$action]) && method_exists($this, $actionMap[$action]['method'])) {
$pass = (array)$this->_getRequest()->param('pass');
call_user_func_array([$this, $actionMap[$action]['method']], $pass);
if ($this->_redirectResponse instanceof Response) {
return $this->_redirectResponse;
}
if (is_string($actionMap[$action]['view'])) {
try {
return $this->getController()->render($this->getController()->request->param('action'));
} catch (MissingTemplateException $e) {
return $this->getController()->render($actionMap[$action]['view']);
}
}
return $this->_getResponse();
}
return false;
}
|
[
"protected",
"function",
"_mapAction",
"(",
"$",
"action",
")",
"{",
"$",
"actionMap",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'actionMap'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"actionMap",
"[",
"$",
"action",
"]",
")",
"&&",
"method_exists",
"(",
"$",
"this",
",",
"$",
"actionMap",
"[",
"$",
"action",
"]",
"[",
"'method'",
"]",
")",
")",
"{",
"$",
"pass",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"param",
"(",
"'pass'",
")",
";",
"call_user_func_array",
"(",
"[",
"$",
"this",
",",
"$",
"actionMap",
"[",
"$",
"action",
"]",
"[",
"'method'",
"]",
"]",
",",
"$",
"pass",
")",
";",
"if",
"(",
"$",
"this",
"->",
"_redirectResponse",
"instanceof",
"Response",
")",
"{",
"return",
"$",
"this",
"->",
"_redirectResponse",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"actionMap",
"[",
"$",
"action",
"]",
"[",
"'view'",
"]",
")",
")",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"render",
"(",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"request",
"->",
"param",
"(",
"'action'",
")",
")",
";",
"}",
"catch",
"(",
"MissingTemplateException",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"render",
"(",
"$",
"actionMap",
"[",
"$",
"action",
"]",
"[",
"'view'",
"]",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"_getResponse",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Maps an action of the controller to the component
@param string $action Action name
@return bool|\Cake\Http\Response
|
[
"Maps",
"an",
"action",
"of",
"the",
"controller",
"to",
"the",
"component"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L408-L430
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._handleUserBeingAlreadyLoggedIn
|
protected function _handleUserBeingAlreadyLoggedIn(array $options) {
$Auth = $this->_getAuthObject();
if ((bool)$Auth->user()) {
if ($options['alreadyLoggedInRedirectUrl'] === null) {
$options['alreadyLoggedInRedirectUrl'] = $this->_getRequest()->referer();
}
$this->handleFlashAndRedirect('alreadyLoggedIn', $options);
}
}
|
php
|
protected function _handleUserBeingAlreadyLoggedIn(array $options) {
$Auth = $this->_getAuthObject();
if ((bool)$Auth->user()) {
if ($options['alreadyLoggedInRedirectUrl'] === null) {
$options['alreadyLoggedInRedirectUrl'] = $this->_getRequest()->referer();
}
$this->handleFlashAndRedirect('alreadyLoggedIn', $options);
}
}
|
[
"protected",
"function",
"_handleUserBeingAlreadyLoggedIn",
"(",
"array",
"$",
"options",
")",
"{",
"$",
"Auth",
"=",
"$",
"this",
"->",
"_getAuthObject",
"(",
")",
";",
"if",
"(",
"(",
"bool",
")",
"$",
"Auth",
"->",
"user",
"(",
")",
")",
"{",
"if",
"(",
"$",
"options",
"[",
"'alreadyLoggedInRedirectUrl'",
"]",
"===",
"null",
")",
"{",
"$",
"options",
"[",
"'alreadyLoggedInRedirectUrl'",
"]",
"=",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"referer",
"(",
")",
";",
"}",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'alreadyLoggedIn'",
",",
"$",
"options",
")",
";",
"}",
"}"
] |
Handles the case when the user is already logged in and triggers a redirect
and flash message if configured for that.
@see UserToolComponent::login()
@param array $options Options
@return void
|
[
"Handles",
"the",
"case",
"when",
"the",
"user",
"is",
"already",
"logged",
"in",
"and",
"triggers",
"a",
"redirect",
"and",
"flash",
"message",
"if",
"configured",
"for",
"that",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L440-L448
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._beforeLogin
|
protected function _beforeLogin(EntityInterface $entity, array $options) {
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData(), ['validate' => false]);
$event = $this->dispatchEvent('User.beforeLogin', [
'options' => $options,
'entity' => $entity
]);
if ($event->isStopped()) {
return $event->result;
}
return $this->_getAuthObject()->identify();
}
|
php
|
protected function _beforeLogin(EntityInterface $entity, array $options) {
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData(), ['validate' => false]);
$event = $this->dispatchEvent('User.beforeLogin', [
'options' => $options,
'entity' => $entity
]);
if ($event->isStopped()) {
return $event->result;
}
return $this->_getAuthObject()->identify();
}
|
[
"protected",
"function",
"_beforeLogin",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"options",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"patchEntity",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"getData",
"(",
")",
",",
"[",
"'validate'",
"=>",
"false",
"]",
")",
";",
"$",
"event",
"=",
"$",
"this",
"->",
"dispatchEvent",
"(",
"'User.beforeLogin'",
",",
"[",
"'options'",
"=>",
"$",
"options",
",",
"'entity'",
"=>",
"$",
"entity",
"]",
")",
";",
"if",
"(",
"$",
"event",
"->",
"isStopped",
"(",
")",
")",
"{",
"return",
"$",
"event",
"->",
"result",
";",
"}",
"return",
"$",
"this",
"->",
"_getAuthObject",
"(",
")",
"->",
"identify",
"(",
")",
";",
"}"
] |
Internal callback to prepare the credentials for the login.
@param \Cake\Datasource\EntityInterface $entity User entity
@param array $options Options
@return mixed
|
[
"Internal",
"callback",
"to",
"prepare",
"the",
"credentials",
"for",
"the",
"login",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L457-L470
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._afterLogin
|
protected function _afterLogin($user, array $options) {
$event = $this->dispatchEvent('User.afterLogin', [
'user' => $user,
'options' => $options
]);
if ($event->isStopped()) {
return $event->result;
}
$Auth = $this->_getAuthObject();
$Auth->setUser($user);
if ($options['successRedirectUrl'] === null) {
$options['successRedirectUrl'] = $Auth->redirectUrl();
}
$this->handleFlashAndRedirect('success', $options);
return true;
}
|
php
|
protected function _afterLogin($user, array $options) {
$event = $this->dispatchEvent('User.afterLogin', [
'user' => $user,
'options' => $options
]);
if ($event->isStopped()) {
return $event->result;
}
$Auth = $this->_getAuthObject();
$Auth->setUser($user);
if ($options['successRedirectUrl'] === null) {
$options['successRedirectUrl'] = $Auth->redirectUrl();
}
$this->handleFlashAndRedirect('success', $options);
return true;
}
|
[
"protected",
"function",
"_afterLogin",
"(",
"$",
"user",
",",
"array",
"$",
"options",
")",
"{",
"$",
"event",
"=",
"$",
"this",
"->",
"dispatchEvent",
"(",
"'User.afterLogin'",
",",
"[",
"'user'",
"=>",
"$",
"user",
",",
"'options'",
"=>",
"$",
"options",
"]",
")",
";",
"if",
"(",
"$",
"event",
"->",
"isStopped",
"(",
")",
")",
"{",
"return",
"$",
"event",
"->",
"result",
";",
"}",
"$",
"Auth",
"=",
"$",
"this",
"->",
"_getAuthObject",
"(",
")",
";",
"$",
"Auth",
"->",
"setUser",
"(",
"$",
"user",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'successRedirectUrl'",
"]",
"===",
"null",
")",
"{",
"$",
"options",
"[",
"'successRedirectUrl'",
"]",
"=",
"$",
"Auth",
"->",
"redirectUrl",
"(",
")",
";",
"}",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'success'",
",",
"$",
"options",
")",
";",
"return",
"true",
";",
"}"
] |
Internal callback to handle the after login procedure.
@param array $user User data
@param array $options Options
@return mixed
|
[
"Internal",
"callback",
"to",
"handle",
"the",
"after",
"login",
"procedure",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L479-L498
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.getUser
|
public function getUser($userId = null, $options = []) {
$options = Hash::merge($this->getConfig('getUser'), $options);
if (is_null($userId)) {
if (isset($this->_getRequest()->getParam('pass')[0])) {
$userId = $this->_getRequest()->getParam('pass')[0];
}
}
$entity = $this->UserTable->getUser($userId);
if ($options['viewVar'] !== false) {
$this->getController()->set($options['viewVar'], $entity);
$this->getController()->set('_serialize', [$options['viewVar']]);
}
return $entity;
}
|
php
|
public function getUser($userId = null, $options = []) {
$options = Hash::merge($this->getConfig('getUser'), $options);
if (is_null($userId)) {
if (isset($this->_getRequest()->getParam('pass')[0])) {
$userId = $this->_getRequest()->getParam('pass')[0];
}
}
$entity = $this->UserTable->getUser($userId);
if ($options['viewVar'] !== false) {
$this->getController()->set($options['viewVar'], $entity);
$this->getController()->set('_serialize', [$options['viewVar']]);
}
return $entity;
}
|
[
"public",
"function",
"getUser",
"(",
"$",
"userId",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'getUser'",
")",
",",
"$",
"options",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"userId",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"getParam",
"(",
"'pass'",
")",
"[",
"0",
"]",
")",
")",
"{",
"$",
"userId",
"=",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"getParam",
"(",
"'pass'",
")",
"[",
"0",
"]",
";",
"}",
"}",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"getUser",
"(",
"$",
"userId",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'viewVar'",
"]",
"!==",
"false",
")",
"{",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"set",
"(",
"$",
"options",
"[",
"'viewVar'",
"]",
",",
"$",
"entity",
")",
";",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"set",
"(",
"'_serialize'",
",",
"[",
"$",
"options",
"[",
"'viewVar'",
"]",
"]",
")",
";",
"}",
"return",
"$",
"entity",
";",
"}"
] |
Gets an user based on it's user id.
- `viewVar` it sets the entity to the view. It's set by default to `user`. To
disable setting the view var just set it to false.
@param int|string $userId UUID or integer type user id.
@param array $options Configuration options.
@return mixed
|
[
"Gets",
"an",
"user",
"based",
"on",
"it",
"s",
"user",
"id",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L537-L553
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.deleteUser
|
public function deleteUser($userId = null, $options = []) {
$entity = $this->_getUserEntity($userId);
if ($this->UserTable->delete($entity)) {
$this->handleFlashAndRedirect('success', $options);
return true;
} else {
$this->handleFlashAndRedirect('error', $options);
return false;
}
}
|
php
|
public function deleteUser($userId = null, $options = []) {
$entity = $this->_getUserEntity($userId);
if ($this->UserTable->delete($entity)) {
$this->handleFlashAndRedirect('success', $options);
return true;
} else {
$this->handleFlashAndRedirect('error', $options);
return false;
}
}
|
[
"public",
"function",
"deleteUser",
"(",
"$",
"userId",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"_getUserEntity",
"(",
"$",
"userId",
")",
";",
"if",
"(",
"$",
"this",
"->",
"UserTable",
"->",
"delete",
"(",
"$",
"entity",
")",
")",
"{",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'success'",
",",
"$",
"options",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'error'",
",",
"$",
"options",
")",
";",
"return",
"false",
";",
"}",
"}"
] |
Deletes an user record
@param mixed $userId User ID
@param array $options Options
@return bool
|
[
"Deletes",
"an",
"user",
"record"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L562-L573
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._getUserEntity
|
protected function _getUserEntity($userId) {
if (is_a($userId, EntityInterface::class)) {
return $userId;
}
if (is_string($userId) || is_integer($userId)) {
$entity = $this->UserTable->newEntity();
return $this->UserTable->patchEntity(
$entity,
[$this->UserTable->primaryKey() => $userId],
['guard' => false]
);
}
if (is_array($userId)) {
$entity = $this->UserTable->newEntity();
return $this->UserTable->patchEntity(
$entity,
$userId,
['guard' => false]
);
}
}
|
php
|
protected function _getUserEntity($userId) {
if (is_a($userId, EntityInterface::class)) {
return $userId;
}
if (is_string($userId) || is_integer($userId)) {
$entity = $this->UserTable->newEntity();
return $this->UserTable->patchEntity(
$entity,
[$this->UserTable->primaryKey() => $userId],
['guard' => false]
);
}
if (is_array($userId)) {
$entity = $this->UserTable->newEntity();
return $this->UserTable->patchEntity(
$entity,
$userId,
['guard' => false]
);
}
}
|
[
"protected",
"function",
"_getUserEntity",
"(",
"$",
"userId",
")",
"{",
"if",
"(",
"is_a",
"(",
"$",
"userId",
",",
"EntityInterface",
"::",
"class",
")",
")",
"{",
"return",
"$",
"userId",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"userId",
")",
"||",
"is_integer",
"(",
"$",
"userId",
")",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"newEntity",
"(",
")",
";",
"return",
"$",
"this",
"->",
"UserTable",
"->",
"patchEntity",
"(",
"$",
"entity",
",",
"[",
"$",
"this",
"->",
"UserTable",
"->",
"primaryKey",
"(",
")",
"=>",
"$",
"userId",
"]",
",",
"[",
"'guard'",
"=>",
"false",
"]",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"userId",
")",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"newEntity",
"(",
")",
";",
"return",
"$",
"this",
"->",
"UserTable",
"->",
"patchEntity",
"(",
"$",
"entity",
",",
"$",
"userId",
",",
"[",
"'guard'",
"=>",
"false",
"]",
")",
";",
"}",
"}"
] |
Gets or constructs an user entity with a given id.
@param mixed array|int|string $userId User ID
@return \Cake\Datasource\EntityInterface
|
[
"Gets",
"or",
"constructs",
"an",
"user",
"entity",
"with",
"a",
"given",
"id",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L581-L605
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.verifyEmailToken
|
public function verifyEmailToken($options = []) {
$options = Hash::merge(
$this->getConfig('verifyEmailToken'),
$options,
['type' => 'Email']
);
return $this->verifyToken($options);
}
|
php
|
public function verifyEmailToken($options = []) {
$options = Hash::merge(
$this->getConfig('verifyEmailToken'),
$options,
['type' => 'Email']
);
return $this->verifyToken($options);
}
|
[
"public",
"function",
"verifyEmailToken",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'verifyEmailToken'",
")",
",",
"$",
"options",
",",
"[",
"'type'",
"=>",
"'Email'",
"]",
")",
";",
"return",
"$",
"this",
"->",
"verifyToken",
"(",
"$",
"options",
")",
";",
"}"
] |
Verifies an email token
@param array $options Options
@return mixed
|
[
"Verifies",
"an",
"email",
"token"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L682-L690
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.requestPassword
|
public function requestPassword($options = []) {
$options = Hash::merge($this->getConfig('requestPassword'), $options);
$entity = $this->UserTable->newEntity(null, [
'validate' => 'requestPassword'
]);
if ($this->_getRequest()->is('post')) {
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData(), [
'validate' => 'requestPassword'
]);
if (!$entity->errors($options['field']) && $this->_initPasswordReset($entity, $options)) {
return true;
}
if ($options['setEntity']) {
if ($entity->dirty('email') && !$entity->errors('email')) {
$entity->email = '';
}
$this->_setViewVar('userEntity', $entity);
}
unset($this->_getRequest()->data[$options['field']]);
return false;
}
if ($options['setEntity']) {
$this->getController()->set('userEntity', $entity);
}
}
|
php
|
public function requestPassword($options = []) {
$options = Hash::merge($this->getConfig('requestPassword'), $options);
$entity = $this->UserTable->newEntity(null, [
'validate' => 'requestPassword'
]);
if ($this->_getRequest()->is('post')) {
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData(), [
'validate' => 'requestPassword'
]);
if (!$entity->errors($options['field']) && $this->_initPasswordReset($entity, $options)) {
return true;
}
if ($options['setEntity']) {
if ($entity->dirty('email') && !$entity->errors('email')) {
$entity->email = '';
}
$this->_setViewVar('userEntity', $entity);
}
unset($this->_getRequest()->data[$options['field']]);
return false;
}
if ($options['setEntity']) {
$this->getController()->set('userEntity', $entity);
}
}
|
[
"public",
"function",
"requestPassword",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'requestPassword'",
")",
",",
"$",
"options",
")",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"newEntity",
"(",
"null",
",",
"[",
"'validate'",
"=>",
"'requestPassword'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"is",
"(",
"'post'",
")",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"patchEntity",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"getData",
"(",
")",
",",
"[",
"'validate'",
"=>",
"'requestPassword'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"entity",
"->",
"errors",
"(",
"$",
"options",
"[",
"'field'",
"]",
")",
"&&",
"$",
"this",
"->",
"_initPasswordReset",
"(",
"$",
"entity",
",",
"$",
"options",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'setEntity'",
"]",
")",
"{",
"if",
"(",
"$",
"entity",
"->",
"dirty",
"(",
"'email'",
")",
"&&",
"!",
"$",
"entity",
"->",
"errors",
"(",
"'email'",
")",
")",
"{",
"$",
"entity",
"->",
"email",
"=",
"''",
";",
"}",
"$",
"this",
"->",
"_setViewVar",
"(",
"'userEntity'",
",",
"$",
"entity",
")",
";",
"}",
"unset",
"(",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"data",
"[",
"$",
"options",
"[",
"'field'",
"]",
"]",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'setEntity'",
"]",
")",
"{",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"set",
"(",
"'userEntity'",
",",
"$",
"entity",
")",
";",
"}",
"}"
] |
The user can request a new password reset token, an email is send to him.
@param array $options Options
@throws \Cake\Datasource\Exception\RecordNotFoundException
@return bool|null
|
[
"The",
"user",
"can",
"request",
"a",
"new",
"password",
"reset",
"token",
"an",
"email",
"is",
"send",
"to",
"him",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L699-L728
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._initPasswordReset
|
protected function _initPasswordReset(EntityInterface $entity, $options) {
try {
$this->UserTable->initPasswordReset($this->_getRequest()->getData($options['field']), $options);
$this->handleFlashAndRedirect('success', $options);
if ($options['setEntity']) {
$this->_setViewVar('userEntity', $entity);
}
return true;
} catch (RecordNotFoundException $e) {
$this->handleFlashAndRedirect('error', $options);
}
return false;
}
|
php
|
protected function _initPasswordReset(EntityInterface $entity, $options) {
try {
$this->UserTable->initPasswordReset($this->_getRequest()->getData($options['field']), $options);
$this->handleFlashAndRedirect('success', $options);
if ($options['setEntity']) {
$this->_setViewVar('userEntity', $entity);
}
return true;
} catch (RecordNotFoundException $e) {
$this->handleFlashAndRedirect('error', $options);
}
return false;
}
|
[
"protected",
"function",
"_initPasswordReset",
"(",
"EntityInterface",
"$",
"entity",
",",
"$",
"options",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"UserTable",
"->",
"initPasswordReset",
"(",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"getData",
"(",
"$",
"options",
"[",
"'field'",
"]",
")",
",",
"$",
"options",
")",
";",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'success'",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'setEntity'",
"]",
")",
"{",
"$",
"this",
"->",
"_setViewVar",
"(",
"'userEntity'",
",",
"$",
"entity",
")",
";",
"}",
"return",
"true",
";",
"}",
"catch",
"(",
"RecordNotFoundException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'error'",
",",
"$",
"options",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Initializes the password reset and handles a possible errors.
@param \Cake\Datasource\EntityInterface $entity User entity
@param array $options Options array Options
@return bool
|
[
"Initializes",
"the",
"password",
"reset",
"and",
"handles",
"a",
"possible",
"errors",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L737-L751
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.resetPassword
|
public function resetPassword($token = null, $options = []) {
$options = Hash::merge($this->getConfig('resetPassword'), $options);
$tokenParam = $this->_getRequest()->getQuery($options['queryParam']);
if (!empty($tokenParam)) {
$token = $tokenParam;
}
// Check of the token exists
try {
$entity = $this->UserTable->verifyPasswordResetToken($token, $options['tokenOptions']);
} catch (RecordNotFoundException $e) {
if (empty($options['errorMessage']) && $options['errorMessage'] !== false) {
$options['errorMessage'] = $e->getMessage();
}
$redirect = $this->handleFlashAndRedirect('invalidError', $options);
if ($redirect instanceof Response) {
return $redirect;
}
$entity = $this->UserTable->newEntity();
}
// Check if the token has expired
if ($entity->get('token_is_expired') === true) {
if (empty($options['invalidErrorMessage'])) {
$options['invalidErrorMessage'] = $e->getMessage();
}
$redirect = $this->handleFlashAndRedirect('expiredError', $options);
if ($redirect instanceof Response) {
return $redirect;
}
}
// Handle the POST
if ($this->_getRequest()->is('post')) {
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData());
if ($this->UserTable->resetPassword($entity)) {
$redirect = $this->handleFlashAndRedirect('success', $options);
} else {
$redirect = $this->handleFlashAndRedirect('error', $options);
}
if ($redirect instanceof Response) {
return $redirect;
}
} else {
$entity = $this->UserTable->newEntity();
}
$this->_setViewVar('entity', $entity);
}
|
php
|
public function resetPassword($token = null, $options = []) {
$options = Hash::merge($this->getConfig('resetPassword'), $options);
$tokenParam = $this->_getRequest()->getQuery($options['queryParam']);
if (!empty($tokenParam)) {
$token = $tokenParam;
}
// Check of the token exists
try {
$entity = $this->UserTable->verifyPasswordResetToken($token, $options['tokenOptions']);
} catch (RecordNotFoundException $e) {
if (empty($options['errorMessage']) && $options['errorMessage'] !== false) {
$options['errorMessage'] = $e->getMessage();
}
$redirect = $this->handleFlashAndRedirect('invalidError', $options);
if ($redirect instanceof Response) {
return $redirect;
}
$entity = $this->UserTable->newEntity();
}
// Check if the token has expired
if ($entity->get('token_is_expired') === true) {
if (empty($options['invalidErrorMessage'])) {
$options['invalidErrorMessage'] = $e->getMessage();
}
$redirect = $this->handleFlashAndRedirect('expiredError', $options);
if ($redirect instanceof Response) {
return $redirect;
}
}
// Handle the POST
if ($this->_getRequest()->is('post')) {
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData());
if ($this->UserTable->resetPassword($entity)) {
$redirect = $this->handleFlashAndRedirect('success', $options);
} else {
$redirect = $this->handleFlashAndRedirect('error', $options);
}
if ($redirect instanceof Response) {
return $redirect;
}
} else {
$entity = $this->UserTable->newEntity();
}
$this->_setViewVar('entity', $entity);
}
|
[
"public",
"function",
"resetPassword",
"(",
"$",
"token",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'resetPassword'",
")",
",",
"$",
"options",
")",
";",
"$",
"tokenParam",
"=",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"getQuery",
"(",
"$",
"options",
"[",
"'queryParam'",
"]",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"tokenParam",
")",
")",
"{",
"$",
"token",
"=",
"$",
"tokenParam",
";",
"}",
"// Check of the token exists",
"try",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"verifyPasswordResetToken",
"(",
"$",
"token",
",",
"$",
"options",
"[",
"'tokenOptions'",
"]",
")",
";",
"}",
"catch",
"(",
"RecordNotFoundException",
"$",
"e",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"options",
"[",
"'errorMessage'",
"]",
")",
"&&",
"$",
"options",
"[",
"'errorMessage'",
"]",
"!==",
"false",
")",
"{",
"$",
"options",
"[",
"'errorMessage'",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"}",
"$",
"redirect",
"=",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'invalidError'",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"redirect",
"instanceof",
"Response",
")",
"{",
"return",
"$",
"redirect",
";",
"}",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"newEntity",
"(",
")",
";",
"}",
"// Check if the token has expired",
"if",
"(",
"$",
"entity",
"->",
"get",
"(",
"'token_is_expired'",
")",
"===",
"true",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"options",
"[",
"'invalidErrorMessage'",
"]",
")",
")",
"{",
"$",
"options",
"[",
"'invalidErrorMessage'",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"}",
"$",
"redirect",
"=",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'expiredError'",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"redirect",
"instanceof",
"Response",
")",
"{",
"return",
"$",
"redirect",
";",
"}",
"}",
"// Handle the POST",
"if",
"(",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"is",
"(",
"'post'",
")",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"patchEntity",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"getData",
"(",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"UserTable",
"->",
"resetPassword",
"(",
"$",
"entity",
")",
")",
"{",
"$",
"redirect",
"=",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'success'",
",",
"$",
"options",
")",
";",
"}",
"else",
"{",
"$",
"redirect",
"=",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'error'",
",",
"$",
"options",
")",
";",
"}",
"if",
"(",
"$",
"redirect",
"instanceof",
"Response",
")",
"{",
"return",
"$",
"redirect",
";",
"}",
"}",
"else",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"newEntity",
"(",
")",
";",
"}",
"$",
"this",
"->",
"_setViewVar",
"(",
"'entity'",
",",
"$",
"entity",
")",
";",
"}"
] |
Allows the user to enter a new password.
@param string|null $token Token
@param array $options Options
@return null|\Cake\Http\Response
|
[
"Allows",
"the",
"user",
"to",
"enter",
"a",
"new",
"password",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L760-L810
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent.changePassword
|
public function changePassword($options = []) {
$options = Hash::merge($this->getConfig('changePassword'), $options);
$entity = $this->UserTable->newEntity();
$entity->accessible([
'old_password',
'password',
'new_password',
'confirm_password'
], true);
if ($this->_getRequest()->is(['post', 'put'])) {
$entity = $this->UserTable->get($this->_getAuthObject()->user('id'));
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->data, [
'validate' => 'changePassword'
]);
if ($this->UserTable->changePassword($entity)) {
$this->_getRequest()->data = [];
$entity = $this->UserTable->newEntity();
$this->handleFlashAndRedirect('success', $options);
} else {
$this->handleFlashAndRedirect('error', $options);
}
}
$this->_setViewVar('entity', $entity);
}
|
php
|
public function changePassword($options = []) {
$options = Hash::merge($this->getConfig('changePassword'), $options);
$entity = $this->UserTable->newEntity();
$entity->accessible([
'old_password',
'password',
'new_password',
'confirm_password'
], true);
if ($this->_getRequest()->is(['post', 'put'])) {
$entity = $this->UserTable->get($this->_getAuthObject()->user('id'));
$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->data, [
'validate' => 'changePassword'
]);
if ($this->UserTable->changePassword($entity)) {
$this->_getRequest()->data = [];
$entity = $this->UserTable->newEntity();
$this->handleFlashAndRedirect('success', $options);
} else {
$this->handleFlashAndRedirect('error', $options);
}
}
$this->_setViewVar('entity', $entity);
}
|
[
"public",
"function",
"changePassword",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'changePassword'",
")",
",",
"$",
"options",
")",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"newEntity",
"(",
")",
";",
"$",
"entity",
"->",
"accessible",
"(",
"[",
"'old_password'",
",",
"'password'",
",",
"'new_password'",
",",
"'confirm_password'",
"]",
",",
"true",
")",
";",
"if",
"(",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"is",
"(",
"[",
"'post'",
",",
"'put'",
"]",
")",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"get",
"(",
"$",
"this",
"->",
"_getAuthObject",
"(",
")",
"->",
"user",
"(",
"'id'",
")",
")",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"patchEntity",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"data",
",",
"[",
"'validate'",
"=>",
"'changePassword'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"UserTable",
"->",
"changePassword",
"(",
"$",
"entity",
")",
")",
"{",
"$",
"this",
"->",
"_getRequest",
"(",
")",
"->",
"data",
"=",
"[",
"]",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"newEntity",
"(",
")",
";",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'success'",
",",
"$",
"options",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"handleFlashAndRedirect",
"(",
"'error'",
",",
"$",
"options",
")",
";",
"}",
"}",
"$",
"this",
"->",
"_setViewVar",
"(",
"'entity'",
",",
"$",
"entity",
")",
";",
"}"
] |
Let the logged in user change his password.
@param array $options Options
@return void
|
[
"Let",
"the",
"logged",
"in",
"user",
"change",
"his",
"password",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L818-L845
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._getAuthObject
|
protected function _getAuthObject() {
if (!$this->_registry->has('Auth')) {
$Auth = $this->_registry->load('Auth', $this->getConfig('auth'));
$Auth->request = $this->_getRequest();
$Auth->response = $this->_getResponse();
return $Auth;
}
return $this->_registry->Auth;
}
|
php
|
protected function _getAuthObject() {
if (!$this->_registry->has('Auth')) {
$Auth = $this->_registry->load('Auth', $this->getConfig('auth'));
$Auth->request = $this->_getRequest();
$Auth->response = $this->_getResponse();
return $Auth;
}
return $this->_registry->Auth;
}
|
[
"protected",
"function",
"_getAuthObject",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_registry",
"->",
"has",
"(",
"'Auth'",
")",
")",
"{",
"$",
"Auth",
"=",
"$",
"this",
"->",
"_registry",
"->",
"load",
"(",
"'Auth'",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'auth'",
")",
")",
";",
"$",
"Auth",
"->",
"request",
"=",
"$",
"this",
"->",
"_getRequest",
"(",
")",
";",
"$",
"Auth",
"->",
"response",
"=",
"$",
"this",
"->",
"_getResponse",
"(",
")",
";",
"return",
"$",
"Auth",
";",
"}",
"return",
"$",
"this",
"->",
"_registry",
"->",
"Auth",
";",
"}"
] |
Gets the auth component object
If there is an auth component loaded it will take that one from the
controller. If not the configured default settings will be used to create
a new instance of the auth component. This is mostly thought as a fallback,
in a real world scenario the app should have set auth set up in it's
AppController.
@return \Cake\Controller\Component\AuthComponent
|
[
"Gets",
"the",
"auth",
"component",
"object"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L889-L899
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/UserToolComponent.php
|
UserToolComponent._setViewVar
|
protected function _setViewVar($viewVar, $entity) {
if ($viewVar === false) {
return;
}
$this->getController()->set($viewVar, $entity);
}
|
php
|
protected function _setViewVar($viewVar, $entity) {
if ($viewVar === false) {
return;
}
$this->getController()->set($viewVar, $entity);
}
|
[
"protected",
"function",
"_setViewVar",
"(",
"$",
"viewVar",
",",
"$",
"entity",
")",
"{",
"if",
"(",
"$",
"viewVar",
"===",
"false",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"getController",
"(",
")",
"->",
"set",
"(",
"$",
"viewVar",
",",
"$",
"entity",
")",
";",
"}"
] |
Handles the optional setting of view vars within the component.
@param bool $viewVar Set the view var or not
@param \Cake\Datasource\EntityInterface $entity User entity
@return void
|
[
"Handles",
"the",
"optional",
"setting",
"of",
"view",
"vars",
"within",
"the",
"component",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/UserToolComponent.php#L908-L914
|
train
|
burzum/cakephp-user-tools
|
src/Shell/UserShell.php
|
UserShell.removeExpired
|
public function removeExpired() {
$count = $this->UserTable->removeExpiredRegistrations();
$this->out(__dn(
'burzum/user_tools',
'Removed {0,number,integer} expired registration.',
'Removed {0,number,integer} expired registrations.',
$count,
$count
));
}
|
php
|
public function removeExpired() {
$count = $this->UserTable->removeExpiredRegistrations();
$this->out(__dn(
'burzum/user_tools',
'Removed {0,number,integer} expired registration.',
'Removed {0,number,integer} expired registrations.',
$count,
$count
));
}
|
[
"public",
"function",
"removeExpired",
"(",
")",
"{",
"$",
"count",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"removeExpiredRegistrations",
"(",
")",
";",
"$",
"this",
"->",
"out",
"(",
"__dn",
"(",
"'burzum/user_tools'",
",",
"'Removed {0,number,integer} expired registration.'",
",",
"'Removed {0,number,integer} expired registrations.'",
",",
"$",
"count",
",",
"$",
"count",
")",
")",
";",
"}"
] |
Removes expired registrations
@return void
|
[
"Removes",
"expired",
"registrations"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Shell/UserShell.php#L47-L56
|
train
|
burzum/cakephp-user-tools
|
src/Shell/UserShell.php
|
UserShell.setPassword
|
public function setPassword() {
if (count($this->args) < 2) {
$this->abort(__d('burzum/user_tools', 'You need to call this command with at least tow arguments.'));
}
$field = 'username';
if (count($this->args) >= 3) {
$field = $this->args[2];
}
$user = $this->UserTable->find()->where([$field => $this->args[0]])->first();
$user->password = $this->UserTable->hashPassword($this->args[1]);
if ($this->UserTable->save($user, ['validate' => false])) {
$this->out('Password saved');
}
}
|
php
|
public function setPassword() {
if (count($this->args) < 2) {
$this->abort(__d('burzum/user_tools', 'You need to call this command with at least tow arguments.'));
}
$field = 'username';
if (count($this->args) >= 3) {
$field = $this->args[2];
}
$user = $this->UserTable->find()->where([$field => $this->args[0]])->first();
$user->password = $this->UserTable->hashPassword($this->args[1]);
if ($this->UserTable->save($user, ['validate' => false])) {
$this->out('Password saved');
}
}
|
[
"public",
"function",
"setPassword",
"(",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"args",
")",
"<",
"2",
")",
"{",
"$",
"this",
"->",
"abort",
"(",
"__d",
"(",
"'burzum/user_tools'",
",",
"'You need to call this command with at least tow arguments.'",
")",
")",
";",
"}",
"$",
"field",
"=",
"'username'",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"args",
")",
">=",
"3",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"args",
"[",
"2",
"]",
";",
"}",
"$",
"user",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"find",
"(",
")",
"->",
"where",
"(",
"[",
"$",
"field",
"=>",
"$",
"this",
"->",
"args",
"[",
"0",
"]",
"]",
")",
"->",
"first",
"(",
")",
";",
"$",
"user",
"->",
"password",
"=",
"$",
"this",
"->",
"UserTable",
"->",
"hashPassword",
"(",
"$",
"this",
"->",
"args",
"[",
"1",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"UserTable",
"->",
"save",
"(",
"$",
"user",
",",
"[",
"'validate'",
"=>",
"false",
"]",
")",
")",
"{",
"$",
"this",
"->",
"out",
"(",
"'Password saved'",
")",
";",
"}",
"}"
] |
Sets a new password for an user.
cake user setPassword <searchTerm> <newPassword> <field | optional>
@return void
|
[
"Sets",
"a",
"new",
"password",
"for",
"an",
"user",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Shell/UserShell.php#L65-L80
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validationPasswordReset
|
public function validationPasswordReset(Validator $validator) {
return $this->validateOldPassword($validator)
->validatePassword($validator)
->validateConfirmPassword($validator);
}
|
php
|
public function validationPasswordReset(Validator $validator) {
return $this->validateOldPassword($validator)
->validatePassword($validator)
->validateConfirmPassword($validator);
}
|
[
"public",
"function",
"validationPasswordReset",
"(",
"Validator",
"$",
"validator",
")",
"{",
"return",
"$",
"this",
"->",
"validateOldPassword",
"(",
"$",
"validator",
")",
"->",
"validatePassword",
"(",
"$",
"validator",
")",
"->",
"validateConfirmPassword",
"(",
"$",
"validator",
")",
";",
"}"
] |
Validates the password reset.
Override it as needed to change the rules for only that field.
@param \Cake\Validation\Validator $validator Validator
@return \Cake\Validation\Validator
|
[
"Validates",
"the",
"password",
"reset",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L23-L27
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validationUserName
|
public function validationUserName(Validator $validator) {
$validator->setProvider('userTable', $this->_table);
$validator->add($this->_field('username'), [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('user_tools', 'An username is required.')
],
'length' => [
'rule' => ['lengthBetween', 3, 32],
'message' => __d('user_tools', 'The username must be between 3 and 32 characters.')
],
'unique' => [
'rule' => ['validateUnique', ['scope' => 'username']],
'provider' => 'userTable',
'message' => __d('user_tools', 'The username is already in use.')
],
'alphaNumeric' => [
'rule' => 'alphaNumeric',
'message' => __d('user_tools', 'The username must be alpha numeric.')
]
]);
return $validator;
}
|
php
|
public function validationUserName(Validator $validator) {
$validator->setProvider('userTable', $this->_table);
$validator->add($this->_field('username'), [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('user_tools', 'An username is required.')
],
'length' => [
'rule' => ['lengthBetween', 3, 32],
'message' => __d('user_tools', 'The username must be between 3 and 32 characters.')
],
'unique' => [
'rule' => ['validateUnique', ['scope' => 'username']],
'provider' => 'userTable',
'message' => __d('user_tools', 'The username is already in use.')
],
'alphaNumeric' => [
'rule' => 'alphaNumeric',
'message' => __d('user_tools', 'The username must be alpha numeric.')
]
]);
return $validator;
}
|
[
"public",
"function",
"validationUserName",
"(",
"Validator",
"$",
"validator",
")",
"{",
"$",
"validator",
"->",
"setProvider",
"(",
"'userTable'",
",",
"$",
"this",
"->",
"_table",
")",
";",
"$",
"validator",
"->",
"add",
"(",
"$",
"this",
"->",
"_field",
"(",
"'username'",
")",
",",
"[",
"'notBlank'",
"=>",
"[",
"'rule'",
"=>",
"'notBlank'",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'An username is required.'",
")",
"]",
",",
"'length'",
"=>",
"[",
"'rule'",
"=>",
"[",
"'lengthBetween'",
",",
"3",
",",
"32",
"]",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'The username must be between 3 and 32 characters.'",
")",
"]",
",",
"'unique'",
"=>",
"[",
"'rule'",
"=>",
"[",
"'validateUnique'",
",",
"[",
"'scope'",
"=>",
"'username'",
"]",
"]",
",",
"'provider'",
"=>",
"'userTable'",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'The username is already in use.'",
")",
"]",
",",
"'alphaNumeric'",
"=>",
"[",
"'rule'",
"=>",
"'alphaNumeric'",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'The username must be alpha numeric.'",
")",
"]",
"]",
")",
";",
"return",
"$",
"validator",
";",
"}"
] |
Validates the username field.
Override it as needed to change the rules for only that field.
@param \Cake\Validation\Validator $validator Validator
@return \Cake\Validation\Validator
|
[
"Validates",
"the",
"username",
"field",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L37-L61
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validationPassword
|
public function validationPassword(Validator $validator) {
$validator->setProvider('userTable', $this->_table);
$validator->add($this->_field('password'), [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('user_tools', 'A password is required.')
],
'minLength' => [
'rule' => ['minLength', $this->_config['passwordMinLength']],
'message' => __d('user_tools', 'The password must have at least 6 characters.')
],
'confirmPassword' => [
'rule' => ['compareFields', 'confirm_password'],
'message' => __d('user_tools', 'The passwords don\'t match!'),
'provider' => 'userTable',
]
]);
return $validator;
}
|
php
|
public function validationPassword(Validator $validator) {
$validator->setProvider('userTable', $this->_table);
$validator->add($this->_field('password'), [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('user_tools', 'A password is required.')
],
'minLength' => [
'rule' => ['minLength', $this->_config['passwordMinLength']],
'message' => __d('user_tools', 'The password must have at least 6 characters.')
],
'confirmPassword' => [
'rule' => ['compareFields', 'confirm_password'],
'message' => __d('user_tools', 'The passwords don\'t match!'),
'provider' => 'userTable',
]
]);
return $validator;
}
|
[
"public",
"function",
"validationPassword",
"(",
"Validator",
"$",
"validator",
")",
"{",
"$",
"validator",
"->",
"setProvider",
"(",
"'userTable'",
",",
"$",
"this",
"->",
"_table",
")",
";",
"$",
"validator",
"->",
"add",
"(",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
",",
"[",
"'notBlank'",
"=>",
"[",
"'rule'",
"=>",
"'notBlank'",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'A password is required.'",
")",
"]",
",",
"'minLength'",
"=>",
"[",
"'rule'",
"=>",
"[",
"'minLength'",
",",
"$",
"this",
"->",
"_config",
"[",
"'passwordMinLength'",
"]",
"]",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'The password must have at least 6 characters.'",
")",
"]",
",",
"'confirmPassword'",
"=>",
"[",
"'rule'",
"=>",
"[",
"'compareFields'",
",",
"'confirm_password'",
"]",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'The passwords don\\'t match!'",
")",
",",
"'provider'",
"=>",
"'userTable'",
",",
"]",
"]",
")",
";",
"return",
"$",
"validator",
";",
"}"
] |
Validates the password field.
Override it as needed to change the rules for only that field.
@param \Cake\Validation\Validator $validator Validator
@return \Cake\Validation\Validator
|
[
"Validates",
"the",
"password",
"field",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L103-L123
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validationConfirmPassword
|
public function validationConfirmPassword(Validator $validator) {
$validator->setProvider('userBehavior', $this);
$validator->add($this->_field('passwordCheck'), [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('user_tools', 'A password is required.')
],
'minLength' => [
'rule' => ['minLength', $this->_config['passwordMinLength']],
'message' => __d('user_tools', 'The password must have at least 6 characters.')
],
'confirmPassword' => [
'rule' => ['compareFields', 'password'],
'message' => __d('user_tools', 'The passwords don\'t match!'),
'provider' => 'userBehavior',
]
]);
return $validator;
}
|
php
|
public function validationConfirmPassword(Validator $validator) {
$validator->setProvider('userBehavior', $this);
$validator->add($this->_field('passwordCheck'), [
'notBlank' => [
'rule' => 'notBlank',
'message' => __d('user_tools', 'A password is required.')
],
'minLength' => [
'rule' => ['minLength', $this->_config['passwordMinLength']],
'message' => __d('user_tools', 'The password must have at least 6 characters.')
],
'confirmPassword' => [
'rule' => ['compareFields', 'password'],
'message' => __d('user_tools', 'The passwords don\'t match!'),
'provider' => 'userBehavior',
]
]);
return $validator;
}
|
[
"public",
"function",
"validationConfirmPassword",
"(",
"Validator",
"$",
"validator",
")",
"{",
"$",
"validator",
"->",
"setProvider",
"(",
"'userBehavior'",
",",
"$",
"this",
")",
";",
"$",
"validator",
"->",
"add",
"(",
"$",
"this",
"->",
"_field",
"(",
"'passwordCheck'",
")",
",",
"[",
"'notBlank'",
"=>",
"[",
"'rule'",
"=>",
"'notBlank'",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'A password is required.'",
")",
"]",
",",
"'minLength'",
"=>",
"[",
"'rule'",
"=>",
"[",
"'minLength'",
",",
"$",
"this",
"->",
"_config",
"[",
"'passwordMinLength'",
"]",
"]",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'The password must have at least 6 characters.'",
")",
"]",
",",
"'confirmPassword'",
"=>",
"[",
"'rule'",
"=>",
"[",
"'compareFields'",
",",
"'password'",
"]",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'The passwords don\\'t match!'",
")",
",",
"'provider'",
"=>",
"'userBehavior'",
",",
"]",
"]",
")",
";",
"return",
"$",
"validator",
";",
"}"
] |
Validates the confirm_password field.
Override it as needed to change the rules for only that field.
@param \Cake\Validation\Validator $validator Validator
@return \Cake\Validation\Validator
|
[
"Validates",
"the",
"confirm_password",
"field",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L133-L153
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validationRequestPassword
|
public function validationRequestPassword(Validator $validator) {
$validator = $this->_table->validationDefault($validator);
$validator->remove($this->_field('email'), 'unique');
return $validator;
}
|
php
|
public function validationRequestPassword(Validator $validator) {
$validator = $this->_table->validationDefault($validator);
$validator->remove($this->_field('email'), 'unique');
return $validator;
}
|
[
"public",
"function",
"validationRequestPassword",
"(",
"Validator",
"$",
"validator",
")",
"{",
"$",
"validator",
"=",
"$",
"this",
"->",
"_table",
"->",
"validationDefault",
"(",
"$",
"validator",
")",
";",
"$",
"validator",
"->",
"remove",
"(",
"$",
"this",
"->",
"_field",
"(",
"'email'",
")",
",",
"'unique'",
")",
";",
"return",
"$",
"validator",
";",
"}"
] |
Validation rules for the password reset request.
@param \Cake\Validation\Validator $validator Validator
@return \Cake\Validation\Validator
@see \Burzum\UserTools\Controller\Component\UserToolComponent::requestPassword()
|
[
"Validation",
"rules",
"for",
"the",
"password",
"reset",
"request",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L162-L167
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validationChangePassword
|
public function validationChangePassword($validator) {
$validator->setProvider('userBehavior', $this);
$validator = $this->validationPassword($validator);
$validator = $this->validationConfirmPassword($validator);
$validator = $this->validationOldPassword($validator);
return $validator;
}
|
php
|
public function validationChangePassword($validator) {
$validator->setProvider('userBehavior', $this);
$validator = $this->validationPassword($validator);
$validator = $this->validationConfirmPassword($validator);
$validator = $this->validationOldPassword($validator);
return $validator;
}
|
[
"public",
"function",
"validationChangePassword",
"(",
"$",
"validator",
")",
"{",
"$",
"validator",
"->",
"setProvider",
"(",
"'userBehavior'",
",",
"$",
"this",
")",
";",
"$",
"validator",
"=",
"$",
"this",
"->",
"validationPassword",
"(",
"$",
"validator",
")",
";",
"$",
"validator",
"=",
"$",
"this",
"->",
"validationConfirmPassword",
"(",
"$",
"validator",
")",
";",
"$",
"validator",
"=",
"$",
"this",
"->",
"validationOldPassword",
"(",
"$",
"validator",
")",
";",
"return",
"$",
"validator",
";",
"}"
] |
Configures the validator with rules for the password change
@param \Cake\Validation\Validator $validator Validator
@return \Cake\Validation\Validator
|
[
"Configures",
"the",
"validator",
"with",
"rules",
"for",
"the",
"password",
"change"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L175-L183
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validationOldPassword
|
protected function validationOldPassword($validator) {
$validator->setProvider('userBehavior', $this);
$validator->setProvider('userTable', $this->_table);
$validator->add('old_password', 'notBlank', [
'rule' => 'notBlank',
'message' => __d('user_tools', 'Enter your old password.')
]);
$validator->add('old_password', 'oldPassword', [
'rule' => ['validateOldPassword', 'password'],
'provider' => 'userBehavior',
'message' => __d('user_tools', 'Wrong password, please try again.')
]);
return $validator;
}
|
php
|
protected function validationOldPassword($validator) {
$validator->setProvider('userBehavior', $this);
$validator->setProvider('userTable', $this->_table);
$validator->add('old_password', 'notBlank', [
'rule' => 'notBlank',
'message' => __d('user_tools', 'Enter your old password.')
]);
$validator->add('old_password', 'oldPassword', [
'rule' => ['validateOldPassword', 'password'],
'provider' => 'userBehavior',
'message' => __d('user_tools', 'Wrong password, please try again.')
]);
return $validator;
}
|
[
"protected",
"function",
"validationOldPassword",
"(",
"$",
"validator",
")",
"{",
"$",
"validator",
"->",
"setProvider",
"(",
"'userBehavior'",
",",
"$",
"this",
")",
";",
"$",
"validator",
"->",
"setProvider",
"(",
"'userTable'",
",",
"$",
"this",
"->",
"_table",
")",
";",
"$",
"validator",
"->",
"add",
"(",
"'old_password'",
",",
"'notBlank'",
",",
"[",
"'rule'",
"=>",
"'notBlank'",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'Enter your old password.'",
")",
"]",
")",
";",
"$",
"validator",
"->",
"add",
"(",
"'old_password'",
",",
"'oldPassword'",
",",
"[",
"'rule'",
"=>",
"[",
"'validateOldPassword'",
",",
"'password'",
"]",
",",
"'provider'",
"=>",
"'userBehavior'",
",",
"'message'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'Wrong password, please try again.'",
")",
"]",
")",
";",
"return",
"$",
"validator",
";",
"}"
] |
Configures the validator with rules to check the old password
@param \Cake\Validation\Validator $validator Validator
@return \Cake\Validation\Validator
|
[
"Configures",
"the",
"validator",
"with",
"rules",
"to",
"check",
"the",
"old",
"password"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L191-L206
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.validateOldPassword
|
public function validateOldPassword($value, $field, $context) {
if (Configure::read('debug') > 0 && empty($context['data'][$this->_table->getPrimaryKey()])) {
throw new RuntimeException('The user id is required as well to validate the old password!');
}
$result = $this->_table->find()
->select([
$this->_table->aliasField($field)
])
->where([
$this->_table->getPrimaryKey() => $context['data'][$this->_table->getPrimaryKey()],
])
->first();
if (!$result) {
return false;
}
return $this->getPasswordHasher()->check($value, $result->get($field));
}
|
php
|
public function validateOldPassword($value, $field, $context) {
if (Configure::read('debug') > 0 && empty($context['data'][$this->_table->getPrimaryKey()])) {
throw new RuntimeException('The user id is required as well to validate the old password!');
}
$result = $this->_table->find()
->select([
$this->_table->aliasField($field)
])
->where([
$this->_table->getPrimaryKey() => $context['data'][$this->_table->getPrimaryKey()],
])
->first();
if (!$result) {
return false;
}
return $this->getPasswordHasher()->check($value, $result->get($field));
}
|
[
"public",
"function",
"validateOldPassword",
"(",
"$",
"value",
",",
"$",
"field",
",",
"$",
"context",
")",
"{",
"if",
"(",
"Configure",
"::",
"read",
"(",
"'debug'",
")",
">",
"0",
"&&",
"empty",
"(",
"$",
"context",
"[",
"'data'",
"]",
"[",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'The user id is required as well to validate the old password!'",
")",
";",
"}",
"$",
"result",
"=",
"$",
"this",
"->",
"_table",
"->",
"find",
"(",
")",
"->",
"select",
"(",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"field",
")",
"]",
")",
"->",
"where",
"(",
"[",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
"=>",
"$",
"context",
"[",
"'data'",
"]",
"[",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
"]",
",",
"]",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"$",
"result",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getPasswordHasher",
"(",
")",
"->",
"check",
"(",
"$",
"value",
",",
"$",
"result",
"->",
"get",
"(",
"$",
"field",
")",
")",
";",
"}"
] |
Validation method for the old password.
This method will hash the old password and compare it to the stored hash
in the database. You don't have to hash it manually before validating.
@param mixed $value Value
@param string $field Field
@param mixed $context Context
@return bool
|
[
"Validation",
"method",
"for",
"the",
"old",
"password",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L219-L238
|
train
|
burzum/cakephp-user-tools
|
src/Model/UserValidationTrait.php
|
UserValidationTrait.compareFields
|
public function compareFields($value, $field, $context) {
if (!isset($context['data'][$field])) {
return true;
}
if ($value === $context['data'][$field]) {
return true;
}
return false;
}
|
php
|
public function compareFields($value, $field, $context) {
if (!isset($context['data'][$field])) {
return true;
}
if ($value === $context['data'][$field]) {
return true;
}
return false;
}
|
[
"public",
"function",
"compareFields",
"(",
"$",
"value",
",",
"$",
"field",
",",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"context",
"[",
"'data'",
"]",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"value",
"===",
"$",
"context",
"[",
"'data'",
"]",
"[",
"$",
"field",
"]",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Compares the value of two fields.
@param mixed $value Value
@param string $field Field
@param Entity $context Context
@return bool
|
[
"Compares",
"the",
"value",
"of",
"two",
"fields",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/UserValidationTrait.php#L248-L257
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/FlashAndRedirectTrait.php
|
FlashAndRedirectTrait.handleFlashAndRedirect
|
public function handleFlashAndRedirect($type, $options) {
$this->_handleFlash($type, $options);
return $this->_handleRedirect($type, $options);
}
|
php
|
public function handleFlashAndRedirect($type, $options) {
$this->_handleFlash($type, $options);
return $this->_handleRedirect($type, $options);
}
|
[
"public",
"function",
"handleFlashAndRedirect",
"(",
"$",
"type",
",",
"$",
"options",
")",
"{",
"$",
"this",
"->",
"_handleFlash",
"(",
"$",
"type",
",",
"$",
"options",
")",
";",
"return",
"$",
"this",
"->",
"_handleRedirect",
"(",
"$",
"type",
",",
"$",
"options",
")",
";",
"}"
] |
Handles flashes and redirects
@param string $type Prefix for the array key, mostly "success" or "error"
@param array $options Options
@return mixed
|
[
"Handles",
"flashes",
"and",
"redirects"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/FlashAndRedirectTrait.php#L35-L39
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/FlashAndRedirectTrait.php
|
FlashAndRedirectTrait._handleRedirect
|
protected function _handleRedirect($type, $options) {
if (isset($options[$type . 'RedirectUrl']) && $options[$type . 'RedirectUrl'] !== false) {
$controller = $this->getController();
$result = $controller->redirect($options[$type . 'RedirectUrl']);
$this->_redirectResponse = $result;
return $result;
}
$this->_redirectResponse = null;
return false;
}
|
php
|
protected function _handleRedirect($type, $options) {
if (isset($options[$type . 'RedirectUrl']) && $options[$type . 'RedirectUrl'] !== false) {
$controller = $this->getController();
$result = $controller->redirect($options[$type . 'RedirectUrl']);
$this->_redirectResponse = $result;
return $result;
}
$this->_redirectResponse = null;
return false;
}
|
[
"protected",
"function",
"_handleRedirect",
"(",
"$",
"type",
",",
"$",
"options",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"$",
"type",
".",
"'RedirectUrl'",
"]",
")",
"&&",
"$",
"options",
"[",
"$",
"type",
".",
"'RedirectUrl'",
"]",
"!==",
"false",
")",
"{",
"$",
"controller",
"=",
"$",
"this",
"->",
"getController",
"(",
")",
";",
"$",
"result",
"=",
"$",
"controller",
"->",
"redirect",
"(",
"$",
"options",
"[",
"$",
"type",
".",
"'RedirectUrl'",
"]",
")",
";",
"$",
"this",
"->",
"_redirectResponse",
"=",
"$",
"result",
";",
"return",
"$",
"result",
";",
"}",
"$",
"this",
"->",
"_redirectResponse",
"=",
"null",
";",
"return",
"false",
";",
"}"
] |
Handles the redirect options.
@param string $type Prefix for the array key, mostly "success" or "error"
@param array $options Options
@return mixed
|
[
"Handles",
"the",
"redirect",
"options",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/FlashAndRedirectTrait.php#L48-L60
|
train
|
burzum/cakephp-user-tools
|
src/Controller/Component/FlashAndRedirectTrait.php
|
FlashAndRedirectTrait._handleFlash
|
protected function _handleFlash($type, $options) {
if (isset($options[$type . 'Message']) && $options[$type . 'Message'] !== false) {
if (is_string($options[$type . 'Message'])) {
$flashOptions = [];
if (isset($options[$type . 'FlashOptions'])) {
$flashOptions = $options[$type . 'FlashOptions'];
}
if (!isset($flashOptions['element'])) {
if (!$this->_registry->has('Flash')) {
$this->_registry->load('Flash');
}
$flashOptions['element'] = $type;
$this->_registry->get('Flash')->set($options[$type . 'Message'], $flashOptions);
}
return true;
}
}
return false;
}
|
php
|
protected function _handleFlash($type, $options) {
if (isset($options[$type . 'Message']) && $options[$type . 'Message'] !== false) {
if (is_string($options[$type . 'Message'])) {
$flashOptions = [];
if (isset($options[$type . 'FlashOptions'])) {
$flashOptions = $options[$type . 'FlashOptions'];
}
if (!isset($flashOptions['element'])) {
if (!$this->_registry->has('Flash')) {
$this->_registry->load('Flash');
}
$flashOptions['element'] = $type;
$this->_registry->get('Flash')->set($options[$type . 'Message'], $flashOptions);
}
return true;
}
}
return false;
}
|
[
"protected",
"function",
"_handleFlash",
"(",
"$",
"type",
",",
"$",
"options",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"$",
"type",
".",
"'Message'",
"]",
")",
"&&",
"$",
"options",
"[",
"$",
"type",
".",
"'Message'",
"]",
"!==",
"false",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"options",
"[",
"$",
"type",
".",
"'Message'",
"]",
")",
")",
"{",
"$",
"flashOptions",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"$",
"type",
".",
"'FlashOptions'",
"]",
")",
")",
"{",
"$",
"flashOptions",
"=",
"$",
"options",
"[",
"$",
"type",
".",
"'FlashOptions'",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"flashOptions",
"[",
"'element'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_registry",
"->",
"has",
"(",
"'Flash'",
")",
")",
"{",
"$",
"this",
"->",
"_registry",
"->",
"load",
"(",
"'Flash'",
")",
";",
"}",
"$",
"flashOptions",
"[",
"'element'",
"]",
"=",
"$",
"type",
";",
"$",
"this",
"->",
"_registry",
"->",
"get",
"(",
"'Flash'",
")",
"->",
"set",
"(",
"$",
"options",
"[",
"$",
"type",
".",
"'Message'",
"]",
",",
"$",
"flashOptions",
")",
";",
"}",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Handles the flash options.
@param string $type Prefix for the array key, mostly "success" or "error"
@param array $options Options
@return bool
|
[
"Handles",
"the",
"flash",
"options",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Controller/Component/FlashAndRedirectTrait.php#L69-L91
|
train
|
burzum/cakephp-user-tools
|
src/Model/PasswordAndTokenTrait.php
|
PasswordAndTokenTrait.generatePassword
|
public function generatePassword($length = 8, $options = []) {
$options = $this->_passwordDictionary($options);
$password = '';
srand((int)microtime() * 1000000);
for ($i = 0; $i < $length; $i++) {
$password .=
$options['cons'][mt_rand(0, count($options['cons']) - 1)] .
$options['vowels'][mt_rand(0, count($options['vowels']) - 1)];
}
return substr($password, 0, $length);
}
|
php
|
public function generatePassword($length = 8, $options = []) {
$options = $this->_passwordDictionary($options);
$password = '';
srand((int)microtime() * 1000000);
for ($i = 0; $i < $length; $i++) {
$password .=
$options['cons'][mt_rand(0, count($options['cons']) - 1)] .
$options['vowels'][mt_rand(0, count($options['vowels']) - 1)];
}
return substr($password, 0, $length);
}
|
[
"public",
"function",
"generatePassword",
"(",
"$",
"length",
"=",
"8",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"_passwordDictionary",
"(",
"$",
"options",
")",
";",
"$",
"password",
"=",
"''",
";",
"srand",
"(",
"(",
"int",
")",
"microtime",
"(",
")",
"*",
"1000000",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"length",
";",
"$",
"i",
"++",
")",
"{",
"$",
"password",
".=",
"$",
"options",
"[",
"'cons'",
"]",
"[",
"mt_rand",
"(",
"0",
",",
"count",
"(",
"$",
"options",
"[",
"'cons'",
"]",
")",
"-",
"1",
")",
"]",
".",
"$",
"options",
"[",
"'vowels'",
"]",
"[",
"mt_rand",
"(",
"0",
",",
"count",
"(",
"$",
"options",
"[",
"'vowels'",
"]",
")",
"-",
"1",
")",
"]",
";",
"}",
"return",
"substr",
"(",
"$",
"password",
",",
"0",
",",
"$",
"length",
")",
";",
"}"
] |
Generates a random password that is more or less user friendly.
@param int $length Password length, default is 8
@param array $options Options array.
@return string
|
[
"Generates",
"a",
"random",
"password",
"that",
"is",
"more",
"or",
"less",
"user",
"friendly",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/PasswordAndTokenTrait.php#L20-L32
|
train
|
burzum/cakephp-user-tools
|
src/Model/PasswordAndTokenTrait.php
|
PasswordAndTokenTrait._passwordDictionary
|
protected function _passwordDictionary(array $options = []) {
$defaults = [
'vowels' => [
'a', 'e', 'i', 'o', 'u'
],
'cons' => [
'b', 'c', 'd', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
'p', 'r', 's', 't', 'u', 'v', 'w', 'tr', 'cr', 'br', 'fr', 'th',
'dr', 'ch', 'ph', 'wr', 'st', 'sp', 'sw', 'pr', 'sl', 'cl'
]
];
if (isset($options['cons'])) {
unset($defaults['cons']);
}
if (isset($options['vowels'])) {
unset($defaults['vowels']);
}
return Hash::merge($defaults, $options);
}
|
php
|
protected function _passwordDictionary(array $options = []) {
$defaults = [
'vowels' => [
'a', 'e', 'i', 'o', 'u'
],
'cons' => [
'b', 'c', 'd', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
'p', 'r', 's', 't', 'u', 'v', 'w', 'tr', 'cr', 'br', 'fr', 'th',
'dr', 'ch', 'ph', 'wr', 'st', 'sp', 'sw', 'pr', 'sl', 'cl'
]
];
if (isset($options['cons'])) {
unset($defaults['cons']);
}
if (isset($options['vowels'])) {
unset($defaults['vowels']);
}
return Hash::merge($defaults, $options);
}
|
[
"protected",
"function",
"_passwordDictionary",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'vowels'",
"=>",
"[",
"'a'",
",",
"'e'",
",",
"'i'",
",",
"'o'",
",",
"'u'",
"]",
",",
"'cons'",
"=>",
"[",
"'b'",
",",
"'c'",
",",
"'d'",
",",
"'g'",
",",
"'h'",
",",
"'j'",
",",
"'k'",
",",
"'l'",
",",
"'m'",
",",
"'n'",
",",
"'p'",
",",
"'r'",
",",
"'s'",
",",
"'t'",
",",
"'u'",
",",
"'v'",
",",
"'w'",
",",
"'tr'",
",",
"'cr'",
",",
"'br'",
",",
"'fr'",
",",
"'th'",
",",
"'dr'",
",",
"'ch'",
",",
"'ph'",
",",
"'wr'",
",",
"'st'",
",",
"'sp'",
",",
"'sw'",
",",
"'pr'",
",",
"'sl'",
",",
"'cl'",
"]",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'cons'",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"defaults",
"[",
"'cons'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'vowels'",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"defaults",
"[",
"'vowels'",
"]",
")",
";",
"}",
"return",
"Hash",
"::",
"merge",
"(",
"$",
"defaults",
",",
"$",
"options",
")",
";",
"}"
] |
The dictionary of vowels and consonants for the password generation.
@param array $options Options List of `vowels` and `cons`
@return array
|
[
"The",
"dictionary",
"of",
"vowels",
"and",
"consonants",
"for",
"the",
"password",
"generation",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/PasswordAndTokenTrait.php#L40-L59
|
train
|
burzum/cakephp-user-tools
|
src/Model/PasswordAndTokenTrait.php
|
PasswordAndTokenTrait.generateToken
|
public function generateToken($length = 10, $chars = '0123456789abcdefghijklmnopqrstuvwxyz') {
$token = '';
$i = 0;
while ($i < $length) {
$char = substr($chars, mt_rand(0, strlen($chars) - 1), 1);
if (!stristr($token, $char)) {
$token .= $char;
$i++;
}
}
return $token;
}
|
php
|
public function generateToken($length = 10, $chars = '0123456789abcdefghijklmnopqrstuvwxyz') {
$token = '';
$i = 0;
while ($i < $length) {
$char = substr($chars, mt_rand(0, strlen($chars) - 1), 1);
if (!stristr($token, $char)) {
$token .= $char;
$i++;
}
}
return $token;
}
|
[
"public",
"function",
"generateToken",
"(",
"$",
"length",
"=",
"10",
",",
"$",
"chars",
"=",
"'0123456789abcdefghijklmnopqrstuvwxyz'",
")",
"{",
"$",
"token",
"=",
"''",
";",
"$",
"i",
"=",
"0",
";",
"while",
"(",
"$",
"i",
"<",
"$",
"length",
")",
"{",
"$",
"char",
"=",
"substr",
"(",
"$",
"chars",
",",
"mt_rand",
"(",
"0",
",",
"strlen",
"(",
"$",
"chars",
")",
"-",
"1",
")",
",",
"1",
")",
";",
"if",
"(",
"!",
"stristr",
"(",
"$",
"token",
",",
"$",
"char",
")",
")",
"{",
"$",
"token",
".=",
"$",
"char",
";",
"$",
"i",
"++",
";",
"}",
"}",
"return",
"$",
"token",
";",
"}"
] |
Generate token used by the user registration system
@param int $length Token Length
@param string $chars Characters used in the token
@return string
|
[
"Generate",
"token",
"used",
"by",
"the",
"user",
"registration",
"system"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/PasswordAndTokenTrait.php#L68-L80
|
train
|
burzum/cakephp-user-tools
|
src/Auth/DefaultAuthSetupTrait.php
|
DefaultAuthSetupTrait.setupAuthentication
|
public function setupAuthentication() {
if (!in_array('Auth', $this->components()->loaded())) {
$this->components()->load('Auth');
}
$this->components()->Auth->setConfig('authenticate', [
'Form' => [
'userModel' => 'Users',
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => [
'Users.email_verified' => 1
]
]
]);
}
|
php
|
public function setupAuthentication() {
if (!in_array('Auth', $this->components()->loaded())) {
$this->components()->load('Auth');
}
$this->components()->Auth->setConfig('authenticate', [
'Form' => [
'userModel' => 'Users',
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => [
'Users.email_verified' => 1
]
]
]);
}
|
[
"public",
"function",
"setupAuthentication",
"(",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"'Auth'",
",",
"$",
"this",
"->",
"components",
"(",
")",
"->",
"loaded",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"components",
"(",
")",
"->",
"load",
"(",
"'Auth'",
")",
";",
"}",
"$",
"this",
"->",
"components",
"(",
")",
"->",
"Auth",
"->",
"setConfig",
"(",
"'authenticate'",
",",
"[",
"'Form'",
"=>",
"[",
"'userModel'",
"=>",
"'Users'",
",",
"'fields'",
"=>",
"[",
"'username'",
"=>",
"'email'",
",",
"'password'",
"=>",
"'password'",
"]",
",",
"'scope'",
"=>",
"[",
"'Users.email_verified'",
"=>",
"1",
"]",
"]",
"]",
")",
";",
"}"
] |
Sets the default authentication settings up.
Call this in your beforeFilter().
@return void
|
[
"Sets",
"the",
"default",
"authentication",
"settings",
"up",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Auth/DefaultAuthSetupTrait.php#L25-L42
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior._field
|
protected function _field($field) {
if (!isset($this->_config['fieldMap'][$field])) {
throw new RuntimeException(__d('user_tools', 'Invalid field "%s"!', $field));
}
return $this->_config['fieldMap'][$field];
}
|
php
|
protected function _field($field) {
if (!isset($this->_config['fieldMap'][$field])) {
throw new RuntimeException(__d('user_tools', 'Invalid field "%s"!', $field));
}
return $this->_config['fieldMap'][$field];
}
|
[
"protected",
"function",
"_field",
"(",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_config",
"[",
"'fieldMap'",
"]",
"[",
"$",
"field",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"__d",
"(",
"'user_tools'",
",",
"'Invalid field \"%s\"!'",
",",
"$",
"field",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"_config",
"[",
"'fieldMap'",
"]",
"[",
"$",
"field",
"]",
";",
"}"
] |
Gets the mapped field name of the table
@param string $field Field name to get the mapped field for
@throws \RuntimeException
@return string field name of the table
|
[
"Gets",
"the",
"mapped",
"field",
"name",
"of",
"the",
"table"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L178-L184
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.setupDefaultValidation
|
public function setupDefaultValidation() {
$validator = $this->_table->getValidator('default');
$validator = $this->validationUserName($validator);
$validator = $this->validationPassword($validator);
$validator = $this->validationConfirmPassword($validator);
$this->validationEmail($validator);
}
|
php
|
public function setupDefaultValidation() {
$validator = $this->_table->getValidator('default');
$validator = $this->validationUserName($validator);
$validator = $this->validationPassword($validator);
$validator = $this->validationConfirmPassword($validator);
$this->validationEmail($validator);
}
|
[
"public",
"function",
"setupDefaultValidation",
"(",
")",
"{",
"$",
"validator",
"=",
"$",
"this",
"->",
"_table",
"->",
"getValidator",
"(",
"'default'",
")",
";",
"$",
"validator",
"=",
"$",
"this",
"->",
"validationUserName",
"(",
"$",
"validator",
")",
";",
"$",
"validator",
"=",
"$",
"this",
"->",
"validationPassword",
"(",
"$",
"validator",
")",
";",
"$",
"validator",
"=",
"$",
"this",
"->",
"validationConfirmPassword",
"(",
"$",
"validator",
")",
";",
"$",
"this",
"->",
"validationEmail",
"(",
"$",
"validator",
")",
";",
"}"
] |
Sets validation rules for users up.
@return void
|
[
"Sets",
"validation",
"rules",
"for",
"users",
"up",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L191-L197
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior._emailVerification
|
protected function _emailVerification(EntityInterface &$entity, $options) {
if ($options['emailVerification'] === true) {
$entity->set($this->_field('emailToken'), $this->generateToken($options['tokenLength']));
if ($options['verificationExpirationTime'] !== false) {
$entity->set($this->_field('emailTokenExpires'), $this->expirationTime($options['verificationExpirationTime']));
}
$entity->set($this->_field('emailVerified'), false);
} else {
$entity->set($this->_field('emailVerified'), true);
}
}
|
php
|
protected function _emailVerification(EntityInterface &$entity, $options) {
if ($options['emailVerification'] === true) {
$entity->set($this->_field('emailToken'), $this->generateToken($options['tokenLength']));
if ($options['verificationExpirationTime'] !== false) {
$entity->set($this->_field('emailTokenExpires'), $this->expirationTime($options['verificationExpirationTime']));
}
$entity->set($this->_field('emailVerified'), false);
} else {
$entity->set($this->_field('emailVerified'), true);
}
}
|
[
"protected",
"function",
"_emailVerification",
"(",
"EntityInterface",
"&",
"$",
"entity",
",",
"$",
"options",
")",
"{",
"if",
"(",
"$",
"options",
"[",
"'emailVerification'",
"]",
"===",
"true",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'emailToken'",
")",
",",
"$",
"this",
"->",
"generateToken",
"(",
"$",
"options",
"[",
"'tokenLength'",
"]",
")",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'verificationExpirationTime'",
"]",
"!==",
"false",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'emailTokenExpires'",
")",
",",
"$",
"this",
"->",
"expirationTime",
"(",
"$",
"options",
"[",
"'verificationExpirationTime'",
"]",
")",
")",
";",
"}",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'emailVerified'",
")",
",",
"false",
")",
";",
"}",
"else",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'emailVerified'",
")",
",",
"true",
")",
";",
"}",
"}"
] |
Handles the email verification if required
@param \Cake\Datasource\EntityInterface $entity User entity
@param array $options Options array
@return void
|
[
"Handles",
"the",
"email",
"verification",
"if",
"required"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L239-L249
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior._beforeRegister
|
protected function _beforeRegister(EntityInterface $entity, $options = []) {
$options = Hash::merge($this->_config['register'], $options);
$schema = $this->_table->getSchema();
$columnType = $schema->getColumnType($this->_table->getPrimaryKey());
if ($this->_config['useUuid'] === true && $columnType !== 'integer') {
$primaryKey = $this->_table->getPrimaryKey();
$entity->set($primaryKey, Text::uuid());
}
if ($options['userActive'] === true) {
$entity->set($this->_field('active'), true);
}
$this->_emailVerification($entity, $options);
if (!isset($entity->{$this->_field('role')})) {
$entity->set($this->_field('role'), $options['defaultRole']);
}
if ($options['generatePassword'] === true) {
$password = $this->generatePassword();
$entity->set($this->_field('password'), $password);
$entity->set('clear_password', $password);
}
if ($options['hashPassword'] === true) {
$entity->set($this->_field('password'), $this->hashPassword($entity->get($this->_field('password'))));
}
return $entity;
}
|
php
|
protected function _beforeRegister(EntityInterface $entity, $options = []) {
$options = Hash::merge($this->_config['register'], $options);
$schema = $this->_table->getSchema();
$columnType = $schema->getColumnType($this->_table->getPrimaryKey());
if ($this->_config['useUuid'] === true && $columnType !== 'integer') {
$primaryKey = $this->_table->getPrimaryKey();
$entity->set($primaryKey, Text::uuid());
}
if ($options['userActive'] === true) {
$entity->set($this->_field('active'), true);
}
$this->_emailVerification($entity, $options);
if (!isset($entity->{$this->_field('role')})) {
$entity->set($this->_field('role'), $options['defaultRole']);
}
if ($options['generatePassword'] === true) {
$password = $this->generatePassword();
$entity->set($this->_field('password'), $password);
$entity->set('clear_password', $password);
}
if ($options['hashPassword'] === true) {
$entity->set($this->_field('password'), $this->hashPassword($entity->get($this->_field('password'))));
}
return $entity;
}
|
[
"protected",
"function",
"_beforeRegister",
"(",
"EntityInterface",
"$",
"entity",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"this",
"->",
"_config",
"[",
"'register'",
"]",
",",
"$",
"options",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"_table",
"->",
"getSchema",
"(",
")",
";",
"$",
"columnType",
"=",
"$",
"schema",
"->",
"getColumnType",
"(",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"_config",
"[",
"'useUuid'",
"]",
"===",
"true",
"&&",
"$",
"columnType",
"!==",
"'integer'",
")",
"{",
"$",
"primaryKey",
"=",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
";",
"$",
"entity",
"->",
"set",
"(",
"$",
"primaryKey",
",",
"Text",
"::",
"uuid",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'userActive'",
"]",
"===",
"true",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'active'",
")",
",",
"true",
")",
";",
"}",
"$",
"this",
"->",
"_emailVerification",
"(",
"$",
"entity",
",",
"$",
"options",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"entity",
"->",
"{",
"$",
"this",
"->",
"_field",
"(",
"'role'",
")",
"}",
")",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'role'",
")",
",",
"$",
"options",
"[",
"'defaultRole'",
"]",
")",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'generatePassword'",
"]",
"===",
"true",
")",
"{",
"$",
"password",
"=",
"$",
"this",
"->",
"generatePassword",
"(",
")",
";",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
",",
"$",
"password",
")",
";",
"$",
"entity",
"->",
"set",
"(",
"'clear_password'",
",",
"$",
"password",
")",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'hashPassword'",
"]",
"===",
"true",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
",",
"$",
"this",
"->",
"hashPassword",
"(",
"$",
"entity",
"->",
"get",
"(",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
")",
")",
")",
";",
"}",
"return",
"$",
"entity",
";",
"}"
] |
Behavior internal before registration callback
This method deals with most of the settings for the registration that can be
applied before the actual user record is saved.
@param \Cake\Datasource\EntityInterface $entity Users entity
@param array $options Options
@return \Cake\Datasource\EntityInterface
|
[
"Behavior",
"internal",
"before",
"registration",
"callback"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L261-L293
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.findEmailVerified
|
public function findEmailVerified(Query $query, array $options) {
$query->where([
$this->_table->aliasField($this->_field('emailVerified')) => true,
]);
return $query;
}
|
php
|
public function findEmailVerified(Query $query, array $options) {
$query->where([
$this->_table->aliasField($this->_field('emailVerified')) => true,
]);
return $query;
}
|
[
"public",
"function",
"findEmailVerified",
"(",
"Query",
"$",
"query",
",",
"array",
"$",
"options",
")",
"{",
"$",
"query",
"->",
"where",
"(",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"_field",
"(",
"'emailVerified'",
")",
")",
"=>",
"true",
",",
"]",
")",
";",
"return",
"$",
"query",
";",
"}"
] |
Find users with verified emails.
@param \Cake\ORM\Query $query Query object
@param array $options Options
@return Query
|
[
"Find",
"users",
"with",
"verified",
"emails",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L302-L308
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.register
|
public function register(EntityInterface $entity, $options = []) {
$options = array_merge($this->_config['register'], $options);
if ($options['beforeRegister'] === true) {
$entity = $this->_beforeRegister($entity, $options);
}
$event = $this->dispatchEvent('User.beforeRegister', [
'data' => $entity,
'table' => $this->_table
]);
if ($event->isStopped()) {
return $event->result;
}
$result = $this->_table->save($entity, $options['saveOptions']);
if (!$result) {
return $result;
}
if ($options['afterRegister'] === true) {
$this->_afterRegister($result, $options);
}
$event = $this->dispatchEvent('user.afterRegister', [
'data' => $result,
'table' => $this->_table
]);
if ($event->isStopped()) {
return $event->result;
}
return $result;
}
|
php
|
public function register(EntityInterface $entity, $options = []) {
$options = array_merge($this->_config['register'], $options);
if ($options['beforeRegister'] === true) {
$entity = $this->_beforeRegister($entity, $options);
}
$event = $this->dispatchEvent('User.beforeRegister', [
'data' => $entity,
'table' => $this->_table
]);
if ($event->isStopped()) {
return $event->result;
}
$result = $this->_table->save($entity, $options['saveOptions']);
if (!$result) {
return $result;
}
if ($options['afterRegister'] === true) {
$this->_afterRegister($result, $options);
}
$event = $this->dispatchEvent('user.afterRegister', [
'data' => $result,
'table' => $this->_table
]);
if ($event->isStopped()) {
return $event->result;
}
return $result;
}
|
[
"public",
"function",
"register",
"(",
"EntityInterface",
"$",
"entity",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"_config",
"[",
"'register'",
"]",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'beforeRegister'",
"]",
"===",
"true",
")",
"{",
"$",
"entity",
"=",
"$",
"this",
"->",
"_beforeRegister",
"(",
"$",
"entity",
",",
"$",
"options",
")",
";",
"}",
"$",
"event",
"=",
"$",
"this",
"->",
"dispatchEvent",
"(",
"'User.beforeRegister'",
",",
"[",
"'data'",
"=>",
"$",
"entity",
",",
"'table'",
"=>",
"$",
"this",
"->",
"_table",
"]",
")",
";",
"if",
"(",
"$",
"event",
"->",
"isStopped",
"(",
")",
")",
"{",
"return",
"$",
"event",
"->",
"result",
";",
"}",
"$",
"result",
"=",
"$",
"this",
"->",
"_table",
"->",
"save",
"(",
"$",
"entity",
",",
"$",
"options",
"[",
"'saveOptions'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"result",
")",
"{",
"return",
"$",
"result",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'afterRegister'",
"]",
"===",
"true",
")",
"{",
"$",
"this",
"->",
"_afterRegister",
"(",
"$",
"result",
",",
"$",
"options",
")",
";",
"}",
"$",
"event",
"=",
"$",
"this",
"->",
"dispatchEvent",
"(",
"'user.afterRegister'",
",",
"[",
"'data'",
"=>",
"$",
"result",
",",
"'table'",
"=>",
"$",
"this",
"->",
"_table",
"]",
")",
";",
"if",
"(",
"$",
"event",
"->",
"isStopped",
"(",
")",
")",
"{",
"return",
"$",
"event",
"->",
"result",
";",
"}",
"return",
"$",
"result",
";",
"}"
] |
Registers a new user
You can modify the registration process through implementing an event
listener for the User.beforeRegister and User.afterRegister events.
If you stop the events the result of the event will be returned.
Flow:
- calls the behaviors _beforeRegister method if not disabled via config
- Fires the User.beforeRegister event
- Attempt to save the user data
- calls the behaviors _afterRegister method if not disabled via config
- Fires the User.afterRegister event
Options:
- `beforeRegister` - Bool to call the internal _beforeRegister() method.
Default is true
- `afterRegister` - Bool to call the internal _beforeRegister() method.
Default is true
- `tokenLength` - Length of the verification token, default is 32
- `saveOptions` Optional save options to be passed to the save() call.
- `verificationExpirationTime` - Default is `+1 day`
- `emailVerification` - Use email verification or not, default is true.
- `defaultRole` - Default role to set in the mapped `role` field.
- `userActive` - Set the user to active by default on registration.
Default is true
- `generatePassword` - To generate a password or not. Default is false.
- `hashPassword` - To has the password or not, default is true.
@param \Cake\Datasource\EntityInterface $entity User Entity
@param array $options Options
@throws \InvalidArgumentException
@return \Cake\Datasource\EntityInterface|bool Returns bool false if the user could not be saved.
|
[
"Registers",
"a",
"new",
"user"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L360-L396
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.verifyPasswordResetToken
|
public function verifyPasswordResetToken($token, $options = []) {
$defaults = [
'tokenField' => $this->_field('passwordToken'),
'expirationField' => $this->_field('passwordTokenExpires'),
'returnData' => true,
];
return $this->verifyToken($token, Hash::merge($defaults, $options));
}
|
php
|
public function verifyPasswordResetToken($token, $options = []) {
$defaults = [
'tokenField' => $this->_field('passwordToken'),
'expirationField' => $this->_field('passwordTokenExpires'),
'returnData' => true,
];
return $this->verifyToken($token, Hash::merge($defaults, $options));
}
|
[
"public",
"function",
"verifyPasswordResetToken",
"(",
"$",
"token",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'tokenField'",
"=>",
"$",
"this",
"->",
"_field",
"(",
"'passwordToken'",
")",
",",
"'expirationField'",
"=>",
"$",
"this",
"->",
"_field",
"(",
"'passwordTokenExpires'",
")",
",",
"'returnData'",
"=>",
"true",
",",
"]",
";",
"return",
"$",
"this",
"->",
"verifyToken",
"(",
"$",
"token",
",",
"Hash",
"::",
"merge",
"(",
"$",
"defaults",
",",
"$",
"options",
")",
")",
";",
"}"
] |
Verify the password reset token
- `tokenField` - The field to check for the token
- `expirationField` - The field to check for the token expiration date
@param string $token Token string
@param array $options Options
@throws \Cake\Datasource\Exception\RecordNotFoundException if the token was not found at all
@return bool Returns false if the token has expired
|
[
"Verify",
"the",
"password",
"reset",
"token"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L516-L524
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.resetPassword
|
public function resetPassword(Entity $user) {
if (!$user->getErrors()) {
$user->{$this->_field('password')} = $this->hashPassword($user->{$this->_field('password')});
$user->{$this->_field('passwordToken')} = null;
$user->{$this->_field('passwordTokenExpires')} = null;
return $this->_table->save($user, ['checkRules' => false]);
}
return false;
}
|
php
|
public function resetPassword(Entity $user) {
if (!$user->getErrors()) {
$user->{$this->_field('password')} = $this->hashPassword($user->{$this->_field('password')});
$user->{$this->_field('passwordToken')} = null;
$user->{$this->_field('passwordTokenExpires')} = null;
return $this->_table->save($user, ['checkRules' => false]);
}
return false;
}
|
[
"public",
"function",
"resetPassword",
"(",
"Entity",
"$",
"user",
")",
"{",
"if",
"(",
"!",
"$",
"user",
"->",
"getErrors",
"(",
")",
")",
"{",
"$",
"user",
"->",
"{",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
"}",
"=",
"$",
"this",
"->",
"hashPassword",
"(",
"$",
"user",
"->",
"{",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
"}",
")",
";",
"$",
"user",
"->",
"{",
"$",
"this",
"->",
"_field",
"(",
"'passwordToken'",
")",
"}",
"=",
"null",
";",
"$",
"user",
"->",
"{",
"$",
"this",
"->",
"_field",
"(",
"'passwordTokenExpires'",
")",
"}",
"=",
"null",
";",
"return",
"$",
"this",
"->",
"_table",
"->",
"save",
"(",
"$",
"user",
",",
"[",
"'checkRules'",
"=>",
"false",
"]",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Password reset, compares the two passwords and saves the new password.
@param \Cake\Datasource\EntityInterface $user Entity object.
@return bool|\Cake\Datasource\EntityInterface
|
[
"Password",
"reset",
"compares",
"the",
"two",
"passwords",
"and",
"saves",
"the",
"new",
"password",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L532-L542
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.removeExpiredRegistrations
|
public function removeExpiredRegistrations($conditions = []) {
$defaults = [
$this->_table->aliasField($this->_field('emailVerified')) => 0,
$this->_table->aliasField($this->_field('emailTokenExpires')) . ' <' => date('Y-m-d H:i:s')
];
$conditions = Hash::merge($defaults, $conditions);
$count = $this->_table
->find()
->where($conditions)
->count();
if ($count > 0) {
$this->_table->deleteAll($conditions);
}
return $count;
}
|
php
|
public function removeExpiredRegistrations($conditions = []) {
$defaults = [
$this->_table->aliasField($this->_field('emailVerified')) => 0,
$this->_table->aliasField($this->_field('emailTokenExpires')) . ' <' => date('Y-m-d H:i:s')
];
$conditions = Hash::merge($defaults, $conditions);
$count = $this->_table
->find()
->where($conditions)
->count();
if ($count > 0) {
$this->_table->deleteAll($conditions);
}
return $count;
}
|
[
"public",
"function",
"removeExpiredRegistrations",
"(",
"$",
"conditions",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"_field",
"(",
"'emailVerified'",
")",
")",
"=>",
"0",
",",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"_field",
"(",
"'emailTokenExpires'",
")",
")",
".",
"' <'",
"=>",
"date",
"(",
"'Y-m-d H:i:s'",
")",
"]",
";",
"$",
"conditions",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"defaults",
",",
"$",
"conditions",
")",
";",
"$",
"count",
"=",
"$",
"this",
"->",
"_table",
"->",
"find",
"(",
")",
"->",
"where",
"(",
"$",
"conditions",
")",
"->",
"count",
"(",
")",
";",
"if",
"(",
"$",
"count",
">",
"0",
")",
"{",
"$",
"this",
"->",
"_table",
"->",
"deleteAll",
"(",
"$",
"conditions",
")",
";",
"}",
"return",
"$",
"count",
";",
"}"
] |
Removes all users from the user table that did not complete the registration
@param array $conditions Find conditions passed to where()
@return int Number of removed records
|
[
"Removes",
"all",
"users",
"from",
"the",
"user",
"table",
"that",
"did",
"not",
"complete",
"the",
"registration"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L550-L567
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.changePassword
|
public function changePassword(EntityInterface $entity, array $options = []) {
$options = Hash::merge($this->_config['changePassword'], $options);
if ($entity->getErrors()) {
return false;
}
if ($options['hashPassword'] === true) {
$field = $this->_field('password');
$entity->set($field, $this->hashPassword($entity->get($field)));
}
return (bool)$this->_table->save($entity);
}
|
php
|
public function changePassword(EntityInterface $entity, array $options = []) {
$options = Hash::merge($this->_config['changePassword'], $options);
if ($entity->getErrors()) {
return false;
}
if ($options['hashPassword'] === true) {
$field = $this->_field('password');
$entity->set($field, $this->hashPassword($entity->get($field)));
}
return (bool)$this->_table->save($entity);
}
|
[
"public",
"function",
"changePassword",
"(",
"EntityInterface",
"$",
"entity",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"this",
"->",
"_config",
"[",
"'changePassword'",
"]",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"entity",
"->",
"getErrors",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"options",
"[",
"'hashPassword'",
"]",
"===",
"true",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
";",
"$",
"entity",
"->",
"set",
"(",
"$",
"field",
",",
"$",
"this",
"->",
"hashPassword",
"(",
"$",
"entity",
"->",
"get",
"(",
"$",
"field",
")",
")",
")",
";",
"}",
"return",
"(",
"bool",
")",
"$",
"this",
"->",
"_table",
"->",
"save",
"(",
"$",
"entity",
")",
";",
"}"
] |
Changes the password for an user.
@param \Cake\Datasource\EntityInterface $entity User entity
@param array $options Options
@return bool
|
[
"Changes",
"the",
"password",
"for",
"an",
"user",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L576-L589
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.initPasswordReset
|
public function initPasswordReset($value, $options = []) {
$defaults = [
'field' => [
$this->_table->aliasField($this->_field('email')),
$this->_table->aliasField($this->_field('username'))
]
];
$options = Hash::merge($defaults, $this->_config['initPasswordReset'], $options);
$result = $this->_getUser($value, $options);
if (empty($result)) {
throw new RecordNotFoundException(__d('burzum/user_tools', 'User not found.'));
}
$result->set([
$this->_field('passwordToken') => $this->generateToken($options['tokenLength']),
$this->_field('passwordTokenExpires') => $this->expirationTime($options['expires'])
], [
'guard' => false
]);
if (!$this->_table->save($result, ['checkRules' => false])) {
new RuntimeException('Could not initialize password reset. Data could not be saved.');
}
$this->sendPasswordResetToken($result, [
'to' => $result->get($this->_field('email'))
]);
}
|
php
|
public function initPasswordReset($value, $options = []) {
$defaults = [
'field' => [
$this->_table->aliasField($this->_field('email')),
$this->_table->aliasField($this->_field('username'))
]
];
$options = Hash::merge($defaults, $this->_config['initPasswordReset'], $options);
$result = $this->_getUser($value, $options);
if (empty($result)) {
throw new RecordNotFoundException(__d('burzum/user_tools', 'User not found.'));
}
$result->set([
$this->_field('passwordToken') => $this->generateToken($options['tokenLength']),
$this->_field('passwordTokenExpires') => $this->expirationTime($options['expires'])
], [
'guard' => false
]);
if (!$this->_table->save($result, ['checkRules' => false])) {
new RuntimeException('Could not initialize password reset. Data could not be saved.');
}
$this->sendPasswordResetToken($result, [
'to' => $result->get($this->_field('email'))
]);
}
|
[
"public",
"function",
"initPasswordReset",
"(",
"$",
"value",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'field'",
"=>",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"_field",
"(",
"'email'",
")",
")",
",",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"_field",
"(",
"'username'",
")",
")",
"]",
"]",
";",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"defaults",
",",
"$",
"this",
"->",
"_config",
"[",
"'initPasswordReset'",
"]",
",",
"$",
"options",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"_getUser",
"(",
"$",
"value",
",",
"$",
"options",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"result",
")",
")",
"{",
"throw",
"new",
"RecordNotFoundException",
"(",
"__d",
"(",
"'burzum/user_tools'",
",",
"'User not found.'",
")",
")",
";",
"}",
"$",
"result",
"->",
"set",
"(",
"[",
"$",
"this",
"->",
"_field",
"(",
"'passwordToken'",
")",
"=>",
"$",
"this",
"->",
"generateToken",
"(",
"$",
"options",
"[",
"'tokenLength'",
"]",
")",
",",
"$",
"this",
"->",
"_field",
"(",
"'passwordTokenExpires'",
")",
"=>",
"$",
"this",
"->",
"expirationTime",
"(",
"$",
"options",
"[",
"'expires'",
"]",
")",
"]",
",",
"[",
"'guard'",
"=>",
"false",
"]",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"_table",
"->",
"save",
"(",
"$",
"result",
",",
"[",
"'checkRules'",
"=>",
"false",
"]",
")",
")",
"{",
"new",
"RuntimeException",
"(",
"'Could not initialize password reset. Data could not be saved.'",
")",
";",
"}",
"$",
"this",
"->",
"sendPasswordResetToken",
"(",
"$",
"result",
",",
"[",
"'to'",
"=>",
"$",
"result",
"->",
"get",
"(",
"$",
"this",
"->",
"_field",
"(",
"'email'",
")",
")",
"]",
")",
";",
"}"
] |
Initializes a password reset process.
@param mixed $value User id or other value to look the user up
@param array $options Options
@return void
|
[
"Initializes",
"a",
"password",
"reset",
"process",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L598-L627
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior._getUser
|
protected function _getUser($value, $options = []) {
$defaults = [
'notFoundErrorMessage' => __d('user_tools', 'User not found.'),
'field' => $this->_table->aliasField($this->_table->getPrimaryKey())
];
$defaults = Hash::merge($defaults, $this->getConfig('getUser'));
if (isset($options['field'])) {
$defaults['field'] = $options['field'];
}
$options = Hash::merge($defaults, $options);
$query = $this->_getFindUserQuery($value, $options);
if (isset($options['queryCallback']) && is_callable($options['queryCallback'])) {
$query = $options['queryCallback']($query, $options);
}
$result = $query->first();
if (empty($result)) {
throw new RecordNotFoundException($options['notFoundErrorMessage']);
}
return $result;
}
|
php
|
protected function _getUser($value, $options = []) {
$defaults = [
'notFoundErrorMessage' => __d('user_tools', 'User not found.'),
'field' => $this->_table->aliasField($this->_table->getPrimaryKey())
];
$defaults = Hash::merge($defaults, $this->getConfig('getUser'));
if (isset($options['field'])) {
$defaults['field'] = $options['field'];
}
$options = Hash::merge($defaults, $options);
$query = $this->_getFindUserQuery($value, $options);
if (isset($options['queryCallback']) && is_callable($options['queryCallback'])) {
$query = $options['queryCallback']($query, $options);
}
$result = $query->first();
if (empty($result)) {
throw new RecordNotFoundException($options['notFoundErrorMessage']);
}
return $result;
}
|
[
"protected",
"function",
"_getUser",
"(",
"$",
"value",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'notFoundErrorMessage'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'User not found.'",
")",
",",
"'field'",
"=>",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"_table",
"->",
"getPrimaryKey",
"(",
")",
")",
"]",
";",
"$",
"defaults",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"defaults",
",",
"$",
"this",
"->",
"getConfig",
"(",
"'getUser'",
")",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'field'",
"]",
")",
")",
"{",
"$",
"defaults",
"[",
"'field'",
"]",
"=",
"$",
"options",
"[",
"'field'",
"]",
";",
"}",
"$",
"options",
"=",
"Hash",
"::",
"merge",
"(",
"$",
"defaults",
",",
"$",
"options",
")",
";",
"$",
"query",
"=",
"$",
"this",
"->",
"_getFindUserQuery",
"(",
"$",
"value",
",",
"$",
"options",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'queryCallback'",
"]",
")",
"&&",
"is_callable",
"(",
"$",
"options",
"[",
"'queryCallback'",
"]",
")",
")",
"{",
"$",
"query",
"=",
"$",
"options",
"[",
"'queryCallback'",
"]",
"(",
"$",
"query",
",",
"$",
"options",
")",
";",
"}",
"$",
"result",
"=",
"$",
"query",
"->",
"first",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"result",
")",
")",
"{",
"throw",
"new",
"RecordNotFoundException",
"(",
"$",
"options",
"[",
"'notFoundErrorMessage'",
"]",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] |
Finds the user for the password reset.
Extend the behavior and override this method if the configuration options
are not sufficient.
@param mixed $value User lookup value
@param array $options Options
@throws \Cake\Datasource\Exception\RecordNotFoundException
@return \Cake\Datasource\EntityInterface
|
[
"Finds",
"the",
"user",
"for",
"the",
"password",
"reset",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L652-L677
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.sendNewPassword
|
public function sendNewPassword($email, $options = []) {
if ($email instanceof EntityInterface) {
$result = $email;
$email = $result->get($this->_field('email'));
} else {
$result = $this->_table->find()
->where([
$this->_table->aliasField($this->_field('email')) => $email
])
->first();
if (empty($result)) {
throw new RecordNotFoundException(__d('user_tools', 'Invalid user'));
}
}
$password = $this->generatePassword();
$result->set([
$this->_field('password') => $this->hashPassword($password),
'clear_password' => $password
], [
'guard' => false
]);
$this->_table->save($result, ['validate' => false]);
return $this->sendNewPasswordEmail($result, ['to' => $result->get($this->_field('email'))]);
}
|
php
|
public function sendNewPassword($email, $options = []) {
if ($email instanceof EntityInterface) {
$result = $email;
$email = $result->get($this->_field('email'));
} else {
$result = $this->_table->find()
->where([
$this->_table->aliasField($this->_field('email')) => $email
])
->first();
if (empty($result)) {
throw new RecordNotFoundException(__d('user_tools', 'Invalid user'));
}
}
$password = $this->generatePassword();
$result->set([
$this->_field('password') => $this->hashPassword($password),
'clear_password' => $password
], [
'guard' => false
]);
$this->_table->save($result, ['validate' => false]);
return $this->sendNewPasswordEmail($result, ['to' => $result->get($this->_field('email'))]);
}
|
[
"public",
"function",
"sendNewPassword",
"(",
"$",
"email",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"email",
"instanceof",
"EntityInterface",
")",
"{",
"$",
"result",
"=",
"$",
"email",
";",
"$",
"email",
"=",
"$",
"result",
"->",
"get",
"(",
"$",
"this",
"->",
"_field",
"(",
"'email'",
")",
")",
";",
"}",
"else",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"_table",
"->",
"find",
"(",
")",
"->",
"where",
"(",
"[",
"$",
"this",
"->",
"_table",
"->",
"aliasField",
"(",
"$",
"this",
"->",
"_field",
"(",
"'email'",
")",
")",
"=>",
"$",
"email",
"]",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"result",
")",
")",
"{",
"throw",
"new",
"RecordNotFoundException",
"(",
"__d",
"(",
"'user_tools'",
",",
"'Invalid user'",
")",
")",
";",
"}",
"}",
"$",
"password",
"=",
"$",
"this",
"->",
"generatePassword",
"(",
")",
";",
"$",
"result",
"->",
"set",
"(",
"[",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
"=>",
"$",
"this",
"->",
"hashPassword",
"(",
"$",
"password",
")",
",",
"'clear_password'",
"=>",
"$",
"password",
"]",
",",
"[",
"'guard'",
"=>",
"false",
"]",
")",
";",
"$",
"this",
"->",
"_table",
"->",
"save",
"(",
"$",
"result",
",",
"[",
"'validate'",
"=>",
"false",
"]",
")",
";",
"return",
"$",
"this",
"->",
"sendNewPasswordEmail",
"(",
"$",
"result",
",",
"[",
"'to'",
"=>",
"$",
"result",
"->",
"get",
"(",
"$",
"this",
"->",
"_field",
"(",
"'email'",
")",
")",
"]",
")",
";",
"}"
] |
Sends a new password to an user by email.
Note that this is *not* a recommended way to reset an user password. A much
more secure approach is to have the user manually enter a new password and
only send him an URL with a token.
@param string|EntityInterface $email The user entity or the email
@param array $options Optional options array, use it to pass config options.
@throws \Cake\Datasource\Exception\RecordNotFoundException
@return bool
|
[
"Sends",
"a",
"new",
"password",
"to",
"an",
"user",
"by",
"email",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L718-L745
|
train
|
burzum/cakephp-user-tools
|
src/Model/Behavior/UserBehavior.php
|
UserBehavior.handleNewPasswordByOldPassword
|
public function handleNewPasswordByOldPassword(EntityInterface $user) {
// Don't do it for new users or the password will end up empty
if ($user->isNew()) {
return;
}
$oldPassword = $user->get($this->_field('oldPassword'));
if (empty($oldPassword) || $user->getErrors()) {
$user->unsetProperty($this->_field('password'));
$user->unsetProperty($this->_field('passwordCheck'));
return;
}
$newPassword = $this->hashPassword($user->get($this->_field('password')));
$user->set($this->_field('password'), $newPassword, ['guard' => false]);
}
|
php
|
public function handleNewPasswordByOldPassword(EntityInterface $user) {
// Don't do it for new users or the password will end up empty
if ($user->isNew()) {
return;
}
$oldPassword = $user->get($this->_field('oldPassword'));
if (empty($oldPassword) || $user->getErrors()) {
$user->unsetProperty($this->_field('password'));
$user->unsetProperty($this->_field('passwordCheck'));
return;
}
$newPassword = $this->hashPassword($user->get($this->_field('password')));
$user->set($this->_field('password'), $newPassword, ['guard' => false]);
}
|
[
"public",
"function",
"handleNewPasswordByOldPassword",
"(",
"EntityInterface",
"$",
"user",
")",
"{",
"// Don't do it for new users or the password will end up empty",
"if",
"(",
"$",
"user",
"->",
"isNew",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"oldPassword",
"=",
"$",
"user",
"->",
"get",
"(",
"$",
"this",
"->",
"_field",
"(",
"'oldPassword'",
")",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"oldPassword",
")",
"||",
"$",
"user",
"->",
"getErrors",
"(",
")",
")",
"{",
"$",
"user",
"->",
"unsetProperty",
"(",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
")",
";",
"$",
"user",
"->",
"unsetProperty",
"(",
"$",
"this",
"->",
"_field",
"(",
"'passwordCheck'",
")",
")",
";",
"return",
";",
"}",
"$",
"newPassword",
"=",
"$",
"this",
"->",
"hashPassword",
"(",
"$",
"user",
"->",
"get",
"(",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
")",
")",
";",
"$",
"user",
"->",
"set",
"(",
"$",
"this",
"->",
"_field",
"(",
"'password'",
")",
",",
"$",
"newPassword",
",",
"[",
"'guard'",
"=>",
"false",
"]",
")",
";",
"}"
] |
Handles the hashing of the password after the old password of the user
was verified and the new password was validated as well.
Call this in your models beforeSave() or wherever else you want.
This method will unset by default the `password` and `confirm_password`
fields if no `old_password` was provided or the entity has validation
errors.
@param \Cake\Datasource\EntityInterface $user User Entity
@return void
|
[
"Handles",
"the",
"hashing",
"of",
"the",
"password",
"after",
"the",
"old",
"password",
"of",
"the",
"user",
"was",
"verified",
"and",
"the",
"new",
"password",
"was",
"validated",
"as",
"well",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Model/Behavior/UserBehavior.php#L774-L791
|
train
|
burzum/cakephp-user-tools
|
src/View/Helper/AuthHelper.php
|
AuthHelper._setupUserData
|
protected function _setupUserData() {
if (is_string($this->_config['session'])) {
$this->_userData = $this->_View->request->session()->read($this->_config['session']);
} else {
if (!array_key_exists($this->_config['viewVar'], $this->_View->viewVars)) {
if ($this->_config['viewVarException'] === true) {
throw new \RuntimeException(sprintf('View var `%s` not present! Please set the auth data to the view. See the documentation.', $this->_config['viewVar']));
} else {
$this->_userData = [];
}
} else {
$this->_userData = $this->_View->viewVars[$this->_config['viewVar']];
}
}
}
|
php
|
protected function _setupUserData() {
if (is_string($this->_config['session'])) {
$this->_userData = $this->_View->request->session()->read($this->_config['session']);
} else {
if (!array_key_exists($this->_config['viewVar'], $this->_View->viewVars)) {
if ($this->_config['viewVarException'] === true) {
throw new \RuntimeException(sprintf('View var `%s` not present! Please set the auth data to the view. See the documentation.', $this->_config['viewVar']));
} else {
$this->_userData = [];
}
} else {
$this->_userData = $this->_View->viewVars[$this->_config['viewVar']];
}
}
}
|
[
"protected",
"function",
"_setupUserData",
"(",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"this",
"->",
"_config",
"[",
"'session'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"_userData",
"=",
"$",
"this",
"->",
"_View",
"->",
"request",
"->",
"session",
"(",
")",
"->",
"read",
"(",
"$",
"this",
"->",
"_config",
"[",
"'session'",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"this",
"->",
"_config",
"[",
"'viewVar'",
"]",
",",
"$",
"this",
"->",
"_View",
"->",
"viewVars",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_config",
"[",
"'viewVarException'",
"]",
"===",
"true",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'View var `%s` not present! Please set the auth data to the view. See the documentation.'",
",",
"$",
"this",
"->",
"_config",
"[",
"'viewVar'",
"]",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"_userData",
"=",
"[",
"]",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"_userData",
"=",
"$",
"this",
"->",
"_View",
"->",
"viewVars",
"[",
"$",
"this",
"->",
"_config",
"[",
"'viewVar'",
"]",
"]",
";",
"}",
"}",
"}"
] |
Sets up the user data from session or view var
@throws \RuntimeException
@return void
|
[
"Sets",
"up",
"the",
"user",
"data",
"from",
"session",
"or",
"view",
"var"
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/View/Helper/AuthHelper.php#L60-L74
|
train
|
burzum/cakephp-user-tools
|
src/View/Helper/AuthHelper.php
|
AuthHelper.hasRole
|
public function hasRole($requestedRole) {
$roles = $this->user($this->getConfig('roleField'));
if (is_null($roles)) {
return false;
}
return $this->_checkRoles($requestedRole, $roles);
}
|
php
|
public function hasRole($requestedRole) {
$roles = $this->user($this->getConfig('roleField'));
if (is_null($roles)) {
return false;
}
return $this->_checkRoles($requestedRole, $roles);
}
|
[
"public",
"function",
"hasRole",
"(",
"$",
"requestedRole",
")",
"{",
"$",
"roles",
"=",
"$",
"this",
"->",
"user",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'roleField'",
")",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"roles",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"_checkRoles",
"(",
"$",
"requestedRole",
",",
"$",
"roles",
")",
";",
"}"
] |
Role check.
@param array|string $requestedRole Role string or set of role identifiers.
@return bool|null True if the role is in the set of roles for the active user data.
|
[
"Role",
"check",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/View/Helper/AuthHelper.php#L134-L141
|
train
|
burzum/cakephp-user-tools
|
src/View/Helper/AuthHelper.php
|
AuthHelper._checkRoles
|
protected function _checkRoles($requestedRole, $roles) {
if (is_string($roles)) {
$roles = [$roles];
}
if (is_string($requestedRole)) {
$requestedRole = [$requestedRole];
}
if (!is_array($requestedRole)) {
throw new InvalidArgumentException('The requested role is not a string or an array!');
}
$result = array_intersect($roles, $requestedRole);
return (count($result) > 0);
}
|
php
|
protected function _checkRoles($requestedRole, $roles) {
if (is_string($roles)) {
$roles = [$roles];
}
if (is_string($requestedRole)) {
$requestedRole = [$requestedRole];
}
if (!is_array($requestedRole)) {
throw new InvalidArgumentException('The requested role is not a string or an array!');
}
$result = array_intersect($roles, $requestedRole);
return (count($result) > 0);
}
|
[
"protected",
"function",
"_checkRoles",
"(",
"$",
"requestedRole",
",",
"$",
"roles",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"roles",
")",
")",
"{",
"$",
"roles",
"=",
"[",
"$",
"roles",
"]",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"requestedRole",
")",
")",
"{",
"$",
"requestedRole",
"=",
"[",
"$",
"requestedRole",
"]",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"requestedRole",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The requested role is not a string or an array!'",
")",
";",
"}",
"$",
"result",
"=",
"array_intersect",
"(",
"$",
"roles",
",",
"$",
"requestedRole",
")",
";",
"return",
"(",
"count",
"(",
"$",
"result",
")",
">",
"0",
")",
";",
"}"
] |
Checks the roles.
@param string|array $requestedRole Requested role
@param string|array $roles List of roles
@return bool
|
[
"Checks",
"the",
"roles",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/View/Helper/AuthHelper.php#L150-L163
|
train
|
burzum/cakephp-user-tools
|
src/Mailer/UsersMailer.php
|
UsersMailer.verificationEmail
|
public function verificationEmail(EntityInterface $user, array $options = []) {
$defaults = [
'to' => $user->get('email'),
'subject' => __d('user_tools', 'Please verify your Email'),
'template' => 'Burzum/UserTools.Users/verification_email',
];
$this->_applyOptions(array_merge($defaults, $options));
$this->set('user', $user);
}
|
php
|
public function verificationEmail(EntityInterface $user, array $options = []) {
$defaults = [
'to' => $user->get('email'),
'subject' => __d('user_tools', 'Please verify your Email'),
'template' => 'Burzum/UserTools.Users/verification_email',
];
$this->_applyOptions(array_merge($defaults, $options));
$this->set('user', $user);
}
|
[
"public",
"function",
"verificationEmail",
"(",
"EntityInterface",
"$",
"user",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'to'",
"=>",
"$",
"user",
"->",
"get",
"(",
"'email'",
")",
",",
"'subject'",
"=>",
"__d",
"(",
"'user_tools'",
",",
"'Please verify your Email'",
")",
",",
"'template'",
"=>",
"'Burzum/UserTools.Users/verification_email'",
",",
"]",
";",
"$",
"this",
"->",
"_applyOptions",
"(",
"array_merge",
"(",
"$",
"defaults",
",",
"$",
"options",
")",
")",
";",
"$",
"this",
"->",
"set",
"(",
"'user'",
",",
"$",
"user",
")",
";",
"}"
] |
Sends the verification email to an user.
@param \Cake\Datasource\EntityInterface $user User entity
@param array $options Options
@return void
|
[
"Sends",
"the",
"verification",
"email",
"to",
"an",
"user",
"."
] |
11ee8381cd60282a190024c42c57d00a4d8c9502
|
https://github.com/burzum/cakephp-user-tools/blob/11ee8381cd60282a190024c42c57d00a4d8c9502/src/Mailer/UsersMailer.php#L21-L29
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.requestChallenges
|
public function requestChallenges(string $dns): Promise {
return call(function () use ($dns) {
/** @var Response $response */
$response = yield $this->acmeClient->post(AcmeResource::NEW_AUTHORIZATION, [
'identifier' => [
'type' => 'dns',
'value' => $dns,
],
]);
if ($response->getStatus() === 201) {
if (!$response->hasHeader('location')) {
throw new AcmeException("Protocol violation: Response didn't carry any location header.");
}
return [$response->getHeader('location'), json_decode(yield $response->getBody())];
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
php
|
public function requestChallenges(string $dns): Promise {
return call(function () use ($dns) {
/** @var Response $response */
$response = yield $this->acmeClient->post(AcmeResource::NEW_AUTHORIZATION, [
'identifier' => [
'type' => 'dns',
'value' => $dns,
],
]);
if ($response->getStatus() === 201) {
if (!$response->hasHeader('location')) {
throw new AcmeException("Protocol violation: Response didn't carry any location header.");
}
return [$response->getHeader('location'), json_decode(yield $response->getBody())];
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
[
"public",
"function",
"requestChallenges",
"(",
"string",
"$",
"dns",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"dns",
")",
"{",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"acmeClient",
"->",
"post",
"(",
"AcmeResource",
"::",
"NEW_AUTHORIZATION",
",",
"[",
"'identifier'",
"=>",
"[",
"'type'",
"=>",
"'dns'",
",",
"'value'",
"=>",
"$",
"dns",
",",
"]",
",",
"]",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatus",
"(",
")",
"===",
"201",
")",
"{",
"if",
"(",
"!",
"$",
"response",
"->",
"hasHeader",
"(",
"'location'",
")",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"\"Protocol violation: Response didn't carry any location header.\"",
")",
";",
"}",
"return",
"[",
"$",
"response",
"->",
"getHeader",
"(",
"'location'",
")",
",",
"json_decode",
"(",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
"]",
";",
"}",
"throw",
"$",
"this",
"->",
"generateException",
"(",
"$",
"response",
",",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] |
Requests challenges for a given DNS name.
@api
@param string $dns DNS name to request challenge for
@return Promise resolves to an array of challenges
@throws AcmeException If something went wrong.
|
[
"Requests",
"challenges",
"for",
"a",
"given",
"DNS",
"name",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L151-L171
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.answerChallenge
|
public function answerChallenge(string $location, string $keyAuth): Promise {
return call(function () use ($location, $keyAuth) {
/** @var Response $response */
$response = yield $this->acmeClient->post($location, [
'resource' => AcmeResource::CHALLENGE,
'keyAuthorization' => $keyAuth,
]);
if ($response->getStatus() === 202) {
return json_decode(yield $response->getBody());
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
php
|
public function answerChallenge(string $location, string $keyAuth): Promise {
return call(function () use ($location, $keyAuth) {
/** @var Response $response */
$response = yield $this->acmeClient->post($location, [
'resource' => AcmeResource::CHALLENGE,
'keyAuthorization' => $keyAuth,
]);
if ($response->getStatus() === 202) {
return json_decode(yield $response->getBody());
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
[
"public",
"function",
"answerChallenge",
"(",
"string",
"$",
"location",
",",
"string",
"$",
"keyAuth",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"location",
",",
"$",
"keyAuth",
")",
"{",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"acmeClient",
"->",
"post",
"(",
"$",
"location",
",",
"[",
"'resource'",
"=>",
"AcmeResource",
"::",
"CHALLENGE",
",",
"'keyAuthorization'",
"=>",
"$",
"keyAuth",
",",
"]",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatus",
"(",
")",
"===",
"202",
")",
"{",
"return",
"json_decode",
"(",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"}",
"throw",
"$",
"this",
"->",
"generateException",
"(",
"$",
"response",
",",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] |
Answers a challenge and signals that the CA should validate it.
@api
@param string $location URI of the challenge
@param string $keyAuth key authorization
@return Promise resolves to the decoded JSON response
@throws AcmeException If something went wrong.
|
[
"Answers",
"a",
"challenge",
"and",
"signals",
"that",
"the",
"CA",
"should",
"validate",
"it",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L184-L198
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.pollForChallenge
|
public function pollForChallenge(string $location): Promise {
return call(function () use ($location) {
do {
/** @var Response $response */
$response = yield $this->acmeClient->get($location);
$body = yield $response->getBody();
$data = json_decode($body);
if ($data->status === 'pending') {
if (!$response->hasHeader('retry-after')) {
// throw new AcmeException("Protocol Violation: No Retry-After Header!");
yield new Delayed(1000);
continue;
}
$waitTime = $this->parseRetryAfter($response->getHeader('retry-after'));
$waitTime = max($waitTime, 1);
yield new Delayed($waitTime * 1000);
continue;
}
if ($data->status === 'invalid') {
$errors = [];
foreach ($data->errors ?? [] as $error) {
$message = $error->title ?? '???';
if ($error->detail ?? '') {
$message .= ' (' . $error->detail . ')';
}
$errors[] = $message;
}
throw new AcmeException('Challenge marked as invalid: ' . ($errors ? \implode(', ', $errors) : ('Unknown error: ' . $body)));
}
if ($data->status === 'valid') {
break;
}
throw new AcmeException("Invalid challenge status: {$data->status}.");
} while (1);
});
}
|
php
|
public function pollForChallenge(string $location): Promise {
return call(function () use ($location) {
do {
/** @var Response $response */
$response = yield $this->acmeClient->get($location);
$body = yield $response->getBody();
$data = json_decode($body);
if ($data->status === 'pending') {
if (!$response->hasHeader('retry-after')) {
// throw new AcmeException("Protocol Violation: No Retry-After Header!");
yield new Delayed(1000);
continue;
}
$waitTime = $this->parseRetryAfter($response->getHeader('retry-after'));
$waitTime = max($waitTime, 1);
yield new Delayed($waitTime * 1000);
continue;
}
if ($data->status === 'invalid') {
$errors = [];
foreach ($data->errors ?? [] as $error) {
$message = $error->title ?? '???';
if ($error->detail ?? '') {
$message .= ' (' . $error->detail . ')';
}
$errors[] = $message;
}
throw new AcmeException('Challenge marked as invalid: ' . ($errors ? \implode(', ', $errors) : ('Unknown error: ' . $body)));
}
if ($data->status === 'valid') {
break;
}
throw new AcmeException("Invalid challenge status: {$data->status}.");
} while (1);
});
}
|
[
"public",
"function",
"pollForChallenge",
"(",
"string",
"$",
"location",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"location",
")",
"{",
"do",
"{",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"acmeClient",
"->",
"get",
"(",
"$",
"location",
")",
";",
"$",
"body",
"=",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"body",
")",
";",
"if",
"(",
"$",
"data",
"->",
"status",
"===",
"'pending'",
")",
"{",
"if",
"(",
"!",
"$",
"response",
"->",
"hasHeader",
"(",
"'retry-after'",
")",
")",
"{",
"// throw new AcmeException(\"Protocol Violation: No Retry-After Header!\");",
"yield",
"new",
"Delayed",
"(",
"1000",
")",
";",
"continue",
";",
"}",
"$",
"waitTime",
"=",
"$",
"this",
"->",
"parseRetryAfter",
"(",
"$",
"response",
"->",
"getHeader",
"(",
"'retry-after'",
")",
")",
";",
"$",
"waitTime",
"=",
"max",
"(",
"$",
"waitTime",
",",
"1",
")",
";",
"yield",
"new",
"Delayed",
"(",
"$",
"waitTime",
"*",
"1000",
")",
";",
"continue",
";",
"}",
"if",
"(",
"$",
"data",
"->",
"status",
"===",
"'invalid'",
")",
"{",
"$",
"errors",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"->",
"errors",
"??",
"[",
"]",
"as",
"$",
"error",
")",
"{",
"$",
"message",
"=",
"$",
"error",
"->",
"title",
"??",
"'???'",
";",
"if",
"(",
"$",
"error",
"->",
"detail",
"??",
"''",
")",
"{",
"$",
"message",
".=",
"' ('",
".",
"$",
"error",
"->",
"detail",
".",
"')'",
";",
"}",
"$",
"errors",
"[",
"]",
"=",
"$",
"message",
";",
"}",
"throw",
"new",
"AcmeException",
"(",
"'Challenge marked as invalid: '",
".",
"(",
"$",
"errors",
"?",
"\\",
"implode",
"(",
"', '",
",",
"$",
"errors",
")",
":",
"(",
"'Unknown error: '",
".",
"$",
"body",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"data",
"->",
"status",
"===",
"'valid'",
")",
"{",
"break",
";",
"}",
"throw",
"new",
"AcmeException",
"(",
"\"Invalid challenge status: {$data->status}.\"",
")",
";",
"}",
"while",
"(",
"1",
")",
";",
"}",
")",
";",
"}"
] |
Polls until a challenge has been validated.
@api
@param string $location URI of the challenge
@return Promise resolves to null
@throws AcmeException
|
[
"Polls",
"until",
"a",
"challenge",
"has",
"been",
"validated",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L210-L257
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.requestCertificate
|
public function requestCertificate(string $csr): Promise {
return call(function () use ($csr) {
$begin = 'REQUEST-----';
$end = '----END';
$beginPos = strpos($csr, $begin) + strlen($begin);
if ($beginPos === false) {
throw new InvalidArgumentException("Invalid CSR, maybe not in PEM format?\n{$csr}");
}
$csr = substr($csr, $beginPos);
$endPos = strpos($csr, $end);
if ($endPos === false) {
throw new InvalidArgumentException("Invalid CSR, maybe not in PEM format?\n{$csr}");
}
$csr = substr($csr, 0, $endPos);
$enc = new Base64UrlSafeEncoder;
/** @var Response $response */
$response = yield $this->acmeClient->post(AcmeResource::NEW_CERTIFICATE, [
'csr' => $enc->encode(base64_decode($csr)),
]);
if ($response->getStatus() === 201) {
if (!$response->hasHeader('location')) {
throw new AcmeException('Protocol Violation: No Location Header');
}
return $response->getHeader('location');
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
php
|
public function requestCertificate(string $csr): Promise {
return call(function () use ($csr) {
$begin = 'REQUEST-----';
$end = '----END';
$beginPos = strpos($csr, $begin) + strlen($begin);
if ($beginPos === false) {
throw new InvalidArgumentException("Invalid CSR, maybe not in PEM format?\n{$csr}");
}
$csr = substr($csr, $beginPos);
$endPos = strpos($csr, $end);
if ($endPos === false) {
throw new InvalidArgumentException("Invalid CSR, maybe not in PEM format?\n{$csr}");
}
$csr = substr($csr, 0, $endPos);
$enc = new Base64UrlSafeEncoder;
/** @var Response $response */
$response = yield $this->acmeClient->post(AcmeResource::NEW_CERTIFICATE, [
'csr' => $enc->encode(base64_decode($csr)),
]);
if ($response->getStatus() === 201) {
if (!$response->hasHeader('location')) {
throw new AcmeException('Protocol Violation: No Location Header');
}
return $response->getHeader('location');
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
[
"public",
"function",
"requestCertificate",
"(",
"string",
"$",
"csr",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"csr",
")",
"{",
"$",
"begin",
"=",
"'REQUEST-----'",
";",
"$",
"end",
"=",
"'----END'",
";",
"$",
"beginPos",
"=",
"strpos",
"(",
"$",
"csr",
",",
"$",
"begin",
")",
"+",
"strlen",
"(",
"$",
"begin",
")",
";",
"if",
"(",
"$",
"beginPos",
"===",
"false",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid CSR, maybe not in PEM format?\\n{$csr}\"",
")",
";",
"}",
"$",
"csr",
"=",
"substr",
"(",
"$",
"csr",
",",
"$",
"beginPos",
")",
";",
"$",
"endPos",
"=",
"strpos",
"(",
"$",
"csr",
",",
"$",
"end",
")",
";",
"if",
"(",
"$",
"endPos",
"===",
"false",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid CSR, maybe not in PEM format?\\n{$csr}\"",
")",
";",
"}",
"$",
"csr",
"=",
"substr",
"(",
"$",
"csr",
",",
"0",
",",
"$",
"endPos",
")",
";",
"$",
"enc",
"=",
"new",
"Base64UrlSafeEncoder",
";",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"acmeClient",
"->",
"post",
"(",
"AcmeResource",
"::",
"NEW_CERTIFICATE",
",",
"[",
"'csr'",
"=>",
"$",
"enc",
"->",
"encode",
"(",
"base64_decode",
"(",
"$",
"csr",
")",
")",
",",
"]",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatus",
"(",
")",
"===",
"201",
")",
"{",
"if",
"(",
"!",
"$",
"response",
"->",
"hasHeader",
"(",
"'location'",
")",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"'Protocol Violation: No Location Header'",
")",
";",
"}",
"return",
"$",
"response",
"->",
"getHeader",
"(",
"'location'",
")",
";",
"}",
"throw",
"$",
"this",
"->",
"generateException",
"(",
"$",
"response",
",",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] |
Requests a new certificate.
@api
@param string $csr certificate signing request
@return Promise resolves to the URI where the certificate will be provided
@throws AcmeException If something went wrong.
|
[
"Requests",
"a",
"new",
"certificate",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L269-L307
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.pollForCertificate
|
public function pollForCertificate(string $location): Promise {
return call(function () use ($location) {
do {
/** @var Response $response */
$response = yield $this->acmeClient->get($location);
if ($response->getStatus() === 202) {
if (!$response->hasHeader('retry-after')) {
// throw new AcmeException("Protocol Violation: No Retry-After Header!");
yield new Delayed(1000);
continue;
}
$waitTime = $this->parseRetryAfter($response->getHeader('retry-after'));
$waitTime = min(max($waitTime, 2), 60);
yield new Delayed($waitTime * 1000);
continue;
}
if ($response->getStatus() === 200) {
$pem = chunk_split(base64_encode(yield $response->getBody()), 64, "\n");
$pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
$certificates = [
$pem,
];
// prevent potential infinite loop
$maximumChainLength = 5;
while ($response->hasHeader('link')) {
if (!$maximumChainLength--) {
throw new AcmeException('Too long certificate chain');
}
$links = $response->getHeaderArray('link');
foreach ($links as $link) {
if (preg_match('#<(.*?)>;rel="up"#x', $link, $match)) {
$uri = \Sabre\Uri\resolve($response->getRequest()->getUri(), $match[1]);
$response = yield $this->acmeClient->get($uri);
$pem = chunk_split(base64_encode(yield $response->getBody()), 64, "\n");
$pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
$certificates[] = $pem;
}
}
}
return $certificates;
}
} while (1);
throw new AcmeException("Couldn't fetch certificate");
});
}
|
php
|
public function pollForCertificate(string $location): Promise {
return call(function () use ($location) {
do {
/** @var Response $response */
$response = yield $this->acmeClient->get($location);
if ($response->getStatus() === 202) {
if (!$response->hasHeader('retry-after')) {
// throw new AcmeException("Protocol Violation: No Retry-After Header!");
yield new Delayed(1000);
continue;
}
$waitTime = $this->parseRetryAfter($response->getHeader('retry-after'));
$waitTime = min(max($waitTime, 2), 60);
yield new Delayed($waitTime * 1000);
continue;
}
if ($response->getStatus() === 200) {
$pem = chunk_split(base64_encode(yield $response->getBody()), 64, "\n");
$pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
$certificates = [
$pem,
];
// prevent potential infinite loop
$maximumChainLength = 5;
while ($response->hasHeader('link')) {
if (!$maximumChainLength--) {
throw new AcmeException('Too long certificate chain');
}
$links = $response->getHeaderArray('link');
foreach ($links as $link) {
if (preg_match('#<(.*?)>;rel="up"#x', $link, $match)) {
$uri = \Sabre\Uri\resolve($response->getRequest()->getUri(), $match[1]);
$response = yield $this->acmeClient->get($uri);
$pem = chunk_split(base64_encode(yield $response->getBody()), 64, "\n");
$pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
$certificates[] = $pem;
}
}
}
return $certificates;
}
} while (1);
throw new AcmeException("Couldn't fetch certificate");
});
}
|
[
"public",
"function",
"pollForCertificate",
"(",
"string",
"$",
"location",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"location",
")",
"{",
"do",
"{",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"acmeClient",
"->",
"get",
"(",
"$",
"location",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatus",
"(",
")",
"===",
"202",
")",
"{",
"if",
"(",
"!",
"$",
"response",
"->",
"hasHeader",
"(",
"'retry-after'",
")",
")",
"{",
"// throw new AcmeException(\"Protocol Violation: No Retry-After Header!\");",
"yield",
"new",
"Delayed",
"(",
"1000",
")",
";",
"continue",
";",
"}",
"$",
"waitTime",
"=",
"$",
"this",
"->",
"parseRetryAfter",
"(",
"$",
"response",
"->",
"getHeader",
"(",
"'retry-after'",
")",
")",
";",
"$",
"waitTime",
"=",
"min",
"(",
"max",
"(",
"$",
"waitTime",
",",
"2",
")",
",",
"60",
")",
";",
"yield",
"new",
"Delayed",
"(",
"$",
"waitTime",
"*",
"1000",
")",
";",
"continue",
";",
"}",
"if",
"(",
"$",
"response",
"->",
"getStatus",
"(",
")",
"===",
"200",
")",
"{",
"$",
"pem",
"=",
"chunk_split",
"(",
"base64_encode",
"(",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
",",
"64",
",",
"\"\\n\"",
")",
";",
"$",
"pem",
"=",
"\"-----BEGIN CERTIFICATE-----\\n\"",
".",
"$",
"pem",
".",
"\"-----END CERTIFICATE-----\\n\"",
";",
"$",
"certificates",
"=",
"[",
"$",
"pem",
",",
"]",
";",
"// prevent potential infinite loop",
"$",
"maximumChainLength",
"=",
"5",
";",
"while",
"(",
"$",
"response",
"->",
"hasHeader",
"(",
"'link'",
")",
")",
"{",
"if",
"(",
"!",
"$",
"maximumChainLength",
"--",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"'Too long certificate chain'",
")",
";",
"}",
"$",
"links",
"=",
"$",
"response",
"->",
"getHeaderArray",
"(",
"'link'",
")",
";",
"foreach",
"(",
"$",
"links",
"as",
"$",
"link",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'#<(.*?)>;rel=\"up\"#x'",
",",
"$",
"link",
",",
"$",
"match",
")",
")",
"{",
"$",
"uri",
"=",
"\\",
"Sabre",
"\\",
"Uri",
"\\",
"resolve",
"(",
"$",
"response",
"->",
"getRequest",
"(",
")",
"->",
"getUri",
"(",
")",
",",
"$",
"match",
"[",
"1",
"]",
")",
";",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"acmeClient",
"->",
"get",
"(",
"$",
"uri",
")",
";",
"$",
"pem",
"=",
"chunk_split",
"(",
"base64_encode",
"(",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
",",
"64",
",",
"\"\\n\"",
")",
";",
"$",
"pem",
"=",
"\"-----BEGIN CERTIFICATE-----\\n\"",
".",
"$",
"pem",
".",
"\"-----END CERTIFICATE-----\\n\"",
";",
"$",
"certificates",
"[",
"]",
"=",
"$",
"pem",
";",
"}",
"}",
"}",
"return",
"$",
"certificates",
";",
"}",
"}",
"while",
"(",
"1",
")",
";",
"throw",
"new",
"AcmeException",
"(",
"\"Couldn't fetch certificate\"",
")",
";",
"}",
")",
";",
"}"
] |
Polls for a certificate.
@api
@param string $location URI of the certificate
@return Promise resolves to the complete certificate chain as array of PEM encoded certificates
@throws AcmeException If something went wrong.
|
[
"Polls",
"for",
"a",
"certificate",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L319-L377
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.revokeCertificate
|
public function revokeCertificate(string $pem): Promise {
return call(function () use ($pem) {
$begin = 'CERTIFICATE-----';
$end = '----END';
$pem = substr($pem, strpos($pem, $begin) + strlen($begin));
$pem = substr($pem, 0, strpos($pem, $end));
$enc = new Base64UrlSafeEncoder;
/** @var Response $response */
$response = yield $this->acmeClient->post(AcmeResource::REVOKE_CERTIFICATE, [
'certificate' => $enc->encode(base64_decode($pem)),
]);
if ($response->getStatus() === 200) {
return true;
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
php
|
public function revokeCertificate(string $pem): Promise {
return call(function () use ($pem) {
$begin = 'CERTIFICATE-----';
$end = '----END';
$pem = substr($pem, strpos($pem, $begin) + strlen($begin));
$pem = substr($pem, 0, strpos($pem, $end));
$enc = new Base64UrlSafeEncoder;
/** @var Response $response */
$response = yield $this->acmeClient->post(AcmeResource::REVOKE_CERTIFICATE, [
'certificate' => $enc->encode(base64_decode($pem)),
]);
if ($response->getStatus() === 200) {
return true;
}
throw $this->generateException($response, yield $response->getBody());
});
}
|
[
"public",
"function",
"revokeCertificate",
"(",
"string",
"$",
"pem",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"pem",
")",
"{",
"$",
"begin",
"=",
"'CERTIFICATE-----'",
";",
"$",
"end",
"=",
"'----END'",
";",
"$",
"pem",
"=",
"substr",
"(",
"$",
"pem",
",",
"strpos",
"(",
"$",
"pem",
",",
"$",
"begin",
")",
"+",
"strlen",
"(",
"$",
"begin",
")",
")",
";",
"$",
"pem",
"=",
"substr",
"(",
"$",
"pem",
",",
"0",
",",
"strpos",
"(",
"$",
"pem",
",",
"$",
"end",
")",
")",
";",
"$",
"enc",
"=",
"new",
"Base64UrlSafeEncoder",
";",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"acmeClient",
"->",
"post",
"(",
"AcmeResource",
"::",
"REVOKE_CERTIFICATE",
",",
"[",
"'certificate'",
"=>",
"$",
"enc",
"->",
"encode",
"(",
"base64_decode",
"(",
"$",
"pem",
")",
")",
",",
"]",
")",
";",
"if",
"(",
"$",
"response",
"->",
"getStatus",
"(",
")",
"===",
"200",
")",
"{",
"return",
"true",
";",
"}",
"throw",
"$",
"this",
"->",
"generateException",
"(",
"$",
"response",
",",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] |
Revokes a certificate.
@api
@param string $pem PEM encoded certificate
@return Promise resolves to true
@throws AcmeException If something went wrong.
|
[
"Revokes",
"a",
"certificate",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L389-L410
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.parseRetryAfter
|
private function parseRetryAfter(string $header): int {
if (preg_match('#^\d+$#', $header)) {
return (int) $header;
}
$time = @strtotime($header);
if ($time === false) {
throw new AcmeException("Invalid retry-after header: '{$header}'");
}
return max($time - time(), 0);
}
|
php
|
private function parseRetryAfter(string $header): int {
if (preg_match('#^\d+$#', $header)) {
return (int) $header;
}
$time = @strtotime($header);
if ($time === false) {
throw new AcmeException("Invalid retry-after header: '{$header}'");
}
return max($time - time(), 0);
}
|
[
"private",
"function",
"parseRetryAfter",
"(",
"string",
"$",
"header",
")",
":",
"int",
"{",
"if",
"(",
"preg_match",
"(",
"'#^\\d+$#'",
",",
"$",
"header",
")",
")",
"{",
"return",
"(",
"int",
")",
"$",
"header",
";",
"}",
"$",
"time",
"=",
"@",
"strtotime",
"(",
"$",
"header",
")",
";",
"if",
"(",
"$",
"time",
"===",
"false",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"\"Invalid retry-after header: '{$header}'\"",
")",
";",
"}",
"return",
"max",
"(",
"$",
"time",
"-",
"time",
"(",
")",
",",
"0",
")",
";",
"}"
] |
Parses a retry header into seconds to wait until a request should be retried.
@param string $header header value
@return int seconds to wait until retry
@throws AcmeException If the header value cannot be parsed.
|
[
"Parses",
"a",
"retry",
"header",
"into",
"seconds",
"to",
"wait",
"until",
"a",
"request",
"should",
"be",
"retried",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L420-L432
|
train
|
kelunik/acme
|
lib/AcmeService.php
|
AcmeService.generateException
|
private function generateException(Response $response, string $body): AcmeException {
$status = $response->getStatus();
$info = json_decode($body);
$uri = $response->getRequest()->getUri();
if (isset($info->type, $info->detail)) {
return new AcmeException("Invalid response: {$info->detail}.\nRequest URI: {$uri}.", $info->type);
}
return new AcmeException("Invalid response: {$body}.\nRequest URI: {$uri}.", $status);
}
|
php
|
private function generateException(Response $response, string $body): AcmeException {
$status = $response->getStatus();
$info = json_decode($body);
$uri = $response->getRequest()->getUri();
if (isset($info->type, $info->detail)) {
return new AcmeException("Invalid response: {$info->detail}.\nRequest URI: {$uri}.", $info->type);
}
return new AcmeException("Invalid response: {$body}.\nRequest URI: {$uri}.", $status);
}
|
[
"private",
"function",
"generateException",
"(",
"Response",
"$",
"response",
",",
"string",
"$",
"body",
")",
":",
"AcmeException",
"{",
"$",
"status",
"=",
"$",
"response",
"->",
"getStatus",
"(",
")",
";",
"$",
"info",
"=",
"json_decode",
"(",
"$",
"body",
")",
";",
"$",
"uri",
"=",
"$",
"response",
"->",
"getRequest",
"(",
")",
"->",
"getUri",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"info",
"->",
"type",
",",
"$",
"info",
"->",
"detail",
")",
")",
"{",
"return",
"new",
"AcmeException",
"(",
"\"Invalid response: {$info->detail}.\\nRequest URI: {$uri}.\"",
",",
"$",
"info",
"->",
"type",
")",
";",
"}",
"return",
"new",
"AcmeException",
"(",
"\"Invalid response: {$body}.\\nRequest URI: {$uri}.\"",
",",
"$",
"status",
")",
";",
"}"
] |
Generates a new exception using the response to provide details.
@param Response $response HTTP response to generate the exception from.
@param string $body HTTP response body.
@return AcmeException exception generated from the response body
|
[
"Generates",
"a",
"new",
"exception",
"using",
"the",
"response",
"to",
"provide",
"details",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeService.php#L442-L452
|
train
|
kelunik/acme
|
lib/Verifiers/Http01.php
|
Http01.verifyChallenge
|
public function verifyChallenge(string $domain, string $token, string $expectedPayload): Promise {
return call(function () use ($domain, $token, $expectedPayload) {
$uri = "http://{$domain}/.well-known/acme-challenge/{$token}";
/** @var Response $response */
$response = yield $this->client->request($uri);
/** @var string $body */
$body = yield $response->getBody();
if (rtrim($expectedPayload) !== rtrim($body)) {
throw new AcmeException("Verification failed, please check the response body for '{$uri}'. It contains '{$body}' but '{$expectedPayload}' was expected.");
}
});
}
|
php
|
public function verifyChallenge(string $domain, string $token, string $expectedPayload): Promise {
return call(function () use ($domain, $token, $expectedPayload) {
$uri = "http://{$domain}/.well-known/acme-challenge/{$token}";
/** @var Response $response */
$response = yield $this->client->request($uri);
/** @var string $body */
$body = yield $response->getBody();
if (rtrim($expectedPayload) !== rtrim($body)) {
throw new AcmeException("Verification failed, please check the response body for '{$uri}'. It contains '{$body}' but '{$expectedPayload}' was expected.");
}
});
}
|
[
"public",
"function",
"verifyChallenge",
"(",
"string",
"$",
"domain",
",",
"string",
"$",
"token",
",",
"string",
"$",
"expectedPayload",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"domain",
",",
"$",
"token",
",",
"$",
"expectedPayload",
")",
"{",
"$",
"uri",
"=",
"\"http://{$domain}/.well-known/acme-challenge/{$token}\"",
";",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"client",
"->",
"request",
"(",
"$",
"uri",
")",
";",
"/** @var string $body */",
"$",
"body",
"=",
"yield",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"if",
"(",
"rtrim",
"(",
"$",
"expectedPayload",
")",
"!==",
"rtrim",
"(",
"$",
"body",
")",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"\"Verification failed, please check the response body for '{$uri}'. It contains '{$body}' but '{$expectedPayload}' was expected.\"",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Verifies a HTTP-01 challenge.
Can be used to verify a challenge before requesting validation from a CA to catch errors early.
@api
@param string $domain Domain to verify.
@param string $token Challenge token.
@param string $expectedPayload Expected payload.
@return Promise Resolves successfully if the challenge has been successfully verified, otherwise fails.
@throws AcmeException If the challenge could not be verified.
|
[
"Verifies",
"a",
"HTTP",
"-",
"01",
"challenge",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/Verifiers/Http01.php#L51-L65
|
train
|
kelunik/acme
|
lib/Verifiers/Dns01.php
|
Dns01.verifyChallenge
|
public function verifyChallenge(string $domain, string $expectedPayload): Promise {
return call(function () use ($domain, $expectedPayload) {
$uri = '_acme-challenge.' . $domain;
try {
/** @var Dns\Record[] $dnsRecords */
$dnsRecords = yield $this->resolver->query($uri, Dns\Record::TXT);
} catch (Dns\NoRecordException $e) {
throw new AcmeException("Verification failed, no TXT record found for '{$uri}'.", 0, $e);
} catch (Dns\ResolutionException $e) {
throw new AcmeException("Verification failed, couldn't query TXT record of '{$uri}': " . $e->getMessage(), 0, $e);
}
$values = [];
foreach ($dnsRecords as $dnsRecord) {
$values[] = $dnsRecord->getValue();
}
if (!\in_array($expectedPayload, $values, true)) {
$values = "'" . \implode("', '", $values) . "'";
throw new AcmeException("Verification failed, please check DNS record for '{$uri}'. It contains {$values} but '{$expectedPayload}' was expected.");
}
});
}
|
php
|
public function verifyChallenge(string $domain, string $expectedPayload): Promise {
return call(function () use ($domain, $expectedPayload) {
$uri = '_acme-challenge.' . $domain;
try {
/** @var Dns\Record[] $dnsRecords */
$dnsRecords = yield $this->resolver->query($uri, Dns\Record::TXT);
} catch (Dns\NoRecordException $e) {
throw new AcmeException("Verification failed, no TXT record found for '{$uri}'.", 0, $e);
} catch (Dns\ResolutionException $e) {
throw new AcmeException("Verification failed, couldn't query TXT record of '{$uri}': " . $e->getMessage(), 0, $e);
}
$values = [];
foreach ($dnsRecords as $dnsRecord) {
$values[] = $dnsRecord->getValue();
}
if (!\in_array($expectedPayload, $values, true)) {
$values = "'" . \implode("', '", $values) . "'";
throw new AcmeException("Verification failed, please check DNS record for '{$uri}'. It contains {$values} but '{$expectedPayload}' was expected.");
}
});
}
|
[
"public",
"function",
"verifyChallenge",
"(",
"string",
"$",
"domain",
",",
"string",
"$",
"expectedPayload",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"domain",
",",
"$",
"expectedPayload",
")",
"{",
"$",
"uri",
"=",
"'_acme-challenge.'",
".",
"$",
"domain",
";",
"try",
"{",
"/** @var Dns\\Record[] $dnsRecords */",
"$",
"dnsRecords",
"=",
"yield",
"$",
"this",
"->",
"resolver",
"->",
"query",
"(",
"$",
"uri",
",",
"Dns",
"\\",
"Record",
"::",
"TXT",
")",
";",
"}",
"catch",
"(",
"Dns",
"\\",
"NoRecordException",
"$",
"e",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"\"Verification failed, no TXT record found for '{$uri}'.\"",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"Dns",
"\\",
"ResolutionException",
"$",
"e",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"\"Verification failed, couldn't query TXT record of '{$uri}': \"",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"$",
"values",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dnsRecords",
"as",
"$",
"dnsRecord",
")",
"{",
"$",
"values",
"[",
"]",
"=",
"$",
"dnsRecord",
"->",
"getValue",
"(",
")",
";",
"}",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"expectedPayload",
",",
"$",
"values",
",",
"true",
")",
")",
"{",
"$",
"values",
"=",
"\"'\"",
".",
"\\",
"implode",
"(",
"\"', '\"",
",",
"$",
"values",
")",
".",
"\"'\"",
";",
"throw",
"new",
"AcmeException",
"(",
"\"Verification failed, please check DNS record for '{$uri}'. It contains {$values} but '{$expectedPayload}' was expected.\"",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Verifies a DNS-01 Challenge.
Can be used to verify a challenge before requesting validation from a CA to catch errors early.
@api
@param string $domain domain to verify
@param string $expectedPayload expected DNS record value
@return Promise Resolves successfully if the challenge has been successfully verified, otherwise fails.
@throws AcmeException If the challenge could not be verified.
|
[
"Verifies",
"a",
"DNS",
"-",
"01",
"Challenge",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/Verifiers/Dns01.php#L48-L72
|
train
|
kelunik/acme
|
lib/AcmeClient.php
|
AcmeClient.getNonce
|
private function getNonce(string $uri): Promise {
if (empty($this->nonces)) {
return $this->requestNonce($uri);
}
return new Success(array_shift($this->nonces));
}
|
php
|
private function getNonce(string $uri): Promise {
if (empty($this->nonces)) {
return $this->requestNonce($uri);
}
return new Success(array_shift($this->nonces));
}
|
[
"private",
"function",
"getNonce",
"(",
"string",
"$",
"uri",
")",
":",
"Promise",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"nonces",
")",
")",
"{",
"return",
"$",
"this",
"->",
"requestNonce",
"(",
"$",
"uri",
")",
";",
"}",
"return",
"new",
"Success",
"(",
"array_shift",
"(",
"$",
"this",
"->",
"nonces",
")",
")",
";",
"}"
] |
Pops a locally stored nonce or requests a new one for usage.
@param string $uri URI to issue the HEAD request against if no nonce is stored locally.
@return Promise Resolves to a valid nonce.
|
[
"Pops",
"a",
"locally",
"stored",
"nonce",
"or",
"requests",
"a",
"new",
"one",
"for",
"usage",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeClient.php#L114-L120
|
train
|
kelunik/acme
|
lib/AcmeClient.php
|
AcmeClient.requestNonce
|
private function requestNonce(string $uri): Promise {
return call(function () use ($uri) {
$request = new Request($uri, 'HEAD');
try {
/** @var Response $response */
$response = yield $this->http->request($request, [
Client::OP_DISCARD_BODY => true,
]);
if (!$response->hasHeader('replay-nonce')) {
throw new AcmeException("HTTP response didn't carry replay-nonce header.");
}
return $response->getHeader('replay-nonce');
} catch (HttpException $e) {
throw new AcmeException("HEAD request to {$uri} failed, could not obtain a replay nonce: " . $e->getMessage(), null, $e);
}
});
}
|
php
|
private function requestNonce(string $uri): Promise {
return call(function () use ($uri) {
$request = new Request($uri, 'HEAD');
try {
/** @var Response $response */
$response = yield $this->http->request($request, [
Client::OP_DISCARD_BODY => true,
]);
if (!$response->hasHeader('replay-nonce')) {
throw new AcmeException("HTTP response didn't carry replay-nonce header.");
}
return $response->getHeader('replay-nonce');
} catch (HttpException $e) {
throw new AcmeException("HEAD request to {$uri} failed, could not obtain a replay nonce: " . $e->getMessage(), null, $e);
}
});
}
|
[
"private",
"function",
"requestNonce",
"(",
"string",
"$",
"uri",
")",
":",
"Promise",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"uri",
")",
"{",
"$",
"request",
"=",
"new",
"Request",
"(",
"$",
"uri",
",",
"'HEAD'",
")",
";",
"try",
"{",
"/** @var Response $response */",
"$",
"response",
"=",
"yield",
"$",
"this",
"->",
"http",
"->",
"request",
"(",
"$",
"request",
",",
"[",
"Client",
"::",
"OP_DISCARD_BODY",
"=>",
"true",
",",
"]",
")",
";",
"if",
"(",
"!",
"$",
"response",
"->",
"hasHeader",
"(",
"'replay-nonce'",
")",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"\"HTTP response didn't carry replay-nonce header.\"",
")",
";",
"}",
"return",
"$",
"response",
"->",
"getHeader",
"(",
"'replay-nonce'",
")",
";",
"}",
"catch",
"(",
"HttpException",
"$",
"e",
")",
"{",
"throw",
"new",
"AcmeException",
"(",
"\"HEAD request to {$uri} failed, could not obtain a replay nonce: \"",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"null",
",",
"$",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Requests a new request nonce from the server.
@param string $uri URI to issue the HEAD request against.
@return Promise Resolves to a valid nonce.
|
[
"Requests",
"a",
"new",
"request",
"nonce",
"from",
"the",
"server",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeClient.php#L129-L148
|
train
|
kelunik/acme
|
lib/AcmeClient.php
|
AcmeClient.getResourceUri
|
private function getResourceUri(string $resource): Promise {
// ACME MUST be served over HTTPS, but we use HTTP for testing …
if (0 === strpos($resource, 'http://') || 0 === strpos($resource, 'https://')) {
return new Success($resource);
}
if (!$this->directory) {
return call(function () use ($resource) {
yield $this->fetchDirectory();
return $this->getResourceUri($resource);
});
}
if (isset($this->directory[$resource])) {
return new Success($this->directory[$resource]);
}
return new Failure(new AcmeException("Resource not found in directory: '{$resource}'."));
}
|
php
|
private function getResourceUri(string $resource): Promise {
// ACME MUST be served over HTTPS, but we use HTTP for testing …
if (0 === strpos($resource, 'http://') || 0 === strpos($resource, 'https://')) {
return new Success($resource);
}
if (!$this->directory) {
return call(function () use ($resource) {
yield $this->fetchDirectory();
return $this->getResourceUri($resource);
});
}
if (isset($this->directory[$resource])) {
return new Success($this->directory[$resource]);
}
return new Failure(new AcmeException("Resource not found in directory: '{$resource}'."));
}
|
[
"private",
"function",
"getResourceUri",
"(",
"string",
"$",
"resource",
")",
":",
"Promise",
"{",
"// ACME MUST be served over HTTPS, but we use HTTP for testing …",
"if",
"(",
"0",
"===",
"strpos",
"(",
"$",
"resource",
",",
"'http://'",
")",
"||",
"0",
"===",
"strpos",
"(",
"$",
"resource",
",",
"'https://'",
")",
")",
"{",
"return",
"new",
"Success",
"(",
"$",
"resource",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"directory",
")",
"{",
"return",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"resource",
")",
"{",
"yield",
"$",
"this",
"->",
"fetchDirectory",
"(",
")",
";",
"return",
"$",
"this",
"->",
"getResourceUri",
"(",
"$",
"resource",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"directory",
"[",
"$",
"resource",
"]",
")",
")",
"{",
"return",
"new",
"Success",
"(",
"$",
"this",
"->",
"directory",
"[",
"$",
"resource",
"]",
")",
";",
"}",
"return",
"new",
"Failure",
"(",
"new",
"AcmeException",
"(",
"\"Resource not found in directory: '{$resource}'.\"",
")",
")",
";",
"}"
] |
Returns the URI to a resource by querying the directory. Can also handle URIs and returns them directly.
@param string $resource URI or directory entry.
@return Promise Resolves to the resource URI.
@throws AcmeException If the specified resource is not in the directory.
|
[
"Returns",
"the",
"URI",
"to",
"a",
"resource",
"by",
"querying",
"the",
"directory",
".",
"Can",
"also",
"handle",
"URIs",
"and",
"returns",
"them",
"directly",
"."
] |
21c7b88b8d3cd70cbf9d40f046719358881f0501
|
https://github.com/kelunik/acme/blob/21c7b88b8d3cd70cbf9d40f046719358881f0501/lib/AcmeClient.php#L158-L177
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.