repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
marmelab/phpcr-api
|
src/PHPCRAPI/PHPCR/Repository.php
|
Repository.getRepository
|
private function getRepository()
{
$c = $this->repository;
if ($c instanceof \Closure) {
$this->repository = $c();
}
return $this->repository;
}
|
php
|
private function getRepository()
{
$c = $this->repository;
if ($c instanceof \Closure) {
$this->repository = $c();
}
return $this->repository;
}
|
[
"private",
"function",
"getRepository",
"(",
")",
"{",
"$",
"c",
"=",
"$",
"this",
"->",
"repository",
";",
"if",
"(",
"$",
"c",
"instanceof",
"\\",
"Closure",
")",
"{",
"$",
"this",
"->",
"repository",
"=",
"$",
"c",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"repository",
";",
"}"
] |
Return the wrapped PHPCR Repository
@return \PHPCR\RepositoryInterface The wrapped repository
|
[
"Return",
"the",
"wrapped",
"PHPCR",
"Repository"
] |
train
|
https://github.com/marmelab/phpcr-api/blob/372149e27d45babe142d0546894362fce987729b/src/PHPCRAPI/PHPCR/Repository.php#L97-L105
|
devhelp/piwik-api
|
src/Param/Segment/Segment.php
|
Segment.getQuery
|
public function getQuery()
{
$queryParts = array_map(function ($value) {
return ($value instanceof Operator) ? $value->expression() : $value;
}, $this->queryParts);
return implode('', $queryParts);
}
|
php
|
public function getQuery()
{
$queryParts = array_map(function ($value) {
return ($value instanceof Operator) ? $value->expression() : $value;
}, $this->queryParts);
return implode('', $queryParts);
}
|
[
"public",
"function",
"getQuery",
"(",
")",
"{",
"$",
"queryParts",
"=",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"(",
"$",
"value",
"instanceof",
"Operator",
")",
"?",
"$",
"value",
"->",
"expression",
"(",
")",
":",
"$",
"value",
";",
"}",
",",
"$",
"this",
"->",
"queryParts",
")",
";",
"return",
"implode",
"(",
"''",
",",
"$",
"queryParts",
")",
";",
"}"
] |
builds the query and returns it as a string
@return string
|
[
"builds",
"the",
"query",
"and",
"returns",
"it",
"as",
"a",
"string"
] |
train
|
https://github.com/devhelp/piwik-api/blob/b50569fac9736a87be48228d8a336a84418be8da/src/Param/Segment/Segment.php#L20-L27
|
blast-project/CoreBundle
|
src/Admin/Traits/Templates.php
|
Templates.fixTemplates
|
protected function fixTemplates($mapper)
{
$librinfo = $this->getConfigurationPool()->getContainer()->getParameter('blast');
if (!isset($librinfo['configuration']) && isset($librinfo['configuration']['templates'])) {
return $this;
}
$mapping = [
'ShowMapper' => 'show',
'ListMapper' => 'list',
];
$rc = new \ReflectionClass($mapper);
if (!isset($mapping[$rc->getShortName()])) {
return $this;
}
$mapType = $mapping[$rc->getShortName()];
if (!isset($librinfo['configuration']['templates'][$mapType])) {
return $this;
}
// get back the new templates
$templates = $librinfo['configuration']['templates'][$mapType];
// checks if something has to be done
foreach ($this->{$mapType . 'FieldDescriptions'} as $fd) {
if (isset($templates[$fd->getType()])) {
$fd->setTemplate($templates[$fd->getType()]);
}
}
return $this;
}
|
php
|
protected function fixTemplates($mapper)
{
$librinfo = $this->getConfigurationPool()->getContainer()->getParameter('blast');
if (!isset($librinfo['configuration']) && isset($librinfo['configuration']['templates'])) {
return $this;
}
$mapping = [
'ShowMapper' => 'show',
'ListMapper' => 'list',
];
$rc = new \ReflectionClass($mapper);
if (!isset($mapping[$rc->getShortName()])) {
return $this;
}
$mapType = $mapping[$rc->getShortName()];
if (!isset($librinfo['configuration']['templates'][$mapType])) {
return $this;
}
// get back the new templates
$templates = $librinfo['configuration']['templates'][$mapType];
// checks if something has to be done
foreach ($this->{$mapType . 'FieldDescriptions'} as $fd) {
if (isset($templates[$fd->getType()])) {
$fd->setTemplate($templates[$fd->getType()]);
}
}
return $this;
}
|
[
"protected",
"function",
"fixTemplates",
"(",
"$",
"mapper",
")",
"{",
"$",
"librinfo",
"=",
"$",
"this",
"->",
"getConfigurationPool",
"(",
")",
"->",
"getContainer",
"(",
")",
"->",
"getParameter",
"(",
"'blast'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"librinfo",
"[",
"'configuration'",
"]",
")",
"&&",
"isset",
"(",
"$",
"librinfo",
"[",
"'configuration'",
"]",
"[",
"'templates'",
"]",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"mapping",
"=",
"[",
"'ShowMapper'",
"=>",
"'show'",
",",
"'ListMapper'",
"=>",
"'list'",
",",
"]",
";",
"$",
"rc",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"mapper",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"mapping",
"[",
"$",
"rc",
"->",
"getShortName",
"(",
")",
"]",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"mapType",
"=",
"$",
"mapping",
"[",
"$",
"rc",
"->",
"getShortName",
"(",
")",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"librinfo",
"[",
"'configuration'",
"]",
"[",
"'templates'",
"]",
"[",
"$",
"mapType",
"]",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"// get back the new templates",
"$",
"templates",
"=",
"$",
"librinfo",
"[",
"'configuration'",
"]",
"[",
"'templates'",
"]",
"[",
"$",
"mapType",
"]",
";",
"// checks if something has to be done",
"foreach",
"(",
"$",
"this",
"->",
"{",
"$",
"mapType",
".",
"'FieldDescriptions'",
"}",
"as",
"$",
"fd",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"templates",
"[",
"$",
"fd",
"->",
"getType",
"(",
")",
"]",
")",
")",
"{",
"$",
"fd",
"->",
"setTemplate",
"(",
"$",
"templates",
"[",
"$",
"fd",
"->",
"getType",
"(",
")",
"]",
")",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] |
@param type $mapper
@return type
|
[
"@param",
"type",
"$mapper"
] |
train
|
https://github.com/blast-project/CoreBundle/blob/7a0832758ca14e5bc5d65515532c1220df3930ae/src/Admin/Traits/Templates.php#L25-L57
|
activecollab/databasemigrations
|
src/Command/Up.php
|
Up.execute
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$migrations = $this->getMigrations()->getMigrations();
if ($migrations_count = count($migrations)) {
$output->writeln('');
if ($migrations_count === 1) {
$output->writeln('<info>One migration</info> found. Executing...');
} else {
$output->writeln("<info>{$migrations_count} migrations</info> found. Executing...");
}
$output->writeln('');
$this->getMigrations()->up(function ($message) use ($output) {
$output->writeln(" <comment>*</comment> $message");
});
$output->writeln('');
$output->writeln('Done. Your database is up to date.');
$output->writeln('');
} else {
$output->writeln('No migrations found');
}
return 0;
}
|
php
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$migrations = $this->getMigrations()->getMigrations();
if ($migrations_count = count($migrations)) {
$output->writeln('');
if ($migrations_count === 1) {
$output->writeln('<info>One migration</info> found. Executing...');
} else {
$output->writeln("<info>{$migrations_count} migrations</info> found. Executing...");
}
$output->writeln('');
$this->getMigrations()->up(function ($message) use ($output) {
$output->writeln(" <comment>*</comment> $message");
});
$output->writeln('');
$output->writeln('Done. Your database is up to date.');
$output->writeln('');
} else {
$output->writeln('No migrations found');
}
return 0;
}
|
[
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"migrations",
"=",
"$",
"this",
"->",
"getMigrations",
"(",
")",
"->",
"getMigrations",
"(",
")",
";",
"if",
"(",
"$",
"migrations_count",
"=",
"count",
"(",
"$",
"migrations",
")",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"if",
"(",
"$",
"migrations_count",
"===",
"1",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'<info>One migration</info> found. Executing...'",
")",
";",
"}",
"else",
"{",
"$",
"output",
"->",
"writeln",
"(",
"\"<info>{$migrations_count} migrations</info> found. Executing...\"",
")",
";",
"}",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"$",
"this",
"->",
"getMigrations",
"(",
")",
"->",
"up",
"(",
"function",
"(",
"$",
"message",
")",
"use",
"(",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"\" <comment>*</comment> $message\"",
")",
";",
"}",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"'Done. Your database is up to date.'",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"}",
"else",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'No migrations found'",
")",
";",
"}",
"return",
"0",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/activecollab/databasemigrations/blob/ef91d5b5f74d79b4a75695393eb25c7c47dad093/src/Command/Up.php#L24-L50
|
jan-dolata/crude-crud
|
src/Engine/CrudeSetupTrait/DateTimePickerOptions.php
|
DateTimePickerOptions.getDateTimePickerOptions
|
public function getDateTimePickerOptions()
{
if (! isset($this->dateTimePickerOptions['language']))
$this->dateTimePickerOptions['language'] = config('app.locale');
$available = ['en', 'pl', 'sv', 'de'];
$this->dateTimePickerOptions['language'] =
in_array($this->dateTimePickerOptions['language'], $available)
? $this->dateTimePickerOptions['language'] : 'en';
return $this->dateTimePickerOptions;
}
|
php
|
public function getDateTimePickerOptions()
{
if (! isset($this->dateTimePickerOptions['language']))
$this->dateTimePickerOptions['language'] = config('app.locale');
$available = ['en', 'pl', 'sv', 'de'];
$this->dateTimePickerOptions['language'] =
in_array($this->dateTimePickerOptions['language'], $available)
? $this->dateTimePickerOptions['language'] : 'en';
return $this->dateTimePickerOptions;
}
|
[
"public",
"function",
"getDateTimePickerOptions",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"dateTimePickerOptions",
"[",
"'language'",
"]",
")",
")",
"$",
"this",
"->",
"dateTimePickerOptions",
"[",
"'language'",
"]",
"=",
"config",
"(",
"'app.locale'",
")",
";",
"$",
"available",
"=",
"[",
"'en'",
",",
"'pl'",
",",
"'sv'",
",",
"'de'",
"]",
";",
"$",
"this",
"->",
"dateTimePickerOptions",
"[",
"'language'",
"]",
"=",
"in_array",
"(",
"$",
"this",
"->",
"dateTimePickerOptions",
"[",
"'language'",
"]",
",",
"$",
"available",
")",
"?",
"$",
"this",
"->",
"dateTimePickerOptions",
"[",
"'language'",
"]",
":",
"'en'",
";",
"return",
"$",
"this",
"->",
"dateTimePickerOptions",
";",
"}"
] |
Gets the Model datetimepickerOptions.
@return array
|
[
"Gets",
"the",
"Model",
"datetimepickerOptions",
"."
] |
train
|
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Engine/CrudeSetupTrait/DateTimePickerOptions.php#L29-L40
|
jan-dolata/crude-crud
|
src/Engine/CrudeSetupTrait/DateTimePickerOptions.php
|
DateTimePickerOptions.setDateTimePickerOptions
|
public function setDateTimePickerOptions($attr, $option = null)
{
$options = is_array($attr)
? $attr
: [$attr => $option];
foreach ($options as $key => $value)
$this->dateTimePickerOptions[$key] = $value;
return $this;
}
|
php
|
public function setDateTimePickerOptions($attr, $option = null)
{
$options = is_array($attr)
? $attr
: [$attr => $option];
foreach ($options as $key => $value)
$this->dateTimePickerOptions[$key] = $value;
return $this;
}
|
[
"public",
"function",
"setDateTimePickerOptions",
"(",
"$",
"attr",
",",
"$",
"option",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"is_array",
"(",
"$",
"attr",
")",
"?",
"$",
"attr",
":",
"[",
"$",
"attr",
"=>",
"$",
"option",
"]",
";",
"foreach",
"(",
"$",
"options",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"$",
"this",
"->",
"dateTimePickerOptions",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] |
Sets the Model datetimepickerOptions.
@param string|array $attr
@param array $option = null
@return self
|
[
"Sets",
"the",
"Model",
"datetimepickerOptions",
"."
] |
train
|
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Engine/CrudeSetupTrait/DateTimePickerOptions.php#L50-L60
|
comelyio/comely
|
src/Comely/Kernel/Toolkit/Time.php
|
Time.difference
|
public static function difference(int $stamp1, int $stamp2 = null): int
{
if (!is_int($stamp2)) {
$stamp2 = time();
}
return $stamp2 > $stamp1 ? $stamp2 - $stamp1 : $stamp1 - $stamp2;
}
|
php
|
public static function difference(int $stamp1, int $stamp2 = null): int
{
if (!is_int($stamp2)) {
$stamp2 = time();
}
return $stamp2 > $stamp1 ? $stamp2 - $stamp1 : $stamp1 - $stamp2;
}
|
[
"public",
"static",
"function",
"difference",
"(",
"int",
"$",
"stamp1",
",",
"int",
"$",
"stamp2",
"=",
"null",
")",
":",
"int",
"{",
"if",
"(",
"!",
"is_int",
"(",
"$",
"stamp2",
")",
")",
"{",
"$",
"stamp2",
"=",
"time",
"(",
")",
";",
"}",
"return",
"$",
"stamp2",
">",
"$",
"stamp1",
"?",
"$",
"stamp2",
"-",
"$",
"stamp1",
":",
"$",
"stamp1",
"-",
"$",
"stamp2",
";",
"}"
] |
Number of seconds elapsed between 2 timestamps
@param int $stamp1
@param int|null $stamp2
@return int
|
[
"Number",
"of",
"seconds",
"elapsed",
"between",
"2",
"timestamps"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/Kernel/Toolkit/Time.php#L30-L37
|
comelyio/comely
|
src/Comely/Kernel/Toolkit/Time.php
|
Time.minutesDifference
|
public static function minutesDifference(int $stamp1, int $stamp2 = null): float
{
return round(self::difference($stamp1, $stamp2) / 60, 1);
}
|
php
|
public static function minutesDifference(int $stamp1, int $stamp2 = null): float
{
return round(self::difference($stamp1, $stamp2) / 60, 1);
}
|
[
"public",
"static",
"function",
"minutesDifference",
"(",
"int",
"$",
"stamp1",
",",
"int",
"$",
"stamp2",
"=",
"null",
")",
":",
"float",
"{",
"return",
"round",
"(",
"self",
"::",
"difference",
"(",
"$",
"stamp1",
",",
"$",
"stamp2",
")",
"/",
"60",
",",
"1",
")",
";",
"}"
] |
Number of minutes elapsed (decimal with 1 digit) between 2 timestamps
@param int $stamp1
@param int|null $stamp2
@return float
|
[
"Number",
"of",
"minutes",
"elapsed",
"(",
"decimal",
"with",
"1",
"digit",
")",
"between",
"2",
"timestamps"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/Kernel/Toolkit/Time.php#L46-L49
|
tonicospinelli/class-generation
|
src/ClassGeneration/NamespaceClass.php
|
NamespaceClass.toString
|
public function toString()
{
if (!$this->getPath()) {
return '';
}
$path = preg_replace('/^\\\/', '', $this->getPath());
$namespace = $this->getDocBlock()->setTabulation($this->getTabulation())->toString()
. $this->getTabulationFormatted()
. 'namespace '
. $path
. ';' . PHP_EOL;
return $namespace;
}
|
php
|
public function toString()
{
if (!$this->getPath()) {
return '';
}
$path = preg_replace('/^\\\/', '', $this->getPath());
$namespace = $this->getDocBlock()->setTabulation($this->getTabulation())->toString()
. $this->getTabulationFormatted()
. 'namespace '
. $path
. ';' . PHP_EOL;
return $namespace;
}
|
[
"public",
"function",
"toString",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getPath",
"(",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"path",
"=",
"preg_replace",
"(",
"'/^\\\\\\/'",
",",
"''",
",",
"$",
"this",
"->",
"getPath",
"(",
")",
")",
";",
"$",
"namespace",
"=",
"$",
"this",
"->",
"getDocBlock",
"(",
")",
"->",
"setTabulation",
"(",
"$",
"this",
"->",
"getTabulation",
"(",
")",
")",
"->",
"toString",
"(",
")",
".",
"$",
"this",
"->",
"getTabulationFormatted",
"(",
")",
".",
"'namespace '",
".",
"$",
"path",
".",
"';'",
".",
"PHP_EOL",
";",
"return",
"$",
"namespace",
";",
"}"
] |
Parse the namespace string;
@return string
|
[
"Parse",
"the",
"namespace",
"string",
";"
] |
train
|
https://github.com/tonicospinelli/class-generation/blob/eee63bdb68c066b25b885b57b23656e809381a76/src/ClassGeneration/NamespaceClass.php#L124-L139
|
codezero-be/cookie
|
src/LaravelCookie.php
|
LaravelCookie.store
|
public function store($cookieName, $cookieValue, $minutes = 60)
{
$this->cookie->queue($cookieName, $cookieValue, $minutes);
return true;
}
|
php
|
public function store($cookieName, $cookieValue, $minutes = 60)
{
$this->cookie->queue($cookieName, $cookieValue, $minutes);
return true;
}
|
[
"public",
"function",
"store",
"(",
"$",
"cookieName",
",",
"$",
"cookieValue",
",",
"$",
"minutes",
"=",
"60",
")",
"{",
"$",
"this",
"->",
"cookie",
"->",
"queue",
"(",
"$",
"cookieName",
",",
"$",
"cookieValue",
",",
"$",
"minutes",
")",
";",
"return",
"true",
";",
"}"
] |
Store a cookie
@param string $cookieName
@param string $cookieValue
@param int $minutes
@return bool
|
[
"Store",
"a",
"cookie"
] |
train
|
https://github.com/codezero-be/cookie/blob/5300089c9dc7bd48c9865d53c3aed8bd513da6d2/src/LaravelCookie.php#L55-L60
|
codezero-be/cookie
|
src/LaravelCookie.php
|
LaravelCookie.delete
|
public function delete($cookieName)
{
$cookie = $this->cookie->forget($cookieName);
$this->cookie->queue($cookie);
return true;
}
|
php
|
public function delete($cookieName)
{
$cookie = $this->cookie->forget($cookieName);
$this->cookie->queue($cookie);
return true;
}
|
[
"public",
"function",
"delete",
"(",
"$",
"cookieName",
")",
"{",
"$",
"cookie",
"=",
"$",
"this",
"->",
"cookie",
"->",
"forget",
"(",
"$",
"cookieName",
")",
";",
"$",
"this",
"->",
"cookie",
"->",
"queue",
"(",
"$",
"cookie",
")",
";",
"return",
"true",
";",
"}"
] |
Delete a cookie
@param string $cookieName
@return bool
|
[
"Delete",
"a",
"cookie"
] |
train
|
https://github.com/codezero-be/cookie/blob/5300089c9dc7bd48c9865d53c3aed8bd513da6d2/src/LaravelCookie.php#L82-L88
|
tonicospinelli/class-generation
|
src/ClassGeneration/Composition/MethodCollection.php
|
MethodCollection.toString
|
public function toString()
{
if ($this->isEmpty()) {
return '';
}
$tabulationFormatted = $this->getTabulationFormatted();
$string = '{' . PHP_EOL;
$string .= $this->toStringMethods();
$string .= $tabulationFormatted . '}';
return $string . PHP_EOL;
}
|
php
|
public function toString()
{
if ($this->isEmpty()) {
return '';
}
$tabulationFormatted = $this->getTabulationFormatted();
$string = '{' . PHP_EOL;
$string .= $this->toStringMethods();
$string .= $tabulationFormatted . '}';
return $string . PHP_EOL;
}
|
[
"public",
"function",
"toString",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isEmpty",
"(",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"tabulationFormatted",
"=",
"$",
"this",
"->",
"getTabulationFormatted",
"(",
")",
";",
"$",
"string",
"=",
"'{'",
".",
"PHP_EOL",
";",
"$",
"string",
".=",
"$",
"this",
"->",
"toStringMethods",
"(",
")",
";",
"$",
"string",
".=",
"$",
"tabulationFormatted",
".",
"'}'",
";",
"return",
"$",
"string",
".",
"PHP_EOL",
";",
"}"
] |
Parse the Composition Collection to string.
@return string
|
[
"Parse",
"the",
"Composition",
"Collection",
"to",
"string",
"."
] |
train
|
https://github.com/tonicospinelli/class-generation/blob/eee63bdb68c066b25b885b57b23656e809381a76/src/ClassGeneration/Composition/MethodCollection.php#L82-L94
|
ray-di/Ray.WebFormModule
|
src/OnFailureMethodHandler.php
|
OnFailureMethodHandler.handle
|
public function handle(AbstractValidation $formValidation, MethodInvocation $invocation, AbstractForm $form)
{
unset($form);
$args = (array) $invocation->getArguments();
$object = $invocation->getThis();
if (! $formValidation instanceof FormValidation) {
throw new InvalidOnFailureMethod(get_class($invocation->getThis()));
}
$onFailureMethod = $formValidation->onFailure ?: $invocation->getMethod()->getName() . self::FAILURE_SUFFIX;
if (! $formValidation instanceof FormValidation || ! method_exists($object, $onFailureMethod)) {
throw new InvalidOnFailureMethod(get_class($invocation->getThis()));
}
return call_user_func_array([$invocation->getThis(), $onFailureMethod], $args);
}
|
php
|
public function handle(AbstractValidation $formValidation, MethodInvocation $invocation, AbstractForm $form)
{
unset($form);
$args = (array) $invocation->getArguments();
$object = $invocation->getThis();
if (! $formValidation instanceof FormValidation) {
throw new InvalidOnFailureMethod(get_class($invocation->getThis()));
}
$onFailureMethod = $formValidation->onFailure ?: $invocation->getMethod()->getName() . self::FAILURE_SUFFIX;
if (! $formValidation instanceof FormValidation || ! method_exists($object, $onFailureMethod)) {
throw new InvalidOnFailureMethod(get_class($invocation->getThis()));
}
return call_user_func_array([$invocation->getThis(), $onFailureMethod], $args);
}
|
[
"public",
"function",
"handle",
"(",
"AbstractValidation",
"$",
"formValidation",
",",
"MethodInvocation",
"$",
"invocation",
",",
"AbstractForm",
"$",
"form",
")",
"{",
"unset",
"(",
"$",
"form",
")",
";",
"$",
"args",
"=",
"(",
"array",
")",
"$",
"invocation",
"->",
"getArguments",
"(",
")",
";",
"$",
"object",
"=",
"$",
"invocation",
"->",
"getThis",
"(",
")",
";",
"if",
"(",
"!",
"$",
"formValidation",
"instanceof",
"FormValidation",
")",
"{",
"throw",
"new",
"InvalidOnFailureMethod",
"(",
"get_class",
"(",
"$",
"invocation",
"->",
"getThis",
"(",
")",
")",
")",
";",
"}",
"$",
"onFailureMethod",
"=",
"$",
"formValidation",
"->",
"onFailure",
"?",
":",
"$",
"invocation",
"->",
"getMethod",
"(",
")",
"->",
"getName",
"(",
")",
".",
"self",
"::",
"FAILURE_SUFFIX",
";",
"if",
"(",
"!",
"$",
"formValidation",
"instanceof",
"FormValidation",
"||",
"!",
"method_exists",
"(",
"$",
"object",
",",
"$",
"onFailureMethod",
")",
")",
"{",
"throw",
"new",
"InvalidOnFailureMethod",
"(",
"get_class",
"(",
"$",
"invocation",
"->",
"getThis",
"(",
")",
")",
")",
";",
"}",
"return",
"call_user_func_array",
"(",
"[",
"$",
"invocation",
"->",
"getThis",
"(",
")",
",",
"$",
"onFailureMethod",
"]",
",",
"$",
"args",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/ray-di/Ray.WebFormModule/blob/4b6d33adb4a5c285278a068f3e7a5afdc4e680d9/src/OnFailureMethodHandler.php#L21-L35
|
czim/laravel-pxlcms
|
src/Generator/CmsAnalyzer.php
|
CmsAnalyzer.processSteps
|
protected function processSteps()
{
return [
Steps\CheckTables::class,
Steps\LoadRawData::class,
Steps\DutchModeInteractive::class,
Steps\ResolveModuleNames::class,
Steps\AnalyzeModels::class,
Steps\UnsetRawData::class,
Steps\AnalyzeSluggableInteractive::class,
];
}
|
php
|
protected function processSteps()
{
return [
Steps\CheckTables::class,
Steps\LoadRawData::class,
Steps\DutchModeInteractive::class,
Steps\ResolveModuleNames::class,
Steps\AnalyzeModels::class,
Steps\UnsetRawData::class,
Steps\AnalyzeSluggableInteractive::class,
];
}
|
[
"protected",
"function",
"processSteps",
"(",
")",
"{",
"return",
"[",
"Steps",
"\\",
"CheckTables",
"::",
"class",
",",
"Steps",
"\\",
"LoadRawData",
"::",
"class",
",",
"Steps",
"\\",
"DutchModeInteractive",
"::",
"class",
",",
"Steps",
"\\",
"ResolveModuleNames",
"::",
"class",
",",
"Steps",
"\\",
"AnalyzeModels",
"::",
"class",
",",
"Steps",
"\\",
"UnsetRawData",
"::",
"class",
",",
"Steps",
"\\",
"AnalyzeSluggableInteractive",
"::",
"class",
",",
"]",
";",
"}"
] |
Gathers the steps to pass the dataobject through as a collection
These are the steps for AFTER the initial checks and retrieval
has been handled.
@return array
|
[
"Gathers",
"the",
"steps",
"to",
"pass",
"the",
"dataobject",
"through",
"as",
"a",
"collection",
"These",
"are",
"the",
"steps",
"for",
"AFTER",
"the",
"initial",
"checks",
"and",
"retrieval",
"has",
"been",
"handled",
"."
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/CmsAnalyzer.php#L43-L54
|
czim/laravel-pxlcms
|
src/Generator/CmsAnalyzer.php
|
CmsAnalyzer.prepareProcessContext
|
protected function prepareProcessContext()
{
$this->context = app($this->processContextClass, [ $this->data, $this->settings ]);
$this->context->command = $this->command;
}
|
php
|
protected function prepareProcessContext()
{
$this->context = app($this->processContextClass, [ $this->data, $this->settings ]);
$this->context->command = $this->command;
}
|
[
"protected",
"function",
"prepareProcessContext",
"(",
")",
"{",
"$",
"this",
"->",
"context",
"=",
"app",
"(",
"$",
"this",
"->",
"processContextClass",
",",
"[",
"$",
"this",
"->",
"data",
",",
"$",
"this",
"->",
"settings",
"]",
")",
";",
"$",
"this",
"->",
"context",
"->",
"command",
"=",
"$",
"this",
"->",
"command",
";",
"}"
] |
Extend this class to configure your own process context setup
Builds a generic processcontext with only the process data injected.
If a context was injected in the constructor, data for it is set,
but settings are not applied.
|
[
"Extend",
"this",
"class",
"to",
"configure",
"your",
"own",
"process",
"context",
"setup",
"Builds",
"a",
"generic",
"processcontext",
"with",
"only",
"the",
"process",
"data",
"injected",
".",
"If",
"a",
"context",
"was",
"injected",
"in",
"the",
"constructor",
"data",
"for",
"it",
"is",
"set",
"but",
"settings",
"are",
"not",
"applied",
"."
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/CmsAnalyzer.php#L62-L67
|
czim/laravel-pxlcms
|
src/Generator/CmsAnalyzer.php
|
CmsAnalyzer.populateResult
|
protected function populateResult()
{
// default: mark that the processor completed succesfully
$this->result->setSuccess(true);
// store output array in result data
$this->result->output = $this->context->output;
}
|
php
|
protected function populateResult()
{
// default: mark that the processor completed succesfully
$this->result->setSuccess(true);
// store output array in result data
$this->result->output = $this->context->output;
}
|
[
"protected",
"function",
"populateResult",
"(",
")",
"{",
"// default: mark that the processor completed succesfully",
"$",
"this",
"->",
"result",
"->",
"setSuccess",
"(",
"true",
")",
";",
"// store output array in result data",
"$",
"this",
"->",
"result",
"->",
"output",
"=",
"$",
"this",
"->",
"context",
"->",
"output",
";",
"}"
] |
Populate the result property based on the current process context
This is called after the pipeline completes (and only if no exceptions are thrown)
|
[
"Populate",
"the",
"result",
"property",
"based",
"on",
"the",
"current",
"process",
"context",
"This",
"is",
"called",
"after",
"the",
"pipeline",
"completes",
"(",
"and",
"only",
"if",
"no",
"exceptions",
"are",
"thrown",
")"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/CmsAnalyzer.php#L73-L80
|
cronario/cronario
|
src/AbstractWorker.php
|
AbstractWorker.factory
|
public static function factory($workerClass)
{
if (!class_exists($workerClass)) {
throw new Exception\WorkerException("Worker {$workerClass} is not exists");
}
$worker = new $workerClass;
if (!$worker instanceof AbstractWorker) {
throw new Exception\WorkerException("Worker {$workerClass} is not instanceof AbstractWorker");
}
return $worker;
}
|
php
|
public static function factory($workerClass)
{
if (!class_exists($workerClass)) {
throw new Exception\WorkerException("Worker {$workerClass} is not exists");
}
$worker = new $workerClass;
if (!$worker instanceof AbstractWorker) {
throw new Exception\WorkerException("Worker {$workerClass} is not instanceof AbstractWorker");
}
return $worker;
}
|
[
"public",
"static",
"function",
"factory",
"(",
"$",
"workerClass",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"workerClass",
")",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"WorkerException",
"(",
"\"Worker {$workerClass} is not exists\"",
")",
";",
"}",
"$",
"worker",
"=",
"new",
"$",
"workerClass",
";",
"if",
"(",
"!",
"$",
"worker",
"instanceof",
"AbstractWorker",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"WorkerException",
"(",
"\"Worker {$workerClass} is not instanceof AbstractWorker\"",
")",
";",
"}",
"return",
"$",
"worker",
";",
"}"
] |
@param $workerClass
@return mixed|self
@throws WorkerException
|
[
"@param",
"$workerClass"
] |
train
|
https://github.com/cronario/cronario/blob/954df60e95efd3085269331d435e8ce6f4980441/src/AbstractWorker.php#L17-L30
|
cronario/cronario
|
src/AbstractWorker.php
|
AbstractWorker.loadConfigFile
|
protected static function loadConfigFile($path)
{
if (!is_file($path)) {
throw new Exception\WorkerException("Configuration file not exist '{$path}'");
}
$extension = pathinfo($path, PATHINFO_EXTENSION);
if ('php' === $extension) {
$config = require_once($path);
} elseif ('json' === $extension) {
$config = file_get_contents($path);
$config = json_decode($config, true);
} else {
throw new Exception\WorkerException("Configuration file must be PHP or JSON : '{$path}'");
}
if (!is_array($config)) {
throw new Exception\WorkerException("Configuration file must return array inside '{$path}'");
}
return $config;
}
|
php
|
protected static function loadConfigFile($path)
{
if (!is_file($path)) {
throw new Exception\WorkerException("Configuration file not exist '{$path}'");
}
$extension = pathinfo($path, PATHINFO_EXTENSION);
if ('php' === $extension) {
$config = require_once($path);
} elseif ('json' === $extension) {
$config = file_get_contents($path);
$config = json_decode($config, true);
} else {
throw new Exception\WorkerException("Configuration file must be PHP or JSON : '{$path}'");
}
if (!is_array($config)) {
throw new Exception\WorkerException("Configuration file must return array inside '{$path}'");
}
return $config;
}
|
[
"protected",
"static",
"function",
"loadConfigFile",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"is_file",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"WorkerException",
"(",
"\"Configuration file not exist '{$path}'\"",
")",
";",
"}",
"$",
"extension",
"=",
"pathinfo",
"(",
"$",
"path",
",",
"PATHINFO_EXTENSION",
")",
";",
"if",
"(",
"'php'",
"===",
"$",
"extension",
")",
"{",
"$",
"config",
"=",
"require_once",
"(",
"$",
"path",
")",
";",
"}",
"elseif",
"(",
"'json'",
"===",
"$",
"extension",
")",
"{",
"$",
"config",
"=",
"file_get_contents",
"(",
"$",
"path",
")",
";",
"$",
"config",
"=",
"json_decode",
"(",
"$",
"config",
",",
"true",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"\\",
"WorkerException",
"(",
"\"Configuration file must be PHP or JSON : '{$path}'\"",
")",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"config",
")",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"WorkerException",
"(",
"\"Configuration file must return array inside '{$path}'\"",
")",
";",
"}",
"return",
"$",
"config",
";",
"}"
] |
@param $path
@return mixed|string
@throws WorkerException
|
[
"@param",
"$path"
] |
train
|
https://github.com/cronario/cronario/blob/954df60e95efd3085269331d435e8ce6f4980441/src/AbstractWorker.php#L88-L110
|
cronario/cronario
|
src/AbstractWorker.php
|
AbstractWorker.getConfig
|
final public static function getConfig($key = null)
{
$calledClass = get_called_class();
// Load config
if (!isset(self::$loadedConfigSet[$calledClass]) || null === self::$loadedConfigSet[$calledClass]) {
self::$loadedConfigSet[$calledClass] = array_merge(self::$configDefault, static::loadConfig());
}
// Get config property
return (null === $key)
? self::$loadedConfigSet[$calledClass]
: self::$loadedConfigSet[$calledClass][$key];
}
|
php
|
final public static function getConfig($key = null)
{
$calledClass = get_called_class();
// Load config
if (!isset(self::$loadedConfigSet[$calledClass]) || null === self::$loadedConfigSet[$calledClass]) {
self::$loadedConfigSet[$calledClass] = array_merge(self::$configDefault, static::loadConfig());
}
// Get config property
return (null === $key)
? self::$loadedConfigSet[$calledClass]
: self::$loadedConfigSet[$calledClass][$key];
}
|
[
"final",
"public",
"static",
"function",
"getConfig",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"calledClass",
"=",
"get_called_class",
"(",
")",
";",
"// Load config",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"loadedConfigSet",
"[",
"$",
"calledClass",
"]",
")",
"||",
"null",
"===",
"self",
"::",
"$",
"loadedConfigSet",
"[",
"$",
"calledClass",
"]",
")",
"{",
"self",
"::",
"$",
"loadedConfigSet",
"[",
"$",
"calledClass",
"]",
"=",
"array_merge",
"(",
"self",
"::",
"$",
"configDefault",
",",
"static",
"::",
"loadConfig",
"(",
")",
")",
";",
"}",
"// Get config property",
"return",
"(",
"null",
"===",
"$",
"key",
")",
"?",
"self",
"::",
"$",
"loadedConfigSet",
"[",
"$",
"calledClass",
"]",
":",
"self",
"::",
"$",
"loadedConfigSet",
"[",
"$",
"calledClass",
"]",
"[",
"$",
"key",
"]",
";",
"}"
] |
@param null $key
@return mixed
|
[
"@param",
"null",
"$key"
] |
train
|
https://github.com/cronario/cronario/blob/954df60e95efd3085269331d435e8ce6f4980441/src/AbstractWorker.php#L117-L130
|
cronario/cronario
|
src/AbstractWorker.php
|
AbstractWorker.setConfigDefault
|
final public static function setConfigDefault(array $config = [])
{
$calledClass = get_called_class();
if (!isset(self::$loadedConfigSet[$calledClass])) {
static::$config = $config;
} else {
self::$loadedConfigSet[$calledClass] = array_merge(self::$configDefault, $config);
}
return true;
}
|
php
|
final public static function setConfigDefault(array $config = [])
{
$calledClass = get_called_class();
if (!isset(self::$loadedConfigSet[$calledClass])) {
static::$config = $config;
} else {
self::$loadedConfigSet[$calledClass] = array_merge(self::$configDefault, $config);
}
return true;
}
|
[
"final",
"public",
"static",
"function",
"setConfigDefault",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"calledClass",
"=",
"get_called_class",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"loadedConfigSet",
"[",
"$",
"calledClass",
"]",
")",
")",
"{",
"static",
"::",
"$",
"config",
"=",
"$",
"config",
";",
"}",
"else",
"{",
"self",
"::",
"$",
"loadedConfigSet",
"[",
"$",
"calledClass",
"]",
"=",
"array_merge",
"(",
"self",
"::",
"$",
"configDefault",
",",
"$",
"config",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
@param array $config
@return bool
|
[
"@param",
"array",
"$config"
] |
train
|
https://github.com/cronario/cronario/blob/954df60e95efd3085269331d435e8ce6f4980441/src/AbstractWorker.php#L137-L148
|
cronario/cronario
|
src/AbstractWorker.php
|
AbstractWorker.invokeCallbacks
|
protected function invokeCallbacks(AbstractJob $job)
{
$result = $job->getResult();
if ($result->isRedirect() || $result->isRetry()) {
return $this;
}
if ($result->isError()) {
$callbackJobs = $job->getCallbacksError();
} else {
$callbackJobs = $job->getCallbacksDone();
if($result->isSuccess()){
$callbackJobs = $callbackJobs + $job->getCallbacksSuccess();
} else {
$callbackJobs = $callbackJobs + $job->getCallbacksError();
}
}
if (!is_array($callbackJobs) || count($callbackJobs) === 0) {
return $this;
}
foreach ($callbackJobs as $index => $callbackJob) {
/** @var $callbackJob AbstractJob */
$callbackJob($job);
}
return $this;
}
|
php
|
protected function invokeCallbacks(AbstractJob $job)
{
$result = $job->getResult();
if ($result->isRedirect() || $result->isRetry()) {
return $this;
}
if ($result->isError()) {
$callbackJobs = $job->getCallbacksError();
} else {
$callbackJobs = $job->getCallbacksDone();
if($result->isSuccess()){
$callbackJobs = $callbackJobs + $job->getCallbacksSuccess();
} else {
$callbackJobs = $callbackJobs + $job->getCallbacksError();
}
}
if (!is_array($callbackJobs) || count($callbackJobs) === 0) {
return $this;
}
foreach ($callbackJobs as $index => $callbackJob) {
/** @var $callbackJob AbstractJob */
$callbackJob($job);
}
return $this;
}
|
[
"protected",
"function",
"invokeCallbacks",
"(",
"AbstractJob",
"$",
"job",
")",
"{",
"$",
"result",
"=",
"$",
"job",
"->",
"getResult",
"(",
")",
";",
"if",
"(",
"$",
"result",
"->",
"isRedirect",
"(",
")",
"||",
"$",
"result",
"->",
"isRetry",
"(",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"$",
"result",
"->",
"isError",
"(",
")",
")",
"{",
"$",
"callbackJobs",
"=",
"$",
"job",
"->",
"getCallbacksError",
"(",
")",
";",
"}",
"else",
"{",
"$",
"callbackJobs",
"=",
"$",
"job",
"->",
"getCallbacksDone",
"(",
")",
";",
"if",
"(",
"$",
"result",
"->",
"isSuccess",
"(",
")",
")",
"{",
"$",
"callbackJobs",
"=",
"$",
"callbackJobs",
"+",
"$",
"job",
"->",
"getCallbacksSuccess",
"(",
")",
";",
"}",
"else",
"{",
"$",
"callbackJobs",
"=",
"$",
"callbackJobs",
"+",
"$",
"job",
"->",
"getCallbacksError",
"(",
")",
";",
"}",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"callbackJobs",
")",
"||",
"count",
"(",
"$",
"callbackJobs",
")",
"===",
"0",
")",
"{",
"return",
"$",
"this",
";",
"}",
"foreach",
"(",
"$",
"callbackJobs",
"as",
"$",
"index",
"=>",
"$",
"callbackJob",
")",
"{",
"/** @var $callbackJob AbstractJob */",
"$",
"callbackJob",
"(",
"$",
"job",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
@param AbstractJob $job
@return $this
|
[
"@param",
"AbstractJob",
"$job"
] |
train
|
https://github.com/cronario/cronario/blob/954df60e95efd3085269331d435e8ce6f4980441/src/AbstractWorker.php#L159-L189
|
drupol/valuewrapper
|
src/Object/Exception/AbstractExceptionObject.php
|
AbstractExceptionObject.hash
|
public function hash(): string
{
/** @var \TypeError $value */
$value = $this->value();
$data = [
'message' => $value->getMessage(),
'code' => $value->getCode(),
'class' => $this->class(),
];
return $this->doHash($this->type() . $this->class() . \implode('', $data));
}
|
php
|
public function hash(): string
{
/** @var \TypeError $value */
$value = $this->value();
$data = [
'message' => $value->getMessage(),
'code' => $value->getCode(),
'class' => $this->class(),
];
return $this->doHash($this->type() . $this->class() . \implode('', $data));
}
|
[
"public",
"function",
"hash",
"(",
")",
":",
"string",
"{",
"/** @var \\TypeError $value */",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
"(",
")",
";",
"$",
"data",
"=",
"[",
"'message'",
"=>",
"$",
"value",
"->",
"getMessage",
"(",
")",
",",
"'code'",
"=>",
"$",
"value",
"->",
"getCode",
"(",
")",
",",
"'class'",
"=>",
"$",
"this",
"->",
"class",
"(",
")",
",",
"]",
";",
"return",
"$",
"this",
"->",
"doHash",
"(",
"$",
"this",
"->",
"type",
"(",
")",
".",
"$",
"this",
"->",
"class",
"(",
")",
".",
"\\",
"implode",
"(",
"''",
",",
"$",
"data",
")",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/drupol/valuewrapper/blob/49cc07e4d0284718c24ba6e9cf524c1f4226694e/src/Object/Exception/AbstractExceptionObject.php#L27-L39
|
drupol/valuewrapper
|
src/Object/Exception/AbstractExceptionObject.php
|
AbstractExceptionObject.unserialize
|
public function unserialize($serialized)
{
$unserialize = \unserialize($serialized);
$reflection = new \ReflectionClass($unserialize['value']['class']);
$this->set(
($reflection->newInstanceArgs([$unserialize['value']['message'], $unserialize['value']['code']]))
);
}
|
php
|
public function unserialize($serialized)
{
$unserialize = \unserialize($serialized);
$reflection = new \ReflectionClass($unserialize['value']['class']);
$this->set(
($reflection->newInstanceArgs([$unserialize['value']['message'], $unserialize['value']['code']]))
);
}
|
[
"public",
"function",
"unserialize",
"(",
"$",
"serialized",
")",
"{",
"$",
"unserialize",
"=",
"\\",
"unserialize",
"(",
"$",
"serialized",
")",
";",
"$",
"reflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"unserialize",
"[",
"'value'",
"]",
"[",
"'class'",
"]",
")",
";",
"$",
"this",
"->",
"set",
"(",
"(",
"$",
"reflection",
"->",
"newInstanceArgs",
"(",
"[",
"$",
"unserialize",
"[",
"'value'",
"]",
"[",
"'message'",
"]",
",",
"$",
"unserialize",
"[",
"'value'",
"]",
"[",
"'code'",
"]",
"]",
")",
")",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/drupol/valuewrapper/blob/49cc07e4d0284718c24ba6e9cf524c1f4226694e/src/Object/Exception/AbstractExceptionObject.php#L58-L67
|
kiwiz/ecl
|
src/Scheduler.php
|
Scheduler.process
|
public function process(array $statementlist, SymbolTable $table=null) {
if(is_null($table)) {
$table = new SymbolTable;
}
$statementlist = $this->optimize($statementlist);
$results = [];
// Loop over every Statement and execute it.
foreach($statementlist as $statement) {
$results = array_merge(
$results,
(array) $statement->process($table)
);
}
return $results;
}
|
php
|
public function process(array $statementlist, SymbolTable $table=null) {
if(is_null($table)) {
$table = new SymbolTable;
}
$statementlist = $this->optimize($statementlist);
$results = [];
// Loop over every Statement and execute it.
foreach($statementlist as $statement) {
$results = array_merge(
$results,
(array) $statement->process($table)
);
}
return $results;
}
|
[
"public",
"function",
"process",
"(",
"array",
"$",
"statementlist",
",",
"SymbolTable",
"$",
"table",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"table",
")",
")",
"{",
"$",
"table",
"=",
"new",
"SymbolTable",
";",
"}",
"$",
"statementlist",
"=",
"$",
"this",
"->",
"optimize",
"(",
"$",
"statementlist",
")",
";",
"$",
"results",
"=",
"[",
"]",
";",
"// Loop over every Statement and execute it.",
"foreach",
"(",
"$",
"statementlist",
"as",
"$",
"statement",
")",
"{",
"$",
"results",
"=",
"array_merge",
"(",
"$",
"results",
",",
"(",
"array",
")",
"$",
"statement",
"->",
"process",
"(",
"$",
"table",
")",
")",
";",
"}",
"return",
"$",
"results",
";",
"}"
] |
Main entrypoint.
@param Statement[] $statementlist A list of Statements for execution.
@return ResultSet[] The list of results.
|
[
"Main",
"entrypoint",
"."
] |
train
|
https://github.com/kiwiz/ecl/blob/6536dd2a4c1905a08cf718bdbef56a22f0e9b488/src/Scheduler.php#L16-L32
|
roshangara/statusable
|
migrations/2017_11_02_141118_create_model_status_table.php
|
CreateModelStatusTable.up
|
public function up()
{
Schema::create('statusable_status', function (Blueprint $table) {
$table->bigIncrements('id');
$table->morphs('statusable');
$table->unsignedTinyInteger('status_id')->default(1);
$table->string('reason')->nullable();
$table->nullableMorphs('agent');
$table->foreign('status_id')->references('id')->on('statuses');
$table->timestamps();
});
}
|
php
|
public function up()
{
Schema::create('statusable_status', function (Blueprint $table) {
$table->bigIncrements('id');
$table->morphs('statusable');
$table->unsignedTinyInteger('status_id')->default(1);
$table->string('reason')->nullable();
$table->nullableMorphs('agent');
$table->foreign('status_id')->references('id')->on('statuses');
$table->timestamps();
});
}
|
[
"public",
"function",
"up",
"(",
")",
"{",
"Schema",
"::",
"create",
"(",
"'statusable_status'",
",",
"function",
"(",
"Blueprint",
"$",
"table",
")",
"{",
"$",
"table",
"->",
"bigIncrements",
"(",
"'id'",
")",
";",
"$",
"table",
"->",
"morphs",
"(",
"'statusable'",
")",
";",
"$",
"table",
"->",
"unsignedTinyInteger",
"(",
"'status_id'",
")",
"->",
"default",
"(",
"1",
")",
";",
"$",
"table",
"->",
"string",
"(",
"'reason'",
")",
"->",
"nullable",
"(",
")",
";",
"$",
"table",
"->",
"nullableMorphs",
"(",
"'agent'",
")",
";",
"$",
"table",
"->",
"foreign",
"(",
"'status_id'",
")",
"->",
"references",
"(",
"'id'",
")",
"->",
"on",
"(",
"'statuses'",
")",
";",
"$",
"table",
"->",
"timestamps",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Run the migrations.
@return void
|
[
"Run",
"the",
"migrations",
"."
] |
train
|
https://github.com/roshangara/statusable/blob/657658ee6bd5d4fa9e5b67fe8094ff69dc30a45d/migrations/2017_11_02_141118_create_model_status_table.php#L14-L25
|
FrenchFrogs/framework
|
src/Form/Element/SelectRemote.php
|
SelectRemote.setLength
|
public function setLength($length)
{
$length = intval($length);
$this->length = empty($length) ? 1 : $length;
return $this;
}
|
php
|
public function setLength($length)
{
$length = intval($length);
$this->length = empty($length) ? 1 : $length;
return $this;
}
|
[
"public",
"function",
"setLength",
"(",
"$",
"length",
")",
"{",
"$",
"length",
"=",
"intval",
"(",
"$",
"length",
")",
";",
"$",
"this",
"->",
"length",
"=",
"empty",
"(",
"$",
"length",
")",
"?",
"1",
":",
"$",
"length",
";",
"return",
"$",
"this",
";",
"}"
] |
Setter for $length
@param $length cannot be under 1
@return $this
|
[
"Setter",
"for",
"$length"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Form/Element/SelectRemote.php#L84-L90
|
crossjoin/Css
|
src/Crossjoin/Css/Format/Rule/Style/StyleDeclaration.php
|
StyleDeclaration.checkValue
|
public function checkValue(&$value)
{
if (parent::checkValue($value)) {
$value = trim($value, " \r\n\t\f;");
// Check if declaration contains "!important"
if (strpos($value, "!") !== false) {
$charset = $this->getStyleSheet()->getCharset();
if (mb_strtolower(mb_substr($value, -10, null, $charset), $charset) === "!important") {
$this->setIsImportant(true);
$value = rtrim(mb_substr($value, 0, -10, $charset));
}
}
// Optimize the value
$value = Optimizer::optimizeDeclarationValue($value);
return true;
}
return false;
}
|
php
|
public function checkValue(&$value)
{
if (parent::checkValue($value)) {
$value = trim($value, " \r\n\t\f;");
// Check if declaration contains "!important"
if (strpos($value, "!") !== false) {
$charset = $this->getStyleSheet()->getCharset();
if (mb_strtolower(mb_substr($value, -10, null, $charset), $charset) === "!important") {
$this->setIsImportant(true);
$value = rtrim(mb_substr($value, 0, -10, $charset));
}
}
// Optimize the value
$value = Optimizer::optimizeDeclarationValue($value);
return true;
}
return false;
}
|
[
"public",
"function",
"checkValue",
"(",
"&",
"$",
"value",
")",
"{",
"if",
"(",
"parent",
"::",
"checkValue",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"trim",
"(",
"$",
"value",
",",
"\" \\r\\n\\t\\f;\"",
")",
";",
"// Check if declaration contains \"!important\"",
"if",
"(",
"strpos",
"(",
"$",
"value",
",",
"\"!\"",
")",
"!==",
"false",
")",
"{",
"$",
"charset",
"=",
"$",
"this",
"->",
"getStyleSheet",
"(",
")",
"->",
"getCharset",
"(",
")",
";",
"if",
"(",
"mb_strtolower",
"(",
"mb_substr",
"(",
"$",
"value",
",",
"-",
"10",
",",
"null",
",",
"$",
"charset",
")",
",",
"$",
"charset",
")",
"===",
"\"!important\"",
")",
"{",
"$",
"this",
"->",
"setIsImportant",
"(",
"true",
")",
";",
"$",
"value",
"=",
"rtrim",
"(",
"mb_substr",
"(",
"$",
"value",
",",
"0",
",",
"-",
"10",
",",
"$",
"charset",
")",
")",
";",
"}",
"}",
"// Optimize the value",
"$",
"value",
"=",
"Optimizer",
"::",
"optimizeDeclarationValue",
"(",
"$",
"value",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks the value.
@param string $value
@return bool
|
[
"Checks",
"the",
"value",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/Rule/Style/StyleDeclaration.php#L21-L42
|
crossjoin/Css
|
src/Crossjoin/Css/Format/Rule/Style/StyleDeclaration.php
|
StyleDeclaration.setIsImportant
|
public function setIsImportant($isImportant)
{
if (is_bool($isImportant)) {
$this->isImportant = $isImportant;
} else {
throw new \InvalidArgumentException(
"Invalid type '" . gettype($isImportant). "' for argument 'isImportant' given."
);
}
}
|
php
|
public function setIsImportant($isImportant)
{
if (is_bool($isImportant)) {
$this->isImportant = $isImportant;
} else {
throw new \InvalidArgumentException(
"Invalid type '" . gettype($isImportant). "' for argument 'isImportant' given."
);
}
}
|
[
"public",
"function",
"setIsImportant",
"(",
"$",
"isImportant",
")",
"{",
"if",
"(",
"is_bool",
"(",
"$",
"isImportant",
")",
")",
"{",
"$",
"this",
"->",
"isImportant",
"=",
"$",
"isImportant",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Invalid type '\"",
".",
"gettype",
"(",
"$",
"isImportant",
")",
".",
"\"' for argument 'isImportant' given.\"",
")",
";",
"}",
"}"
] |
Sets the importance status of the declaration.
@param $isImportant
|
[
"Sets",
"the",
"importance",
"status",
"of",
"the",
"declaration",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/Rule/Style/StyleDeclaration.php#L49-L58
|
sulu/SuluPricingBundle
|
Controller/PricingController.php
|
PricingController.postAction
|
public function postAction(Request $request)
{
try {
$data = $request->request->all();
$this->validatePostData($data);
$locale = $this->getLocale($request);
// Calculate prices for given item
$price = $this->getPriceCalculationManager()->retrieveItemPrices(
$data['items'],
$data['currency'],
$locale
);
$view = $this->view($price, 200);
} catch (PriceCalculationException $pce) {
$view = $this->view($pce->getMessage(), 400);
}
return $this->handleView($view);
}
|
php
|
public function postAction(Request $request)
{
try {
$data = $request->request->all();
$this->validatePostData($data);
$locale = $this->getLocale($request);
// Calculate prices for given item
$price = $this->getPriceCalculationManager()->retrieveItemPrices(
$data['items'],
$data['currency'],
$locale
);
$view = $this->view($price, 200);
} catch (PriceCalculationException $pce) {
$view = $this->view($pce->getMessage(), 400);
}
return $this->handleView($view);
}
|
[
"public",
"function",
"postAction",
"(",
"Request",
"$",
"request",
")",
"{",
"try",
"{",
"$",
"data",
"=",
"$",
"request",
"->",
"request",
"->",
"all",
"(",
")",
";",
"$",
"this",
"->",
"validatePostData",
"(",
"$",
"data",
")",
";",
"$",
"locale",
"=",
"$",
"this",
"->",
"getLocale",
"(",
"$",
"request",
")",
";",
"// Calculate prices for given item",
"$",
"price",
"=",
"$",
"this",
"->",
"getPriceCalculationManager",
"(",
")",
"->",
"retrieveItemPrices",
"(",
"$",
"data",
"[",
"'items'",
"]",
",",
"$",
"data",
"[",
"'currency'",
"]",
",",
"$",
"locale",
")",
";",
"$",
"view",
"=",
"$",
"this",
"->",
"view",
"(",
"$",
"price",
",",
"200",
")",
";",
"}",
"catch",
"(",
"PriceCalculationException",
"$",
"pce",
")",
"{",
"$",
"view",
"=",
"$",
"this",
"->",
"view",
"(",
"$",
"pce",
"->",
"getMessage",
"(",
")",
",",
"400",
")",
";",
"}",
"return",
"$",
"this",
"->",
"handleView",
"(",
"$",
"view",
")",
";",
"}"
] |
Calculates total prices of all given items.
@param Request $request
@return Response
|
[
"Calculates",
"total",
"prices",
"of",
"all",
"given",
"items",
"."
] |
train
|
https://github.com/sulu/SuluPricingBundle/blob/cd65f823c7c72992d0e423ee758a61f951f1d7d9/Controller/PricingController.php#L32-L52
|
sulu/SuluPricingBundle
|
Controller/PricingController.php
|
PricingController.validatePostData
|
private function validatePostData($data)
{
$required = ['items', 'currency'];
foreach ($required as $field) {
if (!isset($data[$field]) && !is_null($data[$field])) {
throw new PriceCalculationException($field . ' is required but not set properly');
}
}
}
|
php
|
private function validatePostData($data)
{
$required = ['items', 'currency'];
foreach ($required as $field) {
if (!isset($data[$field]) && !is_null($data[$field])) {
throw new PriceCalculationException($field . ' is required but not set properly');
}
}
}
|
[
"private",
"function",
"validatePostData",
"(",
"$",
"data",
")",
"{",
"$",
"required",
"=",
"[",
"'items'",
",",
"'currency'",
"]",
";",
"foreach",
"(",
"$",
"required",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"$",
"field",
"]",
")",
"&&",
"!",
"is_null",
"(",
"$",
"data",
"[",
"$",
"field",
"]",
")",
")",
"{",
"throw",
"new",
"PriceCalculationException",
"(",
"$",
"field",
".",
"' is required but not set properly'",
")",
";",
"}",
"}",
"}"
] |
Checks if all necessary data for post request is set.
@param array $data
@throws PriceCalculationException
|
[
"Checks",
"if",
"all",
"necessary",
"data",
"for",
"post",
"request",
"is",
"set",
"."
] |
train
|
https://github.com/sulu/SuluPricingBundle/blob/cd65f823c7c72992d0e423ee758a61f951f1d7d9/Controller/PricingController.php#L61-L70
|
crossjoin/Css
|
src/Crossjoin/Css/Format/StyleSheet/TraitStyleSheet.php
|
TraitStyleSheet.getCharset
|
protected function getCharset()
{
$styleSheet = $this->getStyleSheet();
if ($styleSheet !== null) {
return $styleSheet->getCharset();
} else if ($this->charset === null) {
return "UTF-8";
}
}
|
php
|
protected function getCharset()
{
$styleSheet = $this->getStyleSheet();
if ($styleSheet !== null) {
return $styleSheet->getCharset();
} else if ($this->charset === null) {
return "UTF-8";
}
}
|
[
"protected",
"function",
"getCharset",
"(",
")",
"{",
"$",
"styleSheet",
"=",
"$",
"this",
"->",
"getStyleSheet",
"(",
")",
";",
"if",
"(",
"$",
"styleSheet",
"!==",
"null",
")",
"{",
"return",
"$",
"styleSheet",
"->",
"getCharset",
"(",
")",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"charset",
"===",
"null",
")",
"{",
"return",
"\"UTF-8\"",
";",
"}",
"}"
] |
Gets the style sheet charset (or the default charset).
@return string
|
[
"Gets",
"the",
"style",
"sheet",
"charset",
"(",
"or",
"the",
"default",
"charset",
")",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/StyleSheet/TraitStyleSheet.php#L35-L43
|
contao-bootstrap/buttons
|
src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php
|
ButtonElement.compile
|
protected function compile()
{
$attributes = new Attributes();
$this->setLinkTitle($attributes);
$this->setHref($attributes);
$this->setCssClass($attributes);
$this->enableLightbox($attributes);
$this->setDataAttributes($attributes);
// Override the link target
if ($this->target) {
$attributes->setAttribute('target', '_blank');
}
if ($this->bootstrap_icon) {
$this->Template->icon = Bootstrap::generateIcon($this->bootstrap_icon);
}
$this->Template->attributes = $attributes;
$this->Template->link = $this->linkTitle;
}
|
php
|
protected function compile()
{
$attributes = new Attributes();
$this->setLinkTitle($attributes);
$this->setHref($attributes);
$this->setCssClass($attributes);
$this->enableLightbox($attributes);
$this->setDataAttributes($attributes);
// Override the link target
if ($this->target) {
$attributes->setAttribute('target', '_blank');
}
if ($this->bootstrap_icon) {
$this->Template->icon = Bootstrap::generateIcon($this->bootstrap_icon);
}
$this->Template->attributes = $attributes;
$this->Template->link = $this->linkTitle;
}
|
[
"protected",
"function",
"compile",
"(",
")",
"{",
"$",
"attributes",
"=",
"new",
"Attributes",
"(",
")",
";",
"$",
"this",
"->",
"setLinkTitle",
"(",
"$",
"attributes",
")",
";",
"$",
"this",
"->",
"setHref",
"(",
"$",
"attributes",
")",
";",
"$",
"this",
"->",
"setCssClass",
"(",
"$",
"attributes",
")",
";",
"$",
"this",
"->",
"enableLightbox",
"(",
"$",
"attributes",
")",
";",
"$",
"this",
"->",
"setDataAttributes",
"(",
"$",
"attributes",
")",
";",
"// Override the link target",
"if",
"(",
"$",
"this",
"->",
"target",
")",
"{",
"$",
"attributes",
"->",
"setAttribute",
"(",
"'target'",
",",
"'_blank'",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"bootstrap_icon",
")",
"{",
"$",
"this",
"->",
"Template",
"->",
"icon",
"=",
"Bootstrap",
"::",
"generateIcon",
"(",
"$",
"this",
"->",
"bootstrap_icon",
")",
";",
"}",
"$",
"this",
"->",
"Template",
"->",
"attributes",
"=",
"$",
"attributes",
";",
"$",
"this",
"->",
"Template",
"->",
"link",
"=",
"$",
"this",
"->",
"linkTitle",
";",
"}"
] |
Compile button element, inspired by ContentHyperlink.
@return void
|
[
"Compile",
"button",
"element",
"inspired",
"by",
"ContentHyperlink",
"."
] |
train
|
https://github.com/contao-bootstrap/buttons/blob/f573a24c19ec059aae528a12ba46dfc993844201/src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php#L34-L55
|
contao-bootstrap/buttons
|
src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php
|
ButtonElement.setLinkTitle
|
protected function setLinkTitle(Attributes $attributes)
{
if ($this->linkTitle == '') {
$this->linkTitle = $this->url;
}
// See Contao issue: #6258
if (TL_MODE !== 'BE') {
$attributes->setAttribute('title', $this->titleText ?: $this->linkTitle);
}
}
|
php
|
protected function setLinkTitle(Attributes $attributes)
{
if ($this->linkTitle == '') {
$this->linkTitle = $this->url;
}
// See Contao issue: #6258
if (TL_MODE !== 'BE') {
$attributes->setAttribute('title', $this->titleText ?: $this->linkTitle);
}
}
|
[
"protected",
"function",
"setLinkTitle",
"(",
"Attributes",
"$",
"attributes",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"linkTitle",
"==",
"''",
")",
"{",
"$",
"this",
"->",
"linkTitle",
"=",
"$",
"this",
"->",
"url",
";",
"}",
"// See Contao issue: #6258",
"if",
"(",
"TL_MODE",
"!==",
"'BE'",
")",
"{",
"$",
"attributes",
"->",
"setAttribute",
"(",
"'title'",
",",
"$",
"this",
"->",
"titleText",
"?",
":",
"$",
"this",
"->",
"linkTitle",
")",
";",
"}",
"}"
] |
Set title link.
@param Attributes $attributes Link attributes.
@return void
|
[
"Set",
"title",
"link",
"."
] |
train
|
https://github.com/contao-bootstrap/buttons/blob/f573a24c19ec059aae528a12ba46dfc993844201/src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php#L64-L73
|
contao-bootstrap/buttons
|
src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php
|
ButtonElement.setHref
|
protected function setHref(Attributes $attributes)
{
if (substr($this->url, 0, 7) == 'mailto:') {
if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
$url = \StringUtil::encodeEmail($this->url);
} else {
$url = \String::encodeEmail($this->url);
}
$attributes->setAttribute('href', $url);
} else {
$attributes->setAttribute('href', ampersand($this->url));
}
}
|
php
|
protected function setHref(Attributes $attributes)
{
if (substr($this->url, 0, 7) == 'mailto:') {
if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
$url = \StringUtil::encodeEmail($this->url);
} else {
$url = \String::encodeEmail($this->url);
}
$attributes->setAttribute('href', $url);
} else {
$attributes->setAttribute('href', ampersand($this->url));
}
}
|
[
"protected",
"function",
"setHref",
"(",
"Attributes",
"$",
"attributes",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"this",
"->",
"url",
",",
"0",
",",
"7",
")",
"==",
"'mailto:'",
")",
"{",
"if",
"(",
"version_compare",
"(",
"VERSION",
".",
"'.'",
".",
"BUILD",
",",
"'3.5.5'",
",",
"'>='",
")",
")",
"{",
"$",
"url",
"=",
"\\",
"StringUtil",
"::",
"encodeEmail",
"(",
"$",
"this",
"->",
"url",
")",
";",
"}",
"else",
"{",
"$",
"url",
"=",
"\\",
"String",
"::",
"encodeEmail",
"(",
"$",
"this",
"->",
"url",
")",
";",
"}",
"$",
"attributes",
"->",
"setAttribute",
"(",
"'href'",
",",
"$",
"url",
")",
";",
"}",
"else",
"{",
"$",
"attributes",
"->",
"setAttribute",
"(",
"'href'",
",",
"ampersand",
"(",
"$",
"this",
"->",
"url",
")",
")",
";",
"}",
"}"
] |
Set Link href.
@param Attributes $attributes Link attributes.
@return void
|
[
"Set",
"Link",
"href",
"."
] |
train
|
https://github.com/contao-bootstrap/buttons/blob/f573a24c19ec059aae528a12ba46dfc993844201/src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php#L82-L94
|
contao-bootstrap/buttons
|
src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php
|
ButtonElement.setCssClass
|
protected function setCssClass(Attributes $attributes)
{
$attributes->addClass('btn');
if ($this->cssID[1] == '') {
$attributes->addClass('btn-default');
} else {
$attributes->addClass($this->cssID[1]);
}
}
|
php
|
protected function setCssClass(Attributes $attributes)
{
$attributes->addClass('btn');
if ($this->cssID[1] == '') {
$attributes->addClass('btn-default');
} else {
$attributes->addClass($this->cssID[1]);
}
}
|
[
"protected",
"function",
"setCssClass",
"(",
"Attributes",
"$",
"attributes",
")",
"{",
"$",
"attributes",
"->",
"addClass",
"(",
"'btn'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"cssID",
"[",
"1",
"]",
"==",
"''",
")",
"{",
"$",
"attributes",
"->",
"addClass",
"(",
"'btn-default'",
")",
";",
"}",
"else",
"{",
"$",
"attributes",
"->",
"addClass",
"(",
"$",
"this",
"->",
"cssID",
"[",
"1",
"]",
")",
";",
"}",
"}"
] |
Set css classes.
@param Attributes $attributes Link attributes.
@return void
|
[
"Set",
"css",
"classes",
"."
] |
train
|
https://github.com/contao-bootstrap/buttons/blob/f573a24c19ec059aae528a12ba46dfc993844201/src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php#L103-L112
|
contao-bootstrap/buttons
|
src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php
|
ButtonElement.enableLightbox
|
protected function enableLightbox(Attributes $attributes)
{
if (!$this->rel) {
return;
}
if (strncmp($this->rel, 'lightbox', 8) !== 0) {
$attributes->setAttribute('rel', $this->rel);
} else {
$attributes->setAttribute('data-lightbox', substr($this->rel, 9, -1));
}
}
|
php
|
protected function enableLightbox(Attributes $attributes)
{
if (!$this->rel) {
return;
}
if (strncmp($this->rel, 'lightbox', 8) !== 0) {
$attributes->setAttribute('rel', $this->rel);
} else {
$attributes->setAttribute('data-lightbox', substr($this->rel, 9, -1));
}
}
|
[
"protected",
"function",
"enableLightbox",
"(",
"Attributes",
"$",
"attributes",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"rel",
")",
"{",
"return",
";",
"}",
"if",
"(",
"strncmp",
"(",
"$",
"this",
"->",
"rel",
",",
"'lightbox'",
",",
"8",
")",
"!==",
"0",
")",
"{",
"$",
"attributes",
"->",
"setAttribute",
"(",
"'rel'",
",",
"$",
"this",
"->",
"rel",
")",
";",
"}",
"else",
"{",
"$",
"attributes",
"->",
"setAttribute",
"(",
"'data-lightbox'",
",",
"substr",
"(",
"$",
"this",
"->",
"rel",
",",
"9",
",",
"-",
"1",
")",
")",
";",
"}",
"}"
] |
Enable lightbox.
@param Attributes $attributes Link attributes.
@return void
|
[
"Enable",
"lightbox",
"."
] |
train
|
https://github.com/contao-bootstrap/buttons/blob/f573a24c19ec059aae528a12ba46dfc993844201/src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php#L121-L132
|
contao-bootstrap/buttons
|
src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php
|
ButtonElement.setDataAttributes
|
protected function setDataAttributes(Attributes $attributes)
{
// add data attributes
$this->bootstrap_dataAttributes = deserialize($this->bootstrap_dataAttributes, true);
if (empty($this->bootstrap_dataAttributes)) {
return;
}
foreach ($this->bootstrap_dataAttributes as $attribute) {
if (trim($attribute['value']) != '' && $attribute['name'] != '') {
$attributes->setAttribute('data-' . $attribute['name'], $attribute['value']);
}
}
}
|
php
|
protected function setDataAttributes(Attributes $attributes)
{
// add data attributes
$this->bootstrap_dataAttributes = deserialize($this->bootstrap_dataAttributes, true);
if (empty($this->bootstrap_dataAttributes)) {
return;
}
foreach ($this->bootstrap_dataAttributes as $attribute) {
if (trim($attribute['value']) != '' && $attribute['name'] != '') {
$attributes->setAttribute('data-' . $attribute['name'], $attribute['value']);
}
}
}
|
[
"protected",
"function",
"setDataAttributes",
"(",
"Attributes",
"$",
"attributes",
")",
"{",
"// add data attributes",
"$",
"this",
"->",
"bootstrap_dataAttributes",
"=",
"deserialize",
"(",
"$",
"this",
"->",
"bootstrap_dataAttributes",
",",
"true",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"bootstrap_dataAttributes",
")",
")",
"{",
"return",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"bootstrap_dataAttributes",
"as",
"$",
"attribute",
")",
"{",
"if",
"(",
"trim",
"(",
"$",
"attribute",
"[",
"'value'",
"]",
")",
"!=",
"''",
"&&",
"$",
"attribute",
"[",
"'name'",
"]",
"!=",
"''",
")",
"{",
"$",
"attributes",
"->",
"setAttribute",
"(",
"'data-'",
".",
"$",
"attribute",
"[",
"'name'",
"]",
",",
"$",
"attribute",
"[",
"'value'",
"]",
")",
";",
"}",
"}",
"}"
] |
Set data attributes.
@param Attributes $attributes Link attributes.
@return void
|
[
"Set",
"data",
"attributes",
"."
] |
train
|
https://github.com/contao-bootstrap/buttons/blob/f573a24c19ec059aae528a12ba46dfc993844201/src/Netzmacht/Bootstrap/Buttons/ContentElement/ButtonElement.php#L141-L155
|
WellCommerce/OrderBundle
|
Form/DataTransformer/OrderProductCollectionToArrayTransformer.php
|
OrderProductCollectionToArrayTransformer.transform
|
public function transform($modelData)
{
$values = [];
if ($modelData instanceof Collection) {
$modelData->map(function (OrderProduct $orderProduct) use (&$values) {
$variantId = $orderProduct->hasVariant() ? $orderProduct->getVariant()->getId() : 0;
$photo = $orderProduct->getProduct()->getPhoto();
$photoPath = $photo instanceof ProductPhoto ? $photo->getPath() : '';
$symbol = $orderProduct->hasVariant() ? $orderProduct->getVariant()->getSymbol() : $orderProduct->getProduct()->getSku();
$values[] = [
'id' => $orderProduct->getId(),
'product_id' => $orderProduct->getProduct()->getId(),
'product_name' => $orderProduct->getProduct()->translate()->getName(),
'gross_amount' => $orderProduct->getSellPrice()->getGrossAmount(),
'quantity' => $orderProduct->getQuantity(),
'ean' => $symbol,
'previousquantity' => $orderProduct->getQuantity(),
'trackstock' => $orderProduct->getProduct()->getTrackStock(),
'tax_rate' => $orderProduct->getSellPrice()->getTaxRate(),
'tax_value' => $orderProduct->getSellPrice()->getTaxAmount(),
'previousvariant' => $variantId,
'variant' => $variantId,
'variant_options' => $this->getVariantOptions($orderProduct),
'weight' => $orderProduct->getWeight(),
'stock' => $orderProduct->getProduct()->getStock(),
'thumb' => null !== $photoPath ? $this->imageHelper->getImage($photoPath, 'medium') : '',
];
});
}
return $values;
}
|
php
|
public function transform($modelData)
{
$values = [];
if ($modelData instanceof Collection) {
$modelData->map(function (OrderProduct $orderProduct) use (&$values) {
$variantId = $orderProduct->hasVariant() ? $orderProduct->getVariant()->getId() : 0;
$photo = $orderProduct->getProduct()->getPhoto();
$photoPath = $photo instanceof ProductPhoto ? $photo->getPath() : '';
$symbol = $orderProduct->hasVariant() ? $orderProduct->getVariant()->getSymbol() : $orderProduct->getProduct()->getSku();
$values[] = [
'id' => $orderProduct->getId(),
'product_id' => $orderProduct->getProduct()->getId(),
'product_name' => $orderProduct->getProduct()->translate()->getName(),
'gross_amount' => $orderProduct->getSellPrice()->getGrossAmount(),
'quantity' => $orderProduct->getQuantity(),
'ean' => $symbol,
'previousquantity' => $orderProduct->getQuantity(),
'trackstock' => $orderProduct->getProduct()->getTrackStock(),
'tax_rate' => $orderProduct->getSellPrice()->getTaxRate(),
'tax_value' => $orderProduct->getSellPrice()->getTaxAmount(),
'previousvariant' => $variantId,
'variant' => $variantId,
'variant_options' => $this->getVariantOptions($orderProduct),
'weight' => $orderProduct->getWeight(),
'stock' => $orderProduct->getProduct()->getStock(),
'thumb' => null !== $photoPath ? $this->imageHelper->getImage($photoPath, 'medium') : '',
];
});
}
return $values;
}
|
[
"public",
"function",
"transform",
"(",
"$",
"modelData",
")",
"{",
"$",
"values",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"modelData",
"instanceof",
"Collection",
")",
"{",
"$",
"modelData",
"->",
"map",
"(",
"function",
"(",
"OrderProduct",
"$",
"orderProduct",
")",
"use",
"(",
"&",
"$",
"values",
")",
"{",
"$",
"variantId",
"=",
"$",
"orderProduct",
"->",
"hasVariant",
"(",
")",
"?",
"$",
"orderProduct",
"->",
"getVariant",
"(",
")",
"->",
"getId",
"(",
")",
":",
"0",
";",
"$",
"photo",
"=",
"$",
"orderProduct",
"->",
"getProduct",
"(",
")",
"->",
"getPhoto",
"(",
")",
";",
"$",
"photoPath",
"=",
"$",
"photo",
"instanceof",
"ProductPhoto",
"?",
"$",
"photo",
"->",
"getPath",
"(",
")",
":",
"''",
";",
"$",
"symbol",
"=",
"$",
"orderProduct",
"->",
"hasVariant",
"(",
")",
"?",
"$",
"orderProduct",
"->",
"getVariant",
"(",
")",
"->",
"getSymbol",
"(",
")",
":",
"$",
"orderProduct",
"->",
"getProduct",
"(",
")",
"->",
"getSku",
"(",
")",
";",
"$",
"values",
"[",
"]",
"=",
"[",
"'id'",
"=>",
"$",
"orderProduct",
"->",
"getId",
"(",
")",
",",
"'product_id'",
"=>",
"$",
"orderProduct",
"->",
"getProduct",
"(",
")",
"->",
"getId",
"(",
")",
",",
"'product_name'",
"=>",
"$",
"orderProduct",
"->",
"getProduct",
"(",
")",
"->",
"translate",
"(",
")",
"->",
"getName",
"(",
")",
",",
"'gross_amount'",
"=>",
"$",
"orderProduct",
"->",
"getSellPrice",
"(",
")",
"->",
"getGrossAmount",
"(",
")",
",",
"'quantity'",
"=>",
"$",
"orderProduct",
"->",
"getQuantity",
"(",
")",
",",
"'ean'",
"=>",
"$",
"symbol",
",",
"'previousquantity'",
"=>",
"$",
"orderProduct",
"->",
"getQuantity",
"(",
")",
",",
"'trackstock'",
"=>",
"$",
"orderProduct",
"->",
"getProduct",
"(",
")",
"->",
"getTrackStock",
"(",
")",
",",
"'tax_rate'",
"=>",
"$",
"orderProduct",
"->",
"getSellPrice",
"(",
")",
"->",
"getTaxRate",
"(",
")",
",",
"'tax_value'",
"=>",
"$",
"orderProduct",
"->",
"getSellPrice",
"(",
")",
"->",
"getTaxAmount",
"(",
")",
",",
"'previousvariant'",
"=>",
"$",
"variantId",
",",
"'variant'",
"=>",
"$",
"variantId",
",",
"'variant_options'",
"=>",
"$",
"this",
"->",
"getVariantOptions",
"(",
"$",
"orderProduct",
")",
",",
"'weight'",
"=>",
"$",
"orderProduct",
"->",
"getWeight",
"(",
")",
",",
"'stock'",
"=>",
"$",
"orderProduct",
"->",
"getProduct",
"(",
")",
"->",
"getStock",
"(",
")",
",",
"'thumb'",
"=>",
"null",
"!==",
"$",
"photoPath",
"?",
"$",
"this",
"->",
"imageHelper",
"->",
"getImage",
"(",
"$",
"photoPath",
",",
"'medium'",
")",
":",
"''",
",",
"]",
";",
"}",
")",
";",
"}",
"return",
"$",
"values",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Form/DataTransformer/OrderProductCollectionToArrayTransformer.php#L55-L89
|
dumpk/esetres
|
src/EsetresAWS.php
|
EsetresAWS.setObjectACL
|
public static function setObjectACL($key, $bucket, $acl = 'public-read')
{
$s3c = self::getS3C();
if ($s3c->doesObjectExist($bucket, $key)) {
$result = $s3c->putObjectAcl(array(
'ACL' => $acl,
'Bucket' => $bucket,
'Key' => $key,
));
if ($result) {
return true;
}
}
return false;
}
|
php
|
public static function setObjectACL($key, $bucket, $acl = 'public-read')
{
$s3c = self::getS3C();
if ($s3c->doesObjectExist($bucket, $key)) {
$result = $s3c->putObjectAcl(array(
'ACL' => $acl,
'Bucket' => $bucket,
'Key' => $key,
));
if ($result) {
return true;
}
}
return false;
}
|
[
"public",
"static",
"function",
"setObjectACL",
"(",
"$",
"key",
",",
"$",
"bucket",
",",
"$",
"acl",
"=",
"'public-read'",
")",
"{",
"$",
"s3c",
"=",
"self",
"::",
"getS3C",
"(",
")",
";",
"if",
"(",
"$",
"s3c",
"->",
"doesObjectExist",
"(",
"$",
"bucket",
",",
"$",
"key",
")",
")",
"{",
"$",
"result",
"=",
"$",
"s3c",
"->",
"putObjectAcl",
"(",
"array",
"(",
"'ACL'",
"=>",
"$",
"acl",
",",
"'Bucket'",
"=>",
"$",
"bucket",
",",
"'Key'",
"=>",
"$",
"key",
",",
")",
")",
";",
"if",
"(",
"$",
"result",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
setObjectACL
Change the access level of an object on S3.
@param $key
@param $bucket
@param $acl (private|public-read|public-read-write|authenticated-read|bucket-owner-read|bucket-owner-full-control)
|
[
"setObjectACL",
"Change",
"the",
"access",
"level",
"of",
"an",
"object",
"on",
"S3",
"."
] |
train
|
https://github.com/dumpk/esetres/blob/5ccee3a89e940f2e126e5aaca71a0380c712aa0a/src/EsetresAWS.php#L147-L162
|
mayoturis/properties-ini
|
src/VariableProcessor.php
|
VariableProcessor.getString
|
public function getString($value) {
if ($this->startsWith($value, '\'') && $this->endsWith($value, '\'')) {
return ltrim(rtrim($value, '\''), '\'');
}
if ($this->startsWith($value, '"') && $this->endsWith($value, '"')) {
return ltrim(rtrim($value, '"'), '"');
}
return $value;
}
|
php
|
public function getString($value) {
if ($this->startsWith($value, '\'') && $this->endsWith($value, '\'')) {
return ltrim(rtrim($value, '\''), '\'');
}
if ($this->startsWith($value, '"') && $this->endsWith($value, '"')) {
return ltrim(rtrim($value, '"'), '"');
}
return $value;
}
|
[
"public",
"function",
"getString",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"startsWith",
"(",
"$",
"value",
",",
"'\\''",
")",
"&&",
"$",
"this",
"->",
"endsWith",
"(",
"$",
"value",
",",
"'\\''",
")",
")",
"{",
"return",
"ltrim",
"(",
"rtrim",
"(",
"$",
"value",
",",
"'\\''",
")",
",",
"'\\''",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"startsWith",
"(",
"$",
"value",
",",
"'\"'",
")",
"&&",
"$",
"this",
"->",
"endsWith",
"(",
"$",
"value",
",",
"'\"'",
")",
")",
"{",
"return",
"ltrim",
"(",
"rtrim",
"(",
"$",
"value",
",",
"'\"'",
")",
",",
"'\"'",
")",
";",
"}",
"return",
"$",
"value",
";",
"}"
] |
Removes ' or " from string
@param string $value
@return string
|
[
"Removes",
"or",
"from",
"string"
] |
train
|
https://github.com/mayoturis/properties-ini/blob/79d56d8174637b1124eb90a41ffa3dca4c4a4e93/src/VariableProcessor.php#L10-L19
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.updateModelDataInteractively
|
protected function updateModelDataInteractively($moduleId, array $candidate, $askToSetup = true)
{
$moduleName = array_get($this->context->output, 'models.' . $moduleId . '.name', 'Unknown');
if ($askToSetup) {
if ( ! $this->context->command->confirm(
"Module #{$moduleId} ('{$moduleName}') looks like it could be set up with Sluggify. Do so?"
)) {
return;
}
} else {
$this->context->command->info("Setting up Sluggable for module #{$moduleId} ('{$moduleName}')");
}
// if a model has one sluggable column, ask a y/n for using it
if ($candidate['slug_column']) {
$alternative = $this->context->slugStructurePresent
? "the model slugs will be saved to the CMS slugs table."
: "the model will not be sluggable.";
if ( ! $this->context->command->confirm(
"This module has a field called '{$candidate['slug_column']}'."
. " Use it as a sluggable target column?\n"
. " The slug would be saved on the model itself.\n"
. " If you choose 'no', {$alternative}\n"
)) {
// if there's no alternative, don't sluggify
if ( ! $this->context->slugStructurePresent) return;
$candidate['slug_column'] = null;
}
}
// if a model has multiple possible sources, ask to make a choice which column to use
$selectedSources = ($candidate['translated'])
? $candidate['slug_sources_translated']
: $candidate['slug_sources_normal'];
if (count($selectedSources) == 1) {
$selectedSource = head($selectedSources);
} else {
// ask user to make a choice
$choice = null;
$normalAttributes = array_get($this->context->output, 'models.' . $moduleId . '.normal_attributes', []);
$translatedAttributes = array_get($this->context->output, 'models.' . $moduleId . '.translated_attributes', []);
// it may occur that there are no selectedSources yet (no likely candidates)
// just proceed directly to asking the user which to use
if (count($selectedSources)) {
$choice = $this->context->command->choice(
"Module #{$moduleId} ('{$moduleName}') has a multiple candidate columns to use as a source for slugs.\n"
. " Which one should be used?",
array_merge($selectedSources, [ '<other column>' ])
);
}
// if none picked or 'other' selected, choose any of the model's attributes (in the correct category)
if (empty($choice) || $choice === '<other column>') {
if ( ! empty($candidate['slug_column'])) {
$attributes = ($candidate['translated']) ? $translatedAttributes : $normalAttributes;
} else {
$attributes = array_merge(
$normalAttributes,
$translatedAttributes
);
}
do {
$choice = $this->context->command->choice(
"Choose a source column for the attribute.\n",
array_merge($attributes, [ '<cancel>' ])
);
if ($choice == '<cancel>') return;
if ($candidate['slug_column'] == $choice) {
$this->context->log(
"Source column may not be same as slug target column!",
Generator::LOG_LEVEL_ERROR
);
$choice = null;
}
} while (empty($choice));
}
$selectedSource = $choice;
// make sure the translated flag is still correct
$candidate['translated'] = (in_array($selectedSource, $translatedAttributes));
}
// pick the first sluggable source candidate and be done with it
$this->context->output['models'][ $moduleId ]['sluggable'] = true;
$this->context->output['models'][ $moduleId ]['sluggable_setup'] = [
'translated' => $candidate['translated'],
'source' => $selectedSource,
'target' => $candidate['slug_column'],
];
$this->context->log(
"Picked Sluggable setup for '{$moduleName}': source: '{$selectedSource}',"
. " target: " . ($candidate['slug_column'] ? "'" . $candidate['slug_column'] . "'" : '(CMS slugs table)'),
Generator::LOG_LEVEL_INFO
);
}
|
php
|
protected function updateModelDataInteractively($moduleId, array $candidate, $askToSetup = true)
{
$moduleName = array_get($this->context->output, 'models.' . $moduleId . '.name', 'Unknown');
if ($askToSetup) {
if ( ! $this->context->command->confirm(
"Module #{$moduleId} ('{$moduleName}') looks like it could be set up with Sluggify. Do so?"
)) {
return;
}
} else {
$this->context->command->info("Setting up Sluggable for module #{$moduleId} ('{$moduleName}')");
}
// if a model has one sluggable column, ask a y/n for using it
if ($candidate['slug_column']) {
$alternative = $this->context->slugStructurePresent
? "the model slugs will be saved to the CMS slugs table."
: "the model will not be sluggable.";
if ( ! $this->context->command->confirm(
"This module has a field called '{$candidate['slug_column']}'."
. " Use it as a sluggable target column?\n"
. " The slug would be saved on the model itself.\n"
. " If you choose 'no', {$alternative}\n"
)) {
// if there's no alternative, don't sluggify
if ( ! $this->context->slugStructurePresent) return;
$candidate['slug_column'] = null;
}
}
// if a model has multiple possible sources, ask to make a choice which column to use
$selectedSources = ($candidate['translated'])
? $candidate['slug_sources_translated']
: $candidate['slug_sources_normal'];
if (count($selectedSources) == 1) {
$selectedSource = head($selectedSources);
} else {
// ask user to make a choice
$choice = null;
$normalAttributes = array_get($this->context->output, 'models.' . $moduleId . '.normal_attributes', []);
$translatedAttributes = array_get($this->context->output, 'models.' . $moduleId . '.translated_attributes', []);
// it may occur that there are no selectedSources yet (no likely candidates)
// just proceed directly to asking the user which to use
if (count($selectedSources)) {
$choice = $this->context->command->choice(
"Module #{$moduleId} ('{$moduleName}') has a multiple candidate columns to use as a source for slugs.\n"
. " Which one should be used?",
array_merge($selectedSources, [ '<other column>' ])
);
}
// if none picked or 'other' selected, choose any of the model's attributes (in the correct category)
if (empty($choice) || $choice === '<other column>') {
if ( ! empty($candidate['slug_column'])) {
$attributes = ($candidate['translated']) ? $translatedAttributes : $normalAttributes;
} else {
$attributes = array_merge(
$normalAttributes,
$translatedAttributes
);
}
do {
$choice = $this->context->command->choice(
"Choose a source column for the attribute.\n",
array_merge($attributes, [ '<cancel>' ])
);
if ($choice == '<cancel>') return;
if ($candidate['slug_column'] == $choice) {
$this->context->log(
"Source column may not be same as slug target column!",
Generator::LOG_LEVEL_ERROR
);
$choice = null;
}
} while (empty($choice));
}
$selectedSource = $choice;
// make sure the translated flag is still correct
$candidate['translated'] = (in_array($selectedSource, $translatedAttributes));
}
// pick the first sluggable source candidate and be done with it
$this->context->output['models'][ $moduleId ]['sluggable'] = true;
$this->context->output['models'][ $moduleId ]['sluggable_setup'] = [
'translated' => $candidate['translated'],
'source' => $selectedSource,
'target' => $candidate['slug_column'],
];
$this->context->log(
"Picked Sluggable setup for '{$moduleName}': source: '{$selectedSource}',"
. " target: " . ($candidate['slug_column'] ? "'" . $candidate['slug_column'] . "'" : '(CMS slugs table)'),
Generator::LOG_LEVEL_INFO
);
}
|
[
"protected",
"function",
"updateModelDataInteractively",
"(",
"$",
"moduleId",
",",
"array",
"$",
"candidate",
",",
"$",
"askToSetup",
"=",
"true",
")",
"{",
"$",
"moduleName",
"=",
"array_get",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
",",
"'models.'",
".",
"$",
"moduleId",
".",
"'.name'",
",",
"'Unknown'",
")",
";",
"if",
"(",
"$",
"askToSetup",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"context",
"->",
"command",
"->",
"confirm",
"(",
"\"Module #{$moduleId} ('{$moduleName}') looks like it could be set up with Sluggify. Do so?\"",
")",
")",
"{",
"return",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"context",
"->",
"command",
"->",
"info",
"(",
"\"Setting up Sluggable for module #{$moduleId} ('{$moduleName}')\"",
")",
";",
"}",
"// if a model has one sluggable column, ask a y/n for using it",
"if",
"(",
"$",
"candidate",
"[",
"'slug_column'",
"]",
")",
"{",
"$",
"alternative",
"=",
"$",
"this",
"->",
"context",
"->",
"slugStructurePresent",
"?",
"\"the model slugs will be saved to the CMS slugs table.\"",
":",
"\"the model will not be sluggable.\"",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"context",
"->",
"command",
"->",
"confirm",
"(",
"\"This module has a field called '{$candidate['slug_column']}'.\"",
".",
"\" Use it as a sluggable target column?\\n\"",
".",
"\" The slug would be saved on the model itself.\\n\"",
".",
"\" If you choose 'no', {$alternative}\\n\"",
")",
")",
"{",
"// if there's no alternative, don't sluggify",
"if",
"(",
"!",
"$",
"this",
"->",
"context",
"->",
"slugStructurePresent",
")",
"return",
";",
"$",
"candidate",
"[",
"'slug_column'",
"]",
"=",
"null",
";",
"}",
"}",
"// if a model has multiple possible sources, ask to make a choice which column to use",
"$",
"selectedSources",
"=",
"(",
"$",
"candidate",
"[",
"'translated'",
"]",
")",
"?",
"$",
"candidate",
"[",
"'slug_sources_translated'",
"]",
":",
"$",
"candidate",
"[",
"'slug_sources_normal'",
"]",
";",
"if",
"(",
"count",
"(",
"$",
"selectedSources",
")",
"==",
"1",
")",
"{",
"$",
"selectedSource",
"=",
"head",
"(",
"$",
"selectedSources",
")",
";",
"}",
"else",
"{",
"// ask user to make a choice",
"$",
"choice",
"=",
"null",
";",
"$",
"normalAttributes",
"=",
"array_get",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
",",
"'models.'",
".",
"$",
"moduleId",
".",
"'.normal_attributes'",
",",
"[",
"]",
")",
";",
"$",
"translatedAttributes",
"=",
"array_get",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
",",
"'models.'",
".",
"$",
"moduleId",
".",
"'.translated_attributes'",
",",
"[",
"]",
")",
";",
"// it may occur that there are no selectedSources yet (no likely candidates)",
"// just proceed directly to asking the user which to use",
"if",
"(",
"count",
"(",
"$",
"selectedSources",
")",
")",
"{",
"$",
"choice",
"=",
"$",
"this",
"->",
"context",
"->",
"command",
"->",
"choice",
"(",
"\"Module #{$moduleId} ('{$moduleName}') has a multiple candidate columns to use as a source for slugs.\\n\"",
".",
"\" Which one should be used?\"",
",",
"array_merge",
"(",
"$",
"selectedSources",
",",
"[",
"'<other column>'",
"]",
")",
")",
";",
"}",
"// if none picked or 'other' selected, choose any of the model's attributes (in the correct category)",
"if",
"(",
"empty",
"(",
"$",
"choice",
")",
"||",
"$",
"choice",
"===",
"'<other column>'",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"candidate",
"[",
"'slug_column'",
"]",
")",
")",
"{",
"$",
"attributes",
"=",
"(",
"$",
"candidate",
"[",
"'translated'",
"]",
")",
"?",
"$",
"translatedAttributes",
":",
"$",
"normalAttributes",
";",
"}",
"else",
"{",
"$",
"attributes",
"=",
"array_merge",
"(",
"$",
"normalAttributes",
",",
"$",
"translatedAttributes",
")",
";",
"}",
"do",
"{",
"$",
"choice",
"=",
"$",
"this",
"->",
"context",
"->",
"command",
"->",
"choice",
"(",
"\"Choose a source column for the attribute.\\n\"",
",",
"array_merge",
"(",
"$",
"attributes",
",",
"[",
"'<cancel>'",
"]",
")",
")",
";",
"if",
"(",
"$",
"choice",
"==",
"'<cancel>'",
")",
"return",
";",
"if",
"(",
"$",
"candidate",
"[",
"'slug_column'",
"]",
"==",
"$",
"choice",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Source column may not be same as slug target column!\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"$",
"choice",
"=",
"null",
";",
"}",
"}",
"while",
"(",
"empty",
"(",
"$",
"choice",
")",
")",
";",
"}",
"$",
"selectedSource",
"=",
"$",
"choice",
";",
"// make sure the translated flag is still correct",
"$",
"candidate",
"[",
"'translated'",
"]",
"=",
"(",
"in_array",
"(",
"$",
"selectedSource",
",",
"$",
"translatedAttributes",
")",
")",
";",
"}",
"// pick the first sluggable source candidate and be done with it",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"moduleId",
"]",
"[",
"'sluggable'",
"]",
"=",
"true",
";",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"moduleId",
"]",
"[",
"'sluggable_setup'",
"]",
"=",
"[",
"'translated'",
"=>",
"$",
"candidate",
"[",
"'translated'",
"]",
",",
"'source'",
"=>",
"$",
"selectedSource",
",",
"'target'",
"=>",
"$",
"candidate",
"[",
"'slug_column'",
"]",
",",
"]",
";",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Picked Sluggable setup for '{$moduleName}': source: '{$selectedSource}',\"",
".",
"\" target: \"",
".",
"(",
"$",
"candidate",
"[",
"'slug_column'",
"]",
"?",
"\"'\"",
".",
"$",
"candidate",
"[",
"'slug_column'",
"]",
".",
"\"'\"",
":",
"'(CMS slugs table)'",
")",
",",
"Generator",
"::",
"LOG_LEVEL_INFO",
")",
";",
"}"
] |
Updates the output models data, using interaction where required
@param int $moduleId
@param array $candidate
@param bool $askToSetup
|
[
"Updates",
"the",
"output",
"models",
"data",
"using",
"interaction",
"where",
"required"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L96-L212
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.updateModelDataAutomatically
|
protected function updateModelDataAutomatically($moduleId, array $candidate)
{
$moduleName = array_get($this->context->output, 'models.' . $moduleId . '.name', 'Unknown');
// if translated is still null, we are undecided, so pick one based on the
// available sources (preferring translated candidates)
if (is_null($candidate['translated'])) {
$candidate['translated'] = (bool) count($candidate['slug_sources_translated']);
}
$selectedSource = ($candidate['translated'])
? head($candidate['slug_sources_translated'])
: head($candidate['slug_sources_normal']);
if (empty($selectedSource)) {
$this->context->log(
"Failed to automatically set slugs for '{$moduleName}'. "
. "No candidate for a source attribute despite target column candidate '{$candidate['slug_column']}'.",
Generator::LOG_LEVEL_WARNING
);
return;
}
// pick the first sluggable source candidate and be done with it
$this->context->output['models'][ $moduleId ]['sluggable'] = true;
$this->context->output['models'][ $moduleId ]['sluggable_setup'] = [
'translated' => $candidate['translated'],
'source' => $selectedSource,
'target' => $candidate['slug_column'],
];
$this->context->log(
"Automatic Sluggable setup for '{$moduleName}': source: '{$selectedSource}',"
. " target: " . ($candidate['slug_column'] ? "'" . $candidate['slug_column'] . "'" : '(CMS slugs table)'),
Generator::LOG_LEVEL_INFO
);
}
|
php
|
protected function updateModelDataAutomatically($moduleId, array $candidate)
{
$moduleName = array_get($this->context->output, 'models.' . $moduleId . '.name', 'Unknown');
// if translated is still null, we are undecided, so pick one based on the
// available sources (preferring translated candidates)
if (is_null($candidate['translated'])) {
$candidate['translated'] = (bool) count($candidate['slug_sources_translated']);
}
$selectedSource = ($candidate['translated'])
? head($candidate['slug_sources_translated'])
: head($candidate['slug_sources_normal']);
if (empty($selectedSource)) {
$this->context->log(
"Failed to automatically set slugs for '{$moduleName}'. "
. "No candidate for a source attribute despite target column candidate '{$candidate['slug_column']}'.",
Generator::LOG_LEVEL_WARNING
);
return;
}
// pick the first sluggable source candidate and be done with it
$this->context->output['models'][ $moduleId ]['sluggable'] = true;
$this->context->output['models'][ $moduleId ]['sluggable_setup'] = [
'translated' => $candidate['translated'],
'source' => $selectedSource,
'target' => $candidate['slug_column'],
];
$this->context->log(
"Automatic Sluggable setup for '{$moduleName}': source: '{$selectedSource}',"
. " target: " . ($candidate['slug_column'] ? "'" . $candidate['slug_column'] . "'" : '(CMS slugs table)'),
Generator::LOG_LEVEL_INFO
);
}
|
[
"protected",
"function",
"updateModelDataAutomatically",
"(",
"$",
"moduleId",
",",
"array",
"$",
"candidate",
")",
"{",
"$",
"moduleName",
"=",
"array_get",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
",",
"'models.'",
".",
"$",
"moduleId",
".",
"'.name'",
",",
"'Unknown'",
")",
";",
"// if translated is still null, we are undecided, so pick one based on the",
"// available sources (preferring translated candidates)",
"if",
"(",
"is_null",
"(",
"$",
"candidate",
"[",
"'translated'",
"]",
")",
")",
"{",
"$",
"candidate",
"[",
"'translated'",
"]",
"=",
"(",
"bool",
")",
"count",
"(",
"$",
"candidate",
"[",
"'slug_sources_translated'",
"]",
")",
";",
"}",
"$",
"selectedSource",
"=",
"(",
"$",
"candidate",
"[",
"'translated'",
"]",
")",
"?",
"head",
"(",
"$",
"candidate",
"[",
"'slug_sources_translated'",
"]",
")",
":",
"head",
"(",
"$",
"candidate",
"[",
"'slug_sources_normal'",
"]",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"selectedSource",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Failed to automatically set slugs for '{$moduleName}'. \"",
".",
"\"No candidate for a source attribute despite target column candidate '{$candidate['slug_column']}'.\"",
",",
"Generator",
"::",
"LOG_LEVEL_WARNING",
")",
";",
"return",
";",
"}",
"// pick the first sluggable source candidate and be done with it",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"moduleId",
"]",
"[",
"'sluggable'",
"]",
"=",
"true",
";",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"moduleId",
"]",
"[",
"'sluggable_setup'",
"]",
"=",
"[",
"'translated'",
"=>",
"$",
"candidate",
"[",
"'translated'",
"]",
",",
"'source'",
"=>",
"$",
"selectedSource",
",",
"'target'",
"=>",
"$",
"candidate",
"[",
"'slug_column'",
"]",
",",
"]",
";",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Automatic Sluggable setup for '{$moduleName}': source: '{$selectedSource}',\"",
".",
"\" target: \"",
".",
"(",
"$",
"candidate",
"[",
"'slug_column'",
"]",
"?",
"\"'\"",
".",
"$",
"candidate",
"[",
"'slug_column'",
"]",
".",
"\"'\"",
":",
"'(CMS slugs table)'",
")",
",",
"Generator",
"::",
"LOG_LEVEL_INFO",
")",
";",
"}"
] |
Updates the output models data (non-interactive approach)
@param int $moduleId
@param array $candidate
|
[
"Updates",
"the",
"output",
"models",
"data",
"(",
"non",
"-",
"interactive",
"approach",
")"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L220-L258
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.doIterativeUserSelectionSetup
|
protected function doIterativeUserSelectionSetup()
{
do {
$modelChoices = $this->getIterativeUserSelectionModeChoices();
if (empty($modelChoices)) return;
$choice = $this->context->command->choice(
"Choose a model to set up Sluggable for",
array_merge($modelChoices, [ 'stop' ])
);
if ($choice == 'stop') return;
if ( ! preg_match('#^(\d+):#', $choice, $matches)) return;
$moduleId = (int) $matches[1];
$candidate = $this->createCandidateArrayForIterativeUserSelection($moduleId);
$this->updateModelDataInteractively($moduleId, $candidate, false);
} while ( ! empty($choice));
}
|
php
|
protected function doIterativeUserSelectionSetup()
{
do {
$modelChoices = $this->getIterativeUserSelectionModeChoices();
if (empty($modelChoices)) return;
$choice = $this->context->command->choice(
"Choose a model to set up Sluggable for",
array_merge($modelChoices, [ 'stop' ])
);
if ($choice == 'stop') return;
if ( ! preg_match('#^(\d+):#', $choice, $matches)) return;
$moduleId = (int) $matches[1];
$candidate = $this->createCandidateArrayForIterativeUserSelection($moduleId);
$this->updateModelDataInteractively($moduleId, $candidate, false);
} while ( ! empty($choice));
}
|
[
"protected",
"function",
"doIterativeUserSelectionSetup",
"(",
")",
"{",
"do",
"{",
"$",
"modelChoices",
"=",
"$",
"this",
"->",
"getIterativeUserSelectionModeChoices",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"modelChoices",
")",
")",
"return",
";",
"$",
"choice",
"=",
"$",
"this",
"->",
"context",
"->",
"command",
"->",
"choice",
"(",
"\"Choose a model to set up Sluggable for\"",
",",
"array_merge",
"(",
"$",
"modelChoices",
",",
"[",
"'stop'",
"]",
")",
")",
";",
"if",
"(",
"$",
"choice",
"==",
"'stop'",
")",
"return",
";",
"if",
"(",
"!",
"preg_match",
"(",
"'#^(\\d+):#'",
",",
"$",
"choice",
",",
"$",
"matches",
")",
")",
"return",
";",
"$",
"moduleId",
"=",
"(",
"int",
")",
"$",
"matches",
"[",
"1",
"]",
";",
"$",
"candidate",
"=",
"$",
"this",
"->",
"createCandidateArrayForIterativeUserSelection",
"(",
"$",
"moduleId",
")",
";",
"$",
"this",
"->",
"updateModelDataInteractively",
"(",
"$",
"moduleId",
",",
"$",
"candidate",
",",
"false",
")",
";",
"}",
"while",
"(",
"!",
"empty",
"(",
"$",
"choice",
")",
")",
";",
"}"
] |
Runs through an iterative process wherein the user interactively selects available
models to set up
|
[
"Runs",
"through",
"an",
"iterative",
"process",
"wherein",
"the",
"user",
"interactively",
"selects",
"available",
"models",
"to",
"set",
"up"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L264-L288
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.getIterativeUserSelectionModeChoices
|
protected function getIterativeUserSelectionModeChoices()
{
$choices = [];
foreach ($this->context->output['models'] as $id => $model) {
if (in_array($id, $this->modelsDone)) continue;
$choices[] = $id . ': ' . $model['name'];
}
ksort($choices);
return $choices;
}
|
php
|
protected function getIterativeUserSelectionModeChoices()
{
$choices = [];
foreach ($this->context->output['models'] as $id => $model) {
if (in_array($id, $this->modelsDone)) continue;
$choices[] = $id . ': ' . $model['name'];
}
ksort($choices);
return $choices;
}
|
[
"protected",
"function",
"getIterativeUserSelectionModeChoices",
"(",
")",
"{",
"$",
"choices",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"as",
"$",
"id",
"=>",
"$",
"model",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"id",
",",
"$",
"this",
"->",
"modelsDone",
")",
")",
"continue",
";",
"$",
"choices",
"[",
"]",
"=",
"$",
"id",
".",
"': '",
".",
"$",
"model",
"[",
"'name'",
"]",
";",
"}",
"ksort",
"(",
"$",
"choices",
")",
";",
"return",
"$",
"choices",
";",
"}"
] |
Returns the choices for the iterative user model setup selection process,
leaving out the ones already handled
|
[
"Returns",
"the",
"choices",
"for",
"the",
"iterative",
"user",
"model",
"setup",
"selection",
"process",
"leaving",
"out",
"the",
"ones",
"already",
"handled"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L294-L307
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.createCandidateArrayForIterativeUserSelection
|
protected function createCandidateArrayForIterativeUserSelection($moduleId)
{
$candidate = [
'translated' => null,
'slug_column' => null,
'slug_sources_normal' => $this->context->output['models'][ $moduleId ]['normal_attributes'],
'slug_sources_translated' => $this->context->output['models'][ $moduleId ]['translated_attributes'],
];
if ( ! count($candidate['slug_sources_translated'])) {
$candidate['translated'] = false;
} elseif ( ! count($candidate['slug_sources_normal'])) {
$candidate['translated'] = true;
} else {
// ask the user
$candidate['translated'] = $this->context->command->choice(
"Should the slug source be a translated attribute or not?",
[ 'normal model attribute', 'translated attribute' ]
) == 'translated attribute';
}
return $candidate;
}
|
php
|
protected function createCandidateArrayForIterativeUserSelection($moduleId)
{
$candidate = [
'translated' => null,
'slug_column' => null,
'slug_sources_normal' => $this->context->output['models'][ $moduleId ]['normal_attributes'],
'slug_sources_translated' => $this->context->output['models'][ $moduleId ]['translated_attributes'],
];
if ( ! count($candidate['slug_sources_translated'])) {
$candidate['translated'] = false;
} elseif ( ! count($candidate['slug_sources_normal'])) {
$candidate['translated'] = true;
} else {
// ask the user
$candidate['translated'] = $this->context->command->choice(
"Should the slug source be a translated attribute or not?",
[ 'normal model attribute', 'translated attribute' ]
) == 'translated attribute';
}
return $candidate;
}
|
[
"protected",
"function",
"createCandidateArrayForIterativeUserSelection",
"(",
"$",
"moduleId",
")",
"{",
"$",
"candidate",
"=",
"[",
"'translated'",
"=>",
"null",
",",
"'slug_column'",
"=>",
"null",
",",
"'slug_sources_normal'",
"=>",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"moduleId",
"]",
"[",
"'normal_attributes'",
"]",
",",
"'slug_sources_translated'",
"=>",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"moduleId",
"]",
"[",
"'translated_attributes'",
"]",
",",
"]",
";",
"if",
"(",
"!",
"count",
"(",
"$",
"candidate",
"[",
"'slug_sources_translated'",
"]",
")",
")",
"{",
"$",
"candidate",
"[",
"'translated'",
"]",
"=",
"false",
";",
"}",
"elseif",
"(",
"!",
"count",
"(",
"$",
"candidate",
"[",
"'slug_sources_normal'",
"]",
")",
")",
"{",
"$",
"candidate",
"[",
"'translated'",
"]",
"=",
"true",
";",
"}",
"else",
"{",
"// ask the user",
"$",
"candidate",
"[",
"'translated'",
"]",
"=",
"$",
"this",
"->",
"context",
"->",
"command",
"->",
"choice",
"(",
"\"Should the slug source be a translated attribute or not?\"",
",",
"[",
"'normal model attribute'",
",",
"'translated attribute'",
"]",
")",
"==",
"'translated attribute'",
";",
"}",
"return",
"$",
"candidate",
";",
"}"
] |
Creates candidate array for handling sluggable interactive process for the user selection approach
@param int $moduleId
@return array
|
[
"Creates",
"candidate",
"array",
"for",
"handling",
"sluggable",
"interactive",
"process",
"for",
"the",
"user",
"selection",
"approach"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L315-L341
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.findSluggableCandidateModels
|
protected function findSluggableCandidateModels()
{
$candidates = [];
foreach ($this->context->output['models'] as $model) {
if ($this->isExcludedSluggable($model['module'])) continue;
if ($result = $this->applyOverrideForSluggable($model)) {
$candidates[ $model['module'] ] = $result;
continue;
}
if ($result = $this->analyzeModelForSluggable($model)) {
$candidates[ $model['module'] ] = $result;
}
}
return $candidates;
}
|
php
|
protected function findSluggableCandidateModels()
{
$candidates = [];
foreach ($this->context->output['models'] as $model) {
if ($this->isExcludedSluggable($model['module'])) continue;
if ($result = $this->applyOverrideForSluggable($model)) {
$candidates[ $model['module'] ] = $result;
continue;
}
if ($result = $this->analyzeModelForSluggable($model)) {
$candidates[ $model['module'] ] = $result;
}
}
return $candidates;
}
|
[
"protected",
"function",
"findSluggableCandidateModels",
"(",
")",
"{",
"$",
"candidates",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"as",
"$",
"model",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isExcludedSluggable",
"(",
"$",
"model",
"[",
"'module'",
"]",
")",
")",
"continue",
";",
"if",
"(",
"$",
"result",
"=",
"$",
"this",
"->",
"applyOverrideForSluggable",
"(",
"$",
"model",
")",
")",
"{",
"$",
"candidates",
"[",
"$",
"model",
"[",
"'module'",
"]",
"]",
"=",
"$",
"result",
";",
"continue",
";",
"}",
"if",
"(",
"$",
"result",
"=",
"$",
"this",
"->",
"analyzeModelForSluggable",
"(",
"$",
"model",
")",
")",
"{",
"$",
"candidates",
"[",
"$",
"model",
"[",
"'module'",
"]",
"]",
"=",
"$",
"result",
";",
"}",
"}",
"return",
"$",
"candidates",
";",
"}"
] |
Finds all the models that the user might want to make sluggable
@return array
|
[
"Finds",
"all",
"the",
"models",
"that",
"the",
"user",
"might",
"want",
"to",
"make",
"sluggable"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L348-L369
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.applyOverrideForSluggable
|
protected function applyOverrideForSluggable(array $model)
{
if ( ! array_key_exists($model['module'], $this->overrides)) {
return false;
}
$override = $this->overrides[ $model['module'] ];
$analysis = [
'translated' => false,
'slug_column' => null,
'slug_sources_normal' => [],
'slug_sources_translated' => [],
];
// set the source attribute (determine whether it is available and/or translatable)
if ( ! array_key_exists('source', $override)) {
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. No source.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
if (in_array($override['source'], $model['normal_attributes'])) {
$analysis['slug_sources_normal'] = [ $override['source'] ];
} elseif (in_array($override['source'], $model['translated_attributes'])) {
$analysis['slug_sources_translated'] = [ $override['source'] ];
} else {
// couldn't find the attribute
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Source attribute '{$override['source']}' does not exist.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
// if provided, check and set the slug target attribute (on the model itself)
if (isset($override['slug'])) {
if ($override['slug'] == $override['source']) {
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Slug attribute '{$override['slug']}' is same as source attribute.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
if (in_array($override['slug'], $model['normal_attributes'])) {
$analysis['translated'] = false;
} elseif (in_array($override['slug'], $model['translated_attributes'])) {
$analysis['translated'] = true;
} else {
// couldn't find the attribute
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Slug attribute '{$override['slug']}' does not exist.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
$analysis['slug_column'] = $override['slug'];
// if source is translated, slug must be, and vice versa!
if ( $analysis['translated'] && count($analysis['slug_sources_normal'])
|| ! $analysis['translated'] && count($analysis['slug_sources_translated'])
) {
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Either Slug and Source attribute must be translated, or neither.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
}
// ensure that translated is set if source is translated
$analysis['translated'] = (count($analysis['slug_sources_translated']) > 0);
return $analysis;
}
|
php
|
protected function applyOverrideForSluggable(array $model)
{
if ( ! array_key_exists($model['module'], $this->overrides)) {
return false;
}
$override = $this->overrides[ $model['module'] ];
$analysis = [
'translated' => false,
'slug_column' => null,
'slug_sources_normal' => [],
'slug_sources_translated' => [],
];
// set the source attribute (determine whether it is available and/or translatable)
if ( ! array_key_exists('source', $override)) {
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. No source.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
if (in_array($override['source'], $model['normal_attributes'])) {
$analysis['slug_sources_normal'] = [ $override['source'] ];
} elseif (in_array($override['source'], $model['translated_attributes'])) {
$analysis['slug_sources_translated'] = [ $override['source'] ];
} else {
// couldn't find the attribute
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Source attribute '{$override['source']}' does not exist.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
// if provided, check and set the slug target attribute (on the model itself)
if (isset($override['slug'])) {
if ($override['slug'] == $override['source']) {
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Slug attribute '{$override['slug']}' is same as source attribute.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
if (in_array($override['slug'], $model['normal_attributes'])) {
$analysis['translated'] = false;
} elseif (in_array($override['slug'], $model['translated_attributes'])) {
$analysis['translated'] = true;
} else {
// couldn't find the attribute
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Slug attribute '{$override['slug']}' does not exist.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
$analysis['slug_column'] = $override['slug'];
// if source is translated, slug must be, and vice versa!
if ( $analysis['translated'] && count($analysis['slug_sources_normal'])
|| ! $analysis['translated'] && count($analysis['slug_sources_translated'])
) {
$this->context->log(
"Invalid slugs override configuration for model #{$model['module']}. "
. "Either Slug and Source attribute must be translated, or neither.",
Generator::LOG_LEVEL_ERROR
);
return false;
}
}
// ensure that translated is set if source is translated
$analysis['translated'] = (count($analysis['slug_sources_translated']) > 0);
return $analysis;
}
|
[
"protected",
"function",
"applyOverrideForSluggable",
"(",
"array",
"$",
"model",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"model",
"[",
"'module'",
"]",
",",
"$",
"this",
"->",
"overrides",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"override",
"=",
"$",
"this",
"->",
"overrides",
"[",
"$",
"model",
"[",
"'module'",
"]",
"]",
";",
"$",
"analysis",
"=",
"[",
"'translated'",
"=>",
"false",
",",
"'slug_column'",
"=>",
"null",
",",
"'slug_sources_normal'",
"=>",
"[",
"]",
",",
"'slug_sources_translated'",
"=>",
"[",
"]",
",",
"]",
";",
"// set the source attribute (determine whether it is available and/or translatable)",
"if",
"(",
"!",
"array_key_exists",
"(",
"'source'",
",",
"$",
"override",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Invalid slugs override configuration for model #{$model['module']}. No source.\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"override",
"[",
"'source'",
"]",
",",
"$",
"model",
"[",
"'normal_attributes'",
"]",
")",
")",
"{",
"$",
"analysis",
"[",
"'slug_sources_normal'",
"]",
"=",
"[",
"$",
"override",
"[",
"'source'",
"]",
"]",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"override",
"[",
"'source'",
"]",
",",
"$",
"model",
"[",
"'translated_attributes'",
"]",
")",
")",
"{",
"$",
"analysis",
"[",
"'slug_sources_translated'",
"]",
"=",
"[",
"$",
"override",
"[",
"'source'",
"]",
"]",
";",
"}",
"else",
"{",
"// couldn't find the attribute",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Invalid slugs override configuration for model #{$model['module']}. \"",
".",
"\"Source attribute '{$override['source']}' does not exist.\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"return",
"false",
";",
"}",
"// if provided, check and set the slug target attribute (on the model itself)",
"if",
"(",
"isset",
"(",
"$",
"override",
"[",
"'slug'",
"]",
")",
")",
"{",
"if",
"(",
"$",
"override",
"[",
"'slug'",
"]",
"==",
"$",
"override",
"[",
"'source'",
"]",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Invalid slugs override configuration for model #{$model['module']}. \"",
".",
"\"Slug attribute '{$override['slug']}' is same as source attribute.\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"override",
"[",
"'slug'",
"]",
",",
"$",
"model",
"[",
"'normal_attributes'",
"]",
")",
")",
"{",
"$",
"analysis",
"[",
"'translated'",
"]",
"=",
"false",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"override",
"[",
"'slug'",
"]",
",",
"$",
"model",
"[",
"'translated_attributes'",
"]",
")",
")",
"{",
"$",
"analysis",
"[",
"'translated'",
"]",
"=",
"true",
";",
"}",
"else",
"{",
"// couldn't find the attribute",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Invalid slugs override configuration for model #{$model['module']}. \"",
".",
"\"Slug attribute '{$override['slug']}' does not exist.\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"return",
"false",
";",
"}",
"$",
"analysis",
"[",
"'slug_column'",
"]",
"=",
"$",
"override",
"[",
"'slug'",
"]",
";",
"// if source is translated, slug must be, and vice versa!",
"if",
"(",
"$",
"analysis",
"[",
"'translated'",
"]",
"&&",
"count",
"(",
"$",
"analysis",
"[",
"'slug_sources_normal'",
"]",
")",
"||",
"!",
"$",
"analysis",
"[",
"'translated'",
"]",
"&&",
"count",
"(",
"$",
"analysis",
"[",
"'slug_sources_translated'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Invalid slugs override configuration for model #{$model['module']}. \"",
".",
"\"Either Slug and Source attribute must be translated, or neither.\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"return",
"false",
";",
"}",
"}",
"// ensure that translated is set if source is translated",
"$",
"analysis",
"[",
"'translated'",
"]",
"=",
"(",
"count",
"(",
"$",
"analysis",
"[",
"'slug_sources_translated'",
"]",
")",
">",
"0",
")",
";",
"return",
"$",
"analysis",
";",
"}"
] |
Returns overridden analysis result for model
after checking it against the model's data
@param array $model
@return array|false
|
[
"Returns",
"overridden",
"analysis",
"result",
"for",
"model",
"after",
"checking",
"it",
"against",
"the",
"model",
"s",
"data"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L380-L472
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php
|
AnalyzeSluggableInteractive.analyzeModelForSluggable
|
protected function analyzeModelForSluggable(array $model)
{
$analysis = [
'translated' => null,
'slug_column' => null,
'slug_sources_normal' => [],
'slug_sources_translated' => [],
];
// find out whether the model has a 'slug' column, preferring the first match we find
$slugColumns = config('pxlcms.generator.models.slugs.slug_columns', []);
foreach ($slugColumns as $slugColumn) {
foreach ($model['normal_attributes'] as $attribute) {
if ($attribute == $slugColumn) {
$analysis['slug_column'] = $attribute;
$analysis['translated'] = false;
break 2;
}
}
foreach ($model['translated_attributes'] as $attribute) {
if ($attribute == $slugColumn) {
$analysis['slug_column'] = $attribute;
$analysis['translated'] = true;
break 2;
}
}
}
// discard any matches that don't have a slug column on the model
// if there is no slug structure present (because that could never work)
if ( ! $this->context->slugStructurePresent && empty($analysis['slug_column'])) return false;
// find out whether the model has slug source candidate columns
$slugSources = config('pxlcms.generator.models.slugs.slug_source_columns', []);
// make sure we keep slug and source column in the same model (translated or parent)
$analysis['slug_sources_translated'] = array_values(array_intersect($slugSources, $model['translated_attributes']));
$analysis['slug_sources_normal'] = array_values(array_intersect($slugSources, $model['normal_attributes']));
if ($analysis['translated'] === true) {
$analysis['slug_sources_normal'] = [];
} elseif ($analysis === false) {
$analysis['slug_sources_translated'] = [];
}
// any matches? return as candidate
if ( ! empty($analysis['slug_column'])
|| count($analysis['slug_sources_normal'])
|| count($analysis['slug_sources_translated'])
) {
return $analysis;
}
return false;
}
|
php
|
protected function analyzeModelForSluggable(array $model)
{
$analysis = [
'translated' => null,
'slug_column' => null,
'slug_sources_normal' => [],
'slug_sources_translated' => [],
];
// find out whether the model has a 'slug' column, preferring the first match we find
$slugColumns = config('pxlcms.generator.models.slugs.slug_columns', []);
foreach ($slugColumns as $slugColumn) {
foreach ($model['normal_attributes'] as $attribute) {
if ($attribute == $slugColumn) {
$analysis['slug_column'] = $attribute;
$analysis['translated'] = false;
break 2;
}
}
foreach ($model['translated_attributes'] as $attribute) {
if ($attribute == $slugColumn) {
$analysis['slug_column'] = $attribute;
$analysis['translated'] = true;
break 2;
}
}
}
// discard any matches that don't have a slug column on the model
// if there is no slug structure present (because that could never work)
if ( ! $this->context->slugStructurePresent && empty($analysis['slug_column'])) return false;
// find out whether the model has slug source candidate columns
$slugSources = config('pxlcms.generator.models.slugs.slug_source_columns', []);
// make sure we keep slug and source column in the same model (translated or parent)
$analysis['slug_sources_translated'] = array_values(array_intersect($slugSources, $model['translated_attributes']));
$analysis['slug_sources_normal'] = array_values(array_intersect($slugSources, $model['normal_attributes']));
if ($analysis['translated'] === true) {
$analysis['slug_sources_normal'] = [];
} elseif ($analysis === false) {
$analysis['slug_sources_translated'] = [];
}
// any matches? return as candidate
if ( ! empty($analysis['slug_column'])
|| count($analysis['slug_sources_normal'])
|| count($analysis['slug_sources_translated'])
) {
return $analysis;
}
return false;
}
|
[
"protected",
"function",
"analyzeModelForSluggable",
"(",
"array",
"$",
"model",
")",
"{",
"$",
"analysis",
"=",
"[",
"'translated'",
"=>",
"null",
",",
"'slug_column'",
"=>",
"null",
",",
"'slug_sources_normal'",
"=>",
"[",
"]",
",",
"'slug_sources_translated'",
"=>",
"[",
"]",
",",
"]",
";",
"// find out whether the model has a 'slug' column, preferring the first match we find",
"$",
"slugColumns",
"=",
"config",
"(",
"'pxlcms.generator.models.slugs.slug_columns'",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"slugColumns",
"as",
"$",
"slugColumn",
")",
"{",
"foreach",
"(",
"$",
"model",
"[",
"'normal_attributes'",
"]",
"as",
"$",
"attribute",
")",
"{",
"if",
"(",
"$",
"attribute",
"==",
"$",
"slugColumn",
")",
"{",
"$",
"analysis",
"[",
"'slug_column'",
"]",
"=",
"$",
"attribute",
";",
"$",
"analysis",
"[",
"'translated'",
"]",
"=",
"false",
";",
"break",
"2",
";",
"}",
"}",
"foreach",
"(",
"$",
"model",
"[",
"'translated_attributes'",
"]",
"as",
"$",
"attribute",
")",
"{",
"if",
"(",
"$",
"attribute",
"==",
"$",
"slugColumn",
")",
"{",
"$",
"analysis",
"[",
"'slug_column'",
"]",
"=",
"$",
"attribute",
";",
"$",
"analysis",
"[",
"'translated'",
"]",
"=",
"true",
";",
"break",
"2",
";",
"}",
"}",
"}",
"// discard any matches that don't have a slug column on the model",
"// if there is no slug structure present (because that could never work)",
"if",
"(",
"!",
"$",
"this",
"->",
"context",
"->",
"slugStructurePresent",
"&&",
"empty",
"(",
"$",
"analysis",
"[",
"'slug_column'",
"]",
")",
")",
"return",
"false",
";",
"// find out whether the model has slug source candidate columns",
"$",
"slugSources",
"=",
"config",
"(",
"'pxlcms.generator.models.slugs.slug_source_columns'",
",",
"[",
"]",
")",
";",
"// make sure we keep slug and source column in the same model (translated or parent)",
"$",
"analysis",
"[",
"'slug_sources_translated'",
"]",
"=",
"array_values",
"(",
"array_intersect",
"(",
"$",
"slugSources",
",",
"$",
"model",
"[",
"'translated_attributes'",
"]",
")",
")",
";",
"$",
"analysis",
"[",
"'slug_sources_normal'",
"]",
"=",
"array_values",
"(",
"array_intersect",
"(",
"$",
"slugSources",
",",
"$",
"model",
"[",
"'normal_attributes'",
"]",
")",
")",
";",
"if",
"(",
"$",
"analysis",
"[",
"'translated'",
"]",
"===",
"true",
")",
"{",
"$",
"analysis",
"[",
"'slug_sources_normal'",
"]",
"=",
"[",
"]",
";",
"}",
"elseif",
"(",
"$",
"analysis",
"===",
"false",
")",
"{",
"$",
"analysis",
"[",
"'slug_sources_translated'",
"]",
"=",
"[",
"]",
";",
"}",
"// any matches? return as candidate",
"if",
"(",
"!",
"empty",
"(",
"$",
"analysis",
"[",
"'slug_column'",
"]",
")",
"||",
"count",
"(",
"$",
"analysis",
"[",
"'slug_sources_normal'",
"]",
")",
"||",
"count",
"(",
"$",
"analysis",
"[",
"'slug_sources_translated'",
"]",
")",
")",
"{",
"return",
"$",
"analysis",
";",
"}",
"return",
"false",
";",
"}"
] |
Determines whether the model data makes it a sluggable candidate
and returns analysis result
@param array $model model data
@return array|false false if not a candidate
|
[
"Determines",
"whether",
"the",
"model",
"data",
"makes",
"it",
"a",
"sluggable",
"candidate",
"and",
"returns",
"analysis",
"result"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeSluggableInteractive.php#L481-L539
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &polymorph($value = true)
{
$this->polymorph = (bool) $value;
if ($this->polymorph) {
$this->addTrait(PolymorphInterface::class, PolymorphInterfaceImplementation::class);
}
return $this;
}
|
php
|
public function &polymorph($value = true)
{
$this->polymorph = (bool) $value;
if ($this->polymorph) {
$this->addTrait(PolymorphInterface::class, PolymorphInterfaceImplementation::class);
}
return $this;
}
|
[
"public",
"function",
"&",
"polymorph",
"(",
"$",
"value",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"polymorph",
"=",
"(",
"bool",
")",
"$",
"value",
";",
"if",
"(",
"$",
"this",
"->",
"polymorph",
")",
"{",
"$",
"this",
"->",
"addTrait",
"(",
"PolymorphInterface",
"::",
"class",
",",
"PolymorphInterfaceImplementation",
"::",
"class",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Set this model to be polymorph (type field is added and used to store instance's class name).
@param bool $value
@return $this
|
[
"Set",
"this",
"model",
"to",
"be",
"polymorph",
"(",
"type",
"field",
"is",
"added",
"and",
"used",
"to",
"store",
"instance",
"s",
"class",
"name",
")",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L107-L116
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &permissions($value = true, $permissions_are_permissive = true)
{
$this->permissions = (bool) $value;
$this->permissions_are_permissive = (bool) $permissions_are_permissive;
if ($this->permissions) {
$this->removeTrait(PermissionsInterface::class, [PermissiveImplementation::class, RestrictiveImplementation::class]);
$this->addTrait(PermissionsInterface::class, ($this->permissions_are_permissive ? PermissiveImplementation::class : RestrictiveImplementation::class));
} else {
$this->removeInterface(PermissionsInterface::class);
}
return $this;
}
|
php
|
public function &permissions($value = true, $permissions_are_permissive = true)
{
$this->permissions = (bool) $value;
$this->permissions_are_permissive = (bool) $permissions_are_permissive;
if ($this->permissions) {
$this->removeTrait(PermissionsInterface::class, [PermissiveImplementation::class, RestrictiveImplementation::class]);
$this->addTrait(PermissionsInterface::class, ($this->permissions_are_permissive ? PermissiveImplementation::class : RestrictiveImplementation::class));
} else {
$this->removeInterface(PermissionsInterface::class);
}
return $this;
}
|
[
"public",
"function",
"&",
"permissions",
"(",
"$",
"value",
"=",
"true",
",",
"$",
"permissions_are_permissive",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"permissions",
"=",
"(",
"bool",
")",
"$",
"value",
";",
"$",
"this",
"->",
"permissions_are_permissive",
"=",
"(",
"bool",
")",
"$",
"permissions_are_permissive",
";",
"if",
"(",
"$",
"this",
"->",
"permissions",
")",
"{",
"$",
"this",
"->",
"removeTrait",
"(",
"PermissionsInterface",
"::",
"class",
",",
"[",
"PermissiveImplementation",
"::",
"class",
",",
"RestrictiveImplementation",
"::",
"class",
"]",
")",
";",
"$",
"this",
"->",
"addTrait",
"(",
"PermissionsInterface",
"::",
"class",
",",
"(",
"$",
"this",
"->",
"permissions_are_permissive",
"?",
"PermissiveImplementation",
"::",
"class",
":",
"RestrictiveImplementation",
"::",
"class",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"removeInterface",
"(",
"PermissionsInterface",
"::",
"class",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L147-L161
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &protectFields(...$fields)
{
foreach ($fields as $field) {
if ($field && !in_array($field, $this->protected_fields)) {
$this->protected_fields[] = $field;
}
}
if (!empty($this->protected_fields)) {
$this->addTrait(ProtectedFieldsInterface::class, ProtectedFieldsInterfaceImplementation::class);
}
return $this;
}
|
php
|
public function &protectFields(...$fields)
{
foreach ($fields as $field) {
if ($field && !in_array($field, $this->protected_fields)) {
$this->protected_fields[] = $field;
}
}
if (!empty($this->protected_fields)) {
$this->addTrait(ProtectedFieldsInterface::class, ProtectedFieldsInterfaceImplementation::class);
}
return $this;
}
|
[
"public",
"function",
"&",
"protectFields",
"(",
"...",
"$",
"fields",
")",
"{",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"$",
"field",
"&&",
"!",
"in_array",
"(",
"$",
"field",
",",
"$",
"this",
"->",
"protected_fields",
")",
")",
"{",
"$",
"this",
"->",
"protected_fields",
"[",
"]",
"=",
"$",
"field",
";",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"protected_fields",
")",
")",
"{",
"$",
"this",
"->",
"addTrait",
"(",
"ProtectedFieldsInterface",
"::",
"class",
",",
"ProtectedFieldsInterfaceImplementation",
"::",
"class",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L179-L192
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &unprotectFields(...$fields)
{
foreach ($fields as $field) {
$index = array_search($field, $this->protected_fields);
if ($index !== false) {
unset($this->protected_fields[$index]);
}
}
if (empty($this->protected_fields)) {
$this->removeTrait(ProtectedFieldsInterface::class, ProtectedFieldsInterfaceImplementation::class);
} else {
$this->protected_fields = array_values($this->protected_fields); // Reindex keys
}
return $this;
}
|
php
|
public function &unprotectFields(...$fields)
{
foreach ($fields as $field) {
$index = array_search($field, $this->protected_fields);
if ($index !== false) {
unset($this->protected_fields[$index]);
}
}
if (empty($this->protected_fields)) {
$this->removeTrait(ProtectedFieldsInterface::class, ProtectedFieldsInterfaceImplementation::class);
} else {
$this->protected_fields = array_values($this->protected_fields); // Reindex keys
}
return $this;
}
|
[
"public",
"function",
"&",
"unprotectFields",
"(",
"...",
"$",
"fields",
")",
"{",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
")",
"{",
"$",
"index",
"=",
"array_search",
"(",
"$",
"field",
",",
"$",
"this",
"->",
"protected_fields",
")",
";",
"if",
"(",
"$",
"index",
"!==",
"false",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"protected_fields",
"[",
"$",
"index",
"]",
")",
";",
"}",
"}",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"protected_fields",
")",
")",
"{",
"$",
"this",
"->",
"removeTrait",
"(",
"ProtectedFieldsInterface",
"::",
"class",
",",
"ProtectedFieldsInterfaceImplementation",
"::",
"class",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"protected_fields",
"=",
"array_values",
"(",
"$",
"this",
"->",
"protected_fields",
")",
";",
"// Reindex keys",
"}",
"return",
"$",
"this",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L197-L214
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &setBaseClassExtends($class_name)
{
if ($class_name && class_exists($class_name) && (new \ReflectionClass($class_name))->isSubclassOf(Entity::class)) {
} else {
throw new InvalidArgumentException("Class name '$class_name' is not valid");
}
$this->base_class_extends = $class_name;
return $this;
}
|
php
|
public function &setBaseClassExtends($class_name)
{
if ($class_name && class_exists($class_name) && (new \ReflectionClass($class_name))->isSubclassOf(Entity::class)) {
} else {
throw new InvalidArgumentException("Class name '$class_name' is not valid");
}
$this->base_class_extends = $class_name;
return $this;
}
|
[
"public",
"function",
"&",
"setBaseClassExtends",
"(",
"$",
"class_name",
")",
"{",
"if",
"(",
"$",
"class_name",
"&&",
"class_exists",
"(",
"$",
"class_name",
")",
"&&",
"(",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"class_name",
")",
")",
"->",
"isSubclassOf",
"(",
"Entity",
"::",
"class",
")",
")",
"{",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Class name '$class_name' is not valid\"",
")",
";",
"}",
"$",
"this",
"->",
"base_class_extends",
"=",
"$",
"class_name",
";",
"return",
"$",
"this",
";",
"}"
] |
Set name of a class that base type class should extend.
Note: This class needs to descened from Object class of DatabaseObject package
@param string $class_name
@return $this
|
[
"Set",
"name",
"of",
"a",
"class",
"that",
"base",
"type",
"class",
"should",
"extend",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L248-L258
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &expectedDatasetSize($size)
{
if (in_array($size, [FieldInterface::SIZE_TINY, FieldInterface::SIZE_SMALL, FieldInterface::SIZE_MEDIUM, FieldInterface::SIZE_NORMAL, FieldInterface::SIZE_BIG])) {
$this->expected_dataset_size = $size;
if ($this->id_field instanceof IntegerField && $this->id_field->getSize() != $this->expected_dataset_size) {
$this->id_field = null; // Reset ID field so it can be recreated with the new size
}
} else {
throw new InvalidArgumentException("Value '$size' is not a valid dataset size");
}
return $this;
}
|
php
|
public function &expectedDatasetSize($size)
{
if (in_array($size, [FieldInterface::SIZE_TINY, FieldInterface::SIZE_SMALL, FieldInterface::SIZE_MEDIUM, FieldInterface::SIZE_NORMAL, FieldInterface::SIZE_BIG])) {
$this->expected_dataset_size = $size;
if ($this->id_field instanceof IntegerField && $this->id_field->getSize() != $this->expected_dataset_size) {
$this->id_field = null; // Reset ID field so it can be recreated with the new size
}
} else {
throw new InvalidArgumentException("Value '$size' is not a valid dataset size");
}
return $this;
}
|
[
"public",
"function",
"&",
"expectedDatasetSize",
"(",
"$",
"size",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"size",
",",
"[",
"FieldInterface",
"::",
"SIZE_TINY",
",",
"FieldInterface",
"::",
"SIZE_SMALL",
",",
"FieldInterface",
"::",
"SIZE_MEDIUM",
",",
"FieldInterface",
"::",
"SIZE_NORMAL",
",",
"FieldInterface",
"::",
"SIZE_BIG",
"]",
")",
")",
"{",
"$",
"this",
"->",
"expected_dataset_size",
"=",
"$",
"size",
";",
"if",
"(",
"$",
"this",
"->",
"id_field",
"instanceof",
"IntegerField",
"&&",
"$",
"this",
"->",
"id_field",
"->",
"getSize",
"(",
")",
"!=",
"$",
"this",
"->",
"expected_dataset_size",
")",
"{",
"$",
"this",
"->",
"id_field",
"=",
"null",
";",
"// Reset ID field so it can be recreated with the new size",
"}",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Value '$size' is not a valid dataset size\"",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Set expected databaset size in following increments: TINY, SMALL, MEDIUM, NORMAL and BIG.
@param string $size
@return $this
|
[
"Set",
"expected",
"databaset",
"size",
"in",
"following",
"increments",
":",
"TINY",
"SMALL",
"MEDIUM",
"NORMAL",
"and",
"BIG",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L281-L294
|
activecollab/databasestructure
|
src/Type.php
|
Type.getIdField
|
public function getIdField()
{
if (empty($this->id_field)) {
$this->id_field = (new IntegerField('id', 0))->unsigned(true)->size($this->getExpectedDatasetSize());
}
return $this->id_field;
}
|
php
|
public function getIdField()
{
if (empty($this->id_field)) {
$this->id_field = (new IntegerField('id', 0))->unsigned(true)->size($this->getExpectedDatasetSize());
}
return $this->id_field;
}
|
[
"public",
"function",
"getIdField",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"id_field",
")",
")",
"{",
"$",
"this",
"->",
"id_field",
"=",
"(",
"new",
"IntegerField",
"(",
"'id'",
",",
"0",
")",
")",
"->",
"unsigned",
"(",
"true",
")",
"->",
"size",
"(",
"$",
"this",
"->",
"getExpectedDatasetSize",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"id_field",
";",
"}"
] |
Return ID field for this type.
@return IntegerField
|
[
"Return",
"ID",
"field",
"for",
"this",
"type",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L314-L321
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &addField(FieldInterface $field)
{
if (empty($this->fields[$field->getName()])) {
$this->fields[$field->getName()] = $field;
$field->onAddedToType($this); // Let the field register indexes, custom behaviour etc
} else {
throw new InvalidArgumentException("Field '" . $field->getName() . "' already exists in this type");
}
return $this;
}
|
php
|
public function &addField(FieldInterface $field)
{
if (empty($this->fields[$field->getName()])) {
$this->fields[$field->getName()] = $field;
$field->onAddedToType($this); // Let the field register indexes, custom behaviour etc
} else {
throw new InvalidArgumentException("Field '" . $field->getName() . "' already exists in this type");
}
return $this;
}
|
[
"public",
"function",
"&",
"addField",
"(",
"FieldInterface",
"$",
"field",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"fields",
"[",
"$",
"field",
"->",
"getName",
"(",
")",
"]",
")",
")",
"{",
"$",
"this",
"->",
"fields",
"[",
"$",
"field",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"field",
";",
"$",
"field",
"->",
"onAddedToType",
"(",
"$",
"this",
")",
";",
"// Let the field register indexes, custom behaviour etc",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Field '\"",
".",
"$",
"field",
"->",
"getName",
"(",
")",
".",
"\"' already exists in this type\"",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Add a single field to the type.
@param FieldInterface $field
@return $this
|
[
"Add",
"a",
"single",
"field",
"to",
"the",
"type",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L363-L373
|
activecollab/databasestructure
|
src/Type.php
|
Type.getAllFields
|
public function getAllFields()
{
$result = [];
$this->fieldToFlatList($this->getIdField(), $result);
if ($this->getPolymorph()) {
$this->fieldToFlatList($this->getTypeField(), $result);
}
foreach ($this->getAssociations() as $association) {
if ($association instanceof InjectFieldsInsterface) {
foreach ($association->getFields() as $field) {
$this->fieldToFlatList($field, $result);
}
}
}
foreach ($this->getFields() as $field) {
$this->fieldToFlatList($field, $result);
}
return $result;
}
|
php
|
public function getAllFields()
{
$result = [];
$this->fieldToFlatList($this->getIdField(), $result);
if ($this->getPolymorph()) {
$this->fieldToFlatList($this->getTypeField(), $result);
}
foreach ($this->getAssociations() as $association) {
if ($association instanceof InjectFieldsInsterface) {
foreach ($association->getFields() as $field) {
$this->fieldToFlatList($field, $result);
}
}
}
foreach ($this->getFields() as $field) {
$this->fieldToFlatList($field, $result);
}
return $result;
}
|
[
"public",
"function",
"getAllFields",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"fieldToFlatList",
"(",
"$",
"this",
"->",
"getIdField",
"(",
")",
",",
"$",
"result",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getPolymorph",
"(",
")",
")",
"{",
"$",
"this",
"->",
"fieldToFlatList",
"(",
"$",
"this",
"->",
"getTypeField",
"(",
")",
",",
"$",
"result",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"getAssociations",
"(",
")",
"as",
"$",
"association",
")",
"{",
"if",
"(",
"$",
"association",
"instanceof",
"InjectFieldsInsterface",
")",
"{",
"foreach",
"(",
"$",
"association",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"$",
"this",
"->",
"fieldToFlatList",
"(",
"$",
"field",
",",
"$",
"result",
")",
";",
"}",
"}",
"}",
"foreach",
"(",
"$",
"this",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"$",
"this",
"->",
"fieldToFlatList",
"(",
"$",
"field",
",",
"$",
"result",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L378-L401
|
activecollab/databasestructure
|
src/Type.php
|
Type.getGeneratedFields
|
public function getGeneratedFields()
{
$result = [];
foreach ($this->getAllFields() as $field) {
if ($field instanceof GeneratedFieldsInterface) {
$result = array_merge($result, $field->getGeneratedFields());
}
}
return $result;
}
|
php
|
public function getGeneratedFields()
{
$result = [];
foreach ($this->getAllFields() as $field) {
if ($field instanceof GeneratedFieldsInterface) {
$result = array_merge($result, $field->getGeneratedFields());
}
}
return $result;
}
|
[
"public",
"function",
"getGeneratedFields",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAllFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"$",
"field",
"instanceof",
"GeneratedFieldsInterface",
")",
"{",
"$",
"result",
"=",
"array_merge",
"(",
"$",
"result",
",",
"$",
"field",
"->",
"getGeneratedFields",
"(",
")",
")",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L406-L417
|
activecollab/databasestructure
|
src/Type.php
|
Type.getAllIndexes
|
public function getAllIndexes()
{
$result = [new Index('id', ['id'], IndexInterface::PRIMARY)];
if ($this->getPolymorph()) {
$result[] = new Index('type');
}
if (!empty($this->getIndexes())) {
$result = array_merge($result, $this->getIndexes());
}
foreach ($this->getAssociations() as $assosication) {
if ($assosication instanceof InjectIndexesInsterface) {
$association_indexes = $assosication->getIndexes();
if (!empty($association_indexes)) {
$result = array_merge($result, $association_indexes);
}
}
}
return $result;
}
|
php
|
public function getAllIndexes()
{
$result = [new Index('id', ['id'], IndexInterface::PRIMARY)];
if ($this->getPolymorph()) {
$result[] = new Index('type');
}
if (!empty($this->getIndexes())) {
$result = array_merge($result, $this->getIndexes());
}
foreach ($this->getAssociations() as $assosication) {
if ($assosication instanceof InjectIndexesInsterface) {
$association_indexes = $assosication->getIndexes();
if (!empty($association_indexes)) {
$result = array_merge($result, $association_indexes);
}
}
}
return $result;
}
|
[
"public",
"function",
"getAllIndexes",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"new",
"Index",
"(",
"'id'",
",",
"[",
"'id'",
"]",
",",
"IndexInterface",
"::",
"PRIMARY",
")",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"getPolymorph",
"(",
")",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"new",
"Index",
"(",
"'type'",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"getIndexes",
"(",
")",
")",
")",
"{",
"$",
"result",
"=",
"array_merge",
"(",
"$",
"result",
",",
"$",
"this",
"->",
"getIndexes",
"(",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"getAssociations",
"(",
")",
"as",
"$",
"assosication",
")",
"{",
"if",
"(",
"$",
"assosication",
"instanceof",
"InjectIndexesInsterface",
")",
"{",
"$",
"association_indexes",
"=",
"$",
"assosication",
"->",
"getIndexes",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"association_indexes",
")",
")",
"{",
"$",
"result",
"=",
"array_merge",
"(",
"$",
"result",
",",
"$",
"association_indexes",
")",
";",
"}",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] |
Return all indexes.
@return IndexInterface[]
|
[
"Return",
"all",
"indexes",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L480-L503
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &addTrait($interface = null, $implementation = null)
{
if (is_array($interface)) {
foreach ($interface as $k => $v) {
$this->addTrait($k, $v);
}
} else {
if ($interface || $implementation) {
if (empty($interface)) {
$interface = '--just-paste-trait--';
}
if (empty($this->traits[$interface])) {
$this->traits[$interface] = [];
}
if ($implementation && array_search($implementation, $this->traits[$interface]) === false) {
$this->traits[$interface][] = $implementation;
}
} else {
throw new InvalidArgumentException('Interface or implementation are required');
}
}
return $this;
}
|
php
|
public function &addTrait($interface = null, $implementation = null)
{
if (is_array($interface)) {
foreach ($interface as $k => $v) {
$this->addTrait($k, $v);
}
} else {
if ($interface || $implementation) {
if (empty($interface)) {
$interface = '--just-paste-trait--';
}
if (empty($this->traits[$interface])) {
$this->traits[$interface] = [];
}
if ($implementation && array_search($implementation, $this->traits[$interface]) === false) {
$this->traits[$interface][] = $implementation;
}
} else {
throw new InvalidArgumentException('Interface or implementation are required');
}
}
return $this;
}
|
[
"public",
"function",
"&",
"addTrait",
"(",
"$",
"interface",
"=",
"null",
",",
"$",
"implementation",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"interface",
")",
")",
"{",
"foreach",
"(",
"$",
"interface",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"this",
"->",
"addTrait",
"(",
"$",
"k",
",",
"$",
"v",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"interface",
"||",
"$",
"implementation",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"interface",
")",
")",
"{",
"$",
"interface",
"=",
"'--just-paste-trait--'",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"traits",
"[",
"$",
"interface",
"]",
")",
")",
"{",
"$",
"this",
"->",
"traits",
"[",
"$",
"interface",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"$",
"implementation",
"&&",
"array_search",
"(",
"$",
"implementation",
",",
"$",
"this",
"->",
"traits",
"[",
"$",
"interface",
"]",
")",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"traits",
"[",
"$",
"interface",
"]",
"[",
"]",
"=",
"$",
"implementation",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Interface or implementation are required'",
")",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] |
Implement an interface or add a trait (or both).
@param string $interface
@param string $implementation
@return $this
@throws InvalidArgumentException
|
[
"Implement",
"an",
"interface",
"or",
"add",
"a",
"trait",
"(",
"or",
"both",
")",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L622-L647
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &orderBy($order_by)
{
if (empty($order_by)) {
throw new InvalidArgumentException('Order by value is required');
} elseif (!is_string($order_by) && !is_array($order_by)) {
throw new InvalidArgumentException('Order by can be string or array');
}
$this->order_by = (array) $order_by;
return $this;
}
|
php
|
public function &orderBy($order_by)
{
if (empty($order_by)) {
throw new InvalidArgumentException('Order by value is required');
} elseif (!is_string($order_by) && !is_array($order_by)) {
throw new InvalidArgumentException('Order by can be string or array');
}
$this->order_by = (array) $order_by;
return $this;
}
|
[
"public",
"function",
"&",
"orderBy",
"(",
"$",
"order_by",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"order_by",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Order by value is required'",
")",
";",
"}",
"elseif",
"(",
"!",
"is_string",
"(",
"$",
"order_by",
")",
"&&",
"!",
"is_array",
"(",
"$",
"order_by",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Order by can be string or array'",
")",
";",
"}",
"$",
"this",
"->",
"order_by",
"=",
"(",
"array",
")",
"$",
"order_by",
";",
"return",
"$",
"this",
";",
"}"
] |
Set how records of this type should be ordered by default.
@param string|array $order_by
@return $this
|
[
"Set",
"how",
"records",
"of",
"this",
"type",
"should",
"be",
"ordered",
"by",
"default",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L735-L746
|
activecollab/databasestructure
|
src/Type.php
|
Type.&
|
public function &serialize(...$fields)
{
if (!empty($fields)) {
$this->serialize = array_unique(array_merge($this->serialize, $fields));
}
return $this;
}
|
php
|
public function &serialize(...$fields)
{
if (!empty($fields)) {
$this->serialize = array_unique(array_merge($this->serialize, $fields));
}
return $this;
}
|
[
"public",
"function",
"&",
"serialize",
"(",
"...",
"$",
"fields",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"fields",
")",
")",
"{",
"$",
"this",
"->",
"serialize",
"=",
"array_unique",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"serialize",
",",
"$",
"fields",
")",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Set a list of fields that will be included during object serialization.
@param string[] $fields
@return $this
|
[
"Set",
"a",
"list",
"of",
"fields",
"that",
"will",
"be",
"included",
"during",
"object",
"serialization",
"."
] |
train
|
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Type.php#L769-L776
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.onUserRegistration
|
public function onUserRegistration(EventInterface $e)
{
$user = $e->getParam('user');
if ($this->getOptions()->getSendVerificationEmail() && $this->getZfcUserOptions()->getEnableRegistration()) {
$this->sendVerificationEmail($user);
} elseif ($this->getOptions()->getSendPasswordRequestEmail() && !$this->getZfcUserOptions()->getEnableRegistration()) {
$this->sendPasswordRequestEmail($user);
}
// do nothing
}
|
php
|
public function onUserRegistration(EventInterface $e)
{
$user = $e->getParam('user');
if ($this->getOptions()->getSendVerificationEmail() && $this->getZfcUserOptions()->getEnableRegistration()) {
$this->sendVerificationEmail($user);
} elseif ($this->getOptions()->getSendPasswordRequestEmail() && !$this->getZfcUserOptions()->getEnableRegistration()) {
$this->sendPasswordRequestEmail($user);
}
// do nothing
}
|
[
"public",
"function",
"onUserRegistration",
"(",
"EventInterface",
"$",
"e",
")",
"{",
"$",
"user",
"=",
"$",
"e",
"->",
"getParam",
"(",
"'user'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getOptions",
"(",
")",
"->",
"getSendVerificationEmail",
"(",
")",
"&&",
"$",
"this",
"->",
"getZfcUserOptions",
"(",
")",
"->",
"getEnableRegistration",
"(",
")",
")",
"{",
"$",
"this",
"->",
"sendVerificationEmail",
"(",
"$",
"user",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"getOptions",
"(",
")",
"->",
"getSendPasswordRequestEmail",
"(",
")",
"&&",
"!",
"$",
"this",
"->",
"getZfcUserOptions",
"(",
")",
"->",
"getEnableRegistration",
"(",
")",
")",
"{",
"$",
"this",
"->",
"sendPasswordRequestEmail",
"(",
"$",
"user",
")",
";",
"}",
"// do nothing",
"}"
] |
{@inheritDoc}
|
[
"{"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L71-L81
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.sendVerificationEmail
|
public function sendVerificationEmail(UserInterface $user)
{
$registrationRecord = $this->createRegistrationRecord($user);
$this->mailer->sendVerificationEmail($registrationRecord);
}
|
php
|
public function sendVerificationEmail(UserInterface $user)
{
$registrationRecord = $this->createRegistrationRecord($user);
$this->mailer->sendVerificationEmail($registrationRecord);
}
|
[
"public",
"function",
"sendVerificationEmail",
"(",
"UserInterface",
"$",
"user",
")",
"{",
"$",
"registrationRecord",
"=",
"$",
"this",
"->",
"createRegistrationRecord",
"(",
"$",
"user",
")",
";",
"$",
"this",
"->",
"mailer",
"->",
"sendVerificationEmail",
"(",
"$",
"registrationRecord",
")",
";",
"}"
] |
{@inheritDoc}
|
[
"{"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L86-L90
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.sendPasswordRequestEmail
|
public function sendPasswordRequestEmail(UserInterface $user)
{
$registrationRecord = $this->createRegistrationRecord($user);
$this->mailer->sendPasswordRequestEmail($registrationRecord);
}
|
php
|
public function sendPasswordRequestEmail(UserInterface $user)
{
$registrationRecord = $this->createRegistrationRecord($user);
$this->mailer->sendPasswordRequestEmail($registrationRecord);
}
|
[
"public",
"function",
"sendPasswordRequestEmail",
"(",
"UserInterface",
"$",
"user",
")",
"{",
"$",
"registrationRecord",
"=",
"$",
"this",
"->",
"createRegistrationRecord",
"(",
"$",
"user",
")",
";",
"$",
"this",
"->",
"mailer",
"->",
"sendPasswordRequestEmail",
"(",
"$",
"registrationRecord",
")",
";",
"}"
] |
{@inheritDoc}
|
[
"{"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L95-L99
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.createRegistrationRecord
|
protected function createRegistrationRecord(UserInterface $user)
{
$entityClass = $this->getOptions()->getRegistrationEntityClass();
$entity = new $entityClass($user);
$this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'record' => $entity));
$entity->generateToken();
$this->getUserRegistrationMapper()->insert($entity);
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user, 'record' => $entity));
return $entity;
}
|
php
|
protected function createRegistrationRecord(UserInterface $user)
{
$entityClass = $this->getOptions()->getRegistrationEntityClass();
$entity = new $entityClass($user);
$this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'record' => $entity));
$entity->generateToken();
$this->getUserRegistrationMapper()->insert($entity);
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user, 'record' => $entity));
return $entity;
}
|
[
"protected",
"function",
"createRegistrationRecord",
"(",
"UserInterface",
"$",
"user",
")",
"{",
"$",
"entityClass",
"=",
"$",
"this",
"->",
"getOptions",
"(",
")",
"->",
"getRegistrationEntityClass",
"(",
")",
";",
"$",
"entity",
"=",
"new",
"$",
"entityClass",
"(",
"$",
"user",
")",
";",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"__FUNCTION__",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'record'",
"=>",
"$",
"entity",
")",
")",
";",
"$",
"entity",
"->",
"generateToken",
"(",
")",
";",
"$",
"this",
"->",
"getUserRegistrationMapper",
"(",
")",
"->",
"insert",
"(",
"$",
"entity",
")",
";",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"__FUNCTION__",
".",
"'.post'",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'record'",
"=>",
"$",
"entity",
")",
")",
";",
"return",
"$",
"entity",
";",
"}"
] |
Stored user registration record to database
@return UserInterface $user
@return UserRegistrationInterface
|
[
"Stored",
"user",
"registration",
"record",
"to",
"database"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L107-L117
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.verifyEmail
|
public function verifyEmail(UserInterface $user, $token)
{
$record = $this->getUserRegistrationMapper()->findByUser($user);
$this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'token' => $token, 'record' => $record));
if (!$record || !$this->isTokenValid($user, $token, $record)) {
return false;
}
if (!$record->isResponded()) {
$record->setResponded(UserRegistrationInterface::EMAIL_RESPONDED);
$this->getUserRegistrationMapper()->update($record);
}
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return true;
}
|
php
|
public function verifyEmail(UserInterface $user, $token)
{
$record = $this->getUserRegistrationMapper()->findByUser($user);
$this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'token' => $token, 'record' => $record));
if (!$record || !$this->isTokenValid($user, $token, $record)) {
return false;
}
if (!$record->isResponded()) {
$record->setResponded(UserRegistrationInterface::EMAIL_RESPONDED);
$this->getUserRegistrationMapper()->update($record);
}
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return true;
}
|
[
"public",
"function",
"verifyEmail",
"(",
"UserInterface",
"$",
"user",
",",
"$",
"token",
")",
"{",
"$",
"record",
"=",
"$",
"this",
"->",
"getUserRegistrationMapper",
"(",
")",
"->",
"findByUser",
"(",
"$",
"user",
")",
";",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"__FUNCTION__",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'token'",
"=>",
"$",
"token",
",",
"'record'",
"=>",
"$",
"record",
")",
")",
";",
"if",
"(",
"!",
"$",
"record",
"||",
"!",
"$",
"this",
"->",
"isTokenValid",
"(",
"$",
"user",
",",
"$",
"token",
",",
"$",
"record",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"record",
"->",
"isResponded",
"(",
")",
")",
"{",
"$",
"record",
"->",
"setResponded",
"(",
"UserRegistrationInterface",
"::",
"EMAIL_RESPONDED",
")",
";",
"$",
"this",
"->",
"getUserRegistrationMapper",
"(",
")",
"->",
"update",
"(",
"$",
"record",
")",
";",
"}",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"__FUNCTION__",
".",
"'.post'",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'token'",
"=>",
"$",
"token",
",",
"'record'",
"=>",
"$",
"record",
")",
")",
";",
"return",
"true",
";",
"}"
] |
{@inheritDoc}
|
[
"{"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L122-L138
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.isTokenValid
|
public function isTokenValid(UserInterface $user, $token, UserRegistrationInterface $record)
{
if ($record->getToken() !== $token) {
$this->getEventManager()->trigger('tokenInvalid', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return false;
} elseif ($this->getOptions()->getEnableRequestExpiry() && $this->isTokenExpired($record)) {
$this->getEventManager()->trigger('tokenExpired', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return false;
}
$this->getEventManager()->trigger('tokenValid', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return true;
}
|
php
|
public function isTokenValid(UserInterface $user, $token, UserRegistrationInterface $record)
{
if ($record->getToken() !== $token) {
$this->getEventManager()->trigger('tokenInvalid', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return false;
} elseif ($this->getOptions()->getEnableRequestExpiry() && $this->isTokenExpired($record)) {
$this->getEventManager()->trigger('tokenExpired', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return false;
}
$this->getEventManager()->trigger('tokenValid', $this, array('user' => $user, 'token' => $token, 'record' => $record));
return true;
}
|
[
"public",
"function",
"isTokenValid",
"(",
"UserInterface",
"$",
"user",
",",
"$",
"token",
",",
"UserRegistrationInterface",
"$",
"record",
")",
"{",
"if",
"(",
"$",
"record",
"->",
"getToken",
"(",
")",
"!==",
"$",
"token",
")",
"{",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"'tokenInvalid'",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'token'",
"=>",
"$",
"token",
",",
"'record'",
"=>",
"$",
"record",
")",
")",
";",
"return",
"false",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"getOptions",
"(",
")",
"->",
"getEnableRequestExpiry",
"(",
")",
"&&",
"$",
"this",
"->",
"isTokenExpired",
"(",
"$",
"record",
")",
")",
"{",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"'tokenExpired'",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'token'",
"=>",
"$",
"token",
",",
"'record'",
"=>",
"$",
"record",
")",
")",
";",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"'tokenValid'",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'token'",
"=>",
"$",
"token",
",",
"'record'",
"=>",
"$",
"record",
")",
")",
";",
"return",
"true",
";",
"}"
] |
{@inheritDoc}
|
[
"{"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L143-L157
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.isTokenExpired
|
public function isTokenExpired(UserRegistrationInterface $record)
{
$expiryDate = new DateTime($this->getOptions()->getRequestExpiry() . ' seconds ago');
return $record->getRequestTime() < $expiryDate;
}
|
php
|
public function isTokenExpired(UserRegistrationInterface $record)
{
$expiryDate = new DateTime($this->getOptions()->getRequestExpiry() . ' seconds ago');
return $record->getRequestTime() < $expiryDate;
}
|
[
"public",
"function",
"isTokenExpired",
"(",
"UserRegistrationInterface",
"$",
"record",
")",
"{",
"$",
"expiryDate",
"=",
"new",
"DateTime",
"(",
"$",
"this",
"->",
"getOptions",
"(",
")",
"->",
"getRequestExpiry",
"(",
")",
".",
"' seconds ago'",
")",
";",
"return",
"$",
"record",
"->",
"getRequestTime",
"(",
")",
"<",
"$",
"expiryDate",
";",
"}"
] |
{@inheritDoc}
|
[
"{"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L162-L167
|
hrevert/HtUserRegistration
|
src/Service/UserRegistrationService.php
|
UserRegistrationService.setPassword
|
public function setPassword(array $data, UserRegistrationInterface $registrationRecord)
{
$newPass = $data['newCredential'];
$user = $registrationRecord->getUser();
$bcrypt = new Bcrypt;
$bcrypt->setCost($this->getZfcUserOptions()->getPasswordCost());
$pass = $bcrypt->create($newPass);
$user->setPassword($pass);
$this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'record' => $registrationRecord));
$this->getUserMapper()->update($user);
$registrationRecord->setResponded(UserRegistrationInterface::EMAIL_RESPONDED);
$this->getUserRegistrationMapper()->update($registrationRecord);
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user, 'record' => $registrationRecord));
}
|
php
|
public function setPassword(array $data, UserRegistrationInterface $registrationRecord)
{
$newPass = $data['newCredential'];
$user = $registrationRecord->getUser();
$bcrypt = new Bcrypt;
$bcrypt->setCost($this->getZfcUserOptions()->getPasswordCost());
$pass = $bcrypt->create($newPass);
$user->setPassword($pass);
$this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'record' => $registrationRecord));
$this->getUserMapper()->update($user);
$registrationRecord->setResponded(UserRegistrationInterface::EMAIL_RESPONDED);
$this->getUserRegistrationMapper()->update($registrationRecord);
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user, 'record' => $registrationRecord));
}
|
[
"public",
"function",
"setPassword",
"(",
"array",
"$",
"data",
",",
"UserRegistrationInterface",
"$",
"registrationRecord",
")",
"{",
"$",
"newPass",
"=",
"$",
"data",
"[",
"'newCredential'",
"]",
";",
"$",
"user",
"=",
"$",
"registrationRecord",
"->",
"getUser",
"(",
")",
";",
"$",
"bcrypt",
"=",
"new",
"Bcrypt",
";",
"$",
"bcrypt",
"->",
"setCost",
"(",
"$",
"this",
"->",
"getZfcUserOptions",
"(",
")",
"->",
"getPasswordCost",
"(",
")",
")",
";",
"$",
"pass",
"=",
"$",
"bcrypt",
"->",
"create",
"(",
"$",
"newPass",
")",
";",
"$",
"user",
"->",
"setPassword",
"(",
"$",
"pass",
")",
";",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"__FUNCTION__",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'record'",
"=>",
"$",
"registrationRecord",
")",
")",
";",
"$",
"this",
"->",
"getUserMapper",
"(",
")",
"->",
"update",
"(",
"$",
"user",
")",
";",
"$",
"registrationRecord",
"->",
"setResponded",
"(",
"UserRegistrationInterface",
"::",
"EMAIL_RESPONDED",
")",
";",
"$",
"this",
"->",
"getUserRegistrationMapper",
"(",
")",
"->",
"update",
"(",
"$",
"registrationRecord",
")",
";",
"$",
"this",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"__FUNCTION__",
".",
"'.post'",
",",
"$",
"this",
",",
"array",
"(",
"'user'",
"=>",
"$",
"user",
",",
"'record'",
"=>",
"$",
"registrationRecord",
")",
")",
";",
"}"
] |
{@inheritDoc}
|
[
"{"
] |
train
|
https://github.com/hrevert/HtUserRegistration/blob/6b4a0cc364153757290ab5eed9ffafe1228f3bd6/src/Service/UserRegistrationService.php#L172-L188
|
syhol/mrcolor
|
src/SyHolloway/MrColor/Extension.php
|
Extension.trigger
|
public function trigger(Color $color, $method, $args)
{
if (is_callable(array($this, $method))) {
array_unshift($args, $color);
return call_user_func_array(array($this, $method), $args);
}
return null;
}
|
php
|
public function trigger(Color $color, $method, $args)
{
if (is_callable(array($this, $method))) {
array_unshift($args, $color);
return call_user_func_array(array($this, $method), $args);
}
return null;
}
|
[
"public",
"function",
"trigger",
"(",
"Color",
"$",
"color",
",",
"$",
"method",
",",
"$",
"args",
")",
"{",
"if",
"(",
"is_callable",
"(",
"array",
"(",
"$",
"this",
",",
"$",
"method",
")",
")",
")",
"{",
"array_unshift",
"(",
"$",
"args",
",",
"$",
"color",
")",
";",
"return",
"call_user_func_array",
"(",
"array",
"(",
"$",
"this",
",",
"$",
"method",
")",
",",
"$",
"args",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Handel the method call.
@param Color $color the color object the function was called on
@param string $method the method name
@param array $args arguments
@return mixed this will be returned to the client code
|
[
"Handel",
"the",
"method",
"call",
"."
] |
train
|
https://github.com/syhol/mrcolor/blob/b0cfef8fa3dc52940ff6cb78d19a4fac9e02ef4d/src/SyHolloway/MrColor/Extension.php#L33-L42
|
phpalchemy/cerberus
|
src/Alchemy/Component/Cerberus/Model/Map/UserTableMap.php
|
UserTableMap.addSelectColumns
|
public static function addSelectColumns(Criteria $criteria, $alias = null)
{
if (null === $alias) {
$criteria->addSelectColumn(UserTableMap::COL_ID);
$criteria->addSelectColumn(UserTableMap::COL_USERNAME);
$criteria->addSelectColumn(UserTableMap::COL_PASSWORD);
$criteria->addSelectColumn(UserTableMap::COL_FIRST_NAME);
$criteria->addSelectColumn(UserTableMap::COL_LAST_NAME);
$criteria->addSelectColumn(UserTableMap::COL_CREATE_DATE);
$criteria->addSelectColumn(UserTableMap::COL_UPDATE_DATE);
$criteria->addSelectColumn(UserTableMap::COL_STATUS);
} else {
$criteria->addSelectColumn($alias . '.ID');
$criteria->addSelectColumn($alias . '.USERNAME');
$criteria->addSelectColumn($alias . '.PASSWORD');
$criteria->addSelectColumn($alias . '.FIRST_NAME');
$criteria->addSelectColumn($alias . '.LAST_NAME');
$criteria->addSelectColumn($alias . '.CREATE_DATE');
$criteria->addSelectColumn($alias . '.UPDATE_DATE');
$criteria->addSelectColumn($alias . '.STATUS');
}
}
|
php
|
public static function addSelectColumns(Criteria $criteria, $alias = null)
{
if (null === $alias) {
$criteria->addSelectColumn(UserTableMap::COL_ID);
$criteria->addSelectColumn(UserTableMap::COL_USERNAME);
$criteria->addSelectColumn(UserTableMap::COL_PASSWORD);
$criteria->addSelectColumn(UserTableMap::COL_FIRST_NAME);
$criteria->addSelectColumn(UserTableMap::COL_LAST_NAME);
$criteria->addSelectColumn(UserTableMap::COL_CREATE_DATE);
$criteria->addSelectColumn(UserTableMap::COL_UPDATE_DATE);
$criteria->addSelectColumn(UserTableMap::COL_STATUS);
} else {
$criteria->addSelectColumn($alias . '.ID');
$criteria->addSelectColumn($alias . '.USERNAME');
$criteria->addSelectColumn($alias . '.PASSWORD');
$criteria->addSelectColumn($alias . '.FIRST_NAME');
$criteria->addSelectColumn($alias . '.LAST_NAME');
$criteria->addSelectColumn($alias . '.CREATE_DATE');
$criteria->addSelectColumn($alias . '.UPDATE_DATE');
$criteria->addSelectColumn($alias . '.STATUS');
}
}
|
[
"public",
"static",
"function",
"addSelectColumns",
"(",
"Criteria",
"$",
"criteria",
",",
"$",
"alias",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"alias",
")",
"{",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_ID",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_USERNAME",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_PASSWORD",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_FIRST_NAME",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_LAST_NAME",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_CREATE_DATE",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_UPDATE_DATE",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"UserTableMap",
"::",
"COL_STATUS",
")",
";",
"}",
"else",
"{",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.ID'",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.USERNAME'",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.PASSWORD'",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.FIRST_NAME'",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.LAST_NAME'",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.CREATE_DATE'",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.UPDATE_DATE'",
")",
";",
"$",
"criteria",
"->",
"addSelectColumn",
"(",
"$",
"alias",
".",
"'.STATUS'",
")",
";",
"}",
"}"
] |
Add all the columns needed to create a new object.
Note: any columns that were marked with lazyLoad="true" in the
XML schema will not be added to the select list and only loaded
on demand.
@param Criteria $criteria object containing the columns to add.
@param string $alias optional table alias
@throws PropelException Any exceptions caught during processing will be
rethrown wrapped into a PropelException.
|
[
"Add",
"all",
"the",
"columns",
"needed",
"to",
"create",
"a",
"new",
"object",
"."
] |
train
|
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Map/UserTableMap.php#L331-L352
|
phpalchemy/cerberus
|
src/Alchemy/Component/Cerberus/Model/Map/UserTableMap.php
|
UserTableMap.buildTableMap
|
public static function buildTableMap()
{
$dbMap = Propel::getServiceContainer()->getDatabaseMap(UserTableMap::DATABASE_NAME);
if (!$dbMap->hasTable(UserTableMap::TABLE_NAME)) {
$dbMap->addTableObject(new UserTableMap());
}
}
|
php
|
public static function buildTableMap()
{
$dbMap = Propel::getServiceContainer()->getDatabaseMap(UserTableMap::DATABASE_NAME);
if (!$dbMap->hasTable(UserTableMap::TABLE_NAME)) {
$dbMap->addTableObject(new UserTableMap());
}
}
|
[
"public",
"static",
"function",
"buildTableMap",
"(",
")",
"{",
"$",
"dbMap",
"=",
"Propel",
"::",
"getServiceContainer",
"(",
")",
"->",
"getDatabaseMap",
"(",
"UserTableMap",
"::",
"DATABASE_NAME",
")",
";",
"if",
"(",
"!",
"$",
"dbMap",
"->",
"hasTable",
"(",
"UserTableMap",
"::",
"TABLE_NAME",
")",
")",
"{",
"$",
"dbMap",
"->",
"addTableObject",
"(",
"new",
"UserTableMap",
"(",
")",
")",
";",
"}",
"}"
] |
Add a TableMap instance to the database for this tableMap class.
|
[
"Add",
"a",
"TableMap",
"instance",
"to",
"the",
"database",
"for",
"this",
"tableMap",
"class",
"."
] |
train
|
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Map/UserTableMap.php#L369-L375
|
phpalchemy/cerberus
|
src/Alchemy/Component/Cerberus/Model/Map/UserTableMap.php
|
UserTableMap.doDelete
|
public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(UserTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \Alchemy\Component\Cerberus\Model\User) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(UserTableMap::DATABASE_NAME);
$criteria->add(UserTableMap::COL_ID, (array) $values, Criteria::IN);
}
$query = UserQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) {
UserTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) {
UserTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
}
|
php
|
public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(UserTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \Alchemy\Component\Cerberus\Model\User) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(UserTableMap::DATABASE_NAME);
$criteria->add(UserTableMap::COL_ID, (array) $values, Criteria::IN);
}
$query = UserQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) {
UserTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) {
UserTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
}
|
[
"public",
"static",
"function",
"doDelete",
"(",
"$",
"values",
",",
"ConnectionInterface",
"$",
"con",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"con",
")",
"{",
"$",
"con",
"=",
"Propel",
"::",
"getServiceContainer",
"(",
")",
"->",
"getWriteConnection",
"(",
"UserTableMap",
"::",
"DATABASE_NAME",
")",
";",
"}",
"if",
"(",
"$",
"values",
"instanceof",
"Criteria",
")",
"{",
"// rename for clarity",
"$",
"criteria",
"=",
"$",
"values",
";",
"}",
"elseif",
"(",
"$",
"values",
"instanceof",
"\\",
"Alchemy",
"\\",
"Component",
"\\",
"Cerberus",
"\\",
"Model",
"\\",
"User",
")",
"{",
"// it's a model object",
"// create criteria based on pk values",
"$",
"criteria",
"=",
"$",
"values",
"->",
"buildPkeyCriteria",
"(",
")",
";",
"}",
"else",
"{",
"// it's a primary key, or an array of pks",
"$",
"criteria",
"=",
"new",
"Criteria",
"(",
"UserTableMap",
"::",
"DATABASE_NAME",
")",
";",
"$",
"criteria",
"->",
"add",
"(",
"UserTableMap",
"::",
"COL_ID",
",",
"(",
"array",
")",
"$",
"values",
",",
"Criteria",
"::",
"IN",
")",
";",
"}",
"$",
"query",
"=",
"UserQuery",
"::",
"create",
"(",
")",
"->",
"mergeWith",
"(",
"$",
"criteria",
")",
";",
"if",
"(",
"$",
"values",
"instanceof",
"Criteria",
")",
"{",
"UserTableMap",
"::",
"clearInstancePool",
"(",
")",
";",
"}",
"elseif",
"(",
"!",
"is_object",
"(",
"$",
"values",
")",
")",
"{",
"// it's a primary key, or an array of pks",
"foreach",
"(",
"(",
"array",
")",
"$",
"values",
"as",
"$",
"singleval",
")",
"{",
"UserTableMap",
"::",
"removeInstanceFromPool",
"(",
"$",
"singleval",
")",
";",
"}",
"}",
"return",
"$",
"query",
"->",
"delete",
"(",
"$",
"con",
")",
";",
"}"
] |
Performs a DELETE on the database, given a User or Criteria object OR a primary key value.
@param mixed $values Criteria or User object or primary key or array of primary keys
which is used to create the DELETE statement
@param ConnectionInterface $con the connection to use
@return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
if supported by native driver or if emulated using Propel.
@throws PropelException Any exceptions caught during processing will be
rethrown wrapped into a PropelException.
|
[
"Performs",
"a",
"DELETE",
"on",
"the",
"database",
"given",
"a",
"User",
"or",
"Criteria",
"object",
"OR",
"a",
"primary",
"key",
"value",
"."
] |
train
|
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Map/UserTableMap.php#L388-L416
|
zrcing/phpenv
|
src/Phpenv/Env.php
|
Env.overload
|
public static function overload($envFile = ".env")
{
self::getLoader()->overloader = true;
self::getLoader()->innerLoad($envFile);
}
|
php
|
public static function overload($envFile = ".env")
{
self::getLoader()->overloader = true;
self::getLoader()->innerLoad($envFile);
}
|
[
"public",
"static",
"function",
"overload",
"(",
"$",
"envFile",
"=",
"\".env\"",
")",
"{",
"self",
"::",
"getLoader",
"(",
")",
"->",
"overloader",
"=",
"true",
";",
"self",
"::",
"getLoader",
"(",
")",
"->",
"innerLoad",
"(",
"$",
"envFile",
")",
";",
"}"
] |
Overload environment config
@param string $envFile Absolute path
|
[
"Overload",
"environment",
"config"
] |
train
|
https://github.com/zrcing/phpenv/blob/a2f8a5d88c92f0db99887f7501cb6274833d6d0b/src/Phpenv/Env.php#L48-L52
|
zrcing/phpenv
|
src/Phpenv/Env.php
|
Env.innerLoad
|
protected function innerLoad($envFile)
{
$this->lastEnvFile = $envFile;
if(!is_readable($this->lastEnvFile) || !is_file($this->lastEnvFile)) {
throw new InvalidArgumentException(sprintf('Phpenv: [%s] file not found or no readable', $this->lastEnvFile));
}
$this->envFiles[$envFile] = $envFile;
$systemAutoDetectLine = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$rows = file($this->lastEnvFile, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
ini_set('auto_detect_line_endings', $systemAutoDetectLine);
foreach ($rows as $row) {
$data = $this->filter($row);
if($data != null) {
list($key, $val) = $data;
$val = $this->handleSemanticsVar($val);
$this->setEnv($key, $val);
}
}
}
|
php
|
protected function innerLoad($envFile)
{
$this->lastEnvFile = $envFile;
if(!is_readable($this->lastEnvFile) || !is_file($this->lastEnvFile)) {
throw new InvalidArgumentException(sprintf('Phpenv: [%s] file not found or no readable', $this->lastEnvFile));
}
$this->envFiles[$envFile] = $envFile;
$systemAutoDetectLine = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$rows = file($this->lastEnvFile, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
ini_set('auto_detect_line_endings', $systemAutoDetectLine);
foreach ($rows as $row) {
$data = $this->filter($row);
if($data != null) {
list($key, $val) = $data;
$val = $this->handleSemanticsVar($val);
$this->setEnv($key, $val);
}
}
}
|
[
"protected",
"function",
"innerLoad",
"(",
"$",
"envFile",
")",
"{",
"$",
"this",
"->",
"lastEnvFile",
"=",
"$",
"envFile",
";",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"this",
"->",
"lastEnvFile",
")",
"||",
"!",
"is_file",
"(",
"$",
"this",
"->",
"lastEnvFile",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Phpenv: [%s] file not found or no readable'",
",",
"$",
"this",
"->",
"lastEnvFile",
")",
")",
";",
"}",
"$",
"this",
"->",
"envFiles",
"[",
"$",
"envFile",
"]",
"=",
"$",
"envFile",
";",
"$",
"systemAutoDetectLine",
"=",
"ini_get",
"(",
"'auto_detect_line_endings'",
")",
";",
"ini_set",
"(",
"'auto_detect_line_endings'",
",",
"'1'",
")",
";",
"$",
"rows",
"=",
"file",
"(",
"$",
"this",
"->",
"lastEnvFile",
",",
"FILE_SKIP_EMPTY_LINES",
"|",
"FILE_IGNORE_NEW_LINES",
")",
";",
"ini_set",
"(",
"'auto_detect_line_endings'",
",",
"$",
"systemAutoDetectLine",
")",
";",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"row",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"filter",
"(",
"$",
"row",
")",
";",
"if",
"(",
"$",
"data",
"!=",
"null",
")",
"{",
"list",
"(",
"$",
"key",
",",
"$",
"val",
")",
"=",
"$",
"data",
";",
"$",
"val",
"=",
"$",
"this",
"->",
"handleSemanticsVar",
"(",
"$",
"val",
")",
";",
"$",
"this",
"->",
"setEnv",
"(",
"$",
"key",
",",
"$",
"val",
")",
";",
"}",
"}",
"}"
] |
Inner load
@param string $envFile
@throws \InvalidArgumentException
|
[
"Inner",
"load"
] |
train
|
https://github.com/zrcing/phpenv/blob/a2f8a5d88c92f0db99887f7501cb6274833d6d0b/src/Phpenv/Env.php#L73-L95
|
zrcing/phpenv
|
src/Phpenv/Env.php
|
Env.filter
|
protected function filter($var)
{
switch (true) {
case strpos(trim($var), "#") === 0:
return null;
case strpos($var, "=") !== false:
list($key, $val) = array_map("trim", explode("=", $var ,2));
return array($key, $val);
default:
return null;
}
}
|
php
|
protected function filter($var)
{
switch (true) {
case strpos(trim($var), "#") === 0:
return null;
case strpos($var, "=") !== false:
list($key, $val) = array_map("trim", explode("=", $var ,2));
return array($key, $val);
default:
return null;
}
}
|
[
"protected",
"function",
"filter",
"(",
"$",
"var",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"strpos",
"(",
"trim",
"(",
"$",
"var",
")",
",",
"\"#\"",
")",
"===",
"0",
":",
"return",
"null",
";",
"case",
"strpos",
"(",
"$",
"var",
",",
"\"=\"",
")",
"!==",
"false",
":",
"list",
"(",
"$",
"key",
",",
"$",
"val",
")",
"=",
"array_map",
"(",
"\"trim\"",
",",
"explode",
"(",
"\"=\"",
",",
"$",
"var",
",",
"2",
")",
")",
";",
"return",
"array",
"(",
"$",
"key",
",",
"$",
"val",
")",
";",
"default",
":",
"return",
"null",
";",
"}",
"}"
] |
Filter
@param string $var
@return mixed
|
[
"Filter"
] |
train
|
https://github.com/zrcing/phpenv/blob/a2f8a5d88c92f0db99887f7501cb6274833d6d0b/src/Phpenv/Env.php#L103-L114
|
zrcing/phpenv
|
src/Phpenv/Env.php
|
Env.handleSemanticsVar
|
protected function handleSemanticsVar($var)
{
list($var) = array_map("trim", explode("#", $var));
switch (true) {
case $var === "":
return $var;
case is_numeric($var):
return $var;
default:
$beginStr = substr($var, 0, 1);
if (in_array($beginStr, array('\'','"')) && $beginStr == substr($var, -1, 1)) {
return substr($var, 1, -1);
}
return $var;
}
}
|
php
|
protected function handleSemanticsVar($var)
{
list($var) = array_map("trim", explode("#", $var));
switch (true) {
case $var === "":
return $var;
case is_numeric($var):
return $var;
default:
$beginStr = substr($var, 0, 1);
if (in_array($beginStr, array('\'','"')) && $beginStr == substr($var, -1, 1)) {
return substr($var, 1, -1);
}
return $var;
}
}
|
[
"protected",
"function",
"handleSemanticsVar",
"(",
"$",
"var",
")",
"{",
"list",
"(",
"$",
"var",
")",
"=",
"array_map",
"(",
"\"trim\"",
",",
"explode",
"(",
"\"#\"",
",",
"$",
"var",
")",
")",
";",
"switch",
"(",
"true",
")",
"{",
"case",
"$",
"var",
"===",
"\"\"",
":",
"return",
"$",
"var",
";",
"case",
"is_numeric",
"(",
"$",
"var",
")",
":",
"return",
"$",
"var",
";",
"default",
":",
"$",
"beginStr",
"=",
"substr",
"(",
"$",
"var",
",",
"0",
",",
"1",
")",
";",
"if",
"(",
"in_array",
"(",
"$",
"beginStr",
",",
"array",
"(",
"'\\''",
",",
"'\"'",
")",
")",
"&&",
"$",
"beginStr",
"==",
"substr",
"(",
"$",
"var",
",",
"-",
"1",
",",
"1",
")",
")",
"{",
"return",
"substr",
"(",
"$",
"var",
",",
"1",
",",
"-",
"1",
")",
";",
"}",
"return",
"$",
"var",
";",
"}",
"}"
] |
Resolve variables
@param string $var
@return string
|
[
"Resolve",
"variables"
] |
train
|
https://github.com/zrcing/phpenv/blob/a2f8a5d88c92f0db99887f7501cb6274833d6d0b/src/Phpenv/Env.php#L122-L137
|
zrcing/phpenv
|
src/Phpenv/Env.php
|
Env.setEnv
|
public static function setEnv($key, $val)
{
if (self::getLoader()->overloader == false) {
if(self::getEnv($key)) {
return;
}
}
putenv("{$key}={$val}");
$_ENV[$key] = $val;
$_SERVER[$key] = $val;
}
|
php
|
public static function setEnv($key, $val)
{
if (self::getLoader()->overloader == false) {
if(self::getEnv($key)) {
return;
}
}
putenv("{$key}={$val}");
$_ENV[$key] = $val;
$_SERVER[$key] = $val;
}
|
[
"public",
"static",
"function",
"setEnv",
"(",
"$",
"key",
",",
"$",
"val",
")",
"{",
"if",
"(",
"self",
"::",
"getLoader",
"(",
")",
"->",
"overloader",
"==",
"false",
")",
"{",
"if",
"(",
"self",
"::",
"getEnv",
"(",
"$",
"key",
")",
")",
"{",
"return",
";",
"}",
"}",
"putenv",
"(",
"\"{$key}={$val}\"",
")",
";",
"$",
"_ENV",
"[",
"$",
"key",
"]",
"=",
"$",
"val",
";",
"$",
"_SERVER",
"[",
"$",
"key",
"]",
"=",
"$",
"val",
";",
"}"
] |
Set environment
@param string $key
@param mixed $val
|
[
"Set",
"environment"
] |
train
|
https://github.com/zrcing/phpenv/blob/a2f8a5d88c92f0db99887f7501cb6274833d6d0b/src/Phpenv/Env.php#L145-L155
|
zrcing/phpenv
|
src/Phpenv/Env.php
|
Env.getEnv
|
public static function getEnv($key)
{
switch (true) {
case array_key_exists($key, $_ENV):
return $_ENV[$key];
case array_key_exists($key, $_SERVER);
return $_SERVER[$key];
default:
return getenv($key);
}
}
|
php
|
public static function getEnv($key)
{
switch (true) {
case array_key_exists($key, $_ENV):
return $_ENV[$key];
case array_key_exists($key, $_SERVER);
return $_SERVER[$key];
default:
return getenv($key);
}
}
|
[
"public",
"static",
"function",
"getEnv",
"(",
"$",
"key",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"_ENV",
")",
":",
"return",
"$",
"_ENV",
"[",
"$",
"key",
"]",
";",
"case",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"_SERVER",
")",
";",
"return",
"$",
"_SERVER",
"[",
"$",
"key",
"]",
";",
"default",
":",
"return",
"getenv",
"(",
"$",
"key",
")",
";",
"}",
"}"
] |
Get environment
@param string $key
@return mixed
|
[
"Get",
"environment"
] |
train
|
https://github.com/zrcing/phpenv/blob/a2f8a5d88c92f0db99887f7501cb6274833d6d0b/src/Phpenv/Env.php#L163-L173
|
sauls/helpers
|
src/Operation/ObjectOperation/DefineObject.php
|
DefineObject.execute
|
public function execute(object $object, array $properties, array $methodPrefixes = ['set', 'add']): object
{
try {
foreach ($properties as $property => $value) {
if (false === $this->assignValueWithSetterMethod($object, [$property, $value], $methodPrefixes)) {
$object->$property = $value;
}
}
return $object;
} catch (\Throwable $t) {
throw new PropertyNotAccessibleException($t->getMessage());
}
}
|
php
|
public function execute(object $object, array $properties, array $methodPrefixes = ['set', 'add']): object
{
try {
foreach ($properties as $property => $value) {
if (false === $this->assignValueWithSetterMethod($object, [$property, $value], $methodPrefixes)) {
$object->$property = $value;
}
}
return $object;
} catch (\Throwable $t) {
throw new PropertyNotAccessibleException($t->getMessage());
}
}
|
[
"public",
"function",
"execute",
"(",
"object",
"$",
"object",
",",
"array",
"$",
"properties",
",",
"array",
"$",
"methodPrefixes",
"=",
"[",
"'set'",
",",
"'add'",
"]",
")",
":",
"object",
"{",
"try",
"{",
"foreach",
"(",
"$",
"properties",
"as",
"$",
"property",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"assignValueWithSetterMethod",
"(",
"$",
"object",
",",
"[",
"$",
"property",
",",
"$",
"value",
"]",
",",
"$",
"methodPrefixes",
")",
")",
"{",
"$",
"object",
"->",
"$",
"property",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"object",
";",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"t",
")",
"{",
"throw",
"new",
"PropertyNotAccessibleException",
"(",
"$",
"t",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] |
@param object $object
@param array $properties
@param array $methodPrefixes
@return object
@throws PropertyNotAccessibleException
|
[
"@param",
"object",
"$object",
"@param",
"array",
"$properties",
"@param",
"array",
"$methodPrefixes"
] |
train
|
https://github.com/sauls/helpers/blob/de7dd250eb70ff10bada18acab8c7d8f27fad385/src/Operation/ObjectOperation/DefineObject.php#L29-L42
|
avoo/SerializerTranslation
|
Configuration/Metadata/Driver/AnnotationDriver.php
|
AnnotationDriver.loadMetadataForClass
|
public function loadMetadataForClass(\ReflectionClass $class)
{
$classMetadata = new ClassMetadata($class->getName());
foreach ($class->getProperties() as $reflectionProperty) {
$annotation = $this->reader->getPropertyAnnotation(
$reflectionProperty,
'Avoo\\SerializerTranslation\\Configuration\\Annotation\\Translate'
);
if (null === $annotation) {
continue;
}
$options = $this->createOptions($annotation);
$propertyMetadata = new VirtualPropertyMetadata($class->getName(), $reflectionProperty->getName(), $options);
$classMetadata->addPropertyToTranslate($propertyMetadata);
}
return $classMetadata;
}
|
php
|
public function loadMetadataForClass(\ReflectionClass $class)
{
$classMetadata = new ClassMetadata($class->getName());
foreach ($class->getProperties() as $reflectionProperty) {
$annotation = $this->reader->getPropertyAnnotation(
$reflectionProperty,
'Avoo\\SerializerTranslation\\Configuration\\Annotation\\Translate'
);
if (null === $annotation) {
continue;
}
$options = $this->createOptions($annotation);
$propertyMetadata = new VirtualPropertyMetadata($class->getName(), $reflectionProperty->getName(), $options);
$classMetadata->addPropertyToTranslate($propertyMetadata);
}
return $classMetadata;
}
|
[
"public",
"function",
"loadMetadataForClass",
"(",
"\\",
"ReflectionClass",
"$",
"class",
")",
"{",
"$",
"classMetadata",
"=",
"new",
"ClassMetadata",
"(",
"$",
"class",
"->",
"getName",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"class",
"->",
"getProperties",
"(",
")",
"as",
"$",
"reflectionProperty",
")",
"{",
"$",
"annotation",
"=",
"$",
"this",
"->",
"reader",
"->",
"getPropertyAnnotation",
"(",
"$",
"reflectionProperty",
",",
"'Avoo\\\\SerializerTranslation\\\\Configuration\\\\Annotation\\\\Translate'",
")",
";",
"if",
"(",
"null",
"===",
"$",
"annotation",
")",
"{",
"continue",
";",
"}",
"$",
"options",
"=",
"$",
"this",
"->",
"createOptions",
"(",
"$",
"annotation",
")",
";",
"$",
"propertyMetadata",
"=",
"new",
"VirtualPropertyMetadata",
"(",
"$",
"class",
"->",
"getName",
"(",
")",
",",
"$",
"reflectionProperty",
"->",
"getName",
"(",
")",
",",
"$",
"options",
")",
";",
"$",
"classMetadata",
"->",
"addPropertyToTranslate",
"(",
"$",
"propertyMetadata",
")",
";",
"}",
"return",
"$",
"classMetadata",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/avoo/SerializerTranslation/blob/e66de5482adb944197a36874465ef144b293a157/Configuration/Metadata/Driver/AnnotationDriver.php#L58-L78
|
avoo/SerializerTranslation
|
Configuration/Metadata/Driver/AnnotationDriver.php
|
AnnotationDriver.createOptions
|
private function createOptions(Translate $annotation)
{
$options = array();
if (isset($annotation->domain)) {
$options['domain'] = $annotation->domain;
}
if (isset($annotation->locale)) {
$options['locale'] = $annotation->locale;
}
foreach ($annotation->parameters as $key => $value) {
$options['parameters'][$key] = $value;
}
return $options;
}
|
php
|
private function createOptions(Translate $annotation)
{
$options = array();
if (isset($annotation->domain)) {
$options['domain'] = $annotation->domain;
}
if (isset($annotation->locale)) {
$options['locale'] = $annotation->locale;
}
foreach ($annotation->parameters as $key => $value) {
$options['parameters'][$key] = $value;
}
return $options;
}
|
[
"private",
"function",
"createOptions",
"(",
"Translate",
"$",
"annotation",
")",
"{",
"$",
"options",
"=",
"array",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"annotation",
"->",
"domain",
")",
")",
"{",
"$",
"options",
"[",
"'domain'",
"]",
"=",
"$",
"annotation",
"->",
"domain",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"annotation",
"->",
"locale",
")",
")",
"{",
"$",
"options",
"[",
"'locale'",
"]",
"=",
"$",
"annotation",
"->",
"locale",
";",
"}",
"foreach",
"(",
"$",
"annotation",
"->",
"parameters",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"options",
"[",
"'parameters'",
"]",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"options",
";",
"}"
] |
Create options
@param Translate $annotation
@return array
|
[
"Create",
"options"
] |
train
|
https://github.com/avoo/SerializerTranslation/blob/e66de5482adb944197a36874465ef144b293a157/Configuration/Metadata/Driver/AnnotationDriver.php#L87-L104
|
activecollab/databasemigrations
|
src/Command/All.php
|
All.execute
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$migrations = $this->getMigrations()->getMigrations();
if ($migrations_count = count($migrations)) {
$output->writeln('');
if ($migrations_count === 1) {
$output->writeln('<info>One migration</info> found:');
} else {
$output->writeln("<info>{$migrations_count} migrations</info> found:");
}
$output->writeln('');
foreach ($migrations as $migration) {
$execution_status = $this->getMigrations()->isExecuted($migration) ? '<info>Executed</info>' : '<comment>Not executed</comment>';
$output->writeln(' <comment>*</comment> ' . get_class($migration) . " ($execution_status)");
}
$output->writeln('');
} else {
$output->writeln('No migrations found');
}
return 0;
}
|
php
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$migrations = $this->getMigrations()->getMigrations();
if ($migrations_count = count($migrations)) {
$output->writeln('');
if ($migrations_count === 1) {
$output->writeln('<info>One migration</info> found:');
} else {
$output->writeln("<info>{$migrations_count} migrations</info> found:");
}
$output->writeln('');
foreach ($migrations as $migration) {
$execution_status = $this->getMigrations()->isExecuted($migration) ? '<info>Executed</info>' : '<comment>Not executed</comment>';
$output->writeln(' <comment>*</comment> ' . get_class($migration) . " ($execution_status)");
}
$output->writeln('');
} else {
$output->writeln('No migrations found');
}
return 0;
}
|
[
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"migrations",
"=",
"$",
"this",
"->",
"getMigrations",
"(",
")",
"->",
"getMigrations",
"(",
")",
";",
"if",
"(",
"$",
"migrations_count",
"=",
"count",
"(",
"$",
"migrations",
")",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"if",
"(",
"$",
"migrations_count",
"===",
"1",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'<info>One migration</info> found:'",
")",
";",
"}",
"else",
"{",
"$",
"output",
"->",
"writeln",
"(",
"\"<info>{$migrations_count} migrations</info> found:\"",
")",
";",
"}",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"foreach",
"(",
"$",
"migrations",
"as",
"$",
"migration",
")",
"{",
"$",
"execution_status",
"=",
"$",
"this",
"->",
"getMigrations",
"(",
")",
"->",
"isExecuted",
"(",
"$",
"migration",
")",
"?",
"'<info>Executed</info>'",
":",
"'<comment>Not executed</comment>'",
";",
"$",
"output",
"->",
"writeln",
"(",
"' <comment>*</comment> '",
".",
"get_class",
"(",
"$",
"migration",
")",
".",
"\" ($execution_status)\"",
")",
";",
"}",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"}",
"else",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'No migrations found'",
")",
";",
"}",
"return",
"0",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/activecollab/databasemigrations/blob/ef91d5b5f74d79b4a75695393eb25c7c47dad093/src/Command/All.php#L24-L49
|
yosmanyga/resource
|
src/Yosmanyga/Resource/Reader/Iterator/AnnotationFileReader.php
|
AnnotationFileReader.open
|
public function open(Resource $resource)
{
$file = $resource->getMetadata('file');
if (!is_file($file)) {
throw new \InvalidArgumentException(sprintf('File "%s" not found.', $file));
}
try {
$annotation = $resource->hasMetadata('annotation') ? $resource->getMetadata('annotation') : '';
$data = $this->getData($file, $annotation);
} catch (\Exception $e) {
throw new \InvalidArgumentException($e->getMessage(), 0, $e);
}
$this->inMemoryReader = new InMemoryReader();
$this->inMemoryReader->open(new Resource(['data' => $data], 'in_memory'));
}
|
php
|
public function open(Resource $resource)
{
$file = $resource->getMetadata('file');
if (!is_file($file)) {
throw new \InvalidArgumentException(sprintf('File "%s" not found.', $file));
}
try {
$annotation = $resource->hasMetadata('annotation') ? $resource->getMetadata('annotation') : '';
$data = $this->getData($file, $annotation);
} catch (\Exception $e) {
throw new \InvalidArgumentException($e->getMessage(), 0, $e);
}
$this->inMemoryReader = new InMemoryReader();
$this->inMemoryReader->open(new Resource(['data' => $data], 'in_memory'));
}
|
[
"public",
"function",
"open",
"(",
"Resource",
"$",
"resource",
")",
"{",
"$",
"file",
"=",
"$",
"resource",
"->",
"getMetadata",
"(",
"'file'",
")",
";",
"if",
"(",
"!",
"is_file",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'File \"%s\" not found.'",
",",
"$",
"file",
")",
")",
";",
"}",
"try",
"{",
"$",
"annotation",
"=",
"$",
"resource",
"->",
"hasMetadata",
"(",
"'annotation'",
")",
"?",
"$",
"resource",
"->",
"getMetadata",
"(",
"'annotation'",
")",
":",
"''",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"getData",
"(",
"$",
"file",
",",
"$",
"annotation",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"$",
"this",
"->",
"inMemoryReader",
"=",
"new",
"InMemoryReader",
"(",
")",
";",
"$",
"this",
"->",
"inMemoryReader",
"->",
"open",
"(",
"new",
"Resource",
"(",
"[",
"'data'",
"=>",
"$",
"data",
"]",
",",
"'in_memory'",
")",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/yosmanyga/resource/blob/a8b505c355920a908917a0484f764ddfa63205fa/src/Yosmanyga/Resource/Reader/Iterator/AnnotationFileReader.php#L44-L61
|
movoin/one-swoole
|
src/Console/Runner.php
|
Runner.runCommand
|
public function runCommand(...$cmds): array
{
$this->logger->notice('执行服务命令: ' . implode(' ', $cmds));
$command = array_merge([
Config::get('run_command'),
'server:run'
], $cmds);
$process = new Process(function ($worker) use ($command) {
$worker->exec(Config::get('php_bin', 'php'), $command);
}, true);
$process->start();
$this->logger->debug(
'命令: ' . Config::get('php_bin', 'php') . implode(' ', $command)
);
$recv = Process::wait();
$this->logger->debug('结果: ' . json_encode($recv));
return $recv;
}
|
php
|
public function runCommand(...$cmds): array
{
$this->logger->notice('执行服务命令: ' . implode(' ', $cmds));
$command = array_merge([
Config::get('run_command'),
'server:run'
], $cmds);
$process = new Process(function ($worker) use ($command) {
$worker->exec(Config::get('php_bin', 'php'), $command);
}, true);
$process->start();
$this->logger->debug(
'命令: ' . Config::get('php_bin', 'php') . implode(' ', $command)
);
$recv = Process::wait();
$this->logger->debug('结果: ' . json_encode($recv));
return $recv;
}
|
[
"public",
"function",
"runCommand",
"(",
"...",
"$",
"cmds",
")",
":",
"array",
"{",
"$",
"this",
"->",
"logger",
"->",
"notice",
"(",
"'执行服务命令: ' . implode('",
"'",
" $cmds)",
")",
";",
"",
"",
"",
"",
"",
"",
"$",
"command",
"=",
"array_merge",
"(",
"[",
"Config",
"::",
"get",
"(",
"'run_command'",
")",
",",
"'server:run'",
"]",
",",
"$",
"cmds",
")",
";",
"$",
"process",
"=",
"new",
"Process",
"(",
"function",
"(",
"$",
"worker",
")",
"use",
"(",
"$",
"command",
")",
"{",
"$",
"worker",
"->",
"exec",
"(",
"Config",
"::",
"get",
"(",
"'php_bin'",
",",
"'php'",
")",
",",
"$",
"command",
")",
";",
"}",
",",
"true",
")",
";",
"$",
"process",
"->",
"start",
"(",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'命令: ' . C",
"n",
"ig::ge",
"t(",
"'ph",
"p",
"_bin', 'p",
"h",
"') . ",
"i",
"p",
"ode(' '",
",",
" $c",
"o",
"m",
"and)",
"",
")",
";",
"$",
"recv",
"=",
"Process",
"::",
"wait",
"(",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'结果: ' . j",
"o",
"_encode($re",
"c",
"v",
"));",
"",
"",
"",
"return",
"$",
"recv",
";",
"}"
] |
执行命令
@param array $cmds
@return array
|
[
"执行命令"
] |
train
|
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Console/Runner.php#L48-L73
|
vincentchalamon/VinceCmsSonataAdminBundle
|
Admin/Entity/PublishableAdmin.php
|
PublishableAdmin.configureDatagridFilters
|
protected function configureDatagridFilters(DatagridMapper $mapper)
{
parent::configureDatagridFilters($mapper);
$mapper->add('publication', 'doctrine_orm_callback', array(
'label' => 'field.publication',
'callback' => function () {
$queryBuilder = func_get_arg(0);
$alias = func_get_arg(1);
$value = func_get_arg(3);
if (!$value) {
return;
}
switch ($value['value']) {
case 'Never published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->isNull(sprintf('%s.endedAt', $alias))
));
break;
case 'Published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNull(sprintf('%s.endedAt', $alias)),
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->lte(sprintf('%s.startedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
case 'Pre-published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->gt(sprintf('%s.startedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
case 'Post-published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->lt(sprintf('%s.startedAt', $alias), ':now'),
$queryBuilder->expr()->isNotNull(sprintf('%s.endedAt', $alias)),
$queryBuilder->expr()->lt(sprintf('%s.endedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
case 'Published temp':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->lte(sprintf('%s.startedAt', $alias), ':now'),
$queryBuilder->expr()->isNotNull(sprintf('%s.endedAt', $alias)),
$queryBuilder->expr()->gte(sprintf('%s.endedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
}
},
), 'choice', array(
'choices' => array(
'Never published' => $this->trans('Never published', array(), 'VinceCms'),
'Published' => $this->trans('Published', array(), 'VinceCms'),
'Pre-published' => $this->trans('Pre-published', array(), 'VinceCms'),
'Post-published' => $this->trans('Post-published', array(), 'VinceCms'),
'Published temp' => $this->trans('Published temp', array(), 'VinceCms'),
),
)
);
}
|
php
|
protected function configureDatagridFilters(DatagridMapper $mapper)
{
parent::configureDatagridFilters($mapper);
$mapper->add('publication', 'doctrine_orm_callback', array(
'label' => 'field.publication',
'callback' => function () {
$queryBuilder = func_get_arg(0);
$alias = func_get_arg(1);
$value = func_get_arg(3);
if (!$value) {
return;
}
switch ($value['value']) {
case 'Never published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->isNull(sprintf('%s.endedAt', $alias))
));
break;
case 'Published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNull(sprintf('%s.endedAt', $alias)),
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->lte(sprintf('%s.startedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
case 'Pre-published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->gt(sprintf('%s.startedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
case 'Post-published':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->lt(sprintf('%s.startedAt', $alias), ':now'),
$queryBuilder->expr()->isNotNull(sprintf('%s.endedAt', $alias)),
$queryBuilder->expr()->lt(sprintf('%s.endedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
case 'Published temp':
$queryBuilder->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull(sprintf('%s.startedAt', $alias)),
$queryBuilder->expr()->lte(sprintf('%s.startedAt', $alias), ':now'),
$queryBuilder->expr()->isNotNull(sprintf('%s.endedAt', $alias)),
$queryBuilder->expr()->gte(sprintf('%s.endedAt', $alias), ':now')
))->setParameter('now', new \DateTime());
break;
}
},
), 'choice', array(
'choices' => array(
'Never published' => $this->trans('Never published', array(), 'VinceCms'),
'Published' => $this->trans('Published', array(), 'VinceCms'),
'Pre-published' => $this->trans('Pre-published', array(), 'VinceCms'),
'Post-published' => $this->trans('Post-published', array(), 'VinceCms'),
'Published temp' => $this->trans('Published temp', array(), 'VinceCms'),
),
)
);
}
|
[
"protected",
"function",
"configureDatagridFilters",
"(",
"DatagridMapper",
"$",
"mapper",
")",
"{",
"parent",
"::",
"configureDatagridFilters",
"(",
"$",
"mapper",
")",
";",
"$",
"mapper",
"->",
"add",
"(",
"'publication'",
",",
"'doctrine_orm_callback'",
",",
"array",
"(",
"'label'",
"=>",
"'field.publication'",
",",
"'callback'",
"=>",
"function",
"(",
")",
"{",
"$",
"queryBuilder",
"=",
"func_get_arg",
"(",
"0",
")",
";",
"$",
"alias",
"=",
"func_get_arg",
"(",
"1",
")",
";",
"$",
"value",
"=",
"func_get_arg",
"(",
"3",
")",
";",
"if",
"(",
"!",
"$",
"value",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"$",
"value",
"[",
"'value'",
"]",
")",
"{",
"case",
"'Never published'",
":",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"andX",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNull",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNull",
"(",
"sprintf",
"(",
"'%s.endedAt'",
",",
"$",
"alias",
")",
")",
")",
")",
";",
"break",
";",
"case",
"'Published'",
":",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"andX",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNull",
"(",
"sprintf",
"(",
"'%s.endedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNotNull",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"lte",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
",",
"':now'",
")",
")",
")",
"->",
"setParameter",
"(",
"'now'",
",",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"break",
";",
"case",
"'Pre-published'",
":",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"andX",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNotNull",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"gt",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
",",
"':now'",
")",
")",
")",
"->",
"setParameter",
"(",
"'now'",
",",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"break",
";",
"case",
"'Post-published'",
":",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"andX",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNotNull",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"lt",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
",",
"':now'",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNotNull",
"(",
"sprintf",
"(",
"'%s.endedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"lt",
"(",
"sprintf",
"(",
"'%s.endedAt'",
",",
"$",
"alias",
")",
",",
"':now'",
")",
")",
")",
"->",
"setParameter",
"(",
"'now'",
",",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"break",
";",
"case",
"'Published temp'",
":",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"andX",
"(",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNotNull",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"lte",
"(",
"sprintf",
"(",
"'%s.startedAt'",
",",
"$",
"alias",
")",
",",
"':now'",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"isNotNull",
"(",
"sprintf",
"(",
"'%s.endedAt'",
",",
"$",
"alias",
")",
")",
",",
"$",
"queryBuilder",
"->",
"expr",
"(",
")",
"->",
"gte",
"(",
"sprintf",
"(",
"'%s.endedAt'",
",",
"$",
"alias",
")",
",",
"':now'",
")",
")",
")",
"->",
"setParameter",
"(",
"'now'",
",",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"break",
";",
"}",
"}",
",",
")",
",",
"'choice'",
",",
"array",
"(",
"'choices'",
"=>",
"array",
"(",
"'Never published'",
"=>",
"$",
"this",
"->",
"trans",
"(",
"'Never published'",
",",
"array",
"(",
")",
",",
"'VinceCms'",
")",
",",
"'Published'",
"=>",
"$",
"this",
"->",
"trans",
"(",
"'Published'",
",",
"array",
"(",
")",
",",
"'VinceCms'",
")",
",",
"'Pre-published'",
"=>",
"$",
"this",
"->",
"trans",
"(",
"'Pre-published'",
",",
"array",
"(",
")",
",",
"'VinceCms'",
")",
",",
"'Post-published'",
"=>",
"$",
"this",
"->",
"trans",
"(",
"'Post-published'",
",",
"array",
"(",
")",
",",
"'VinceCms'",
")",
",",
"'Published temp'",
"=>",
"$",
"this",
"->",
"trans",
"(",
"'Published temp'",
",",
"array",
"(",
")",
",",
"'VinceCms'",
")",
",",
")",
",",
")",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/vincentchalamon/VinceCmsSonataAdminBundle/blob/edc768061734a92ba116488dd7b61ad40af21ceb/Admin/Entity/PublishableAdmin.php#L66-L130
|
vincentchalamon/VinceCmsSonataAdminBundle
|
Admin/Entity/PublishableAdmin.php
|
PublishableAdmin.configureFormFields
|
protected function configureFormFields(FormMapper $mapper)
{
$mapper
->with('field.publication', array('class' => 'col-md-6'))
->add('startedAt', 'datepicker', array(
'label' => 'field.startedAt',
'required' => false,
)
)
->add('endedAt', 'datepicker', array(
'label' => 'field.endedAt',
'required' => false,
)
)
->end();
}
|
php
|
protected function configureFormFields(FormMapper $mapper)
{
$mapper
->with('field.publication', array('class' => 'col-md-6'))
->add('startedAt', 'datepicker', array(
'label' => 'field.startedAt',
'required' => false,
)
)
->add('endedAt', 'datepicker', array(
'label' => 'field.endedAt',
'required' => false,
)
)
->end();
}
|
[
"protected",
"function",
"configureFormFields",
"(",
"FormMapper",
"$",
"mapper",
")",
"{",
"$",
"mapper",
"->",
"with",
"(",
"'field.publication'",
",",
"array",
"(",
"'class'",
"=>",
"'col-md-6'",
")",
")",
"->",
"add",
"(",
"'startedAt'",
",",
"'datepicker'",
",",
"array",
"(",
"'label'",
"=>",
"'field.startedAt'",
",",
"'required'",
"=>",
"false",
",",
")",
")",
"->",
"add",
"(",
"'endedAt'",
",",
"'datepicker'",
",",
"array",
"(",
"'label'",
"=>",
"'field.endedAt'",
",",
"'required'",
"=>",
"false",
",",
")",
")",
"->",
"end",
"(",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/vincentchalamon/VinceCmsSonataAdminBundle/blob/edc768061734a92ba116488dd7b61ad40af21ceb/Admin/Entity/PublishableAdmin.php#L135-L150
|
acasademont/wurfl
|
WURFL/Storage/Memcache.php
|
WURFL_Storage_Memcache.initialize
|
final public function initialize()
{
$this->_ensureModuleExistence();
$this->memcache = new Memcache();
// support multiple hosts using semicolon to separate hosts
$hosts = explode(";", $this->host);
// different ports for each hosts the same way
$ports = explode(";", $this->port);
if (count($hosts) > 1) {
if (count($ports) < 1) {
$ports = array_fill(0, count($hosts), self::DEFAULT_PORT);
} elseif (count($ports) == 1) {
// if we have just one port, use it for all hosts
$_p = $ports[0];
$ports = array_fill(0, count($hosts), $_p);
}
foreach ($hosts as $i => $host) {
$this->memcache->addServer($host, $ports[$i]);
}
} else {
// just connect to the single host
$this->memcache->connect($hosts[0], $ports[0]);
}
}
|
php
|
final public function initialize()
{
$this->_ensureModuleExistence();
$this->memcache = new Memcache();
// support multiple hosts using semicolon to separate hosts
$hosts = explode(";", $this->host);
// different ports for each hosts the same way
$ports = explode(";", $this->port);
if (count($hosts) > 1) {
if (count($ports) < 1) {
$ports = array_fill(0, count($hosts), self::DEFAULT_PORT);
} elseif (count($ports) == 1) {
// if we have just one port, use it for all hosts
$_p = $ports[0];
$ports = array_fill(0, count($hosts), $_p);
}
foreach ($hosts as $i => $host) {
$this->memcache->addServer($host, $ports[$i]);
}
} else {
// just connect to the single host
$this->memcache->connect($hosts[0], $ports[0]);
}
}
|
[
"final",
"public",
"function",
"initialize",
"(",
")",
"{",
"$",
"this",
"->",
"_ensureModuleExistence",
"(",
")",
";",
"$",
"this",
"->",
"memcache",
"=",
"new",
"Memcache",
"(",
")",
";",
"// support multiple hosts using semicolon to separate hosts",
"$",
"hosts",
"=",
"explode",
"(",
"\";\"",
",",
"$",
"this",
"->",
"host",
")",
";",
"// different ports for each hosts the same way",
"$",
"ports",
"=",
"explode",
"(",
"\";\"",
",",
"$",
"this",
"->",
"port",
")",
";",
"if",
"(",
"count",
"(",
"$",
"hosts",
")",
">",
"1",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"ports",
")",
"<",
"1",
")",
"{",
"$",
"ports",
"=",
"array_fill",
"(",
"0",
",",
"count",
"(",
"$",
"hosts",
")",
",",
"self",
"::",
"DEFAULT_PORT",
")",
";",
"}",
"elseif",
"(",
"count",
"(",
"$",
"ports",
")",
"==",
"1",
")",
"{",
"// if we have just one port, use it for all hosts",
"$",
"_p",
"=",
"$",
"ports",
"[",
"0",
"]",
";",
"$",
"ports",
"=",
"array_fill",
"(",
"0",
",",
"count",
"(",
"$",
"hosts",
")",
",",
"$",
"_p",
")",
";",
"}",
"foreach",
"(",
"$",
"hosts",
"as",
"$",
"i",
"=>",
"$",
"host",
")",
"{",
"$",
"this",
"->",
"memcache",
"->",
"addServer",
"(",
"$",
"host",
",",
"$",
"ports",
"[",
"$",
"i",
"]",
")",
";",
"}",
"}",
"else",
"{",
"// just connect to the single host",
"$",
"this",
"->",
"memcache",
"->",
"connect",
"(",
"$",
"hosts",
"[",
"0",
"]",
",",
"$",
"ports",
"[",
"0",
"]",
")",
";",
"}",
"}"
] |
Initializes the Memcache Module
|
[
"Initializes",
"the",
"Memcache",
"Module"
] |
train
|
https://github.com/acasademont/wurfl/blob/0f4fb6e06b452ba95ad1d15e7d8226d0974b60c2/WURFL/Storage/Memcache.php#L64-L87
|
comelyio/comely
|
src/Comely/IO/Cache/Indexing.php
|
Indexing.load
|
public function load(): void
{
try {
$keys = $this->cache->get(self::INDEXING_KEY);
if ($keys instanceof Keys) {
$this->keys = $keys;
return;
}
} catch (CacheException $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
}
$this->keys = new Keys();
}
|
php
|
public function load(): void
{
try {
$keys = $this->cache->get(self::INDEXING_KEY);
if ($keys instanceof Keys) {
$this->keys = $keys;
return;
}
} catch (CacheException $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
}
$this->keys = new Keys();
}
|
[
"public",
"function",
"load",
"(",
")",
":",
"void",
"{",
"try",
"{",
"$",
"keys",
"=",
"$",
"this",
"->",
"cache",
"->",
"get",
"(",
"self",
"::",
"INDEXING_KEY",
")",
";",
"if",
"(",
"$",
"keys",
"instanceof",
"Keys",
")",
"{",
"$",
"this",
"->",
"keys",
"=",
"$",
"keys",
";",
"return",
";",
"}",
"}",
"catch",
"(",
"CacheException",
"$",
"e",
")",
"{",
"trigger_error",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"E_USER_WARNING",
")",
";",
"}",
"$",
"this",
"->",
"keys",
"=",
"new",
"Keys",
"(",
")",
";",
"}"
] |
Load stored keys from Cache or create new index
|
[
"Load",
"stored",
"keys",
"from",
"Cache",
"or",
"create",
"new",
"index"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Indexing.php#L61-L74
|
sulu/SuluPricingBundle
|
Pricing/GroupedItemsPriceCalculator.php
|
GroupedItemsPriceCalculator.calculate
|
public function calculate(
array $items,
$netShippingCosts,
array &$groupPrices = [],
array &$groupedItems = [],
$currency = null,
$taxfree = false
) {
$totalNetPriceExclShippingCosts = 0;
$totalPrice = 0;
$totalRecurringNetPrice = 0;
$totalRecurringPrice = 0;
$taxes = [];
if (!$currency) {
$currency = $this->defaultCurrencyCode;
}
/** @var CalculableBulkPriceItemInterface $item */
foreach ($items as $item) {
$itemTotalNetPrice = $this->itemPriceCalculator->calculateItemTotalNetPrice(
$item,
$currency,
$item->getUseProductsPrice()
);
// Add total-item-price to group.
$this->addPriceToPriceGroup($itemTotalNetPrice, $item, $groupPrices, $groupedItems);
// Calculate Taxes.
$taxValue = 0;
if (!$taxfree) {
$taxValue = $itemTotalNetPrice * $item->getTax() / 100.0;
$tax = (string)$item->getTax();
if (array_key_exists($tax, $taxes)) {
$taxes[$tax] = (float)$taxes[$tax] + $taxValue;
} else {
$taxes[$tax] = $taxValue;
}
}
// Add to total price.
if ($item->isRecurringPrice()) {
$totalRecurringNetPrice += $itemTotalNetPrice;
$totalRecurringPrice += $itemTotalNetPrice + $taxValue;
} else {
$totalNetPriceExclShippingCosts += $itemTotalNetPrice;
$totalPrice += $itemTotalNetPrice + $taxValue;
}
}
// Calculate shipping costs.
$shippingCostsTax = 0;
if (!$taxfree) {
/** @var CalculableBulkPriceItemInterface $item */
foreach ($items as $item) {
if (!$item->isRecurringPrice()) {
$itemTotalNetPrice = $this->itemPriceCalculator->calculateItemTotalNetPrice(
$item,
$currency,
$item->getUseProductsPrice()
);
$tax = (string)$item->getTax();
$ratio = 0;
if ($totalNetPriceExclShippingCosts != 0) {
$ratio = $itemTotalNetPrice / $totalNetPriceExclShippingCosts;
} else if (count($items) > 0) {
// Handle total net price of 0. Each item has the same ratio.
$ratio = 1 / count($items);
}
$taxValue = $ratio * $netShippingCosts * $item->getTax() / 100;
$taxes[$tax] += $taxValue;
$shippingCostsTax += $taxValue;
}
}
}
$shippingCosts = $netShippingCosts + $shippingCostsTax;
// Add net shipping costs to total prices.
$totalPrice += $shippingCosts;
$totalNetPrice = $totalNetPriceExclShippingCosts + $netShippingCosts;
return [
'totalNetPriceExclShippingCosts' => $totalNetPriceExclShippingCosts,
'totalNetPrice' => $totalNetPrice,
'totalPrice' => $totalPrice,
'totalRecurringNetPrice' => $totalRecurringNetPrice,
'totalRecurringPrice' => $totalRecurringPrice,
'shippingCosts' => $shippingCosts,
'taxes' => $taxes,
];
}
|
php
|
public function calculate(
array $items,
$netShippingCosts,
array &$groupPrices = [],
array &$groupedItems = [],
$currency = null,
$taxfree = false
) {
$totalNetPriceExclShippingCosts = 0;
$totalPrice = 0;
$totalRecurringNetPrice = 0;
$totalRecurringPrice = 0;
$taxes = [];
if (!$currency) {
$currency = $this->defaultCurrencyCode;
}
/** @var CalculableBulkPriceItemInterface $item */
foreach ($items as $item) {
$itemTotalNetPrice = $this->itemPriceCalculator->calculateItemTotalNetPrice(
$item,
$currency,
$item->getUseProductsPrice()
);
// Add total-item-price to group.
$this->addPriceToPriceGroup($itemTotalNetPrice, $item, $groupPrices, $groupedItems);
// Calculate Taxes.
$taxValue = 0;
if (!$taxfree) {
$taxValue = $itemTotalNetPrice * $item->getTax() / 100.0;
$tax = (string)$item->getTax();
if (array_key_exists($tax, $taxes)) {
$taxes[$tax] = (float)$taxes[$tax] + $taxValue;
} else {
$taxes[$tax] = $taxValue;
}
}
// Add to total price.
if ($item->isRecurringPrice()) {
$totalRecurringNetPrice += $itemTotalNetPrice;
$totalRecurringPrice += $itemTotalNetPrice + $taxValue;
} else {
$totalNetPriceExclShippingCosts += $itemTotalNetPrice;
$totalPrice += $itemTotalNetPrice + $taxValue;
}
}
// Calculate shipping costs.
$shippingCostsTax = 0;
if (!$taxfree) {
/** @var CalculableBulkPriceItemInterface $item */
foreach ($items as $item) {
if (!$item->isRecurringPrice()) {
$itemTotalNetPrice = $this->itemPriceCalculator->calculateItemTotalNetPrice(
$item,
$currency,
$item->getUseProductsPrice()
);
$tax = (string)$item->getTax();
$ratio = 0;
if ($totalNetPriceExclShippingCosts != 0) {
$ratio = $itemTotalNetPrice / $totalNetPriceExclShippingCosts;
} else if (count($items) > 0) {
// Handle total net price of 0. Each item has the same ratio.
$ratio = 1 / count($items);
}
$taxValue = $ratio * $netShippingCosts * $item->getTax() / 100;
$taxes[$tax] += $taxValue;
$shippingCostsTax += $taxValue;
}
}
}
$shippingCosts = $netShippingCosts + $shippingCostsTax;
// Add net shipping costs to total prices.
$totalPrice += $shippingCosts;
$totalNetPrice = $totalNetPriceExclShippingCosts + $netShippingCosts;
return [
'totalNetPriceExclShippingCosts' => $totalNetPriceExclShippingCosts,
'totalNetPrice' => $totalNetPrice,
'totalPrice' => $totalPrice,
'totalRecurringNetPrice' => $totalRecurringNetPrice,
'totalRecurringPrice' => $totalRecurringPrice,
'shippingCosts' => $shippingCosts,
'taxes' => $taxes,
];
}
|
[
"public",
"function",
"calculate",
"(",
"array",
"$",
"items",
",",
"$",
"netShippingCosts",
",",
"array",
"&",
"$",
"groupPrices",
"=",
"[",
"]",
",",
"array",
"&",
"$",
"groupedItems",
"=",
"[",
"]",
",",
"$",
"currency",
"=",
"null",
",",
"$",
"taxfree",
"=",
"false",
")",
"{",
"$",
"totalNetPriceExclShippingCosts",
"=",
"0",
";",
"$",
"totalPrice",
"=",
"0",
";",
"$",
"totalRecurringNetPrice",
"=",
"0",
";",
"$",
"totalRecurringPrice",
"=",
"0",
";",
"$",
"taxes",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"currency",
")",
"{",
"$",
"currency",
"=",
"$",
"this",
"->",
"defaultCurrencyCode",
";",
"}",
"/** @var CalculableBulkPriceItemInterface $item */",
"foreach",
"(",
"$",
"items",
"as",
"$",
"item",
")",
"{",
"$",
"itemTotalNetPrice",
"=",
"$",
"this",
"->",
"itemPriceCalculator",
"->",
"calculateItemTotalNetPrice",
"(",
"$",
"item",
",",
"$",
"currency",
",",
"$",
"item",
"->",
"getUseProductsPrice",
"(",
")",
")",
";",
"// Add total-item-price to group.",
"$",
"this",
"->",
"addPriceToPriceGroup",
"(",
"$",
"itemTotalNetPrice",
",",
"$",
"item",
",",
"$",
"groupPrices",
",",
"$",
"groupedItems",
")",
";",
"// Calculate Taxes.",
"$",
"taxValue",
"=",
"0",
";",
"if",
"(",
"!",
"$",
"taxfree",
")",
"{",
"$",
"taxValue",
"=",
"$",
"itemTotalNetPrice",
"*",
"$",
"item",
"->",
"getTax",
"(",
")",
"/",
"100.0",
";",
"$",
"tax",
"=",
"(",
"string",
")",
"$",
"item",
"->",
"getTax",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"tax",
",",
"$",
"taxes",
")",
")",
"{",
"$",
"taxes",
"[",
"$",
"tax",
"]",
"=",
"(",
"float",
")",
"$",
"taxes",
"[",
"$",
"tax",
"]",
"+",
"$",
"taxValue",
";",
"}",
"else",
"{",
"$",
"taxes",
"[",
"$",
"tax",
"]",
"=",
"$",
"taxValue",
";",
"}",
"}",
"// Add to total price.",
"if",
"(",
"$",
"item",
"->",
"isRecurringPrice",
"(",
")",
")",
"{",
"$",
"totalRecurringNetPrice",
"+=",
"$",
"itemTotalNetPrice",
";",
"$",
"totalRecurringPrice",
"+=",
"$",
"itemTotalNetPrice",
"+",
"$",
"taxValue",
";",
"}",
"else",
"{",
"$",
"totalNetPriceExclShippingCosts",
"+=",
"$",
"itemTotalNetPrice",
";",
"$",
"totalPrice",
"+=",
"$",
"itemTotalNetPrice",
"+",
"$",
"taxValue",
";",
"}",
"}",
"// Calculate shipping costs.",
"$",
"shippingCostsTax",
"=",
"0",
";",
"if",
"(",
"!",
"$",
"taxfree",
")",
"{",
"/** @var CalculableBulkPriceItemInterface $item */",
"foreach",
"(",
"$",
"items",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"!",
"$",
"item",
"->",
"isRecurringPrice",
"(",
")",
")",
"{",
"$",
"itemTotalNetPrice",
"=",
"$",
"this",
"->",
"itemPriceCalculator",
"->",
"calculateItemTotalNetPrice",
"(",
"$",
"item",
",",
"$",
"currency",
",",
"$",
"item",
"->",
"getUseProductsPrice",
"(",
")",
")",
";",
"$",
"tax",
"=",
"(",
"string",
")",
"$",
"item",
"->",
"getTax",
"(",
")",
";",
"$",
"ratio",
"=",
"0",
";",
"if",
"(",
"$",
"totalNetPriceExclShippingCosts",
"!=",
"0",
")",
"{",
"$",
"ratio",
"=",
"$",
"itemTotalNetPrice",
"/",
"$",
"totalNetPriceExclShippingCosts",
";",
"}",
"else",
"if",
"(",
"count",
"(",
"$",
"items",
")",
">",
"0",
")",
"{",
"// Handle total net price of 0. Each item has the same ratio.",
"$",
"ratio",
"=",
"1",
"/",
"count",
"(",
"$",
"items",
")",
";",
"}",
"$",
"taxValue",
"=",
"$",
"ratio",
"*",
"$",
"netShippingCosts",
"*",
"$",
"item",
"->",
"getTax",
"(",
")",
"/",
"100",
";",
"$",
"taxes",
"[",
"$",
"tax",
"]",
"+=",
"$",
"taxValue",
";",
"$",
"shippingCostsTax",
"+=",
"$",
"taxValue",
";",
"}",
"}",
"}",
"$",
"shippingCosts",
"=",
"$",
"netShippingCosts",
"+",
"$",
"shippingCostsTax",
";",
"// Add net shipping costs to total prices.",
"$",
"totalPrice",
"+=",
"$",
"shippingCosts",
";",
"$",
"totalNetPrice",
"=",
"$",
"totalNetPriceExclShippingCosts",
"+",
"$",
"netShippingCosts",
";",
"return",
"[",
"'totalNetPriceExclShippingCosts'",
"=>",
"$",
"totalNetPriceExclShippingCosts",
",",
"'totalNetPrice'",
"=>",
"$",
"totalNetPrice",
",",
"'totalPrice'",
"=>",
"$",
"totalPrice",
",",
"'totalRecurringNetPrice'",
"=>",
"$",
"totalRecurringNetPrice",
",",
"'totalRecurringPrice'",
"=>",
"$",
"totalRecurringPrice",
",",
"'shippingCosts'",
"=>",
"$",
"shippingCosts",
",",
"'taxes'",
"=>",
"$",
"taxes",
",",
"]",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/sulu/SuluPricingBundle/blob/cd65f823c7c72992d0e423ee758a61f951f1d7d9/Pricing/GroupedItemsPriceCalculator.php#L43-L136
|
harp-orm/query
|
src/Compiler/Direction.php
|
Direction.render
|
public static function render(SQL\Direction $item)
{
return Compiler::expression(array(
Compiler::name($item->getContent()),
$item->getDirection(),
));
}
|
php
|
public static function render(SQL\Direction $item)
{
return Compiler::expression(array(
Compiler::name($item->getContent()),
$item->getDirection(),
));
}
|
[
"public",
"static",
"function",
"render",
"(",
"SQL",
"\\",
"Direction",
"$",
"item",
")",
"{",
"return",
"Compiler",
"::",
"expression",
"(",
"array",
"(",
"Compiler",
"::",
"name",
"(",
"$",
"item",
"->",
"getContent",
"(",
")",
")",
",",
"$",
"item",
"->",
"getDirection",
"(",
")",
",",
")",
")",
";",
"}"
] |
Render a Direction object
@param SQL\Direction $item
@return string
|
[
"Render",
"a",
"Direction",
"object"
] |
train
|
https://github.com/harp-orm/query/blob/98ce2468a0a31fe15ed3692bad32547bf6dbe41a/src/Compiler/Direction.php#L32-L38
|
stubbles/stubbles-webapp-core
|
src/main/php/session/storage/ArraySessionStorage.php
|
ArraySessionStorage.putValue
|
public function putValue(string $key, $value): SessionStorage
{
$this->data[$key] = $value;
return $this;
}
|
php
|
public function putValue(string $key, $value): SessionStorage
{
$this->data[$key] = $value;
return $this;
}
|
[
"public",
"function",
"putValue",
"(",
"string",
"$",
"key",
",",
"$",
"value",
")",
":",
"SessionStorage",
"{",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] |
stores a value associated with the key
@param string $key key to store value under
@param mixed $value data to store
@return \stubbles\webapp\session\storage\SessionStorage
|
[
"stores",
"a",
"value",
"associated",
"with",
"the",
"key"
] |
train
|
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/session/storage/ArraySessionStorage.php#L75-L79
|
pageon/SlackWebhookMonolog
|
src/Slack/Attachment/BasicInfoAttachment.php
|
BasicInfoAttachment.addRecordDataAsJsonEncodedField
|
private function addRecordDataAsJsonEncodedField($key, $label)
{
if (!empty($this->record[$key])) {
$this->addField(new Field($label, json_encode($this->record[$key])));
}
}
|
php
|
private function addRecordDataAsJsonEncodedField($key, $label)
{
if (!empty($this->record[$key])) {
$this->addField(new Field($label, json_encode($this->record[$key])));
}
}
|
[
"private",
"function",
"addRecordDataAsJsonEncodedField",
"(",
"$",
"key",
",",
"$",
"label",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"record",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"this",
"->",
"addField",
"(",
"new",
"Field",
"(",
"$",
"label",
",",
"json_encode",
"(",
"$",
"this",
"->",
"record",
"[",
"$",
"key",
"]",
")",
")",
")",
";",
"}",
"}"
] |
Check if a key is available in the record. If so, add it as a field.
@param string $key
@param string $label
|
[
"Check",
"if",
"a",
"key",
"is",
"available",
"in",
"the",
"record",
".",
"If",
"so",
"add",
"it",
"as",
"a",
"field",
"."
] |
train
|
https://github.com/pageon/SlackWebhookMonolog/blob/6755060ddd6429620fd4c7decbb95f05463fc36b/src/Slack/Attachment/BasicInfoAttachment.php#L64-L69
|
pageon/SlackWebhookMonolog
|
src/Slack/Attachment/BasicInfoAttachment.php
|
BasicInfoAttachment.getColourForLoggerLevel
|
private function getColourForLoggerLevel()
{
switch (true) {
case $this->record['level'] >= Logger::ERROR:
return new Colour('danger');
case $this->record['level'] >= Logger::WARNING:
return new Colour('warning');
case $this->record['level'] >= Logger::INFO:
return new Colour('good');
default:
return new Colour('#e3e4e6');
}
}
|
php
|
private function getColourForLoggerLevel()
{
switch (true) {
case $this->record['level'] >= Logger::ERROR:
return new Colour('danger');
case $this->record['level'] >= Logger::WARNING:
return new Colour('warning');
case $this->record['level'] >= Logger::INFO:
return new Colour('good');
default:
return new Colour('#e3e4e6');
}
}
|
[
"private",
"function",
"getColourForLoggerLevel",
"(",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"$",
"this",
"->",
"record",
"[",
"'level'",
"]",
">=",
"Logger",
"::",
"ERROR",
":",
"return",
"new",
"Colour",
"(",
"'danger'",
")",
";",
"case",
"$",
"this",
"->",
"record",
"[",
"'level'",
"]",
">=",
"Logger",
"::",
"WARNING",
":",
"return",
"new",
"Colour",
"(",
"'warning'",
")",
";",
"case",
"$",
"this",
"->",
"record",
"[",
"'level'",
"]",
">=",
"Logger",
"::",
"INFO",
":",
"return",
"new",
"Colour",
"(",
"'good'",
")",
";",
"default",
":",
"return",
"new",
"Colour",
"(",
"'#e3e4e6'",
")",
";",
"}",
"}"
] |
Returned a Slack message attachment color associated with
provided level.
@return Colour
|
[
"Returned",
"a",
"Slack",
"message",
"attachment",
"color",
"associated",
"with",
"provided",
"level",
"."
] |
train
|
https://github.com/pageon/SlackWebhookMonolog/blob/6755060ddd6429620fd4c7decbb95f05463fc36b/src/Slack/Attachment/BasicInfoAttachment.php#L77-L89
|
nicolasmure/NmureEncryptor
|
src/Encryptor.php
|
Encryptor.encrypt
|
public function encrypt($data)
{
if (!$this->iv || $this->autoIvUpdate) {
$this->generateIv();
}
$output = openssl_encrypt($data, $this->cipher, $this->secret, OPENSSL_RAW_DATA, $this->iv);
if ($this->formatter) {
$output = $this->formatter->format($this->iv, $output);
}
return $output;
}
|
php
|
public function encrypt($data)
{
if (!$this->iv || $this->autoIvUpdate) {
$this->generateIv();
}
$output = openssl_encrypt($data, $this->cipher, $this->secret, OPENSSL_RAW_DATA, $this->iv);
if ($this->formatter) {
$output = $this->formatter->format($this->iv, $output);
}
return $output;
}
|
[
"public",
"function",
"encrypt",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"iv",
"||",
"$",
"this",
"->",
"autoIvUpdate",
")",
"{",
"$",
"this",
"->",
"generateIv",
"(",
")",
";",
"}",
"$",
"output",
"=",
"openssl_encrypt",
"(",
"$",
"data",
",",
"$",
"this",
"->",
"cipher",
",",
"$",
"this",
"->",
"secret",
",",
"OPENSSL_RAW_DATA",
",",
"$",
"this",
"->",
"iv",
")",
";",
"if",
"(",
"$",
"this",
"->",
"formatter",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"formatter",
"->",
"format",
"(",
"$",
"this",
"->",
"iv",
",",
"$",
"output",
")",
";",
"}",
"return",
"$",
"output",
";",
"}"
] |
@param string $data Data to encrypt.
@return string Encrypted data, or encrypted and formatted data
when a formatter has been provided.
|
[
"@param",
"string",
"$data",
"Data",
"to",
"encrypt",
"."
] |
train
|
https://github.com/nicolasmure/NmureEncryptor/blob/571b5311e7230f5a1241706edacbb2346624634d/src/Encryptor.php#L66-L79
|
nicolasmure/NmureEncryptor
|
src/Encryptor.php
|
Encryptor.decrypt
|
public function decrypt($data)
{
if ($this->formatter) {
$parsed = $this->formatter->parse($data, $this->getIvLength());
$this->iv = $parsed[FormatterInterface::KEY_IV];
$data = $parsed[FormatterInterface::KEY_DATA];
}
if (!$this->iv) {
throw new DecryptException('No Initialization Vector set to this encryptor : unable to decrypt data');
}
return openssl_decrypt($data, $this->cipher, $this->secret, OPENSSL_RAW_DATA, $this->iv);
}
|
php
|
public function decrypt($data)
{
if ($this->formatter) {
$parsed = $this->formatter->parse($data, $this->getIvLength());
$this->iv = $parsed[FormatterInterface::KEY_IV];
$data = $parsed[FormatterInterface::KEY_DATA];
}
if (!$this->iv) {
throw new DecryptException('No Initialization Vector set to this encryptor : unable to decrypt data');
}
return openssl_decrypt($data, $this->cipher, $this->secret, OPENSSL_RAW_DATA, $this->iv);
}
|
[
"public",
"function",
"decrypt",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"formatter",
")",
"{",
"$",
"parsed",
"=",
"$",
"this",
"->",
"formatter",
"->",
"parse",
"(",
"$",
"data",
",",
"$",
"this",
"->",
"getIvLength",
"(",
")",
")",
";",
"$",
"this",
"->",
"iv",
"=",
"$",
"parsed",
"[",
"FormatterInterface",
"::",
"KEY_IV",
"]",
";",
"$",
"data",
"=",
"$",
"parsed",
"[",
"FormatterInterface",
"::",
"KEY_DATA",
"]",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"iv",
")",
"{",
"throw",
"new",
"DecryptException",
"(",
"'No Initialization Vector set to this encryptor : unable to decrypt data'",
")",
";",
"}",
"return",
"openssl_decrypt",
"(",
"$",
"data",
",",
"$",
"this",
"->",
"cipher",
",",
"$",
"this",
"->",
"secret",
",",
"OPENSSL_RAW_DATA",
",",
"$",
"this",
"->",
"iv",
")",
";",
"}"
] |
@param string $data When a formatter is set to this encryptor,
the $data should be the formetted string by the formatter.
When no formatter is used, the $data should be the raw encrypted
data returned by this encryptor.
@throws DecryptException When not able to decrypt the given data.
@return string Decrypted data.
|
[
"@param",
"string",
"$data",
"When",
"a",
"formatter",
"is",
"set",
"to",
"this",
"encryptor",
"the",
"$data",
"should",
"be",
"the",
"formetted",
"string",
"by",
"the",
"formatter",
".",
"When",
"no",
"formatter",
"is",
"used",
"the",
"$data",
"should",
"be",
"the",
"raw",
"encrypted",
"data",
"returned",
"by",
"this",
"encryptor",
"."
] |
train
|
https://github.com/nicolasmure/NmureEncryptor/blob/571b5311e7230f5a1241706edacbb2346624634d/src/Encryptor.php#L91-L104
|
nicolasmure/NmureEncryptor
|
src/Encryptor.php
|
Encryptor.turnHexKeyToBin
|
public function turnHexKeyToBin()
{
if (!ctype_xdigit($this->secret)) {
throw new InvalidSecretKeyException(sprintf('The secret key "%s" is not a hex key', $this->secret));
}
$this->secret = hex2bin($this->secret);
}
|
php
|
public function turnHexKeyToBin()
{
if (!ctype_xdigit($this->secret)) {
throw new InvalidSecretKeyException(sprintf('The secret key "%s" is not a hex key', $this->secret));
}
$this->secret = hex2bin($this->secret);
}
|
[
"public",
"function",
"turnHexKeyToBin",
"(",
")",
"{",
"if",
"(",
"!",
"ctype_xdigit",
"(",
"$",
"this",
"->",
"secret",
")",
")",
"{",
"throw",
"new",
"InvalidSecretKeyException",
"(",
"sprintf",
"(",
"'The secret key \"%s\" is not a hex key'",
",",
"$",
"this",
"->",
"secret",
")",
")",
";",
"}",
"$",
"this",
"->",
"secret",
"=",
"hex2bin",
"(",
"$",
"this",
"->",
"secret",
")",
";",
"}"
] |
Turns the secret hex key into a binary key.
@throws InvalidSecretKeyException When the secret key is not a hex key.
|
[
"Turns",
"the",
"secret",
"hex",
"key",
"into",
"a",
"binary",
"key",
"."
] |
train
|
https://github.com/nicolasmure/NmureEncryptor/blob/571b5311e7230f5a1241706edacbb2346624634d/src/Encryptor.php#L143-L150
|
AbuseIO/notification-mail
|
src/Mail.php
|
Mail.send
|
public function send($notifications)
{
$anonymize_domain = env('GDPR_ANONYMIZE_DOMAIN', 'example.com');
foreach ($notifications as $customerReference => $notificationTypes) {
$mails = [];
$tickets = [];
$accounts = [];
foreach ($notificationTypes as $notificationType => $tickets) {
foreach ($tickets as $ticket) {
$token['ip'] = $ticket->ash_token_ip;
$token['domain'] = $ticket->ash_token_domain;
$ashUrl = config('main.ash.url') . 'collect/' . $ticket->id . '/';
$this->addIodefObject($ticket, $token[$notificationType], $ashUrl);
$box = [
'ticket_notification_type' => $notificationType,
'ip_contact_ash_link' => $ashUrl . $token['ip'],
'domain_contact_ash_link' => $ashUrl . $token['domain'],
'ticket_number' => $ticket->id,
'ticket_ip' => $ticket->ip,
'ticket_domain' => $ticket->domain,
'ticket_type_name' => trans("types.type.{$ticket->type_id}.name"),
'ticket_type_description' => trans("types.type.{$ticket->type_id}.description"),
'ticket_class_name' => trans("classifications.{$ticket->class_id}.name"),
'ticket_event_count' => $ticket->events->count(),
];
/*
* Even that all these tickets relate to the same customer reference, the contacts might be
* changed (added addresses, etc) for a specific ticket. To make sure people only get their own
* notificiations we aggregate them here before sending.
*/
if ($notificationType == 'ip') {
$recipient = $ticket->ip_contact_email;
$mails[$recipient][] = $box;
$accounts[$recipient] = Account::find($ticket->ip_contact_account_id);
}
if ($notificationType == 'domain') {
$recipient = $ticket->domain_contact_email;
$mails[$recipient][] = $box;
$accounts[$recipient] = Account::find($ticket->domain_contact_account_id);
}
}
}
foreach ($mails as $recipient => $boxes) {
if (!empty($boxes)) {
// create a new message
$message = Swift_Message::newInstance();
// create the src url for the active brand logo
if (!empty($accounts[$recipient]))
{
$account = $accounts[$recipient];
} else {
$account = Account::getSystemAccount();
}
$logo_url = URL::to('/ash/logo/' . $account->brand_id);
$brand = $account->brand;
$replacements = [
'boxes' => $boxes,
'ticket_count' => count($tickets),
'logo_src' => $logo_url,
];
$subject = config("{$this->configBase}.templates.subject");
$htmlmail = config("{$this->configBase}.templates.html_mail");
$plainmail = config("{$this->configBase}.templates.plain_mail");
// render the default templates
if(!empty($htmlmail)) {
$htmlmail = view(['template' => $htmlmail], $replacements)->render();
} else {
Log::warning("Incorrect template, it does not exist");
}
if(!empty($plainmail)) {
$plainmail = view(['template' => $plainmail], $replacements)->render();
} else {
Log::warning("Incorrect template, it does not exist");
}
// if the current brand has custom mail template, use them
if ($brand->mail_custom_template) {
// defensive programming, doubble check the templates
$validator = \Validator::make(
[
'html' => $brand->mail_template_html,
'plain' => $brand->mail_template_plain,
],
[
'html' => 'required|bladetemplate',
'plain' => 'required|bladetemplate',
]);
if ($validator->passes()) {
try {
// only use the templates if they pass the validation
$htmloutput = view(['template' => $brand->mail_template_html], $replacements)->render();
$plainoutput = view(['template' => $brand->mail_template_plain], $replacements)->render();
// no errors occurred while rendering
$htmlmail = $htmloutput;
$plainmail = $plainoutput;
} catch (\ErrorException $e) {
Log::warning("Incorrect template, falling back to default: " . $e->getMessage());
}
}
}
$iodef = new Iodef\Writer();
$iodef->formatOutput = true;
$iodef->write(
[
[
'name' => 'IODEF-Document',
'attributes' => $this->iodefDocument->getAttributes(),
'value' => $this->iodefDocument,
]
]
);
$XmlAttachmentData = $iodef->outputMemory();
if (!empty(Config::get('mail.smime.enabled')) &&
(Config::get('mail.smime.enabled')) === true &&
!empty(Config::get('mail.smime.certificate')) &&
!empty(Config::get('mail.smime.key')) &&
is_file(Config::get('mail.smime.certificate')) &&
is_file(Config::get('mail.smime.key'))
) {
$smimeSigner = Swift_Signers_SMimeSigner::newInstance();
$smimeSigner->setSignCertificate(
Config::get('mail.smime.certificate'),
Config::get('mail.smime.key')
);
$message->attachSigner($smimeSigner);
}
$message->setFrom(
[
Config::get('main.notifications.from_address') =>
Config::get('main.notifications.from_name')
]
);
if (!empty(Config::get('mail.override_address'))) {
$message->setTo([Config::get('mail.override_address')]);
} else {
$message->setTo(explode(',', $recipient));
}
if (!empty(Config::get('main.notifications.bcc_enabled'))) {
$message->setBcc([(Config::get('main.notifications.bcc_address'))]);
}
$message->setPriority(1);
$message->setSubject($subject);
if(config("{$this->configBase}.notification.prefer_html_body")) {
$message->setBody($htmlmail, 'text/html');
if(config("{$this->configBase}.notification.text_part_enabled")) {
$message->addPart($plainmail, 'text/plain');
}
} else {
$message->setBody($plainmail, 'text/plain');
if(config("{$this->configBase}.notification.html_part_enabled")) {
$message->addPart($htmlmail, 'text/html');
}
}
$message->attach(
Swift_Attachment::newInstance(gzencode($XmlAttachmentData), 'iodef.xml.gz', 'application/gzip')
);
$transport = Swift_SmtpTransport::newInstance();
$transport->setHost(config('mail.host'));
$transport->setPort(config('mail.port'));
$transport->setUsername(config('mail.username'));
$transport->setPassword(config('mail.password'));
$transport->setEncryption(config('mail.encryption'));
$mailer = Swift_Mailer::newInstance($transport);
// only really send if the email address isn't anonymized
$regexp = '/@'.$anonymize_domain.'$/';
if (preg_match($regexp, $recipient) !== 1) {
if (!$mailer->send($message)) {
return $this->failed("Error while sending message to {$recipient}");
}
}
}
}
}
return $this->success();
}
|
php
|
public function send($notifications)
{
$anonymize_domain = env('GDPR_ANONYMIZE_DOMAIN', 'example.com');
foreach ($notifications as $customerReference => $notificationTypes) {
$mails = [];
$tickets = [];
$accounts = [];
foreach ($notificationTypes as $notificationType => $tickets) {
foreach ($tickets as $ticket) {
$token['ip'] = $ticket->ash_token_ip;
$token['domain'] = $ticket->ash_token_domain;
$ashUrl = config('main.ash.url') . 'collect/' . $ticket->id . '/';
$this->addIodefObject($ticket, $token[$notificationType], $ashUrl);
$box = [
'ticket_notification_type' => $notificationType,
'ip_contact_ash_link' => $ashUrl . $token['ip'],
'domain_contact_ash_link' => $ashUrl . $token['domain'],
'ticket_number' => $ticket->id,
'ticket_ip' => $ticket->ip,
'ticket_domain' => $ticket->domain,
'ticket_type_name' => trans("types.type.{$ticket->type_id}.name"),
'ticket_type_description' => trans("types.type.{$ticket->type_id}.description"),
'ticket_class_name' => trans("classifications.{$ticket->class_id}.name"),
'ticket_event_count' => $ticket->events->count(),
];
/*
* Even that all these tickets relate to the same customer reference, the contacts might be
* changed (added addresses, etc) for a specific ticket. To make sure people only get their own
* notificiations we aggregate them here before sending.
*/
if ($notificationType == 'ip') {
$recipient = $ticket->ip_contact_email;
$mails[$recipient][] = $box;
$accounts[$recipient] = Account::find($ticket->ip_contact_account_id);
}
if ($notificationType == 'domain') {
$recipient = $ticket->domain_contact_email;
$mails[$recipient][] = $box;
$accounts[$recipient] = Account::find($ticket->domain_contact_account_id);
}
}
}
foreach ($mails as $recipient => $boxes) {
if (!empty($boxes)) {
// create a new message
$message = Swift_Message::newInstance();
// create the src url for the active brand logo
if (!empty($accounts[$recipient]))
{
$account = $accounts[$recipient];
} else {
$account = Account::getSystemAccount();
}
$logo_url = URL::to('/ash/logo/' . $account->brand_id);
$brand = $account->brand;
$replacements = [
'boxes' => $boxes,
'ticket_count' => count($tickets),
'logo_src' => $logo_url,
];
$subject = config("{$this->configBase}.templates.subject");
$htmlmail = config("{$this->configBase}.templates.html_mail");
$plainmail = config("{$this->configBase}.templates.plain_mail");
// render the default templates
if(!empty($htmlmail)) {
$htmlmail = view(['template' => $htmlmail], $replacements)->render();
} else {
Log::warning("Incorrect template, it does not exist");
}
if(!empty($plainmail)) {
$plainmail = view(['template' => $plainmail], $replacements)->render();
} else {
Log::warning("Incorrect template, it does not exist");
}
// if the current brand has custom mail template, use them
if ($brand->mail_custom_template) {
// defensive programming, doubble check the templates
$validator = \Validator::make(
[
'html' => $brand->mail_template_html,
'plain' => $brand->mail_template_plain,
],
[
'html' => 'required|bladetemplate',
'plain' => 'required|bladetemplate',
]);
if ($validator->passes()) {
try {
// only use the templates if they pass the validation
$htmloutput = view(['template' => $brand->mail_template_html], $replacements)->render();
$plainoutput = view(['template' => $brand->mail_template_plain], $replacements)->render();
// no errors occurred while rendering
$htmlmail = $htmloutput;
$plainmail = $plainoutput;
} catch (\ErrorException $e) {
Log::warning("Incorrect template, falling back to default: " . $e->getMessage());
}
}
}
$iodef = new Iodef\Writer();
$iodef->formatOutput = true;
$iodef->write(
[
[
'name' => 'IODEF-Document',
'attributes' => $this->iodefDocument->getAttributes(),
'value' => $this->iodefDocument,
]
]
);
$XmlAttachmentData = $iodef->outputMemory();
if (!empty(Config::get('mail.smime.enabled')) &&
(Config::get('mail.smime.enabled')) === true &&
!empty(Config::get('mail.smime.certificate')) &&
!empty(Config::get('mail.smime.key')) &&
is_file(Config::get('mail.smime.certificate')) &&
is_file(Config::get('mail.smime.key'))
) {
$smimeSigner = Swift_Signers_SMimeSigner::newInstance();
$smimeSigner->setSignCertificate(
Config::get('mail.smime.certificate'),
Config::get('mail.smime.key')
);
$message->attachSigner($smimeSigner);
}
$message->setFrom(
[
Config::get('main.notifications.from_address') =>
Config::get('main.notifications.from_name')
]
);
if (!empty(Config::get('mail.override_address'))) {
$message->setTo([Config::get('mail.override_address')]);
} else {
$message->setTo(explode(',', $recipient));
}
if (!empty(Config::get('main.notifications.bcc_enabled'))) {
$message->setBcc([(Config::get('main.notifications.bcc_address'))]);
}
$message->setPriority(1);
$message->setSubject($subject);
if(config("{$this->configBase}.notification.prefer_html_body")) {
$message->setBody($htmlmail, 'text/html');
if(config("{$this->configBase}.notification.text_part_enabled")) {
$message->addPart($plainmail, 'text/plain');
}
} else {
$message->setBody($plainmail, 'text/plain');
if(config("{$this->configBase}.notification.html_part_enabled")) {
$message->addPart($htmlmail, 'text/html');
}
}
$message->attach(
Swift_Attachment::newInstance(gzencode($XmlAttachmentData), 'iodef.xml.gz', 'application/gzip')
);
$transport = Swift_SmtpTransport::newInstance();
$transport->setHost(config('mail.host'));
$transport->setPort(config('mail.port'));
$transport->setUsername(config('mail.username'));
$transport->setPassword(config('mail.password'));
$transport->setEncryption(config('mail.encryption'));
$mailer = Swift_Mailer::newInstance($transport);
// only really send if the email address isn't anonymized
$regexp = '/@'.$anonymize_domain.'$/';
if (preg_match($regexp, $recipient) !== 1) {
if (!$mailer->send($message)) {
return $this->failed("Error while sending message to {$recipient}");
}
}
}
}
}
return $this->success();
}
|
[
"public",
"function",
"send",
"(",
"$",
"notifications",
")",
"{",
"$",
"anonymize_domain",
"=",
"env",
"(",
"'GDPR_ANONYMIZE_DOMAIN'",
",",
"'example.com'",
")",
";",
"foreach",
"(",
"$",
"notifications",
"as",
"$",
"customerReference",
"=>",
"$",
"notificationTypes",
")",
"{",
"$",
"mails",
"=",
"[",
"]",
";",
"$",
"tickets",
"=",
"[",
"]",
";",
"$",
"accounts",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"notificationTypes",
"as",
"$",
"notificationType",
"=>",
"$",
"tickets",
")",
"{",
"foreach",
"(",
"$",
"tickets",
"as",
"$",
"ticket",
")",
"{",
"$",
"token",
"[",
"'ip'",
"]",
"=",
"$",
"ticket",
"->",
"ash_token_ip",
";",
"$",
"token",
"[",
"'domain'",
"]",
"=",
"$",
"ticket",
"->",
"ash_token_domain",
";",
"$",
"ashUrl",
"=",
"config",
"(",
"'main.ash.url'",
")",
".",
"'collect/'",
".",
"$",
"ticket",
"->",
"id",
".",
"'/'",
";",
"$",
"this",
"->",
"addIodefObject",
"(",
"$",
"ticket",
",",
"$",
"token",
"[",
"$",
"notificationType",
"]",
",",
"$",
"ashUrl",
")",
";",
"$",
"box",
"=",
"[",
"'ticket_notification_type'",
"=>",
"$",
"notificationType",
",",
"'ip_contact_ash_link'",
"=>",
"$",
"ashUrl",
".",
"$",
"token",
"[",
"'ip'",
"]",
",",
"'domain_contact_ash_link'",
"=>",
"$",
"ashUrl",
".",
"$",
"token",
"[",
"'domain'",
"]",
",",
"'ticket_number'",
"=>",
"$",
"ticket",
"->",
"id",
",",
"'ticket_ip'",
"=>",
"$",
"ticket",
"->",
"ip",
",",
"'ticket_domain'",
"=>",
"$",
"ticket",
"->",
"domain",
",",
"'ticket_type_name'",
"=>",
"trans",
"(",
"\"types.type.{$ticket->type_id}.name\"",
")",
",",
"'ticket_type_description'",
"=>",
"trans",
"(",
"\"types.type.{$ticket->type_id}.description\"",
")",
",",
"'ticket_class_name'",
"=>",
"trans",
"(",
"\"classifications.{$ticket->class_id}.name\"",
")",
",",
"'ticket_event_count'",
"=>",
"$",
"ticket",
"->",
"events",
"->",
"count",
"(",
")",
",",
"]",
";",
"/*\n * Even that all these tickets relate to the same customer reference, the contacts might be\n * changed (added addresses, etc) for a specific ticket. To make sure people only get their own\n * notificiations we aggregate them here before sending.\n */",
"if",
"(",
"$",
"notificationType",
"==",
"'ip'",
")",
"{",
"$",
"recipient",
"=",
"$",
"ticket",
"->",
"ip_contact_email",
";",
"$",
"mails",
"[",
"$",
"recipient",
"]",
"[",
"]",
"=",
"$",
"box",
";",
"$",
"accounts",
"[",
"$",
"recipient",
"]",
"=",
"Account",
"::",
"find",
"(",
"$",
"ticket",
"->",
"ip_contact_account_id",
")",
";",
"}",
"if",
"(",
"$",
"notificationType",
"==",
"'domain'",
")",
"{",
"$",
"recipient",
"=",
"$",
"ticket",
"->",
"domain_contact_email",
";",
"$",
"mails",
"[",
"$",
"recipient",
"]",
"[",
"]",
"=",
"$",
"box",
";",
"$",
"accounts",
"[",
"$",
"recipient",
"]",
"=",
"Account",
"::",
"find",
"(",
"$",
"ticket",
"->",
"domain_contact_account_id",
")",
";",
"}",
"}",
"}",
"foreach",
"(",
"$",
"mails",
"as",
"$",
"recipient",
"=>",
"$",
"boxes",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"boxes",
")",
")",
"{",
"// create a new message",
"$",
"message",
"=",
"Swift_Message",
"::",
"newInstance",
"(",
")",
";",
"// create the src url for the active brand logo",
"if",
"(",
"!",
"empty",
"(",
"$",
"accounts",
"[",
"$",
"recipient",
"]",
")",
")",
"{",
"$",
"account",
"=",
"$",
"accounts",
"[",
"$",
"recipient",
"]",
";",
"}",
"else",
"{",
"$",
"account",
"=",
"Account",
"::",
"getSystemAccount",
"(",
")",
";",
"}",
"$",
"logo_url",
"=",
"URL",
"::",
"to",
"(",
"'/ash/logo/'",
".",
"$",
"account",
"->",
"brand_id",
")",
";",
"$",
"brand",
"=",
"$",
"account",
"->",
"brand",
";",
"$",
"replacements",
"=",
"[",
"'boxes'",
"=>",
"$",
"boxes",
",",
"'ticket_count'",
"=>",
"count",
"(",
"$",
"tickets",
")",
",",
"'logo_src'",
"=>",
"$",
"logo_url",
",",
"]",
";",
"$",
"subject",
"=",
"config",
"(",
"\"{$this->configBase}.templates.subject\"",
")",
";",
"$",
"htmlmail",
"=",
"config",
"(",
"\"{$this->configBase}.templates.html_mail\"",
")",
";",
"$",
"plainmail",
"=",
"config",
"(",
"\"{$this->configBase}.templates.plain_mail\"",
")",
";",
"// render the default templates",
"if",
"(",
"!",
"empty",
"(",
"$",
"htmlmail",
")",
")",
"{",
"$",
"htmlmail",
"=",
"view",
"(",
"[",
"'template'",
"=>",
"$",
"htmlmail",
"]",
",",
"$",
"replacements",
")",
"->",
"render",
"(",
")",
";",
"}",
"else",
"{",
"Log",
"::",
"warning",
"(",
"\"Incorrect template, it does not exist\"",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"plainmail",
")",
")",
"{",
"$",
"plainmail",
"=",
"view",
"(",
"[",
"'template'",
"=>",
"$",
"plainmail",
"]",
",",
"$",
"replacements",
")",
"->",
"render",
"(",
")",
";",
"}",
"else",
"{",
"Log",
"::",
"warning",
"(",
"\"Incorrect template, it does not exist\"",
")",
";",
"}",
"// if the current brand has custom mail template, use them",
"if",
"(",
"$",
"brand",
"->",
"mail_custom_template",
")",
"{",
"// defensive programming, doubble check the templates",
"$",
"validator",
"=",
"\\",
"Validator",
"::",
"make",
"(",
"[",
"'html'",
"=>",
"$",
"brand",
"->",
"mail_template_html",
",",
"'plain'",
"=>",
"$",
"brand",
"->",
"mail_template_plain",
",",
"]",
",",
"[",
"'html'",
"=>",
"'required|bladetemplate'",
",",
"'plain'",
"=>",
"'required|bladetemplate'",
",",
"]",
")",
";",
"if",
"(",
"$",
"validator",
"->",
"passes",
"(",
")",
")",
"{",
"try",
"{",
"// only use the templates if they pass the validation",
"$",
"htmloutput",
"=",
"view",
"(",
"[",
"'template'",
"=>",
"$",
"brand",
"->",
"mail_template_html",
"]",
",",
"$",
"replacements",
")",
"->",
"render",
"(",
")",
";",
"$",
"plainoutput",
"=",
"view",
"(",
"[",
"'template'",
"=>",
"$",
"brand",
"->",
"mail_template_plain",
"]",
",",
"$",
"replacements",
")",
"->",
"render",
"(",
")",
";",
"// no errors occurred while rendering",
"$",
"htmlmail",
"=",
"$",
"htmloutput",
";",
"$",
"plainmail",
"=",
"$",
"plainoutput",
";",
"}",
"catch",
"(",
"\\",
"ErrorException",
"$",
"e",
")",
"{",
"Log",
"::",
"warning",
"(",
"\"Incorrect template, falling back to default: \"",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"}",
"$",
"iodef",
"=",
"new",
"Iodef",
"\\",
"Writer",
"(",
")",
";",
"$",
"iodef",
"->",
"formatOutput",
"=",
"true",
";",
"$",
"iodef",
"->",
"write",
"(",
"[",
"[",
"'name'",
"=>",
"'IODEF-Document'",
",",
"'attributes'",
"=>",
"$",
"this",
"->",
"iodefDocument",
"->",
"getAttributes",
"(",
")",
",",
"'value'",
"=>",
"$",
"this",
"->",
"iodefDocument",
",",
"]",
"]",
")",
";",
"$",
"XmlAttachmentData",
"=",
"$",
"iodef",
"->",
"outputMemory",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"Config",
"::",
"get",
"(",
"'mail.smime.enabled'",
")",
")",
"&&",
"(",
"Config",
"::",
"get",
"(",
"'mail.smime.enabled'",
")",
")",
"===",
"true",
"&&",
"!",
"empty",
"(",
"Config",
"::",
"get",
"(",
"'mail.smime.certificate'",
")",
")",
"&&",
"!",
"empty",
"(",
"Config",
"::",
"get",
"(",
"'mail.smime.key'",
")",
")",
"&&",
"is_file",
"(",
"Config",
"::",
"get",
"(",
"'mail.smime.certificate'",
")",
")",
"&&",
"is_file",
"(",
"Config",
"::",
"get",
"(",
"'mail.smime.key'",
")",
")",
")",
"{",
"$",
"smimeSigner",
"=",
"Swift_Signers_SMimeSigner",
"::",
"newInstance",
"(",
")",
";",
"$",
"smimeSigner",
"->",
"setSignCertificate",
"(",
"Config",
"::",
"get",
"(",
"'mail.smime.certificate'",
")",
",",
"Config",
"::",
"get",
"(",
"'mail.smime.key'",
")",
")",
";",
"$",
"message",
"->",
"attachSigner",
"(",
"$",
"smimeSigner",
")",
";",
"}",
"$",
"message",
"->",
"setFrom",
"(",
"[",
"Config",
"::",
"get",
"(",
"'main.notifications.from_address'",
")",
"=>",
"Config",
"::",
"get",
"(",
"'main.notifications.from_name'",
")",
"]",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"Config",
"::",
"get",
"(",
"'mail.override_address'",
")",
")",
")",
"{",
"$",
"message",
"->",
"setTo",
"(",
"[",
"Config",
"::",
"get",
"(",
"'mail.override_address'",
")",
"]",
")",
";",
"}",
"else",
"{",
"$",
"message",
"->",
"setTo",
"(",
"explode",
"(",
"','",
",",
"$",
"recipient",
")",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"Config",
"::",
"get",
"(",
"'main.notifications.bcc_enabled'",
")",
")",
")",
"{",
"$",
"message",
"->",
"setBcc",
"(",
"[",
"(",
"Config",
"::",
"get",
"(",
"'main.notifications.bcc_address'",
")",
")",
"]",
")",
";",
"}",
"$",
"message",
"->",
"setPriority",
"(",
"1",
")",
";",
"$",
"message",
"->",
"setSubject",
"(",
"$",
"subject",
")",
";",
"if",
"(",
"config",
"(",
"\"{$this->configBase}.notification.prefer_html_body\"",
")",
")",
"{",
"$",
"message",
"->",
"setBody",
"(",
"$",
"htmlmail",
",",
"'text/html'",
")",
";",
"if",
"(",
"config",
"(",
"\"{$this->configBase}.notification.text_part_enabled\"",
")",
")",
"{",
"$",
"message",
"->",
"addPart",
"(",
"$",
"plainmail",
",",
"'text/plain'",
")",
";",
"}",
"}",
"else",
"{",
"$",
"message",
"->",
"setBody",
"(",
"$",
"plainmail",
",",
"'text/plain'",
")",
";",
"if",
"(",
"config",
"(",
"\"{$this->configBase}.notification.html_part_enabled\"",
")",
")",
"{",
"$",
"message",
"->",
"addPart",
"(",
"$",
"htmlmail",
",",
"'text/html'",
")",
";",
"}",
"}",
"$",
"message",
"->",
"attach",
"(",
"Swift_Attachment",
"::",
"newInstance",
"(",
"gzencode",
"(",
"$",
"XmlAttachmentData",
")",
",",
"'iodef.xml.gz'",
",",
"'application/gzip'",
")",
")",
";",
"$",
"transport",
"=",
"Swift_SmtpTransport",
"::",
"newInstance",
"(",
")",
";",
"$",
"transport",
"->",
"setHost",
"(",
"config",
"(",
"'mail.host'",
")",
")",
";",
"$",
"transport",
"->",
"setPort",
"(",
"config",
"(",
"'mail.port'",
")",
")",
";",
"$",
"transport",
"->",
"setUsername",
"(",
"config",
"(",
"'mail.username'",
")",
")",
";",
"$",
"transport",
"->",
"setPassword",
"(",
"config",
"(",
"'mail.password'",
")",
")",
";",
"$",
"transport",
"->",
"setEncryption",
"(",
"config",
"(",
"'mail.encryption'",
")",
")",
";",
"$",
"mailer",
"=",
"Swift_Mailer",
"::",
"newInstance",
"(",
"$",
"transport",
")",
";",
"// only really send if the email address isn't anonymized",
"$",
"regexp",
"=",
"'/@'",
".",
"$",
"anonymize_domain",
".",
"'$/'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"regexp",
",",
"$",
"recipient",
")",
"!==",
"1",
")",
"{",
"if",
"(",
"!",
"$",
"mailer",
"->",
"send",
"(",
"$",
"message",
")",
")",
"{",
"return",
"$",
"this",
"->",
"failed",
"(",
"\"Error while sending message to {$recipient}\"",
")",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"$",
"this",
"->",
"success",
"(",
")",
";",
"}"
] |
Sends out mail notifications for a specific $customerReference
@param array $notifications
@return boolean Returns if succeeded or not
|
[
"Sends",
"out",
"mail",
"notifications",
"for",
"a",
"specific",
"$customerReference"
] |
train
|
https://github.com/AbuseIO/notification-mail/blob/c1e64c341151a06e79f58243968577d175a92d46/src/Mail.php#L43-L251
|
AbuseIO/notification-mail
|
src/Mail.php
|
Mail.addIodefObject
|
private function addIodefObject($ticket, $token, $ashUrl)
{
// Add report type, origin and date
$incident = new Iodef\Elements\Incident();
$incident->setAttributes(
[
'purpose' => 'reporting'
]
);
// Add ASH Link
$ashlink = new Iodef\Elements\AdditionalData;
$ashlink->setAttributes(
[
'dtype' => 'string',
'meaning' => 'ASH Link',
'restriction' => 'private',
]
);
$ashlink->value = $ashUrl . $token;
$incident->addChild($ashlink);
// Add ASH Token seperatly
$ashtoken = new Iodef\Elements\AdditionalData;
$ashtoken->setAttributes(
[
'dtype' => 'string',
'meaning' => 'ASH Token',
'restriction' => 'private',
]
);
$ashtoken->value = $token;
$incident->addChild($ashtoken);
// Add AbuseDesk Status seperatly
$ticketStatus = new Iodef\Elements\AdditionalData;
$ticketStatus->setAttributes(
[
'dtype' => 'string',
'meaning' => 'Ticket status',
'restriction' => 'private',
]
);
$ticketStatus->value = $ticket->status_id;
$incident->addChild($ticketStatus);
// Add Contact Status seperatly
$contactStatus = new Iodef\Elements\AdditionalData;
$contactStatus->setAttributes(
[
'dtype' => 'string',
'meaning' => 'Contact status',
'restriction' => 'private',
]
);
$contactStatus->value = $ticket->contact_status_id;
$incident->addChild($contactStatus);
// Add SourceID seperatly
$sourceID = new Iodef\Elements\AdditionalData;
$sourceID->setAttributes(
[
'dtype' => 'string',
'meaning' => 'SourceID',
'restriction' => 'private',
]
);
$sourceID->value = config('app.id');
$incident->addChild($sourceID);
// Add Incident data
$incidentID = new Iodef\Elements\IncidentID();
$incidentID->setAttributes(
[
'name' => 'https://myhost.isp.local/api/',
'restriction' => 'need-to-know',
]
);
$incidentID->value($ticket->id);
$incident->addChild($incidentID);
$reportTime = new Iodef\Elements\ReportTime();
$reportTime->value(date('Y-m-d\TH:i:sP'));
$incident->addChild($reportTime);
// Add ticket abuse classification and type
$assessment = new Iodef\Elements\Assessment();
$impact = new Iodef\Elements\Impact();
$severity = [
'INFO' => 'low',
'ABUSE' => 'medium',
'ESCALATION' => 'high',
];
echo $ticket->class;
$impact->setAttributes(
[
'type' => 'ext-value',
'ext-type' => $ticket->class_id,
'severity' => $severity[$ticket->type_id],
]
);
$assessment->addChild($impact);
$incident->addChild($assessment);
// Add Origin/Creator contact information for this ticket
$contact = new Iodef\Elements\Contact();
$contact->setAttributes(
[
'role' => 'creator',
'type' => 'ext-value',
'ext-type' => 'Software',
'restriction' => 'need-to-know',
]
);
$contactName = new Iodef\Elements\ContactName();
$contactName->value('AbuseIO downstream provider');
$contact->addChild($contactName);
$email = new Iodef\Elements\Email();
$email->value('[email protected]');
$contact->addChild($email);
$incident->addChild($contact);
// Add Abusedesk contact information for this ticket
$contact = new Iodef\Elements\Contact();
$contact->setAttributes(
[
'role' => 'irt',
'type' => 'organization',
'restriction' => 'need-to-know',
]
);
$contactName = new Iodef\Elements\ContactName();
$contactName->value(config('main.notifications.from_name'));
$contact->addChild($contactName);
$email = new Iodef\Elements\Email();
$email->value(config('main.notifications.from_address'));
$contact->addChild($email);
$incident->addChild($contact);
// Add ticket events as records
if ($ticket->events->count() >= 1) {
foreach ($ticket->events as $event) {
$eventData = new Iodef\Elements\EventData();
// Add the IP and Domain data to each record
$flow = new Iodef\Elements\Flow;
$system = new Iodef\Elements\System;
$system->setAttributes(
[
'category' => 'source',
'spoofed' => 'no'
]
);
$node = new Iodef\Elements\Node;
if (!empty($ticket->ip)) {
$address = new Iodef\Elements\Address;
$category = [];
if (filter_var($ticket->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$category['category'] = 'ipv4-addr';
} elseif (filter_var($ticket->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$category['category'] = 'ipv6-addr';
} else {
$category['category'] = 'ext-value';
$category['ext-category'] = 'unknown';
}
$address->setAttributes($category);
$address->value = $ticket->ip;
$node->addChild($address);
}
if (!empty($ticket->domain)) {
$domain = new Iodef\Elements\NodeName;
$domain->value = $ticket->domain;
$node->addChild($domain);
}
$system->addChild($node);
$flow->addChild($system);
$eventData->addChild($flow);
// Now actually add event data
$record = new Iodef\Elements\Record;
$record->setAttributes(['restriction' => 'need-to-know']);
$recordData = new Iodef\Elements\RecordData;
$recordDateTime = new Iodef\Elements\DateTime;
$recordDateTime->value = date('Y-m-d\TH:i:sP', $event->timestamp);
$recordData->addChild($recordDateTime);
$recordDescription = new Iodef\Elements\Description;
$recordDescription->value = "Source:{$event->source}";
$recordData->addChild($recordDescription);
$recordItem = new Iodef\Elements\RecordItem;
$recordItem->setAttributes(
[
'dtype' => 'ext-value',
'ext-dtype' => 'json',
]
);
$recordItem->value = $event->information;
$recordData->addChild($recordItem);
$record->addChild($recordData);
$eventData->addChild($record);
$incident->addChild($eventData);
}
}
// Add ticket notes as history items
if ($ticket->notes->count() >= 1) {
$history = new Iodef\Elements\History;
$elementCounter = 0;
foreach ($ticket->notes as $note) {
if ($note->hidden == true) {
continue;
}
$historyItem = new Iodef\Elements\HistoryItem;
$historyItem->setAttributes(
[
'action' => 'status-new-info',
'restriction' => 'need-to-know'
]
);
$historyDateTime = new Iodef\Elements\DateTime;
$historyDateTime->value = date('Y-m-d\TH:i:sP', strtotime($note->created_at));
$historyItem->addChild($historyDateTime);
$historySubmitter = new Iodef\Elements\AdditionalData;
$historySubmitter->setAttributes(
[
'meaning' => 'submitter',
]
);
$historySubmitter->value = "{$note->submitter}";
$historyItem->addChild($historySubmitter);
$historyNote = new Iodef\Elements\AdditionalData;
$historyNote->setAttributes(
[
'meaning' => 'text',
]
);
if(empty(trim($note->text))) {
$historyNote->value = false;
} else {
$historyNote->value = "{$note->text}";
}
$historyItem->addChild($historyNote);
$history->addChild($historyItem);
}
if($elementCounter >= 1) {
$incident->addChild($history);
}
}
// Add incident to the document
$this->iodefDocument->addChild($incident);
}
|
php
|
private function addIodefObject($ticket, $token, $ashUrl)
{
// Add report type, origin and date
$incident = new Iodef\Elements\Incident();
$incident->setAttributes(
[
'purpose' => 'reporting'
]
);
// Add ASH Link
$ashlink = new Iodef\Elements\AdditionalData;
$ashlink->setAttributes(
[
'dtype' => 'string',
'meaning' => 'ASH Link',
'restriction' => 'private',
]
);
$ashlink->value = $ashUrl . $token;
$incident->addChild($ashlink);
// Add ASH Token seperatly
$ashtoken = new Iodef\Elements\AdditionalData;
$ashtoken->setAttributes(
[
'dtype' => 'string',
'meaning' => 'ASH Token',
'restriction' => 'private',
]
);
$ashtoken->value = $token;
$incident->addChild($ashtoken);
// Add AbuseDesk Status seperatly
$ticketStatus = new Iodef\Elements\AdditionalData;
$ticketStatus->setAttributes(
[
'dtype' => 'string',
'meaning' => 'Ticket status',
'restriction' => 'private',
]
);
$ticketStatus->value = $ticket->status_id;
$incident->addChild($ticketStatus);
// Add Contact Status seperatly
$contactStatus = new Iodef\Elements\AdditionalData;
$contactStatus->setAttributes(
[
'dtype' => 'string',
'meaning' => 'Contact status',
'restriction' => 'private',
]
);
$contactStatus->value = $ticket->contact_status_id;
$incident->addChild($contactStatus);
// Add SourceID seperatly
$sourceID = new Iodef\Elements\AdditionalData;
$sourceID->setAttributes(
[
'dtype' => 'string',
'meaning' => 'SourceID',
'restriction' => 'private',
]
);
$sourceID->value = config('app.id');
$incident->addChild($sourceID);
// Add Incident data
$incidentID = new Iodef\Elements\IncidentID();
$incidentID->setAttributes(
[
'name' => 'https://myhost.isp.local/api/',
'restriction' => 'need-to-know',
]
);
$incidentID->value($ticket->id);
$incident->addChild($incidentID);
$reportTime = new Iodef\Elements\ReportTime();
$reportTime->value(date('Y-m-d\TH:i:sP'));
$incident->addChild($reportTime);
// Add ticket abuse classification and type
$assessment = new Iodef\Elements\Assessment();
$impact = new Iodef\Elements\Impact();
$severity = [
'INFO' => 'low',
'ABUSE' => 'medium',
'ESCALATION' => 'high',
];
echo $ticket->class;
$impact->setAttributes(
[
'type' => 'ext-value',
'ext-type' => $ticket->class_id,
'severity' => $severity[$ticket->type_id],
]
);
$assessment->addChild($impact);
$incident->addChild($assessment);
// Add Origin/Creator contact information for this ticket
$contact = new Iodef\Elements\Contact();
$contact->setAttributes(
[
'role' => 'creator',
'type' => 'ext-value',
'ext-type' => 'Software',
'restriction' => 'need-to-know',
]
);
$contactName = new Iodef\Elements\ContactName();
$contactName->value('AbuseIO downstream provider');
$contact->addChild($contactName);
$email = new Iodef\Elements\Email();
$email->value('[email protected]');
$contact->addChild($email);
$incident->addChild($contact);
// Add Abusedesk contact information for this ticket
$contact = new Iodef\Elements\Contact();
$contact->setAttributes(
[
'role' => 'irt',
'type' => 'organization',
'restriction' => 'need-to-know',
]
);
$contactName = new Iodef\Elements\ContactName();
$contactName->value(config('main.notifications.from_name'));
$contact->addChild($contactName);
$email = new Iodef\Elements\Email();
$email->value(config('main.notifications.from_address'));
$contact->addChild($email);
$incident->addChild($contact);
// Add ticket events as records
if ($ticket->events->count() >= 1) {
foreach ($ticket->events as $event) {
$eventData = new Iodef\Elements\EventData();
// Add the IP and Domain data to each record
$flow = new Iodef\Elements\Flow;
$system = new Iodef\Elements\System;
$system->setAttributes(
[
'category' => 'source',
'spoofed' => 'no'
]
);
$node = new Iodef\Elements\Node;
if (!empty($ticket->ip)) {
$address = new Iodef\Elements\Address;
$category = [];
if (filter_var($ticket->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$category['category'] = 'ipv4-addr';
} elseif (filter_var($ticket->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$category['category'] = 'ipv6-addr';
} else {
$category['category'] = 'ext-value';
$category['ext-category'] = 'unknown';
}
$address->setAttributes($category);
$address->value = $ticket->ip;
$node->addChild($address);
}
if (!empty($ticket->domain)) {
$domain = new Iodef\Elements\NodeName;
$domain->value = $ticket->domain;
$node->addChild($domain);
}
$system->addChild($node);
$flow->addChild($system);
$eventData->addChild($flow);
// Now actually add event data
$record = new Iodef\Elements\Record;
$record->setAttributes(['restriction' => 'need-to-know']);
$recordData = new Iodef\Elements\RecordData;
$recordDateTime = new Iodef\Elements\DateTime;
$recordDateTime->value = date('Y-m-d\TH:i:sP', $event->timestamp);
$recordData->addChild($recordDateTime);
$recordDescription = new Iodef\Elements\Description;
$recordDescription->value = "Source:{$event->source}";
$recordData->addChild($recordDescription);
$recordItem = new Iodef\Elements\RecordItem;
$recordItem->setAttributes(
[
'dtype' => 'ext-value',
'ext-dtype' => 'json',
]
);
$recordItem->value = $event->information;
$recordData->addChild($recordItem);
$record->addChild($recordData);
$eventData->addChild($record);
$incident->addChild($eventData);
}
}
// Add ticket notes as history items
if ($ticket->notes->count() >= 1) {
$history = new Iodef\Elements\History;
$elementCounter = 0;
foreach ($ticket->notes as $note) {
if ($note->hidden == true) {
continue;
}
$historyItem = new Iodef\Elements\HistoryItem;
$historyItem->setAttributes(
[
'action' => 'status-new-info',
'restriction' => 'need-to-know'
]
);
$historyDateTime = new Iodef\Elements\DateTime;
$historyDateTime->value = date('Y-m-d\TH:i:sP', strtotime($note->created_at));
$historyItem->addChild($historyDateTime);
$historySubmitter = new Iodef\Elements\AdditionalData;
$historySubmitter->setAttributes(
[
'meaning' => 'submitter',
]
);
$historySubmitter->value = "{$note->submitter}";
$historyItem->addChild($historySubmitter);
$historyNote = new Iodef\Elements\AdditionalData;
$historyNote->setAttributes(
[
'meaning' => 'text',
]
);
if(empty(trim($note->text))) {
$historyNote->value = false;
} else {
$historyNote->value = "{$note->text}";
}
$historyItem->addChild($historyNote);
$history->addChild($historyItem);
}
if($elementCounter >= 1) {
$incident->addChild($history);
}
}
// Add incident to the document
$this->iodefDocument->addChild($incident);
}
|
[
"private",
"function",
"addIodefObject",
"(",
"$",
"ticket",
",",
"$",
"token",
",",
"$",
"ashUrl",
")",
"{",
"// Add report type, origin and date",
"$",
"incident",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Incident",
"(",
")",
";",
"$",
"incident",
"->",
"setAttributes",
"(",
"[",
"'purpose'",
"=>",
"'reporting'",
"]",
")",
";",
"// Add ASH Link",
"$",
"ashlink",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"AdditionalData",
";",
"$",
"ashlink",
"->",
"setAttributes",
"(",
"[",
"'dtype'",
"=>",
"'string'",
",",
"'meaning'",
"=>",
"'ASH Link'",
",",
"'restriction'",
"=>",
"'private'",
",",
"]",
")",
";",
"$",
"ashlink",
"->",
"value",
"=",
"$",
"ashUrl",
".",
"$",
"token",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"ashlink",
")",
";",
"// Add ASH Token seperatly",
"$",
"ashtoken",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"AdditionalData",
";",
"$",
"ashtoken",
"->",
"setAttributes",
"(",
"[",
"'dtype'",
"=>",
"'string'",
",",
"'meaning'",
"=>",
"'ASH Token'",
",",
"'restriction'",
"=>",
"'private'",
",",
"]",
")",
";",
"$",
"ashtoken",
"->",
"value",
"=",
"$",
"token",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"ashtoken",
")",
";",
"// Add AbuseDesk Status seperatly",
"$",
"ticketStatus",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"AdditionalData",
";",
"$",
"ticketStatus",
"->",
"setAttributes",
"(",
"[",
"'dtype'",
"=>",
"'string'",
",",
"'meaning'",
"=>",
"'Ticket status'",
",",
"'restriction'",
"=>",
"'private'",
",",
"]",
")",
";",
"$",
"ticketStatus",
"->",
"value",
"=",
"$",
"ticket",
"->",
"status_id",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"ticketStatus",
")",
";",
"// Add Contact Status seperatly",
"$",
"contactStatus",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"AdditionalData",
";",
"$",
"contactStatus",
"->",
"setAttributes",
"(",
"[",
"'dtype'",
"=>",
"'string'",
",",
"'meaning'",
"=>",
"'Contact status'",
",",
"'restriction'",
"=>",
"'private'",
",",
"]",
")",
";",
"$",
"contactStatus",
"->",
"value",
"=",
"$",
"ticket",
"->",
"contact_status_id",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"contactStatus",
")",
";",
"// Add SourceID seperatly",
"$",
"sourceID",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"AdditionalData",
";",
"$",
"sourceID",
"->",
"setAttributes",
"(",
"[",
"'dtype'",
"=>",
"'string'",
",",
"'meaning'",
"=>",
"'SourceID'",
",",
"'restriction'",
"=>",
"'private'",
",",
"]",
")",
";",
"$",
"sourceID",
"->",
"value",
"=",
"config",
"(",
"'app.id'",
")",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"sourceID",
")",
";",
"// Add Incident data",
"$",
"incidentID",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"IncidentID",
"(",
")",
";",
"$",
"incidentID",
"->",
"setAttributes",
"(",
"[",
"'name'",
"=>",
"'https://myhost.isp.local/api/'",
",",
"'restriction'",
"=>",
"'need-to-know'",
",",
"]",
")",
";",
"$",
"incidentID",
"->",
"value",
"(",
"$",
"ticket",
"->",
"id",
")",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"incidentID",
")",
";",
"$",
"reportTime",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"ReportTime",
"(",
")",
";",
"$",
"reportTime",
"->",
"value",
"(",
"date",
"(",
"'Y-m-d\\TH:i:sP'",
")",
")",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"reportTime",
")",
";",
"// Add ticket abuse classification and type",
"$",
"assessment",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Assessment",
"(",
")",
";",
"$",
"impact",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Impact",
"(",
")",
";",
"$",
"severity",
"=",
"[",
"'INFO'",
"=>",
"'low'",
",",
"'ABUSE'",
"=>",
"'medium'",
",",
"'ESCALATION'",
"=>",
"'high'",
",",
"]",
";",
"echo",
"$",
"ticket",
"->",
"class",
";",
"$",
"impact",
"->",
"setAttributes",
"(",
"[",
"'type'",
"=>",
"'ext-value'",
",",
"'ext-type'",
"=>",
"$",
"ticket",
"->",
"class_id",
",",
"'severity'",
"=>",
"$",
"severity",
"[",
"$",
"ticket",
"->",
"type_id",
"]",
",",
"]",
")",
";",
"$",
"assessment",
"->",
"addChild",
"(",
"$",
"impact",
")",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"assessment",
")",
";",
"// Add Origin/Creator contact information for this ticket",
"$",
"contact",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Contact",
"(",
")",
";",
"$",
"contact",
"->",
"setAttributes",
"(",
"[",
"'role'",
"=>",
"'creator'",
",",
"'type'",
"=>",
"'ext-value'",
",",
"'ext-type'",
"=>",
"'Software'",
",",
"'restriction'",
"=>",
"'need-to-know'",
",",
"]",
")",
";",
"$",
"contactName",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"ContactName",
"(",
")",
";",
"$",
"contactName",
"->",
"value",
"(",
"'AbuseIO downstream provider'",
")",
";",
"$",
"contact",
"->",
"addChild",
"(",
"$",
"contactName",
")",
";",
"$",
"email",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Email",
"(",
")",
";",
"$",
"email",
"->",
"value",
"(",
"'[email protected]'",
")",
";",
"$",
"contact",
"->",
"addChild",
"(",
"$",
"email",
")",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"contact",
")",
";",
"// Add Abusedesk contact information for this ticket",
"$",
"contact",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Contact",
"(",
")",
";",
"$",
"contact",
"->",
"setAttributes",
"(",
"[",
"'role'",
"=>",
"'irt'",
",",
"'type'",
"=>",
"'organization'",
",",
"'restriction'",
"=>",
"'need-to-know'",
",",
"]",
")",
";",
"$",
"contactName",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"ContactName",
"(",
")",
";",
"$",
"contactName",
"->",
"value",
"(",
"config",
"(",
"'main.notifications.from_name'",
")",
")",
";",
"$",
"contact",
"->",
"addChild",
"(",
"$",
"contactName",
")",
";",
"$",
"email",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Email",
"(",
")",
";",
"$",
"email",
"->",
"value",
"(",
"config",
"(",
"'main.notifications.from_address'",
")",
")",
";",
"$",
"contact",
"->",
"addChild",
"(",
"$",
"email",
")",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"contact",
")",
";",
"// Add ticket events as records",
"if",
"(",
"$",
"ticket",
"->",
"events",
"->",
"count",
"(",
")",
">=",
"1",
")",
"{",
"foreach",
"(",
"$",
"ticket",
"->",
"events",
"as",
"$",
"event",
")",
"{",
"$",
"eventData",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"EventData",
"(",
")",
";",
"// Add the IP and Domain data to each record",
"$",
"flow",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Flow",
";",
"$",
"system",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"System",
";",
"$",
"system",
"->",
"setAttributes",
"(",
"[",
"'category'",
"=>",
"'source'",
",",
"'spoofed'",
"=>",
"'no'",
"]",
")",
";",
"$",
"node",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Node",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"ticket",
"->",
"ip",
")",
")",
"{",
"$",
"address",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Address",
";",
"$",
"category",
"=",
"[",
"]",
";",
"if",
"(",
"filter_var",
"(",
"$",
"ticket",
"->",
"ip",
",",
"FILTER_VALIDATE_IP",
",",
"FILTER_FLAG_IPV4",
")",
")",
"{",
"$",
"category",
"[",
"'category'",
"]",
"=",
"'ipv4-addr'",
";",
"}",
"elseif",
"(",
"filter_var",
"(",
"$",
"ticket",
"->",
"ip",
",",
"FILTER_VALIDATE_IP",
",",
"FILTER_FLAG_IPV6",
")",
")",
"{",
"$",
"category",
"[",
"'category'",
"]",
"=",
"'ipv6-addr'",
";",
"}",
"else",
"{",
"$",
"category",
"[",
"'category'",
"]",
"=",
"'ext-value'",
";",
"$",
"category",
"[",
"'ext-category'",
"]",
"=",
"'unknown'",
";",
"}",
"$",
"address",
"->",
"setAttributes",
"(",
"$",
"category",
")",
";",
"$",
"address",
"->",
"value",
"=",
"$",
"ticket",
"->",
"ip",
";",
"$",
"node",
"->",
"addChild",
"(",
"$",
"address",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"ticket",
"->",
"domain",
")",
")",
"{",
"$",
"domain",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"NodeName",
";",
"$",
"domain",
"->",
"value",
"=",
"$",
"ticket",
"->",
"domain",
";",
"$",
"node",
"->",
"addChild",
"(",
"$",
"domain",
")",
";",
"}",
"$",
"system",
"->",
"addChild",
"(",
"$",
"node",
")",
";",
"$",
"flow",
"->",
"addChild",
"(",
"$",
"system",
")",
";",
"$",
"eventData",
"->",
"addChild",
"(",
"$",
"flow",
")",
";",
"// Now actually add event data",
"$",
"record",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Record",
";",
"$",
"record",
"->",
"setAttributes",
"(",
"[",
"'restriction'",
"=>",
"'need-to-know'",
"]",
")",
";",
"$",
"recordData",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"RecordData",
";",
"$",
"recordDateTime",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"DateTime",
";",
"$",
"recordDateTime",
"->",
"value",
"=",
"date",
"(",
"'Y-m-d\\TH:i:sP'",
",",
"$",
"event",
"->",
"timestamp",
")",
";",
"$",
"recordData",
"->",
"addChild",
"(",
"$",
"recordDateTime",
")",
";",
"$",
"recordDescription",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"Description",
";",
"$",
"recordDescription",
"->",
"value",
"=",
"\"Source:{$event->source}\"",
";",
"$",
"recordData",
"->",
"addChild",
"(",
"$",
"recordDescription",
")",
";",
"$",
"recordItem",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"RecordItem",
";",
"$",
"recordItem",
"->",
"setAttributes",
"(",
"[",
"'dtype'",
"=>",
"'ext-value'",
",",
"'ext-dtype'",
"=>",
"'json'",
",",
"]",
")",
";",
"$",
"recordItem",
"->",
"value",
"=",
"$",
"event",
"->",
"information",
";",
"$",
"recordData",
"->",
"addChild",
"(",
"$",
"recordItem",
")",
";",
"$",
"record",
"->",
"addChild",
"(",
"$",
"recordData",
")",
";",
"$",
"eventData",
"->",
"addChild",
"(",
"$",
"record",
")",
";",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"eventData",
")",
";",
"}",
"}",
"// Add ticket notes as history items",
"if",
"(",
"$",
"ticket",
"->",
"notes",
"->",
"count",
"(",
")",
">=",
"1",
")",
"{",
"$",
"history",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"History",
";",
"$",
"elementCounter",
"=",
"0",
";",
"foreach",
"(",
"$",
"ticket",
"->",
"notes",
"as",
"$",
"note",
")",
"{",
"if",
"(",
"$",
"note",
"->",
"hidden",
"==",
"true",
")",
"{",
"continue",
";",
"}",
"$",
"historyItem",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"HistoryItem",
";",
"$",
"historyItem",
"->",
"setAttributes",
"(",
"[",
"'action'",
"=>",
"'status-new-info'",
",",
"'restriction'",
"=>",
"'need-to-know'",
"]",
")",
";",
"$",
"historyDateTime",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"DateTime",
";",
"$",
"historyDateTime",
"->",
"value",
"=",
"date",
"(",
"'Y-m-d\\TH:i:sP'",
",",
"strtotime",
"(",
"$",
"note",
"->",
"created_at",
")",
")",
";",
"$",
"historyItem",
"->",
"addChild",
"(",
"$",
"historyDateTime",
")",
";",
"$",
"historySubmitter",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"AdditionalData",
";",
"$",
"historySubmitter",
"->",
"setAttributes",
"(",
"[",
"'meaning'",
"=>",
"'submitter'",
",",
"]",
")",
";",
"$",
"historySubmitter",
"->",
"value",
"=",
"\"{$note->submitter}\"",
";",
"$",
"historyItem",
"->",
"addChild",
"(",
"$",
"historySubmitter",
")",
";",
"$",
"historyNote",
"=",
"new",
"Iodef",
"\\",
"Elements",
"\\",
"AdditionalData",
";",
"$",
"historyNote",
"->",
"setAttributes",
"(",
"[",
"'meaning'",
"=>",
"'text'",
",",
"]",
")",
";",
"if",
"(",
"empty",
"(",
"trim",
"(",
"$",
"note",
"->",
"text",
")",
")",
")",
"{",
"$",
"historyNote",
"->",
"value",
"=",
"false",
";",
"}",
"else",
"{",
"$",
"historyNote",
"->",
"value",
"=",
"\"{$note->text}\"",
";",
"}",
"$",
"historyItem",
"->",
"addChild",
"(",
"$",
"historyNote",
")",
";",
"$",
"history",
"->",
"addChild",
"(",
"$",
"historyItem",
")",
";",
"}",
"if",
"(",
"$",
"elementCounter",
">=",
"1",
")",
"{",
"$",
"incident",
"->",
"addChild",
"(",
"$",
"history",
")",
";",
"}",
"}",
"// Add incident to the document",
"$",
"this",
"->",
"iodefDocument",
"->",
"addChild",
"(",
"$",
"incident",
")",
";",
"}"
] |
Adds IOdef data from this ticket to the document
@param object $ticket Ticket model
@param string $token ASH token
@param string $ashUrl ASH Url
|
[
"Adds",
"IOdef",
"data",
"from",
"this",
"ticket",
"to",
"the",
"document"
] |
train
|
https://github.com/AbuseIO/notification-mail/blob/c1e64c341151a06e79f58243968577d175a92d46/src/Mail.php#L260-L543
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.