repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.initialize | protected function initialize()
{
$this->currentLineNumber = 1;
$this->currentObjectPathStack = [];
$this->currentSourceCodeLines = [];
$this->currentBlockCommentState = false;
$this->objectTree = [];
} | php | protected function initialize()
{
$this->currentLineNumber = 1;
$this->currentObjectPathStack = [];
$this->currentSourceCodeLines = [];
$this->currentBlockCommentState = false;
$this->objectTree = [];
} | [
"protected",
"function",
"initialize",
"(",
")",
"{",
"$",
"this",
"->",
"currentLineNumber",
"=",
"1",
";",
"$",
"this",
"->",
"currentObjectPathStack",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"currentSourceCodeLines",
"=",
"[",
"]",
";",
"$",
"this",
"-... | Initializes the Fusion parser
@return void | [
"Initializes",
"the",
"Fusion",
"parser"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L335-L342 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.getNextFusionLine | protected function getNextFusionLine()
{
$fusionLine = current($this->currentSourceCodeLines);
next($this->currentSourceCodeLines);
$this->currentLineNumber++;
return $fusionLine;
} | php | protected function getNextFusionLine()
{
$fusionLine = current($this->currentSourceCodeLines);
next($this->currentSourceCodeLines);
$this->currentLineNumber++;
return $fusionLine;
} | [
"protected",
"function",
"getNextFusionLine",
"(",
")",
"{",
"$",
"fusionLine",
"=",
"current",
"(",
"$",
"this",
"->",
"currentSourceCodeLines",
")",
";",
"next",
"(",
"$",
"this",
"->",
"currentSourceCodeLines",
")",
";",
"$",
"this",
"->",
"currentLineNumbe... | Get the next, unparsed line of Fusion from this->currentSourceCodeLines and increase the pointer
@return string next line of Fusion to parse | [
"Get",
"the",
"next",
"unparsed",
"line",
"of",
"Fusion",
"from",
"this",
"-",
">",
"currentSourceCodeLines",
"and",
"increase",
"the",
"pointer"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L349-L355 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseFusionLine | protected function parseFusionLine($fusionLine)
{
$fusionLine = trim($fusionLine);
if ($this->currentBlockCommentState === true) {
$this->parseComment($fusionLine);
} else {
if ($fusionLine === '') {
return;
} elseif (preg_match(self::SCAN_PATTERN_COMMENT, $fusionLine)) {
$this->parseComment($fusionLine);
} elseif (preg_match(self::SCAN_PATTERN_OPENINGCONFINEMENT, $fusionLine)) {
$this->parseConfinementBlock($fusionLine, true);
} elseif (preg_match(self::SCAN_PATTERN_CLOSINGCONFINEMENT, $fusionLine)) {
$this->parseConfinementBlock($fusionLine, false);
} elseif (preg_match(self::SCAN_PATTERN_DECLARATION, $fusionLine)) {
$this->parseDeclaration($fusionLine);
} elseif (preg_match(self::SCAN_PATTERN_OBJECTDEFINITION, $fusionLine)) {
$this->parseObjectDefinition($fusionLine);
} else {
throw new Fusion\Exception('Syntax error in line ' . $this->currentLineNumber . '. (' . $fusionLine . ')', 1180547966);
}
}
} | php | protected function parseFusionLine($fusionLine)
{
$fusionLine = trim($fusionLine);
if ($this->currentBlockCommentState === true) {
$this->parseComment($fusionLine);
} else {
if ($fusionLine === '') {
return;
} elseif (preg_match(self::SCAN_PATTERN_COMMENT, $fusionLine)) {
$this->parseComment($fusionLine);
} elseif (preg_match(self::SCAN_PATTERN_OPENINGCONFINEMENT, $fusionLine)) {
$this->parseConfinementBlock($fusionLine, true);
} elseif (preg_match(self::SCAN_PATTERN_CLOSINGCONFINEMENT, $fusionLine)) {
$this->parseConfinementBlock($fusionLine, false);
} elseif (preg_match(self::SCAN_PATTERN_DECLARATION, $fusionLine)) {
$this->parseDeclaration($fusionLine);
} elseif (preg_match(self::SCAN_PATTERN_OBJECTDEFINITION, $fusionLine)) {
$this->parseObjectDefinition($fusionLine);
} else {
throw new Fusion\Exception('Syntax error in line ' . $this->currentLineNumber . '. (' . $fusionLine . ')', 1180547966);
}
}
} | [
"protected",
"function",
"parseFusionLine",
"(",
"$",
"fusionLine",
")",
"{",
"$",
"fusionLine",
"=",
"trim",
"(",
"$",
"fusionLine",
")",
";",
"if",
"(",
"$",
"this",
"->",
"currentBlockCommentState",
"===",
"true",
")",
"{",
"$",
"this",
"->",
"parseComm... | Parses one line of Fusion
@param string $fusionLine One line of Fusion code
@return void
@throws Fusion\Exception | [
"Parses",
"one",
"line",
"of",
"Fusion"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L364-L387 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseComment | protected function parseComment($fusionLine)
{
if (preg_match(self::SPLIT_PATTERN_COMMENTTYPE, $fusionLine, $matches, PREG_OFFSET_CAPTURE) === 1) {
switch ($matches[1][0]) {
case '/*':
$this->currentBlockCommentState = true;
break;
case '*/':
if ($this->currentBlockCommentState !== true) {
throw new Fusion\Exception('Unexpected closing block comment without matching opening block comment.', 1180615119);
}
$this->currentBlockCommentState = false;
$this->parseFusionLine(substr($fusionLine, ($matches[1][1] + 2)));
break;
case '#':
case '//':
default:
break;
}
} elseif ($this->currentBlockCommentState === false) {
throw new Fusion\Exception('No comment type matched although the comment scan regex matched the Fusion line (' . $fusionLine . ').', 1180614895);
}
} | php | protected function parseComment($fusionLine)
{
if (preg_match(self::SPLIT_PATTERN_COMMENTTYPE, $fusionLine, $matches, PREG_OFFSET_CAPTURE) === 1) {
switch ($matches[1][0]) {
case '/*':
$this->currentBlockCommentState = true;
break;
case '*/':
if ($this->currentBlockCommentState !== true) {
throw new Fusion\Exception('Unexpected closing block comment without matching opening block comment.', 1180615119);
}
$this->currentBlockCommentState = false;
$this->parseFusionLine(substr($fusionLine, ($matches[1][1] + 2)));
break;
case '#':
case '//':
default:
break;
}
} elseif ($this->currentBlockCommentState === false) {
throw new Fusion\Exception('No comment type matched although the comment scan regex matched the Fusion line (' . $fusionLine . ').', 1180614895);
}
} | [
"protected",
"function",
"parseComment",
"(",
"$",
"fusionLine",
")",
"{",
"if",
"(",
"preg_match",
"(",
"self",
"::",
"SPLIT_PATTERN_COMMENTTYPE",
",",
"$",
"fusionLine",
",",
"$",
"matches",
",",
"PREG_OFFSET_CAPTURE",
")",
"===",
"1",
")",
"{",
"switch",
... | Parses a line with comments or a line while parsing is in block comment mode.
@param string $fusionLine One line of Fusion code
@return void
@throws Fusion\Exception | [
"Parses",
"a",
"line",
"with",
"comments",
"or",
"a",
"line",
"while",
"parsing",
"is",
"in",
"block",
"comment",
"mode",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L396-L418 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseConfinementBlock | protected function parseConfinementBlock($fusionLine, $isOpeningConfinement)
{
if ($isOpeningConfinement) {
$result = trim(trim(trim($fusionLine), '{'));
array_push($this->currentObjectPathStack, $this->getCurrentObjectPathPrefix() . $result);
} else {
if (count($this->currentObjectPathStack) < 1) {
throw new Fusion\Exception('Unexpected closing confinement without matching opening confinement. Check the number of your curly braces.', 1181575973);
}
array_pop($this->currentObjectPathStack);
}
} | php | protected function parseConfinementBlock($fusionLine, $isOpeningConfinement)
{
if ($isOpeningConfinement) {
$result = trim(trim(trim($fusionLine), '{'));
array_push($this->currentObjectPathStack, $this->getCurrentObjectPathPrefix() . $result);
} else {
if (count($this->currentObjectPathStack) < 1) {
throw new Fusion\Exception('Unexpected closing confinement without matching opening confinement. Check the number of your curly braces.', 1181575973);
}
array_pop($this->currentObjectPathStack);
}
} | [
"protected",
"function",
"parseConfinementBlock",
"(",
"$",
"fusionLine",
",",
"$",
"isOpeningConfinement",
")",
"{",
"if",
"(",
"$",
"isOpeningConfinement",
")",
"{",
"$",
"result",
"=",
"trim",
"(",
"trim",
"(",
"trim",
"(",
"$",
"fusionLine",
")",
",",
... | Parses a line which opens or closes a confinement
@param string $fusionLine One line of Fusion code
@param boolean $isOpeningConfinement Set to true, if an opening confinement is to be parsed and false if it's a closing confinement.
@return void
@throws Fusion\Exception | [
"Parses",
"a",
"line",
"which",
"opens",
"or",
"closes",
"a",
"confinement"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L428-L439 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseObjectDefinition | protected function parseObjectDefinition($fusionLine)
{
$result = preg_match(self::SPLIT_PATTERN_OBJECTDEFINITION, $fusionLine, $matches);
if ($result !== 1) {
throw new Fusion\Exception('Invalid object definition "' . $fusionLine . '"', 1180548488);
}
$objectPath = $this->getCurrentObjectPathPrefix() . $matches['ObjectPath'];
switch ($matches['Operator']) {
case '=':
$this->parseValueAssignment($objectPath, $matches['Value']);
break;
case '>':
$this->parseValueUnAssignment($objectPath);
break;
case '<':
$this->parseValueCopy($matches['Value'], $objectPath);
break;
}
if (isset($matches['OpeningConfinement'])) {
$this->parseConfinementBlock($matches['ObjectPath'], true);
}
} | php | protected function parseObjectDefinition($fusionLine)
{
$result = preg_match(self::SPLIT_PATTERN_OBJECTDEFINITION, $fusionLine, $matches);
if ($result !== 1) {
throw new Fusion\Exception('Invalid object definition "' . $fusionLine . '"', 1180548488);
}
$objectPath = $this->getCurrentObjectPathPrefix() . $matches['ObjectPath'];
switch ($matches['Operator']) {
case '=':
$this->parseValueAssignment($objectPath, $matches['Value']);
break;
case '>':
$this->parseValueUnAssignment($objectPath);
break;
case '<':
$this->parseValueCopy($matches['Value'], $objectPath);
break;
}
if (isset($matches['OpeningConfinement'])) {
$this->parseConfinementBlock($matches['ObjectPath'], true);
}
} | [
"protected",
"function",
"parseObjectDefinition",
"(",
"$",
"fusionLine",
")",
"{",
"$",
"result",
"=",
"preg_match",
"(",
"self",
"::",
"SPLIT_PATTERN_OBJECTDEFINITION",
",",
"$",
"fusionLine",
",",
"$",
"matches",
")",
";",
"if",
"(",
"$",
"result",
"!==",
... | Parses an object definition.
@param string $fusionLine One line of Fusion code
@return void
@throws Fusion\Exception | [
"Parses",
"an",
"object",
"definition",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L472-L495 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseValueAssignment | protected function parseValueAssignment($objectPath, $value)
{
$processedValue = $this->getProcessedValue($value);
$this->setValueInObjectTree($this->getParsedObjectPath($objectPath), $processedValue);
} | php | protected function parseValueAssignment($objectPath, $value)
{
$processedValue = $this->getProcessedValue($value);
$this->setValueInObjectTree($this->getParsedObjectPath($objectPath), $processedValue);
} | [
"protected",
"function",
"parseValueAssignment",
"(",
"$",
"objectPath",
",",
"$",
"value",
")",
"{",
"$",
"processedValue",
"=",
"$",
"this",
"->",
"getProcessedValue",
"(",
"$",
"value",
")",
";",
"$",
"this",
"->",
"setValueInObjectTree",
"(",
"$",
"this"... | Parses a value operation of the type "assignment".
@param string $objectPath The object path as a string
@param string $value The unparsed value as a string
@return void | [
"Parses",
"a",
"value",
"operation",
"of",
"the",
"type",
"assignment",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L504-L508 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseValueUnAssignment | protected function parseValueUnAssignment($objectPath)
{
$objectPathArray = $this->getParsedObjectPath($objectPath);
$this->setValueInObjectTree($objectPathArray, null);
} | php | protected function parseValueUnAssignment($objectPath)
{
$objectPathArray = $this->getParsedObjectPath($objectPath);
$this->setValueInObjectTree($objectPathArray, null);
} | [
"protected",
"function",
"parseValueUnAssignment",
"(",
"$",
"objectPath",
")",
"{",
"$",
"objectPathArray",
"=",
"$",
"this",
"->",
"getParsedObjectPath",
"(",
"$",
"objectPath",
")",
";",
"$",
"this",
"->",
"setValueInObjectTree",
"(",
"$",
"objectPathArray",
... | Unsets the object, property or variable specified by the object path.
@param string $objectPath The object path as a string
@return void | [
"Unsets",
"the",
"object",
"property",
"or",
"variable",
"specified",
"by",
"the",
"object",
"path",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L516-L520 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseValueCopy | protected function parseValueCopy($sourceObjectPath, $targetObjectPath)
{
$sourceObjectPathArray = $this->getParsedObjectPath($sourceObjectPath);
$targetObjectPathArray = $this->getParsedObjectPath($targetObjectPath);
$sourceIsPrototypeDefinition = (count($sourceObjectPathArray) >= 2 && $sourceObjectPathArray[count($sourceObjectPathArray) - 2] === '__prototypes');
$targetIsPrototypeDefinition = (count($targetObjectPathArray) >= 2 && $targetObjectPathArray[count($targetObjectPathArray) - 2] === '__prototypes');
if ($sourceIsPrototypeDefinition || $targetIsPrototypeDefinition) {
// either source or target are a prototype definition
if ($sourceIsPrototypeDefinition && $targetIsPrototypeDefinition && count($sourceObjectPathArray) === 2 && count($targetObjectPathArray) === 2) {
// both are a prototype definition and the path has length 2: this means
// it must be of the form "prototype(Foo) < prototype(Bar)"
$targetObjectPathArray[] = '__prototypeObjectName';
$this->setValueInObjectTree($targetObjectPathArray, end($sourceObjectPathArray));
} elseif ($sourceIsPrototypeDefinition && $targetIsPrototypeDefinition) {
// Both are prototype definitions, but at least one is nested (f.e. foo.prototype(Bar))
// Currently, it is not supported to override the prototypical inheritance in
// parts of the TS rendering tree.
// Although this might work conceptually, it makes reasoning about the prototypical
// inheritance tree a lot more complex; that's why we forbid it right away.
throw new Fusion\Exception('Tried to parse "' . $targetObjectPath . '" < "' . $sourceObjectPath . '", however one of the sides is nested (e.g. foo.prototype(Bar)). Setting up prototype inheritance is only supported at the top level: prototype(Foo) < prototype(Bar)', 1358418019);
} else {
// Either "source" or "target" are no prototypes. We do not support copying a
// non-prototype value to a prototype value or vice-versa.
throw new Fusion\Exception('Tried to parse "' . $targetObjectPath . '" < "' . $sourceObjectPath . '", however one of the sides is no prototype definition of the form prototype(Foo). It is only allowed to build inheritance chains with prototype objects.', 1358418015);
}
} else {
$originalValue = $this->getValueFromObjectTree($sourceObjectPathArray);
$value = is_object($originalValue) ? clone $originalValue : $originalValue;
$this->setValueInObjectTree($targetObjectPathArray, $value);
}
} | php | protected function parseValueCopy($sourceObjectPath, $targetObjectPath)
{
$sourceObjectPathArray = $this->getParsedObjectPath($sourceObjectPath);
$targetObjectPathArray = $this->getParsedObjectPath($targetObjectPath);
$sourceIsPrototypeDefinition = (count($sourceObjectPathArray) >= 2 && $sourceObjectPathArray[count($sourceObjectPathArray) - 2] === '__prototypes');
$targetIsPrototypeDefinition = (count($targetObjectPathArray) >= 2 && $targetObjectPathArray[count($targetObjectPathArray) - 2] === '__prototypes');
if ($sourceIsPrototypeDefinition || $targetIsPrototypeDefinition) {
// either source or target are a prototype definition
if ($sourceIsPrototypeDefinition && $targetIsPrototypeDefinition && count($sourceObjectPathArray) === 2 && count($targetObjectPathArray) === 2) {
// both are a prototype definition and the path has length 2: this means
// it must be of the form "prototype(Foo) < prototype(Bar)"
$targetObjectPathArray[] = '__prototypeObjectName';
$this->setValueInObjectTree($targetObjectPathArray, end($sourceObjectPathArray));
} elseif ($sourceIsPrototypeDefinition && $targetIsPrototypeDefinition) {
// Both are prototype definitions, but at least one is nested (f.e. foo.prototype(Bar))
// Currently, it is not supported to override the prototypical inheritance in
// parts of the TS rendering tree.
// Although this might work conceptually, it makes reasoning about the prototypical
// inheritance tree a lot more complex; that's why we forbid it right away.
throw new Fusion\Exception('Tried to parse "' . $targetObjectPath . '" < "' . $sourceObjectPath . '", however one of the sides is nested (e.g. foo.prototype(Bar)). Setting up prototype inheritance is only supported at the top level: prototype(Foo) < prototype(Bar)', 1358418019);
} else {
// Either "source" or "target" are no prototypes. We do not support copying a
// non-prototype value to a prototype value or vice-versa.
throw new Fusion\Exception('Tried to parse "' . $targetObjectPath . '" < "' . $sourceObjectPath . '", however one of the sides is no prototype definition of the form prototype(Foo). It is only allowed to build inheritance chains with prototype objects.', 1358418015);
}
} else {
$originalValue = $this->getValueFromObjectTree($sourceObjectPathArray);
$value = is_object($originalValue) ? clone $originalValue : $originalValue;
$this->setValueInObjectTree($targetObjectPathArray, $value);
}
} | [
"protected",
"function",
"parseValueCopy",
"(",
"$",
"sourceObjectPath",
",",
"$",
"targetObjectPath",
")",
"{",
"$",
"sourceObjectPathArray",
"=",
"$",
"this",
"->",
"getParsedObjectPath",
"(",
"$",
"sourceObjectPath",
")",
";",
"$",
"targetObjectPathArray",
"=",
... | Copies the object or value specified by sourcObjectPath and assigns
it to targetObjectPath.
@param string $sourceObjectPath Specifies the location in the object tree from where the object or value will be taken
@param string $targetObjectPath Specifies the location in the object tree where the copy will be stored
@return void
@throws Fusion\Exception | [
"Copies",
"the",
"object",
"or",
"value",
"specified",
"by",
"sourcObjectPath",
"and",
"assigns",
"it",
"to",
"targetObjectPath",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L531-L564 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseNamespaceDeclaration | protected function parseNamespaceDeclaration($namespaceDeclaration)
{
$result = preg_match(self::SPLIT_PATTERN_NAMESPACEDECLARATION, $namespaceDeclaration, $matches);
if ($result !== 1 || !(isset($matches['alias']) && isset($matches['packageKey']))) {
throw new Fusion\Exception('Invalid namespace declaration "' . $namespaceDeclaration . '"', 1180547190);
}
$namespaceAlias = $matches['alias'];
$namespacePackageKey = $matches['packageKey'];
$this->objectTypeNamespaces[$namespaceAlias] = $namespacePackageKey;
} | php | protected function parseNamespaceDeclaration($namespaceDeclaration)
{
$result = preg_match(self::SPLIT_PATTERN_NAMESPACEDECLARATION, $namespaceDeclaration, $matches);
if ($result !== 1 || !(isset($matches['alias']) && isset($matches['packageKey']))) {
throw new Fusion\Exception('Invalid namespace declaration "' . $namespaceDeclaration . '"', 1180547190);
}
$namespaceAlias = $matches['alias'];
$namespacePackageKey = $matches['packageKey'];
$this->objectTypeNamespaces[$namespaceAlias] = $namespacePackageKey;
} | [
"protected",
"function",
"parseNamespaceDeclaration",
"(",
"$",
"namespaceDeclaration",
")",
"{",
"$",
"result",
"=",
"preg_match",
"(",
"self",
"::",
"SPLIT_PATTERN_NAMESPACEDECLARATION",
",",
"$",
"namespaceDeclaration",
",",
"$",
"matches",
")",
";",
"if",
"(",
... | Parses a namespace declaration and stores the result in the namespace registry.
@param string $namespaceDeclaration The namespace declaration, for example "neos = Neos.Neos"
@return void
@throws Fusion\Exception | [
"Parses",
"a",
"namespace",
"declaration",
"and",
"stores",
"the",
"result",
"in",
"the",
"namespace",
"registry",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L573-L583 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.parseInclude | protected function parseInclude($include)
{
$include = trim($include);
$parser = new Parser();
if (strpos($include, 'resource://') !== 0) {
// Resolve relative paths
if ($this->contextPathAndFilename !== null) {
$include = dirname($this->contextPathAndFilename) . '/' . $include;
} else {
throw new Fusion\Exception('Relative file inclusions are only possible if a context path and filename has been passed as second argument to parse()', 1329806940);
}
}
// Match recursive wildcard globbing "**/*"
if (preg_match('#([^\*]*)\*\*/\*#', $include, $matches) === 1) {
$basePath = $matches['1'];
if (!is_dir($basePath)) {
throw new Fusion\Exception(sprintf('The path %s does not point to a directory.', $basePath), 1415033179);
}
$recursiveDirectoryIterator = new \RecursiveDirectoryIterator($basePath);
$iterator = new \RecursiveIteratorIterator($recursiveDirectoryIterator);
// Match simple wildcard globbing "*"
} elseif (preg_match('#([^\*]*)\*#', $include, $matches) === 1) {
$basePath = $matches['1'];
if (!is_dir($basePath)) {
throw new Fusion\Exception(sprintf('The path %s does not point to a directory.', $basePath), 1415033180);
}
$iterator = new \DirectoryIterator($basePath);
}
// If iterator is set it means we're doing globbing
if (isset($iterator)) {
foreach ($iterator as $fileInfo) {
$pathAndFilename = $fileInfo->getPathname();
if ($fileInfo->getExtension() === 'fusion') {
// Check if not trying to recursively include the current file via globbing
if (stat($pathAndFilename) !== stat($this->contextPathAndFilename)) {
if (!is_readable($pathAndFilename)) {
throw new Fusion\Exception(sprintf('Could not include Fusion file "%s"', $pathAndFilename), 1347977018);
}
$this->objectTree = $parser->parse(file_get_contents($pathAndFilename), $pathAndFilename, $this->objectTree, false);
}
}
}
} else {
if (!is_readable($include)) {
throw new Fusion\Exception(sprintf('Could not include Fusion file "%s"', $include), 1347977017);
}
$this->objectTree = $parser->parse(file_get_contents($include), $include, $this->objectTree, false);
}
} | php | protected function parseInclude($include)
{
$include = trim($include);
$parser = new Parser();
if (strpos($include, 'resource://') !== 0) {
// Resolve relative paths
if ($this->contextPathAndFilename !== null) {
$include = dirname($this->contextPathAndFilename) . '/' . $include;
} else {
throw new Fusion\Exception('Relative file inclusions are only possible if a context path and filename has been passed as second argument to parse()', 1329806940);
}
}
// Match recursive wildcard globbing "**/*"
if (preg_match('#([^\*]*)\*\*/\*#', $include, $matches) === 1) {
$basePath = $matches['1'];
if (!is_dir($basePath)) {
throw new Fusion\Exception(sprintf('The path %s does not point to a directory.', $basePath), 1415033179);
}
$recursiveDirectoryIterator = new \RecursiveDirectoryIterator($basePath);
$iterator = new \RecursiveIteratorIterator($recursiveDirectoryIterator);
// Match simple wildcard globbing "*"
} elseif (preg_match('#([^\*]*)\*#', $include, $matches) === 1) {
$basePath = $matches['1'];
if (!is_dir($basePath)) {
throw new Fusion\Exception(sprintf('The path %s does not point to a directory.', $basePath), 1415033180);
}
$iterator = new \DirectoryIterator($basePath);
}
// If iterator is set it means we're doing globbing
if (isset($iterator)) {
foreach ($iterator as $fileInfo) {
$pathAndFilename = $fileInfo->getPathname();
if ($fileInfo->getExtension() === 'fusion') {
// Check if not trying to recursively include the current file via globbing
if (stat($pathAndFilename) !== stat($this->contextPathAndFilename)) {
if (!is_readable($pathAndFilename)) {
throw new Fusion\Exception(sprintf('Could not include Fusion file "%s"', $pathAndFilename), 1347977018);
}
$this->objectTree = $parser->parse(file_get_contents($pathAndFilename), $pathAndFilename, $this->objectTree, false);
}
}
}
} else {
if (!is_readable($include)) {
throw new Fusion\Exception(sprintf('Could not include Fusion file "%s"', $include), 1347977017);
}
$this->objectTree = $parser->parse(file_get_contents($include), $include, $this->objectTree, false);
}
} | [
"protected",
"function",
"parseInclude",
"(",
"$",
"include",
")",
"{",
"$",
"include",
"=",
"trim",
"(",
"$",
"include",
")",
";",
"$",
"parser",
"=",
"new",
"Parser",
"(",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"include",
",",
"'resource://'",
")... | Parse an include file. Currently, we start a new parser object; but we could as well re-use
the given one.
@param string $include The include value, for example " FooBar" or " resource://....". Can also include wildcard mask for Fusion globbing.
@return void
@throws Fusion\Exception | [
"Parse",
"an",
"include",
"file",
".",
"Currently",
"we",
"start",
"a",
"new",
"parser",
"object",
";",
"but",
"we",
"could",
"as",
"well",
"re",
"-",
"use",
"the",
"given",
"one",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L593-L643 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.getParsedObjectPath | protected function getParsedObjectPath($objectPath)
{
if (preg_match(self::SCAN_PATTERN_OBJECTPATH, $objectPath) === 1) {
if ($objectPath[0] === '.') {
$objectPath = $this->getCurrentObjectPathPrefix() . substr($objectPath, 1);
}
$objectPathArray = [];
foreach (preg_split(self::SPLIT_PATTERN_OBJECTPATH, $objectPath) as $objectPathSegment) {
if ($objectPathSegment[0] === '@') {
$objectPathArray[] = '__meta';
$metaProperty = substr($objectPathSegment, 1);
if ($metaProperty === 'override') {
$metaProperty = 'context';
}
$objectPathArray[] = $metaProperty;
} elseif (preg_match(self::SCAN_PATTERN_OBJECTPATHSEGMENT_IS_PROTOTYPE, $objectPathSegment)) {
$objectPathArray[] = '__prototypes';
$unexpandedObjectType = substr($objectPathSegment, 10, -1);
$objectTypeParts = explode(':', $unexpandedObjectType);
if (!isset($objectTypeParts[1])) {
$fullyQualifiedObjectType = $this->objectTypeNamespaces['default'] . ':' . $objectTypeParts[0];
} elseif (isset($this->objectTypeNamespaces[$objectTypeParts[0]])) {
$fullyQualifiedObjectType = $this->objectTypeNamespaces[$objectTypeParts[0]] . ':' . $objectTypeParts[1];
} else {
$fullyQualifiedObjectType = $unexpandedObjectType;
}
$objectPathArray[] = $fullyQualifiedObjectType;
} else {
$key = $objectPathSegment;
if (substr($key, 0, 2) === '__' && in_array($key, self::$reservedParseTreeKeys, true)) {
throw new Fusion\Exception(sprintf('Reversed key "%s" used in object path "%s".', $key, $objectPath), 1437065270);
}
$objectPathArray[] = $this->unquoteString($key);
}
}
} else {
throw new Fusion\Exception('Syntax error: Invalid object path "' . $objectPath . '".', 1180603499);
}
return $objectPathArray;
} | php | protected function getParsedObjectPath($objectPath)
{
if (preg_match(self::SCAN_PATTERN_OBJECTPATH, $objectPath) === 1) {
if ($objectPath[0] === '.') {
$objectPath = $this->getCurrentObjectPathPrefix() . substr($objectPath, 1);
}
$objectPathArray = [];
foreach (preg_split(self::SPLIT_PATTERN_OBJECTPATH, $objectPath) as $objectPathSegment) {
if ($objectPathSegment[0] === '@') {
$objectPathArray[] = '__meta';
$metaProperty = substr($objectPathSegment, 1);
if ($metaProperty === 'override') {
$metaProperty = 'context';
}
$objectPathArray[] = $metaProperty;
} elseif (preg_match(self::SCAN_PATTERN_OBJECTPATHSEGMENT_IS_PROTOTYPE, $objectPathSegment)) {
$objectPathArray[] = '__prototypes';
$unexpandedObjectType = substr($objectPathSegment, 10, -1);
$objectTypeParts = explode(':', $unexpandedObjectType);
if (!isset($objectTypeParts[1])) {
$fullyQualifiedObjectType = $this->objectTypeNamespaces['default'] . ':' . $objectTypeParts[0];
} elseif (isset($this->objectTypeNamespaces[$objectTypeParts[0]])) {
$fullyQualifiedObjectType = $this->objectTypeNamespaces[$objectTypeParts[0]] . ':' . $objectTypeParts[1];
} else {
$fullyQualifiedObjectType = $unexpandedObjectType;
}
$objectPathArray[] = $fullyQualifiedObjectType;
} else {
$key = $objectPathSegment;
if (substr($key, 0, 2) === '__' && in_array($key, self::$reservedParseTreeKeys, true)) {
throw new Fusion\Exception(sprintf('Reversed key "%s" used in object path "%s".', $key, $objectPath), 1437065270);
}
$objectPathArray[] = $this->unquoteString($key);
}
}
} else {
throw new Fusion\Exception('Syntax error: Invalid object path "' . $objectPath . '".', 1180603499);
}
return $objectPathArray;
} | [
"protected",
"function",
"getParsedObjectPath",
"(",
"$",
"objectPath",
")",
"{",
"if",
"(",
"preg_match",
"(",
"self",
"::",
"SCAN_PATTERN_OBJECTPATH",
",",
"$",
"objectPath",
")",
"===",
"1",
")",
"{",
"if",
"(",
"$",
"objectPath",
"[",
"0",
"]",
"===",
... | Parse an object path specified as a string and returns an array.
@param string $objectPath The object path to parse
@return array An object path array
@throws Fusion\Exception | [
"Parse",
"an",
"object",
"path",
"specified",
"as",
"a",
"string",
"and",
"returns",
"an",
"array",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L652-L694 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.setValueInObjectTree | protected function setValueInObjectTree(array $objectPathArray, $value, &$objectTree = null)
{
if ($objectTree === null) {
$objectTree = &$this->objectTree;
}
$currentKey = array_shift($objectPathArray);
if (is_numeric($currentKey)) {
$currentKey = (int)$currentKey;
}
if (empty($objectPathArray)) {
// last part of the iteration, setting the final value
if (isset($objectTree[$currentKey]) && $value === null) {
unset($objectTree[$currentKey]);
} elseif (isset($objectTree[$currentKey]) && is_array($objectTree[$currentKey])) {
if (is_array($value)) {
$objectTree[$currentKey] = Arrays::arrayMergeRecursiveOverrule($objectTree[$currentKey], $value);
} else {
$objectTree[$currentKey]['__value'] = $value;
$objectTree[$currentKey]['__eelExpression'] = null;
$objectTree[$currentKey]['__objectType'] = null;
}
} else {
$objectTree[$currentKey] = $value;
}
} else {
// we still need to traverse further down
if (isset($objectTree[$currentKey]) && !is_array($objectTree[$currentKey])) {
// the element one-level-down is already defined, but it is NOT an array. So we need to convert the simple type to __value
$objectTree[$currentKey] = [
'__value' => $objectTree[$currentKey],
'__eelExpression' => null,
'__objectType' => null
];
} elseif (!isset($objectTree[$currentKey])) {
$objectTree[$currentKey] = [];
}
$this->setValueInObjectTree($objectPathArray, $value, $objectTree[$currentKey]);
}
return $objectTree;
} | php | protected function setValueInObjectTree(array $objectPathArray, $value, &$objectTree = null)
{
if ($objectTree === null) {
$objectTree = &$this->objectTree;
}
$currentKey = array_shift($objectPathArray);
if (is_numeric($currentKey)) {
$currentKey = (int)$currentKey;
}
if (empty($objectPathArray)) {
// last part of the iteration, setting the final value
if (isset($objectTree[$currentKey]) && $value === null) {
unset($objectTree[$currentKey]);
} elseif (isset($objectTree[$currentKey]) && is_array($objectTree[$currentKey])) {
if (is_array($value)) {
$objectTree[$currentKey] = Arrays::arrayMergeRecursiveOverrule($objectTree[$currentKey], $value);
} else {
$objectTree[$currentKey]['__value'] = $value;
$objectTree[$currentKey]['__eelExpression'] = null;
$objectTree[$currentKey]['__objectType'] = null;
}
} else {
$objectTree[$currentKey] = $value;
}
} else {
// we still need to traverse further down
if (isset($objectTree[$currentKey]) && !is_array($objectTree[$currentKey])) {
// the element one-level-down is already defined, but it is NOT an array. So we need to convert the simple type to __value
$objectTree[$currentKey] = [
'__value' => $objectTree[$currentKey],
'__eelExpression' => null,
'__objectType' => null
];
} elseif (!isset($objectTree[$currentKey])) {
$objectTree[$currentKey] = [];
}
$this->setValueInObjectTree($objectPathArray, $value, $objectTree[$currentKey]);
}
return $objectTree;
} | [
"protected",
"function",
"setValueInObjectTree",
"(",
"array",
"$",
"objectPathArray",
",",
"$",
"value",
",",
"&",
"$",
"objectTree",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"objectTree",
"===",
"null",
")",
"{",
"$",
"objectTree",
"=",
"&",
"$",
"this",... | Assigns a value to a node or a property in the object tree, specified by the object path array.
@param array $objectPathArray The object path, specifying the node / property to set
@param mixed $value The value to assign, is a non-array type or an array with __eelExpression etc.
@param array $objectTree The current (sub-) tree, used internally - don't specify!
@return array The modified object tree | [
"Assigns",
"a",
"value",
"to",
"a",
"node",
"or",
"a",
"property",
"in",
"the",
"object",
"tree",
"specified",
"by",
"the",
"object",
"path",
"array",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L826-L869 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.& | protected function &getValueFromObjectTree(array $objectPathArray, &$objectTree = null)
{
if (is_null($objectTree)) {
$objectTree = &$this->objectTree;
}
if (count($objectPathArray) > 0) {
$currentKey = array_shift($objectPathArray);
if (is_numeric($currentKey)) {
$currentKey = (int)$currentKey;
}
if (!isset($objectTree[$currentKey])) {
$objectTree[$currentKey] = [];
}
$value = &$this->getValueFromObjectTree($objectPathArray, $objectTree[$currentKey]);
} else {
$value = &$objectTree;
}
return $value;
} | php | protected function &getValueFromObjectTree(array $objectPathArray, &$objectTree = null)
{
if (is_null($objectTree)) {
$objectTree = &$this->objectTree;
}
if (count($objectPathArray) > 0) {
$currentKey = array_shift($objectPathArray);
if (is_numeric($currentKey)) {
$currentKey = (int)$currentKey;
}
if (!isset($objectTree[$currentKey])) {
$objectTree[$currentKey] = [];
}
$value = &$this->getValueFromObjectTree($objectPathArray, $objectTree[$currentKey]);
} else {
$value = &$objectTree;
}
return $value;
} | [
"protected",
"function",
"&",
"getValueFromObjectTree",
"(",
"array",
"$",
"objectPathArray",
",",
"&",
"$",
"objectTree",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"objectTree",
")",
")",
"{",
"$",
"objectTree",
"=",
"&",
"$",
"this",
"->",... | Retrieves a value from a node in the object tree, specified by the object path array.
@param array $objectPathArray The object path, specifying the node to retrieve the value of
@param array $objectTree The current (sub-) tree, used internally - don't specify!
@return mixed The value | [
"Retrieves",
"a",
"value",
"from",
"a",
"node",
"in",
"the",
"object",
"tree",
"specified",
"by",
"the",
"object",
"path",
"array",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L878-L897 | train |
neos/neos-development-collection | Neos.Fusion/Classes/Core/Parser.php | Parser.buildPrototypeHierarchy | protected function buildPrototypeHierarchy()
{
if (!isset($this->objectTree['__prototypes'])) {
return;
}
foreach ($this->objectTree['__prototypes'] as $prototypeName => $prototypeConfiguration) {
$prototypeInheritanceHierarchy = [];
$currentPrototypeName = $prototypeName;
while (isset($this->objectTree['__prototypes'][$currentPrototypeName]['__prototypeObjectName'])) {
$currentPrototypeName = $this->objectTree['__prototypes'][$currentPrototypeName]['__prototypeObjectName'];
array_unshift($prototypeInheritanceHierarchy, $currentPrototypeName);
if ($prototypeName === $currentPrototypeName) {
throw new Fusion\Exception(sprintf('Recursive inheritance found for prototype "%s". Prototype chain: %s', $prototypeName, implode(' < ', array_reverse($prototypeInheritanceHierarchy))), 1492801503);
}
}
if (count($prototypeInheritanceHierarchy)) {
// prototype chain from most *general* to most *specific* WITHOUT the current node type!
$this->objectTree['__prototypes'][$prototypeName]['__prototypeChain'] = $prototypeInheritanceHierarchy;
}
}
} | php | protected function buildPrototypeHierarchy()
{
if (!isset($this->objectTree['__prototypes'])) {
return;
}
foreach ($this->objectTree['__prototypes'] as $prototypeName => $prototypeConfiguration) {
$prototypeInheritanceHierarchy = [];
$currentPrototypeName = $prototypeName;
while (isset($this->objectTree['__prototypes'][$currentPrototypeName]['__prototypeObjectName'])) {
$currentPrototypeName = $this->objectTree['__prototypes'][$currentPrototypeName]['__prototypeObjectName'];
array_unshift($prototypeInheritanceHierarchy, $currentPrototypeName);
if ($prototypeName === $currentPrototypeName) {
throw new Fusion\Exception(sprintf('Recursive inheritance found for prototype "%s". Prototype chain: %s', $prototypeName, implode(' < ', array_reverse($prototypeInheritanceHierarchy))), 1492801503);
}
}
if (count($prototypeInheritanceHierarchy)) {
// prototype chain from most *general* to most *specific* WITHOUT the current node type!
$this->objectTree['__prototypes'][$prototypeName]['__prototypeChain'] = $prototypeInheritanceHierarchy;
}
}
} | [
"protected",
"function",
"buildPrototypeHierarchy",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"objectTree",
"[",
"'__prototypes'",
"]",
")",
")",
"{",
"return",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"objectTree",
"[",
"'__pro... | Precalculate merged configuration for inherited prototypes.
@return void
@throws Fusion\Exception | [
"Precalculate",
"merged",
"configuration",
"for",
"inherited",
"prototypes",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Fusion/Classes/Core/Parser.php#L917-L939 | train |
neos/neos-development-collection | Neos.Media/Classes/Domain/Service/ImageService.php | ImageService.getImageSize | public function getImageSize(PersistentResource $resource)
{
$cacheIdentifier = $resource->getCacheEntryIdentifier();
$imageSize = $this->imageSizeCache->get($cacheIdentifier);
if ($imageSize !== false) {
return $imageSize;
}
// TODO: Special handling for SVG should be refactored at a later point.
if ($resource->getMediaType() === 'image/svg+xml') {
$imageSize = ['width' => null, 'height' => null];
} else {
try {
$imagineImage = $this->imagineService->read($resource->getStream());
$sizeBox = $imagineImage->getSize();
$imageSize = ['width' => $sizeBox->getWidth(), 'height' => $sizeBox->getHeight()];
} catch (\Exception $e) {
throw new ImageFileException(sprintf('The given resource was not an image file your choosen driver can open. The original error was: %s', $e->getMessage()), 1336662898);
}
}
$this->imageSizeCache->set($cacheIdentifier, $imageSize);
return $imageSize;
} | php | public function getImageSize(PersistentResource $resource)
{
$cacheIdentifier = $resource->getCacheEntryIdentifier();
$imageSize = $this->imageSizeCache->get($cacheIdentifier);
if ($imageSize !== false) {
return $imageSize;
}
// TODO: Special handling for SVG should be refactored at a later point.
if ($resource->getMediaType() === 'image/svg+xml') {
$imageSize = ['width' => null, 'height' => null];
} else {
try {
$imagineImage = $this->imagineService->read($resource->getStream());
$sizeBox = $imagineImage->getSize();
$imageSize = ['width' => $sizeBox->getWidth(), 'height' => $sizeBox->getHeight()];
} catch (\Exception $e) {
throw new ImageFileException(sprintf('The given resource was not an image file your choosen driver can open. The original error was: %s', $e->getMessage()), 1336662898);
}
}
$this->imageSizeCache->set($cacheIdentifier, $imageSize);
return $imageSize;
} | [
"public",
"function",
"getImageSize",
"(",
"PersistentResource",
"$",
"resource",
")",
"{",
"$",
"cacheIdentifier",
"=",
"$",
"resource",
"->",
"getCacheEntryIdentifier",
"(",
")",
";",
"$",
"imageSize",
"=",
"$",
"this",
"->",
"imageSizeCache",
"->",
"get",
"... | Get the size of a Flow PersistentResource that contains an image file.
@param PersistentResource $resource
@return array width and height as keys
@throws ImageFileException | [
"Get",
"the",
"size",
"of",
"a",
"Flow",
"PersistentResource",
"that",
"contains",
"an",
"image",
"file",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Media/Classes/Domain/Service/ImageService.php#L248-L272 | train |
neos/neos-development-collection | Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php | AbstractMenuItemsImplementation.getRenderHiddenInIndex | public function getRenderHiddenInIndex()
{
if ($this->renderHiddenInIndex === null) {
$this->renderHiddenInIndex = (boolean)$this->fusionValue('renderHiddenInIndex');
}
return $this->renderHiddenInIndex;
} | php | public function getRenderHiddenInIndex()
{
if ($this->renderHiddenInIndex === null) {
$this->renderHiddenInIndex = (boolean)$this->fusionValue('renderHiddenInIndex');
}
return $this->renderHiddenInIndex;
} | [
"public",
"function",
"getRenderHiddenInIndex",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"renderHiddenInIndex",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"renderHiddenInIndex",
"=",
"(",
"boolean",
")",
"$",
"this",
"->",
"fusionValue",
"(",
"'renderHi... | Should nodes that have "hiddenInIndex" set still be visible in this menu.
@return boolean | [
"Should",
"nodes",
"that",
"have",
"hiddenInIndex",
"set",
"still",
"be",
"visible",
"in",
"this",
"menu",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php#L69-L76 | train |
neos/neos-development-collection | Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php | AbstractMenuItemsImplementation.getItems | public function getItems()
{
if ($this->items === null) {
$fusionContext = $this->runtime->getCurrentContext();
$this->currentNode = isset($fusionContext['activeNode']) ? $fusionContext['activeNode'] : $fusionContext['documentNode'];
$this->currentLevel = 1;
$this->items = $this->buildItems();
}
return $this->items;
} | php | public function getItems()
{
if ($this->items === null) {
$fusionContext = $this->runtime->getCurrentContext();
$this->currentNode = isset($fusionContext['activeNode']) ? $fusionContext['activeNode'] : $fusionContext['documentNode'];
$this->currentLevel = 1;
$this->items = $this->buildItems();
}
return $this->items;
} | [
"public",
"function",
"getItems",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"items",
"===",
"null",
")",
"{",
"$",
"fusionContext",
"=",
"$",
"this",
"->",
"runtime",
"->",
"getCurrentContext",
"(",
")",
";",
"$",
"this",
"->",
"currentNode",
"=",
... | Main API method which sends the to-be-rendered data to Fluid
@return array | [
"Main",
"API",
"method",
"which",
"sends",
"the",
"to",
"-",
"be",
"-",
"rendered",
"data",
"to",
"Fluid"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php#L83-L93 | train |
neos/neos-development-collection | Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php | AbstractMenuItemsImplementation.getCurrentNodeRootline | protected function getCurrentNodeRootline()
{
if ($this->currentNodeRootline === null) {
$nodeRootline = $this->currentNode->getContext()->getNodesOnPath($this->currentNode->getContext()->getCurrentSiteNode()->getPath(), $this->currentNode->getPath());
$this->currentNodeRootline = [];
foreach ($nodeRootline as $rootlineElement) {
$this->currentNodeRootline[$this->getNodeLevelInSite($rootlineElement)] = $rootlineElement;
}
}
return $this->currentNodeRootline;
} | php | protected function getCurrentNodeRootline()
{
if ($this->currentNodeRootline === null) {
$nodeRootline = $this->currentNode->getContext()->getNodesOnPath($this->currentNode->getContext()->getCurrentSiteNode()->getPath(), $this->currentNode->getPath());
$this->currentNodeRootline = [];
foreach ($nodeRootline as $rootlineElement) {
$this->currentNodeRootline[$this->getNodeLevelInSite($rootlineElement)] = $rootlineElement;
}
}
return $this->currentNodeRootline;
} | [
"protected",
"function",
"getCurrentNodeRootline",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"currentNodeRootline",
"===",
"null",
")",
"{",
"$",
"nodeRootline",
"=",
"$",
"this",
"->",
"currentNode",
"->",
"getContext",
"(",
")",
"->",
"getNodesOnPath",
... | Get the rootline from the current node up to the site node.
@return array | [
"Get",
"the",
"rootline",
"from",
"the",
"current",
"node",
"up",
"to",
"the",
"site",
"node",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php#L160-L172 | train |
neos/neos-development-collection | Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php | AbstractMenuItemsImplementation.getNodeLevelInSite | protected function getNodeLevelInSite(NodeInterface $node)
{
$siteNode = $this->currentNode->getContext()->getCurrentSiteNode();
return $node->getDepth() - $siteNode->getDepth();
} | php | protected function getNodeLevelInSite(NodeInterface $node)
{
$siteNode = $this->currentNode->getContext()->getCurrentSiteNode();
return $node->getDepth() - $siteNode->getDepth();
} | [
"protected",
"function",
"getNodeLevelInSite",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"$",
"siteNode",
"=",
"$",
"this",
"->",
"currentNode",
"->",
"getContext",
"(",
")",
"->",
"getCurrentSiteNode",
"(",
")",
";",
"return",
"$",
"node",
"->",
"getDept... | Node Level relative to site root node.
0 = Site root node
@param NodeInterface $node
@return integer | [
"Node",
"Level",
"relative",
"to",
"site",
"root",
"node",
".",
"0",
"=",
"Site",
"root",
"node"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Fusion/AbstractMenuItemsImplementation.php#L181-L185 | train |
neos/neos-development-collection | Neos.SiteKickstarter/Classes/Command/KickstartCommandController.php | KickstartCommandController.siteCommand | public function siteCommand($packageKey, $siteName)
{
if (!$this->packageManager->isPackageKeyValid($packageKey)) {
$this->outputLine('Package key "%s" is not valid. Only UpperCamelCase in the format "Vendor.PackageKey", please!', [$packageKey]);
$this->quit(1);
}
if ($this->packageManager->isPackageAvailable($packageKey)) {
$this->outputLine('Package "%s" already exists.', [$packageKey]);
$this->quit(1);
}
$generatedFiles = $this->generatorService->generateSitePackage($packageKey, $siteName);
$this->outputLine(implode(PHP_EOL, $generatedFiles));
} | php | public function siteCommand($packageKey, $siteName)
{
if (!$this->packageManager->isPackageKeyValid($packageKey)) {
$this->outputLine('Package key "%s" is not valid. Only UpperCamelCase in the format "Vendor.PackageKey", please!', [$packageKey]);
$this->quit(1);
}
if ($this->packageManager->isPackageAvailable($packageKey)) {
$this->outputLine('Package "%s" already exists.', [$packageKey]);
$this->quit(1);
}
$generatedFiles = $this->generatorService->generateSitePackage($packageKey, $siteName);
$this->outputLine(implode(PHP_EOL, $generatedFiles));
} | [
"public",
"function",
"siteCommand",
"(",
"$",
"packageKey",
",",
"$",
"siteName",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"packageManager",
"->",
"isPackageKeyValid",
"(",
"$",
"packageKey",
")",
")",
"{",
"$",
"this",
"->",
"outputLine",
"(",
"'Pa... | Kickstart a new site package
This command generates a new site package with basic Fusion and Sites.xml
@param string $packageKey The packageKey for your site
@param string $siteName The siteName of your site
@return string | [
"Kickstart",
"a",
"new",
"site",
"package"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.SiteKickstarter/Classes/Command/KickstartCommandController.php#L45-L59 | train |
neos/neos-development-collection | Neos.Neos/Classes/Security/Authorization/Privilege/ModulePrivilege.php | ModulePrivilege.matchesSubject | public function matchesSubject(PrivilegeSubjectInterface $subject)
{
if (!($subject instanceof ModulePrivilegeSubject) && !($subject instanceof MethodPrivilegeSubject)) {
throw new InvalidPrivilegeTypeException(
sprintf(
'Privileges of type "%s" only support subjects of type "%s" or "%s", but we got a subject of type: "%s".',
self::class,
ModulePrivilegeSubject::class,
MethodPrivilegeSubject::class,
get_class($subject)
), 1493130646);
}
$this->initialize();
if ($subject instanceof MethodPrivilegeSubject) {
return $this->methodPrivilege->matchesSubject($subject);
}
return $subject->getModulePath() === $this->getParsedMatcher();
} | php | public function matchesSubject(PrivilegeSubjectInterface $subject)
{
if (!($subject instanceof ModulePrivilegeSubject) && !($subject instanceof MethodPrivilegeSubject)) {
throw new InvalidPrivilegeTypeException(
sprintf(
'Privileges of type "%s" only support subjects of type "%s" or "%s", but we got a subject of type: "%s".',
self::class,
ModulePrivilegeSubject::class,
MethodPrivilegeSubject::class,
get_class($subject)
), 1493130646);
}
$this->initialize();
if ($subject instanceof MethodPrivilegeSubject) {
return $this->methodPrivilege->matchesSubject($subject);
}
return $subject->getModulePath() === $this->getParsedMatcher();
} | [
"public",
"function",
"matchesSubject",
"(",
"PrivilegeSubjectInterface",
"$",
"subject",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"subject",
"instanceof",
"ModulePrivilegeSubject",
")",
"&&",
"!",
"(",
"$",
"subject",
"instanceof",
"MethodPrivilegeSubject",
")",
")",
... | Returns true, if this privilege covers the given subject
@param PrivilegeSubjectInterface $subject
@return boolean
@throws InvalidPrivilegeTypeException if the given $subject is not supported by the privilege | [
"Returns",
"true",
"if",
"this",
"privilege",
"covers",
"the",
"given",
"subject"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Security/Authorization/Privilege/ModulePrivilege.php#L92-L109 | train |
neos/neos-development-collection | Neos.ContentRepository/Classes/Domain/Service/ConfigurationContentDimensionPresetSource.php | ConfigurationContentDimensionPresetSource.getAllowedDimensionPresetsAccordingToPreselection | public function getAllowedDimensionPresetsAccordingToPreselection($dimensionName, array $preselectedDimensionPresets)
{
if (!isset($this->configuration[$dimensionName])) {
return null;
}
$dimensionConfiguration = [$dimensionName => $this->configuration[$dimensionName]];
$sorter = new PositionalArraySorter($dimensionConfiguration[$dimensionName]['presets']);
$dimensionConfiguration[$dimensionName]['presets'] = $sorter->toArray();
foreach (array_keys($dimensionConfiguration[$dimensionName]['presets']) as $presetIdentifier) {
$currentPresetCombination = $preselectedDimensionPresets;
$currentPresetCombination[$dimensionName] = $presetIdentifier;
if (!$this->isPresetCombinationAllowedByConstraints($currentPresetCombination)) {
unset($dimensionConfiguration[$dimensionName]['presets'][$presetIdentifier]);
}
}
return $dimensionConfiguration;
} | php | public function getAllowedDimensionPresetsAccordingToPreselection($dimensionName, array $preselectedDimensionPresets)
{
if (!isset($this->configuration[$dimensionName])) {
return null;
}
$dimensionConfiguration = [$dimensionName => $this->configuration[$dimensionName]];
$sorter = new PositionalArraySorter($dimensionConfiguration[$dimensionName]['presets']);
$dimensionConfiguration[$dimensionName]['presets'] = $sorter->toArray();
foreach (array_keys($dimensionConfiguration[$dimensionName]['presets']) as $presetIdentifier) {
$currentPresetCombination = $preselectedDimensionPresets;
$currentPresetCombination[$dimensionName] = $presetIdentifier;
if (!$this->isPresetCombinationAllowedByConstraints($currentPresetCombination)) {
unset($dimensionConfiguration[$dimensionName]['presets'][$presetIdentifier]);
}
}
return $dimensionConfiguration;
} | [
"public",
"function",
"getAllowedDimensionPresetsAccordingToPreselection",
"(",
"$",
"dimensionName",
",",
"array",
"$",
"preselectedDimensionPresets",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"configuration",
"[",
"$",
"dimensionName",
"]",
")",
... | Returns a list of presets of the specified dimension which are allowed in combination with the given presets
of other dimensions.
@param string $dimensionName Name of the dimension to return presets for
@param array $preselectedDimensionPresets An array of dimension name and preset identifier specifying the presets which are already selected
@return array An array of presets only for the dimension specified in $dimensionName. Structure is: array($dimensionName => array('presets' => array(...)) | [
"Returns",
"a",
"list",
"of",
"presets",
"of",
"the",
"specified",
"dimension",
"which",
"are",
"allowed",
"in",
"combination",
"with",
"the",
"given",
"presets",
"of",
"other",
"dimensions",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.ContentRepository/Classes/Domain/Service/ConfigurationContentDimensionPresetSource.php#L90-L109 | train |
neos/neos-development-collection | Neos.ContentRepository/Classes/Domain/Service/ConfigurationContentDimensionPresetSource.php | ConfigurationContentDimensionPresetSource.isPresetCombinationAllowedByConstraints | public function isPresetCombinationAllowedByConstraints(array $dimensionsNamesAndPresetIdentifiers)
{
foreach ($dimensionsNamesAndPresetIdentifiers as $dimensionName => $presetIdentifier) {
if (!isset($this->configuration[$dimensionName]) || !isset($this->configuration[$dimensionName]['presets'][$presetIdentifier])) {
return false;
}
foreach ($this->configuration as $currentDimensionName => $dimensionConfiguration) {
if (!isset($dimensionsNamesAndPresetIdentifiers[$currentDimensionName])) {
continue;
}
$currentPresetIdentifier = $dimensionsNamesAndPresetIdentifiers[$currentDimensionName];
if (isset($dimensionConfiguration['presets'][$currentPresetIdentifier]['constraints'])) {
$constraintsResult = $this->isPresetAllowedByConstraints($dimensionName, $presetIdentifier, $dimensionConfiguration['presets'][$currentPresetIdentifier]['constraints']);
if ($constraintsResult === false) {
return false;
}
}
}
}
return true;
} | php | public function isPresetCombinationAllowedByConstraints(array $dimensionsNamesAndPresetIdentifiers)
{
foreach ($dimensionsNamesAndPresetIdentifiers as $dimensionName => $presetIdentifier) {
if (!isset($this->configuration[$dimensionName]) || !isset($this->configuration[$dimensionName]['presets'][$presetIdentifier])) {
return false;
}
foreach ($this->configuration as $currentDimensionName => $dimensionConfiguration) {
if (!isset($dimensionsNamesAndPresetIdentifiers[$currentDimensionName])) {
continue;
}
$currentPresetIdentifier = $dimensionsNamesAndPresetIdentifiers[$currentDimensionName];
if (isset($dimensionConfiguration['presets'][$currentPresetIdentifier]['constraints'])) {
$constraintsResult = $this->isPresetAllowedByConstraints($dimensionName, $presetIdentifier, $dimensionConfiguration['presets'][$currentPresetIdentifier]['constraints']);
if ($constraintsResult === false) {
return false;
}
}
}
}
return true;
} | [
"public",
"function",
"isPresetCombinationAllowedByConstraints",
"(",
"array",
"$",
"dimensionsNamesAndPresetIdentifiers",
")",
"{",
"foreach",
"(",
"$",
"dimensionsNamesAndPresetIdentifiers",
"as",
"$",
"dimensionName",
"=>",
"$",
"presetIdentifier",
")",
"{",
"if",
"(",... | Checks if the given combination of presets is allowed, according to possibly defined constraints in the
content dimension configuration.
@param array $dimensionsNamesAndPresetIdentifiers Preset pairs, for example array('language' => 'de', 'country' => 'GER', 'persona' => 'clueless')
@return boolean | [
"Checks",
"if",
"the",
"given",
"combination",
"of",
"presets",
"is",
"allowed",
"according",
"to",
"possibly",
"defined",
"constraints",
"in",
"the",
"content",
"dimension",
"configuration",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.ContentRepository/Classes/Domain/Service/ConfigurationContentDimensionPresetSource.php#L118-L139 | train |
neos/neos-development-collection | Neos.ContentRepository/Classes/Domain/Service/ConfigurationContentDimensionPresetSource.php | ConfigurationContentDimensionPresetSource.isPresetAllowedByConstraints | protected function isPresetAllowedByConstraints($dimensionName, $presetIdentifier, array $constraints)
{
if (!array_key_exists($dimensionName, $constraints)) {
return true;
}
if (array_key_exists($presetIdentifier, $constraints[$dimensionName]) && $constraints[$dimensionName][$presetIdentifier] === true) {
return true;
}
if (array_key_exists($presetIdentifier, $constraints[$dimensionName]) && $constraints[$dimensionName][$presetIdentifier] === false) {
return false;
}
if (array_key_exists('*', $constraints[$dimensionName])) {
return (boolean)$constraints[$dimensionName]['*'];
}
return true;
} | php | protected function isPresetAllowedByConstraints($dimensionName, $presetIdentifier, array $constraints)
{
if (!array_key_exists($dimensionName, $constraints)) {
return true;
}
if (array_key_exists($presetIdentifier, $constraints[$dimensionName]) && $constraints[$dimensionName][$presetIdentifier] === true) {
return true;
}
if (array_key_exists($presetIdentifier, $constraints[$dimensionName]) && $constraints[$dimensionName][$presetIdentifier] === false) {
return false;
}
if (array_key_exists('*', $constraints[$dimensionName])) {
return (boolean)$constraints[$dimensionName]['*'];
}
return true;
} | [
"protected",
"function",
"isPresetAllowedByConstraints",
"(",
"$",
"dimensionName",
",",
"$",
"presetIdentifier",
",",
"array",
"$",
"constraints",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"dimensionName",
",",
"$",
"constraints",
")",
")",
"{",
... | Checks if the given preset of the specified dimension is allowed according to the given constraints
@param string $dimensionName Name of the dimension the preset belongs to
@param string $presetIdentifier Identifier of the preset to check
@param array $constraints Constraints to use for the check
@return boolean | [
"Checks",
"if",
"the",
"given",
"preset",
"of",
"the",
"specified",
"dimension",
"is",
"allowed",
"according",
"to",
"the",
"given",
"constraints"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.ContentRepository/Classes/Domain/Service/ConfigurationContentDimensionPresetSource.php#L149-L165 | train |
neos/neos-development-collection | Neos.Neos/Classes/Controller/Module/User/UserSettingsController.php | UserSettingsController.updateAction | public function updateAction(User $user)
{
$this->userService->updateUser($user);
$this->addFlashMessage('Your user has been updated.', 'User updated', Message::SEVERITY_OK);
$this->redirect('edit');
} | php | public function updateAction(User $user)
{
$this->userService->updateUser($user);
$this->addFlashMessage('Your user has been updated.', 'User updated', Message::SEVERITY_OK);
$this->redirect('edit');
} | [
"public",
"function",
"updateAction",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"userService",
"->",
"updateUser",
"(",
"$",
"user",
")",
";",
"$",
"this",
"->",
"addFlashMessage",
"(",
"'Your user has been updated.'",
",",
"'User updated'",
",",
... | Update the current user
@param User $user The user to update, including updated data already (name, email address etc)
@return void | [
"Update",
"the",
"current",
"user"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Controller/Module/User/UserSettingsController.php#L101-L106 | train |
neos/neos-development-collection | Neos.Neos/Classes/Controller/Module/User/UserSettingsController.php | UserSettingsController.editAccountAction | public function editAccountAction(Account $account)
{
$this->view->assignMultiple([
'account' => $account,
'user' => $this->userService->getUser($account->getAccountIdentifier(), $account->getAuthenticationProviderName())
]);
} | php | public function editAccountAction(Account $account)
{
$this->view->assignMultiple([
'account' => $account,
'user' => $this->userService->getUser($account->getAccountIdentifier(), $account->getAuthenticationProviderName())
]);
} | [
"public",
"function",
"editAccountAction",
"(",
"Account",
"$",
"account",
")",
"{",
"$",
"this",
"->",
"view",
"->",
"assignMultiple",
"(",
"[",
"'account'",
"=>",
"$",
"account",
",",
"'user'",
"=>",
"$",
"this",
"->",
"userService",
"->",
"getUser",
"("... | Edit the given account
@param Account $account
@return void | [
"Edit",
"the",
"given",
"account"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Controller/Module/User/UserSettingsController.php#L114-L120 | train |
neos/neos-development-collection | Neos.Neos/Classes/Controller/Module/User/UserSettingsController.php | UserSettingsController.updateAccountAction | public function updateAccountAction(array $password = [])
{
$user = $this->currentUser;
$password = array_shift($password);
if (strlen(trim(strval($password))) > 0) {
$this->userService->setUserPassword($user, $password);
$this->addFlashMessage('The password has been updated.', 'Password updated', Message::SEVERITY_OK);
}
$this->redirect('index');
} | php | public function updateAccountAction(array $password = [])
{
$user = $this->currentUser;
$password = array_shift($password);
if (strlen(trim(strval($password))) > 0) {
$this->userService->setUserPassword($user, $password);
$this->addFlashMessage('The password has been updated.', 'Password updated', Message::SEVERITY_OK);
}
$this->redirect('index');
} | [
"public",
"function",
"updateAccountAction",
"(",
"array",
"$",
"password",
"=",
"[",
"]",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"currentUser",
";",
"$",
"password",
"=",
"array_shift",
"(",
"$",
"password",
")",
";",
"if",
"(",
"strlen",
"(",... | Update a given account, ie. the password
@param array $password Expects an array in the format array('<password>', '<password confirmation>')
@Flow\Validate(argumentName="password", type="\Neos\Neos\Validation\Validator\PasswordValidator", options={ "allowEmpty"=1, "minimum"=1, "maximum"=255 })
@return void | [
"Update",
"a",
"given",
"account",
"ie",
".",
"the",
"password"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Controller/Module/User/UserSettingsController.php#L129-L138 | train |
neos/neos-development-collection | Neos.Neos/Classes/Fusion/ConvertUrisImplementation.php | ConvertUrisImplementation.evaluate | public function evaluate()
{
$text = $this->fusionValue('value');
if ($text === '' || $text === null) {
return '';
}
if (!is_string($text)) {
throw new Exception(sprintf('Only strings can be processed by this Fusion object, given: "%s".', gettype($text)), 1382624080);
}
$node = $this->fusionValue('node');
if (!$node instanceof NodeInterface) {
throw new Exception(sprintf('The current node must be an instance of NodeInterface, given: "%s".', gettype($text)), 1382624087);
}
if ($node->getContext()->getWorkspace()->getName() !== 'live' && !($this->fusionValue('forceConversion'))) {
return $text;
}
$unresolvedUris = [];
$linkingService = $this->linkingService;
$controllerContext = $this->runtime->getControllerContext();
$absolute = $this->fusionValue('absolute');
$processedContent = preg_replace_callback(LinkingService::PATTERN_SUPPORTED_URIS, function (array $matches) use ($node, $linkingService, $controllerContext, &$unresolvedUris, $absolute) {
switch ($matches[1]) {
case 'node':
$resolvedUri = $linkingService->resolveNodeUri($matches[0], $node, $controllerContext, $absolute);
$this->runtime->addCacheTag('node', $matches[2]);
break;
case 'asset':
$resolvedUri = $linkingService->resolveAssetUri($matches[0]);
$this->runtime->addCacheTag('asset', $matches[2]);
break;
default:
$resolvedUri = null;
}
if ($resolvedUri === null) {
$unresolvedUris[] = $matches[0];
return $matches[0];
}
return $resolvedUri;
}, $text);
if ($unresolvedUris !== []) {
$processedContent = preg_replace('/<a[^>]* href="(node|asset):\/\/[^"]+"[^>]*>(.*?)<\/a>/', '$2', $processedContent);
$processedContent = preg_replace(LinkingService::PATTERN_SUPPORTED_URIS, '', $processedContent);
}
$processedContent = $this->replaceLinkTargets($processedContent);
return $processedContent;
} | php | public function evaluate()
{
$text = $this->fusionValue('value');
if ($text === '' || $text === null) {
return '';
}
if (!is_string($text)) {
throw new Exception(sprintf('Only strings can be processed by this Fusion object, given: "%s".', gettype($text)), 1382624080);
}
$node = $this->fusionValue('node');
if (!$node instanceof NodeInterface) {
throw new Exception(sprintf('The current node must be an instance of NodeInterface, given: "%s".', gettype($text)), 1382624087);
}
if ($node->getContext()->getWorkspace()->getName() !== 'live' && !($this->fusionValue('forceConversion'))) {
return $text;
}
$unresolvedUris = [];
$linkingService = $this->linkingService;
$controllerContext = $this->runtime->getControllerContext();
$absolute = $this->fusionValue('absolute');
$processedContent = preg_replace_callback(LinkingService::PATTERN_SUPPORTED_URIS, function (array $matches) use ($node, $linkingService, $controllerContext, &$unresolvedUris, $absolute) {
switch ($matches[1]) {
case 'node':
$resolvedUri = $linkingService->resolveNodeUri($matches[0], $node, $controllerContext, $absolute);
$this->runtime->addCacheTag('node', $matches[2]);
break;
case 'asset':
$resolvedUri = $linkingService->resolveAssetUri($matches[0]);
$this->runtime->addCacheTag('asset', $matches[2]);
break;
default:
$resolvedUri = null;
}
if ($resolvedUri === null) {
$unresolvedUris[] = $matches[0];
return $matches[0];
}
return $resolvedUri;
}, $text);
if ($unresolvedUris !== []) {
$processedContent = preg_replace('/<a[^>]* href="(node|asset):\/\/[^"]+"[^>]*>(.*?)<\/a>/', '$2', $processedContent);
$processedContent = preg_replace(LinkingService::PATTERN_SUPPORTED_URIS, '', $processedContent);
}
$processedContent = $this->replaceLinkTargets($processedContent);
return $processedContent;
} | [
"public",
"function",
"evaluate",
"(",
")",
"{",
"$",
"text",
"=",
"$",
"this",
"->",
"fusionValue",
"(",
"'value'",
")",
";",
"if",
"(",
"$",
"text",
"===",
"''",
"||",
"$",
"text",
"===",
"null",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
... | Convert URIs matching a supported scheme with generated URIs
If the workspace of the current node context is not live, no replacement will be done unless forceConversion is
set. This is needed to show the editable links with metadata in the content module.
@return string
@throws Exception | [
"Convert",
"URIs",
"matching",
"a",
"supported",
"scheme",
"with",
"generated",
"URIs"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Fusion/ConvertUrisImplementation.php#L68-L126 | train |
neos/neos-development-collection | Neos.Neos/Classes/Fusion/ConvertUrisImplementation.php | ConvertUrisImplementation.replaceLinkTargets | protected function replaceLinkTargets($processedContent)
{
$noOpenerString = $this->fusionValue('setNoOpener') ? ' rel="noopener"' : '';
$externalLinkTarget = trim($this->fusionValue('externalLinkTarget'));
$resourceLinkTarget = trim($this->fusionValue('resourceLinkTarget'));
if ($externalLinkTarget === '' && $resourceLinkTarget === '') {
return $processedContent;
}
$controllerContext = $this->runtime->getControllerContext();
$host = $controllerContext->getRequest()->getHttpRequest()->getUri()->getHost();
$processedContent = preg_replace_callback(
'~<a .*?href="(.*?)".*?>~i',
function ($matches) use ($externalLinkTarget, $resourceLinkTarget, $host, $noOpenerString) {
list($linkText, $linkHref) = $matches;
$uriHost = parse_url($linkHref, PHP_URL_HOST);
$target = null;
if ($externalLinkTarget !== '' && is_string($uriHost) && $uriHost !== $host) {
$target = $externalLinkTarget;
}
if ($resourceLinkTarget !== '' && strpos($linkHref, '_Resources') !== false) {
$target = $resourceLinkTarget;
}
if ($target === null) {
return $linkText;
}
if (preg_match_all('~target="(.*?)~i', $linkText, $targetMatches)) {
return preg_replace('/target=".*?"/', sprintf('target="%s"%s', $target, $target === '_blank' ? $noOpenerString : ''), $linkText);
}
return str_replace('<a', sprintf('<a target="%s"%s', $target, $target === '_blank' ? $noOpenerString : ''), $linkText);
},
$processedContent
);
return $processedContent;
} | php | protected function replaceLinkTargets($processedContent)
{
$noOpenerString = $this->fusionValue('setNoOpener') ? ' rel="noopener"' : '';
$externalLinkTarget = trim($this->fusionValue('externalLinkTarget'));
$resourceLinkTarget = trim($this->fusionValue('resourceLinkTarget'));
if ($externalLinkTarget === '' && $resourceLinkTarget === '') {
return $processedContent;
}
$controllerContext = $this->runtime->getControllerContext();
$host = $controllerContext->getRequest()->getHttpRequest()->getUri()->getHost();
$processedContent = preg_replace_callback(
'~<a .*?href="(.*?)".*?>~i',
function ($matches) use ($externalLinkTarget, $resourceLinkTarget, $host, $noOpenerString) {
list($linkText, $linkHref) = $matches;
$uriHost = parse_url($linkHref, PHP_URL_HOST);
$target = null;
if ($externalLinkTarget !== '' && is_string($uriHost) && $uriHost !== $host) {
$target = $externalLinkTarget;
}
if ($resourceLinkTarget !== '' && strpos($linkHref, '_Resources') !== false) {
$target = $resourceLinkTarget;
}
if ($target === null) {
return $linkText;
}
if (preg_match_all('~target="(.*?)~i', $linkText, $targetMatches)) {
return preg_replace('/target=".*?"/', sprintf('target="%s"%s', $target, $target === '_blank' ? $noOpenerString : ''), $linkText);
}
return str_replace('<a', sprintf('<a target="%s"%s', $target, $target === '_blank' ? $noOpenerString : ''), $linkText);
},
$processedContent
);
return $processedContent;
} | [
"protected",
"function",
"replaceLinkTargets",
"(",
"$",
"processedContent",
")",
"{",
"$",
"noOpenerString",
"=",
"$",
"this",
"->",
"fusionValue",
"(",
"'setNoOpener'",
")",
"?",
"' rel=\"noopener\"'",
":",
"''",
";",
"$",
"externalLinkTarget",
"=",
"trim",
"(... | Replace the target attribute of link tags in processedContent with the target
specified by externalLinkTarget and resourceLinkTarget options.
Additionally set rel="noopener" for links with target="_blank".
@param string $processedContent
@return string | [
"Replace",
"the",
"target",
"attribute",
"of",
"link",
"tags",
"in",
"processedContent",
"with",
"the",
"target",
"specified",
"by",
"externalLinkTarget",
"and",
"resourceLinkTarget",
"options",
".",
"Additionally",
"set",
"rel",
"=",
"noopener",
"for",
"links",
"... | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Fusion/ConvertUrisImplementation.php#L136-L169 | train |
neos/neos-development-collection | Neos.Neos/Classes/Domain/Model/PluginViewDefinition.php | PluginViewDefinition.getLabel | public function getLabel()
{
$translationHelper = new TranslationHelper();
return isset($this->configuration['label']) ? $translationHelper->translate($this->configuration['label']) : '';
} | php | public function getLabel()
{
$translationHelper = new TranslationHelper();
return isset($this->configuration['label']) ? $translationHelper->translate($this->configuration['label']) : '';
} | [
"public",
"function",
"getLabel",
"(",
")",
"{",
"$",
"translationHelper",
"=",
"new",
"TranslationHelper",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"configuration",
"[",
"'label'",
"]",
")",
"?",
"$",
"translationHelper",
"->",
"translate",... | Get the human-readable label of this node type
@return string
@api | [
"Get",
"the",
"human",
"-",
"readable",
"label",
"of",
"this",
"node",
"type"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Domain/Model/PluginViewDefinition.php#L92-L96 | train |
neos/neos-development-collection | Neos.Neos/Classes/EventLog/Domain/Service/EventEmittingService.php | EventEmittingService.emit | public function emit($eventType, array $data, $eventClassName = Event::class)
{
if (!$this->isEnabled()) {
throw new Exception('Event log not enabled', 1418464933);
}
$event = $this->generate($eventType, $data, $eventClassName);
$this->add($event);
return $event;
} | php | public function emit($eventType, array $data, $eventClassName = Event::class)
{
if (!$this->isEnabled()) {
throw new Exception('Event log not enabled', 1418464933);
}
$event = $this->generate($eventType, $data, $eventClassName);
$this->add($event);
return $event;
} | [
"public",
"function",
"emit",
"(",
"$",
"eventType",
",",
"array",
"$",
"data",
",",
"$",
"eventClassName",
"=",
"Event",
"::",
"class",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isEnabled",
"(",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
... | Convenience method for generating an event and directly adding it afterwards to persistence.
@param string $eventType
@param array $data
@param string $eventClassName
@throws Exception
@return Event | [
"Convenience",
"method",
"for",
"generating",
"an",
"event",
"and",
"directly",
"adding",
"it",
"afterwards",
"to",
"persistence",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/EventLog/Domain/Service/EventEmittingService.php#L86-L96 | train |
neos/neos-development-collection | Neos.Neos/Classes/EventLog/Domain/Service/EventEmittingService.php | EventEmittingService.generate | public function generate($eventType, array $data, $eventClassName = Event::class)
{
$this->initializeCurrentUsername();
$event = new $eventClassName($eventType, $data, $this->currentUsername, $this->getCurrentContext());
$this->lastGeneratedEvent = $event;
return $event;
} | php | public function generate($eventType, array $data, $eventClassName = Event::class)
{
$this->initializeCurrentUsername();
$event = new $eventClassName($eventType, $data, $this->currentUsername, $this->getCurrentContext());
$this->lastGeneratedEvent = $event;
return $event;
} | [
"public",
"function",
"generate",
"(",
"$",
"eventType",
",",
"array",
"$",
"data",
",",
"$",
"eventClassName",
"=",
"Event",
"::",
"class",
")",
"{",
"$",
"this",
"->",
"initializeCurrentUsername",
"(",
")",
";",
"$",
"event",
"=",
"new",
"$",
"eventCla... | Generates a new event, without persisting it yet.
Note: Make sure to call add($event) afterwards.
@param string $eventType
@param array $data
@param string $eventClassName
@return Event
@see emit() | [
"Generates",
"a",
"new",
"event",
"without",
"persisting",
"it",
"yet",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/EventLog/Domain/Service/EventEmittingService.php#L109-L116 | train |
neos/neos-development-collection | Neos.Neos/Classes/EventLog/Domain/Service/EventEmittingService.php | EventEmittingService.initializeCurrentUsername | protected function initializeCurrentUsername()
{
if (isset($this->currentUsername)) {
return;
}
$currentUser = $this->userDomainService->getCurrentUser();
if (!$currentUser instanceof User) {
return;
}
$this->currentUsername = $this->userDomainService->getUsername($currentUser);
} | php | protected function initializeCurrentUsername()
{
if (isset($this->currentUsername)) {
return;
}
$currentUser = $this->userDomainService->getCurrentUser();
if (!$currentUser instanceof User) {
return;
}
$this->currentUsername = $this->userDomainService->getUsername($currentUser);
} | [
"protected",
"function",
"initializeCurrentUsername",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"currentUsername",
")",
")",
"{",
"return",
";",
"}",
"$",
"currentUser",
"=",
"$",
"this",
"->",
"userDomainService",
"->",
"getCurrentUser",
"(... | Try to set the current username emitting the events, if possible
@return void | [
"Try",
"to",
"set",
"the",
"current",
"username",
"emitting",
"the",
"events",
"if",
"possible"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/EventLog/Domain/Service/EventEmittingService.php#L187-L199 | train |
neos/neos-development-collection | Neos.Neos/Classes/ViewHelpers/Uri/NodeViewHelper.php | NodeViewHelper.render | public function render($node = null, $format = null, $absolute = false, array $arguments = [], $section = '', $addQueryString = false, array $argumentsToBeExcludedFromQueryString = [], $baseNodeName = 'documentNode', $resolveShortcuts = true)
{
$baseNode = null;
if (!$node instanceof NodeInterface) {
$baseNode = $this->getContextVariable($baseNodeName);
if (is_string($node) && substr($node, 0, 7) === 'node://') {
$node = $this->linkingService->convertUriToObject($node, $baseNode);
}
}
try {
return $this->linkingService->createNodeUri(
$this->controllerContext,
$node,
$baseNode,
$format,
$absolute,
$arguments,
$section,
$addQueryString,
$argumentsToBeExcludedFromQueryString,
$resolveShortcuts
);
} catch (NeosException $exception) {
$this->systemLogger->logException($exception);
} catch (NoMatchingRouteException $exception) {
$this->systemLogger->logException($exception);
}
return '';
} | php | public function render($node = null, $format = null, $absolute = false, array $arguments = [], $section = '', $addQueryString = false, array $argumentsToBeExcludedFromQueryString = [], $baseNodeName = 'documentNode', $resolveShortcuts = true)
{
$baseNode = null;
if (!$node instanceof NodeInterface) {
$baseNode = $this->getContextVariable($baseNodeName);
if (is_string($node) && substr($node, 0, 7) === 'node://') {
$node = $this->linkingService->convertUriToObject($node, $baseNode);
}
}
try {
return $this->linkingService->createNodeUri(
$this->controllerContext,
$node,
$baseNode,
$format,
$absolute,
$arguments,
$section,
$addQueryString,
$argumentsToBeExcludedFromQueryString,
$resolveShortcuts
);
} catch (NeosException $exception) {
$this->systemLogger->logException($exception);
} catch (NoMatchingRouteException $exception) {
$this->systemLogger->logException($exception);
}
return '';
} | [
"public",
"function",
"render",
"(",
"$",
"node",
"=",
"null",
",",
"$",
"format",
"=",
"null",
",",
"$",
"absolute",
"=",
"false",
",",
"array",
"$",
"arguments",
"=",
"[",
"]",
",",
"$",
"section",
"=",
"''",
",",
"$",
"addQueryString",
"=",
"fal... | Renders the URI.
@param mixed $node A node object, a string node path (absolute or relative), a string node://-uri or NULL
@param string $format Format to use for the URL, for example "html" or "json"
@param boolean $absolute If set, an absolute URI is rendered
@param array $arguments Additional arguments to be passed to the UriBuilder (for example pagination parameters)
@param string $section
@param boolean $addQueryString If set, the current query parameters will be kept in the URI
@param array $argumentsToBeExcludedFromQueryString arguments to be removed from the URI. Only active if $addQueryString = true
@param string $baseNodeName The name of the base node inside the Fusion context to use for the ContentContext or resolving relative paths
@param boolean $resolveShortcuts INTERNAL Parameter - if false, shortcuts are not redirected to their target. Only needed on rare backend occasions when we want to link to the shortcut itself.
@return string The rendered URI or NULL if no URI could be resolved for the given node
@throws ViewHelperException | [
"Renders",
"the",
"URI",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/ViewHelpers/Uri/NodeViewHelper.php#L116-L145 | train |
neos/neos-development-collection | Neos.Neos/Classes/Controller/Backend/MenuHelper.php | MenuHelper.buildSiteList | public function buildSiteList(ControllerContext $controllerContext)
{
$requestUriHost = $controllerContext->getRequest()->getHttpRequest()->getUri()->getHost();
$domainsFound = false;
$sites = [];
foreach ($this->siteRepository->findOnline() as $site) {
$uri = null;
$active = false;
/** @var $site Site */
if ($site->hasActiveDomains()) {
$activeHostPatterns = $site->getActiveDomains()->map(function ($domain) {
return $domain->getHostname();
})->toArray();
$active = in_array($requestUriHost, $activeHostPatterns, true);
if ($active) {
$uri = $controllerContext->getUriBuilder()
->reset()
->setCreateAbsoluteUri(true)
->uriFor('index', [], 'Backend\Backend', 'Neos.Neos');
} else {
$uri = $controllerContext->getUriBuilder()
->reset()
->uriFor('switchSite', ['site' => $site], 'Backend\Backend', 'Neos.Neos');
}
$domainsFound = true;
}
$sites[] = [
'name' => $site->getName(),
'nodeName' => $site->getNodeName(),
'uri' => $uri,
'active' => $active
];
}
if ($domainsFound === false) {
$uri = $controllerContext->getUriBuilder()
->reset()
->setCreateAbsoluteUri(true)
->uriFor('index', [], 'Backend\Backend', 'Neos.Neos');
$sites[0]['uri'] = $uri;
}
return $sites;
} | php | public function buildSiteList(ControllerContext $controllerContext)
{
$requestUriHost = $controllerContext->getRequest()->getHttpRequest()->getUri()->getHost();
$domainsFound = false;
$sites = [];
foreach ($this->siteRepository->findOnline() as $site) {
$uri = null;
$active = false;
/** @var $site Site */
if ($site->hasActiveDomains()) {
$activeHostPatterns = $site->getActiveDomains()->map(function ($domain) {
return $domain->getHostname();
})->toArray();
$active = in_array($requestUriHost, $activeHostPatterns, true);
if ($active) {
$uri = $controllerContext->getUriBuilder()
->reset()
->setCreateAbsoluteUri(true)
->uriFor('index', [], 'Backend\Backend', 'Neos.Neos');
} else {
$uri = $controllerContext->getUriBuilder()
->reset()
->uriFor('switchSite', ['site' => $site], 'Backend\Backend', 'Neos.Neos');
}
$domainsFound = true;
}
$sites[] = [
'name' => $site->getName(),
'nodeName' => $site->getNodeName(),
'uri' => $uri,
'active' => $active
];
}
if ($domainsFound === false) {
$uri = $controllerContext->getUriBuilder()
->reset()
->setCreateAbsoluteUri(true)
->uriFor('index', [], 'Backend\Backend', 'Neos.Neos');
$sites[0]['uri'] = $uri;
}
return $sites;
} | [
"public",
"function",
"buildSiteList",
"(",
"ControllerContext",
"$",
"controllerContext",
")",
"{",
"$",
"requestUriHost",
"=",
"$",
"controllerContext",
"->",
"getRequest",
"(",
")",
"->",
"getHttpRequest",
"(",
")",
"->",
"getUri",
"(",
")",
"->",
"getHost",
... | Build a list of sites
@param ControllerContext $controllerContext
@return array | [
"Build",
"a",
"list",
"of",
"sites"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Controller/Backend/MenuHelper.php#L68-L113 | train |
neos/neos-development-collection | Neos.Neos/Classes/Controller/Backend/MenuHelper.php | MenuHelper.isModuleEnabled | public function isModuleEnabled($modulePath)
{
$modulePathSegments = explode('/', $modulePath);
$moduleConfiguration = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $modulePathSegments));
if (isset($moduleConfiguration['enabled']) && $moduleConfiguration['enabled'] !== true) {
return false;
}
array_pop($modulePathSegments);
if ($modulePathSegments === []) {
return true;
}
return $this->isModuleEnabled(implode('/', $modulePathSegments));
} | php | public function isModuleEnabled($modulePath)
{
$modulePathSegments = explode('/', $modulePath);
$moduleConfiguration = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $modulePathSegments));
if (isset($moduleConfiguration['enabled']) && $moduleConfiguration['enabled'] !== true) {
return false;
}
array_pop($modulePathSegments);
if ($modulePathSegments === []) {
return true;
}
return $this->isModuleEnabled(implode('/', $modulePathSegments));
} | [
"public",
"function",
"isModuleEnabled",
"(",
"$",
"modulePath",
")",
"{",
"$",
"modulePathSegments",
"=",
"explode",
"(",
"'/'",
",",
"$",
"modulePath",
")",
";",
"$",
"moduleConfiguration",
"=",
"Arrays",
"::",
"getValueByPath",
"(",
"$",
"this",
"->",
"se... | Checks whether a module is enabled or disabled in the configuration
@param string $modulePath name of the module including parent modules ("mainModule/subModule/subSubModule")
@return boolean true if module is enabled (default), false otherwise | [
"Checks",
"whether",
"a",
"module",
"is",
"enabled",
"or",
"disabled",
"in",
"the",
"configuration"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Controller/Backend/MenuHelper.php#L164-L176 | train |
neos/neos-development-collection | Neos.Diff/Classes/SequenceMatcher.php | SequenceMatcher.linesAreDifferent | public function linesAreDifferent($aIndex, $bIndex)
{
$lineA = $this->a[$aIndex];
$lineB = $this->b[$bIndex];
if ($this->options['ignoreWhitespace']) {
$replace = ["\t", ' '];
$lineA = str_replace($replace, '', $lineA);
$lineB = str_replace($replace, '', $lineB);
}
if ($this->options['ignoreCase']) {
$lineA = strtolower($lineA);
$lineB = strtolower($lineB);
}
if ($lineA != $lineB) {
return true;
}
return false;
} | php | public function linesAreDifferent($aIndex, $bIndex)
{
$lineA = $this->a[$aIndex];
$lineB = $this->b[$bIndex];
if ($this->options['ignoreWhitespace']) {
$replace = ["\t", ' '];
$lineA = str_replace($replace, '', $lineA);
$lineB = str_replace($replace, '', $lineB);
}
if ($this->options['ignoreCase']) {
$lineA = strtolower($lineA);
$lineB = strtolower($lineB);
}
if ($lineA != $lineB) {
return true;
}
return false;
} | [
"public",
"function",
"linesAreDifferent",
"(",
"$",
"aIndex",
",",
"$",
"bIndex",
")",
"{",
"$",
"lineA",
"=",
"$",
"this",
"->",
"a",
"[",
"$",
"aIndex",
"]",
";",
"$",
"lineB",
"=",
"$",
"this",
"->",
"b",
"[",
"$",
"bIndex",
"]",
";",
"if",
... | Check if the two lines at the given indexes are different or not.
@param int $aIndex Line number to check against in a.
@param int $bIndex Line number to check against in b.
@return boolean True if the lines are different and false if not. | [
"Check",
"if",
"the",
"two",
"lines",
"at",
"the",
"given",
"indexes",
"are",
"different",
"or",
"not",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Diff/Classes/SequenceMatcher.php#L322-L343 | train |
neos/neos-development-collection | Neos.Diff/Classes/SequenceMatcher.php | SequenceMatcher.ratio | public function ratio()
{
$matches = array_reduce($this->getMatchingBlocks(), [$this, 'ratioReduce'], 0);
return $this->calculateRatio($matches, count($this->a) + count($this->b));
} | php | public function ratio()
{
$matches = array_reduce($this->getMatchingBlocks(), [$this, 'ratioReduce'], 0);
return $this->calculateRatio($matches, count($this->a) + count($this->b));
} | [
"public",
"function",
"ratio",
"(",
")",
"{",
"$",
"matches",
"=",
"array_reduce",
"(",
"$",
"this",
"->",
"getMatchingBlocks",
"(",
")",
",",
"[",
"$",
"this",
",",
"'ratioReduce'",
"]",
",",
"0",
")",
";",
"return",
"$",
"this",
"->",
"calculateRatio... | Return a measure of the similarity between the two sequences.
This will be a float value between 0 and 1.
Out of all of the ratio calculation functions, this is the most
expensive to call if getMatchingBlocks or getOpCodes is yet to be
called. The other calculation methods (quickRatio and realquickRatio)
can be used to perform quicker calculations but may be less accurate.
The ratio is calculated as (2 * number of matches) / total number of
elements in both sequences.
@return float The calculated ratio. | [
"Return",
"a",
"measure",
"of",
"the",
"similarity",
"between",
"the",
"two",
"sequences",
".",
"This",
"will",
"be",
"a",
"float",
"value",
"between",
"0",
"and",
"1",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Diff/Classes/SequenceMatcher.php#L616-L620 | train |
neos/neos-development-collection | Neos.Diff/Classes/SequenceMatcher.php | SequenceMatcher.tupleSort | private function tupleSort(array $a, array $b)
{
$max = max(count($a), count($b));
for ($i = 0; $i < $max; ++$i) {
if ($a[$i] < $b[$i]) {
return -1;
} else {
if ($a[$i] > $b[$i]) {
return 1;
}
}
}
if (count($a) == count($b)) {
return 0;
} else {
if (count($a) < count($b)) {
return -1;
} else {
return 1;
}
}
} | php | private function tupleSort(array $a, array $b)
{
$max = max(count($a), count($b));
for ($i = 0; $i < $max; ++$i) {
if ($a[$i] < $b[$i]) {
return -1;
} else {
if ($a[$i] > $b[$i]) {
return 1;
}
}
}
if (count($a) == count($b)) {
return 0;
} else {
if (count($a) < count($b)) {
return -1;
} else {
return 1;
}
}
} | [
"private",
"function",
"tupleSort",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
"{",
"$",
"max",
"=",
"max",
"(",
"count",
"(",
"$",
"a",
")",
",",
"count",
"(",
"$",
"b",
")",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
... | Sort an array by the nested arrays it contains. Helper function for getMatchingBlocks
@param array $a First array to compare.
@param array $b Second array to compare.
@return int -1, 0 or 1, as expected by the usort function. | [
"Sort",
"an",
"array",
"by",
"the",
"nested",
"arrays",
"it",
"contains",
".",
"Helper",
"function",
"for",
"getMatchingBlocks"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Diff/Classes/SequenceMatcher.php#L729-L751 | train |
neos/neos-development-collection | Neos.Neos/Classes/Domain/Service/SiteService.php | SiteService.pruneSite | public function pruneSite(Site $site)
{
$siteNodePath = NodePaths::addNodePathSegment(static::SITES_ROOT_PATH, $site->getNodeName());
$this->nodeDataRepository->removeAllInPath($siteNodePath);
$siteNodes = $this->nodeDataRepository->findByPath($siteNodePath);
foreach ($siteNodes as $siteNode) {
$this->nodeDataRepository->remove($siteNode);
}
$site->setPrimaryDomain(null);
$this->siteRepository->update($site);
$domainsForSite = $this->domainRepository->findBySite($site);
foreach ($domainsForSite as $domain) {
$this->domainRepository->remove($domain);
}
$this->persistenceManager->persistAll();
$this->siteRepository->remove($site);
$this->emitSitePruned($site);
} | php | public function pruneSite(Site $site)
{
$siteNodePath = NodePaths::addNodePathSegment(static::SITES_ROOT_PATH, $site->getNodeName());
$this->nodeDataRepository->removeAllInPath($siteNodePath);
$siteNodes = $this->nodeDataRepository->findByPath($siteNodePath);
foreach ($siteNodes as $siteNode) {
$this->nodeDataRepository->remove($siteNode);
}
$site->setPrimaryDomain(null);
$this->siteRepository->update($site);
$domainsForSite = $this->domainRepository->findBySite($site);
foreach ($domainsForSite as $domain) {
$this->domainRepository->remove($domain);
}
$this->persistenceManager->persistAll();
$this->siteRepository->remove($site);
$this->emitSitePruned($site);
} | [
"public",
"function",
"pruneSite",
"(",
"Site",
"$",
"site",
")",
"{",
"$",
"siteNodePath",
"=",
"NodePaths",
"::",
"addNodePathSegment",
"(",
"static",
"::",
"SITES_ROOT_PATH",
",",
"$",
"site",
"->",
"getNodeName",
"(",
")",
")",
";",
"$",
"this",
"->",
... | Remove given site all nodes for that site and all domains associated.
@param Site $site
@return void | [
"Remove",
"given",
"site",
"all",
"nodes",
"for",
"that",
"site",
"and",
"all",
"domains",
"associated",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Domain/Service/SiteService.php#L80-L101 | train |
neos/neos-development-collection | Neos.Media/Classes/Domain/Model/ImportedAssetManager.php | ImportedAssetManager.registerCreatedAsset | public function registerCreatedAsset(AssetInterface $asset)
{
if (!$asset instanceof AssetVariantInterface || !$asset instanceof AssetSourceAwareInterface) {
return;
}
$variantAssetIdentifier = $this->persistenceManager->getIdentifierByObject($asset);
$originalAsset = $asset->getOriginalAsset();
$originalAssetIdentifier = $this->persistenceManager->getIdentifierByObject($originalAsset);
$originalImportedAsset = $this->importedAssetRepository->findOneByLocalAssetIdentifier($originalAssetIdentifier);
if ($originalImportedAsset instanceof ImportedAsset) {
$asset->setAssetSourceIdentifier($originalImportedAsset->getAssetSourceIdentifier());
$variantImportedAsset = new ImportedAsset(
$originalImportedAsset->getAssetSourceIdentifier(),
$originalImportedAsset->getRemoteAssetIdentifier(),
$variantAssetIdentifier, new \DateTimeImmutable(),
$originalAssetIdentifier
);
$this->importedAssetRepository->add($variantImportedAsset);
$this->logger->debug(sprintf('Asset created: %s / %s', $asset->getResource()->getFilename(), $this->persistenceManager->getIdentifierByObject($asset)));
}
} | php | public function registerCreatedAsset(AssetInterface $asset)
{
if (!$asset instanceof AssetVariantInterface || !$asset instanceof AssetSourceAwareInterface) {
return;
}
$variantAssetIdentifier = $this->persistenceManager->getIdentifierByObject($asset);
$originalAsset = $asset->getOriginalAsset();
$originalAssetIdentifier = $this->persistenceManager->getIdentifierByObject($originalAsset);
$originalImportedAsset = $this->importedAssetRepository->findOneByLocalAssetIdentifier($originalAssetIdentifier);
if ($originalImportedAsset instanceof ImportedAsset) {
$asset->setAssetSourceIdentifier($originalImportedAsset->getAssetSourceIdentifier());
$variantImportedAsset = new ImportedAsset(
$originalImportedAsset->getAssetSourceIdentifier(),
$originalImportedAsset->getRemoteAssetIdentifier(),
$variantAssetIdentifier, new \DateTimeImmutable(),
$originalAssetIdentifier
);
$this->importedAssetRepository->add($variantImportedAsset);
$this->logger->debug(sprintf('Asset created: %s / %s', $asset->getResource()->getFilename(), $this->persistenceManager->getIdentifierByObject($asset)));
}
} | [
"public",
"function",
"registerCreatedAsset",
"(",
"AssetInterface",
"$",
"asset",
")",
"{",
"if",
"(",
"!",
"$",
"asset",
"instanceof",
"AssetVariantInterface",
"||",
"!",
"$",
"asset",
"instanceof",
"AssetSourceAwareInterface",
")",
"{",
"return",
";",
"}",
"$... | Register that an asset was created.
Wired via signal-slot with AssetService::assetCreated – see Package.php
@param AssetInterface $asset
@throws IllegalObjectTypeException | [
"Register",
"that",
"an",
"asset",
"was",
"created",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Media/Classes/Domain/Model/ImportedAssetManager.php#L59-L83 | train |
neos/neos-development-collection | Neos.ContentRepository/Classes/Validation/Validator/NodeIdentifierValidator.php | NodeIdentifierValidator.isValid | protected function isValid($value)
{
if (!is_string($value) || !preg_match(self::PATTERN_MATCH_NODE_IDENTIFIER, $value)) {
$this->addError('The given subject was not a valid node identifier.', 1489921024);
}
} | php | protected function isValid($value)
{
if (!is_string($value) || !preg_match(self::PATTERN_MATCH_NODE_IDENTIFIER, $value)) {
$this->addError('The given subject was not a valid node identifier.', 1489921024);
}
} | [
"protected",
"function",
"isValid",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
"||",
"!",
"preg_match",
"(",
"self",
"::",
"PATTERN_MATCH_NODE_IDENTIFIER",
",",
"$",
"value",
")",
")",
"{",
"$",
"this",
"->",
"add... | Checks if the given value is a syntactically valid node identifier.
@param mixed $value The value that should be validated
@return void
@api | [
"Checks",
"if",
"the",
"given",
"value",
"is",
"a",
"syntactically",
"valid",
"node",
"identifier",
"."
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.ContentRepository/Classes/Validation/Validator/NodeIdentifierValidator.php#L39-L44 | train |
neos/neos-development-collection | Neos.Neos/Classes/Service/PluginService.php | PluginService.getPluginNodes | public function getPluginNodes(ContentContext $context)
{
$pluginNodeTypes = $this->nodeTypeManager->getSubNodeTypes('Neos.Neos:Plugin', false);
return $this->getNodes(array_keys($pluginNodeTypes), $context);
} | php | public function getPluginNodes(ContentContext $context)
{
$pluginNodeTypes = $this->nodeTypeManager->getSubNodeTypes('Neos.Neos:Plugin', false);
return $this->getNodes(array_keys($pluginNodeTypes), $context);
} | [
"public",
"function",
"getPluginNodes",
"(",
"ContentContext",
"$",
"context",
")",
"{",
"$",
"pluginNodeTypes",
"=",
"$",
"this",
"->",
"nodeTypeManager",
"->",
"getSubNodeTypes",
"(",
"'Neos.Neos:Plugin'",
",",
"false",
")",
";",
"return",
"$",
"this",
"->",
... | Returns an array of all available plugin nodes
@param ContentContext $context current content context, see class doc comment for details
@return array<NodeInterface> all plugin nodes in the current $context | [
"Returns",
"an",
"array",
"of",
"all",
"available",
"plugin",
"nodes"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Service/PluginService.php#L75-L79 | train |
neos/neos-development-collection | Neos.Neos/Classes/Service/PluginService.php | PluginService.getPluginNodesWithViewDefinitions | public function getPluginNodesWithViewDefinitions(ContentContext $context)
{
$pluginNodes = [];
foreach ($this->getPluginNodes($context) as $pluginNode) {
/** @var NodeInterface $pluginNode */
if ($this->getPluginViewDefinitionsByPluginNodeType($pluginNode->getNodeType()) !== []) {
$pluginNodes[] = $pluginNode;
}
}
return $pluginNodes;
} | php | public function getPluginNodesWithViewDefinitions(ContentContext $context)
{
$pluginNodes = [];
foreach ($this->getPluginNodes($context) as $pluginNode) {
/** @var NodeInterface $pluginNode */
if ($this->getPluginViewDefinitionsByPluginNodeType($pluginNode->getNodeType()) !== []) {
$pluginNodes[] = $pluginNode;
}
}
return $pluginNodes;
} | [
"public",
"function",
"getPluginNodesWithViewDefinitions",
"(",
"ContentContext",
"$",
"context",
")",
"{",
"$",
"pluginNodes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getPluginNodes",
"(",
"$",
"context",
")",
"as",
"$",
"pluginNode",
")",
"... | Returns an array of all plugin nodes with View Definitions
@param ContentContext $context
@return array<NodeInterface> all plugin nodes with View Definitions in the current $context | [
"Returns",
"an",
"array",
"of",
"all",
"plugin",
"nodes",
"with",
"View",
"Definitions"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Service/PluginService.php#L87-L97 | train |
neos/neos-development-collection | Neos.Neos/Classes/Service/PluginService.php | PluginService.getNodes | protected function getNodes(array $nodeTypes, ContentContext $context)
{
$nodes = [];
$siteNode = $context->getCurrentSiteNode();
foreach ($this->nodeDataRepository->findByParentAndNodeTypeRecursively($siteNode->getPath(), implode(',', $nodeTypes), $context->getWorkspace()) as $nodeData) {
$nodes[] = $this->nodeFactory->createFromNodeData($nodeData, $context);
}
return $nodes;
} | php | protected function getNodes(array $nodeTypes, ContentContext $context)
{
$nodes = [];
$siteNode = $context->getCurrentSiteNode();
foreach ($this->nodeDataRepository->findByParentAndNodeTypeRecursively($siteNode->getPath(), implode(',', $nodeTypes), $context->getWorkspace()) as $nodeData) {
$nodes[] = $this->nodeFactory->createFromNodeData($nodeData, $context);
}
return $nodes;
} | [
"protected",
"function",
"getNodes",
"(",
"array",
"$",
"nodeTypes",
",",
"ContentContext",
"$",
"context",
")",
"{",
"$",
"nodes",
"=",
"[",
"]",
";",
"$",
"siteNode",
"=",
"$",
"context",
"->",
"getCurrentSiteNode",
"(",
")",
";",
"foreach",
"(",
"$",
... | Find all nodes of a specific node type
@param array $nodeTypes
@param ContentContext $context current content context, see class doc comment for details
@return array<NodeInterface> all nodes of type $nodeType in the current $context | [
"Find",
"all",
"nodes",
"of",
"a",
"specific",
"node",
"type"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Service/PluginService.php#L106-L114 | train |
neos/neos-development-collection | Neos.Neos/Classes/Service/PluginService.php | PluginService.getPluginNodeByAction | public function getPluginNodeByAction(NodeInterface $currentNode, $controllerObjectName, $actionName)
{
$viewDefinition = $this->getPluginViewDefinitionByAction($controllerObjectName, $actionName);
if ($currentNode->getNodeType()->isOfType('Neos.Neos:PluginView')) {
$masterPluginNode = $this->getPluginViewNodeByMasterPlugin($currentNode, $viewDefinition->getName());
} else {
$masterPluginNode = $currentNode;
}
if ($viewDefinition !== null) {
$viewNode = $this->getPluginViewNodeByMasterPlugin($currentNode, $viewDefinition->getName());
if ($viewNode instanceof Node) {
return $viewNode;
}
}
return $masterPluginNode;
} | php | public function getPluginNodeByAction(NodeInterface $currentNode, $controllerObjectName, $actionName)
{
$viewDefinition = $this->getPluginViewDefinitionByAction($controllerObjectName, $actionName);
if ($currentNode->getNodeType()->isOfType('Neos.Neos:PluginView')) {
$masterPluginNode = $this->getPluginViewNodeByMasterPlugin($currentNode, $viewDefinition->getName());
} else {
$masterPluginNode = $currentNode;
}
if ($viewDefinition !== null) {
$viewNode = $this->getPluginViewNodeByMasterPlugin($currentNode, $viewDefinition->getName());
if ($viewNode instanceof Node) {
return $viewNode;
}
}
return $masterPluginNode;
} | [
"public",
"function",
"getPluginNodeByAction",
"(",
"NodeInterface",
"$",
"currentNode",
",",
"$",
"controllerObjectName",
",",
"$",
"actionName",
")",
"{",
"$",
"viewDefinition",
"=",
"$",
"this",
"->",
"getPluginViewDefinitionByAction",
"(",
"$",
"controllerObjectNa... | returns a plugin node or one of it's view nodes
if an view has been configured for that specific
controller and action combination
@param NodeInterface $currentNode
@param string $controllerObjectName
@param string $actionName
@return NodeInterface | [
"returns",
"a",
"plugin",
"node",
"or",
"one",
"of",
"it",
"s",
"view",
"nodes",
"if",
"an",
"view",
"has",
"been",
"configured",
"for",
"that",
"specific",
"controller",
"and",
"action",
"combination"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Service/PluginService.php#L151-L169 | train |
neos/neos-development-collection | Neos.Neos/Classes/Service/PluginService.php | PluginService.getPluginViewDefinitionByAction | public function getPluginViewDefinitionByAction($controllerObjectName, $actionName)
{
$pluginNodeTypes = $this->nodeTypeManager->getSubNodeTypes('Neos.Neos:Plugin', false);
$matchingPluginViewDefinitions = [];
foreach ($pluginNodeTypes as $pluginNodeType) {
/** @var $pluginViewDefinition PluginViewDefinition */
foreach ($this->getPluginViewDefinitionsByPluginNodeType($pluginNodeType) as $pluginViewDefinition) {
if ($pluginViewDefinition->matchesControllerActionPair($controllerObjectName, $actionName) !== true) {
continue;
}
$matchingPluginViewDefinitions[] = $pluginViewDefinition;
}
}
if (count($matchingPluginViewDefinitions) > 1) {
throw new Neos\Exception(sprintf('More than one PluginViewDefinition found for controller "%s", action "%s":%s', $controllerObjectName, $actionName, chr(10) . implode(chr(10), $matchingPluginViewDefinitions)), 1377597671);
}
return count($matchingPluginViewDefinitions) > 0 ? current($matchingPluginViewDefinitions) : null;
} | php | public function getPluginViewDefinitionByAction($controllerObjectName, $actionName)
{
$pluginNodeTypes = $this->nodeTypeManager->getSubNodeTypes('Neos.Neos:Plugin', false);
$matchingPluginViewDefinitions = [];
foreach ($pluginNodeTypes as $pluginNodeType) {
/** @var $pluginViewDefinition PluginViewDefinition */
foreach ($this->getPluginViewDefinitionsByPluginNodeType($pluginNodeType) as $pluginViewDefinition) {
if ($pluginViewDefinition->matchesControllerActionPair($controllerObjectName, $actionName) !== true) {
continue;
}
$matchingPluginViewDefinitions[] = $pluginViewDefinition;
}
}
if (count($matchingPluginViewDefinitions) > 1) {
throw new Neos\Exception(sprintf('More than one PluginViewDefinition found for controller "%s", action "%s":%s', $controllerObjectName, $actionName, chr(10) . implode(chr(10), $matchingPluginViewDefinitions)), 1377597671);
}
return count($matchingPluginViewDefinitions) > 0 ? current($matchingPluginViewDefinitions) : null;
} | [
"public",
"function",
"getPluginViewDefinitionByAction",
"(",
"$",
"controllerObjectName",
",",
"$",
"actionName",
")",
"{",
"$",
"pluginNodeTypes",
"=",
"$",
"this",
"->",
"nodeTypeManager",
"->",
"getSubNodeTypes",
"(",
"'Neos.Neos:Plugin'",
",",
"false",
")",
";"... | Fetch a PluginView definition that matches the specified controller and action combination
@param string $controllerObjectName
@param string $actionName
@return PluginViewDefinition
@throws Neos\Exception if more than one PluginView matches the given controller/action pair | [
"Fetch",
"a",
"PluginView",
"definition",
"that",
"matches",
"the",
"specified",
"controller",
"and",
"action",
"combination"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Service/PluginService.php#L179-L198 | train |
neos/neos-development-collection | Neos.Neos/Classes/Service/PluginService.php | PluginService.getPluginViewNodeByMasterPlugin | public function getPluginViewNodeByMasterPlugin(NodeInterface $node, $viewName)
{
/** @var $context ContentContext */
$context = $node->getContext();
foreach ($this->getNodes(['Neos.Neos:PluginView'], $context) as $pluginViewNode) {
/** @var NodeInterface $pluginViewNode */
if ($pluginViewNode->isRemoved()) {
continue;
}
if ($pluginViewNode->getProperty('plugin') === $node->getIdentifier()
&& $pluginViewNode->getProperty('view') === $viewName) {
return $pluginViewNode;
}
}
return null;
} | php | public function getPluginViewNodeByMasterPlugin(NodeInterface $node, $viewName)
{
/** @var $context ContentContext */
$context = $node->getContext();
foreach ($this->getNodes(['Neos.Neos:PluginView'], $context) as $pluginViewNode) {
/** @var NodeInterface $pluginViewNode */
if ($pluginViewNode->isRemoved()) {
continue;
}
if ($pluginViewNode->getProperty('plugin') === $node->getIdentifier()
&& $pluginViewNode->getProperty('view') === $viewName) {
return $pluginViewNode;
}
}
return null;
} | [
"public",
"function",
"getPluginViewNodeByMasterPlugin",
"(",
"NodeInterface",
"$",
"node",
",",
"$",
"viewName",
")",
"{",
"/** @var $context ContentContext */",
"$",
"context",
"=",
"$",
"node",
"->",
"getContext",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"... | returns a specific view node of an master plugin
or NULL if it does not exist
@param NodeInterface $node
@param string $viewName
@return NodeInterface | [
"returns",
"a",
"specific",
"view",
"node",
"of",
"an",
"master",
"plugin",
"or",
"NULL",
"if",
"it",
"does",
"not",
"exist"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Service/PluginService.php#L208-L224 | train |
neos/neos-development-collection | Neos.Neos/Classes/Utility/NodeUriPathSegmentGenerator.php | NodeUriPathSegmentGenerator.setUniqueUriPathSegment | public static function setUniqueUriPathSegment(NodeInterface $node)
{
if ($node->getNodeType()->isOfType('Neos.Neos:Document')) {
$q = new FlowQuery([$node]);
$q = $q->context(['invisibleContentShown' => true, 'removedContentShown' => true, 'inaccessibleContentShown' => true]);
$possibleUriPathSegment = $initialUriPathSegment = !$node->hasProperty('uriPathSegment') ? $node->getName() : $node->getProperty('uriPathSegment');
$i = 1;
while ($q->siblings('[instanceof Neos.Neos:Document][uriPathSegment="' . $possibleUriPathSegment . '"]')->count() > 0) {
$possibleUriPathSegment = $initialUriPathSegment . '-' . $i++;
}
$node->setProperty('uriPathSegment', $possibleUriPathSegment);
}
} | php | public static function setUniqueUriPathSegment(NodeInterface $node)
{
if ($node->getNodeType()->isOfType('Neos.Neos:Document')) {
$q = new FlowQuery([$node]);
$q = $q->context(['invisibleContentShown' => true, 'removedContentShown' => true, 'inaccessibleContentShown' => true]);
$possibleUriPathSegment = $initialUriPathSegment = !$node->hasProperty('uriPathSegment') ? $node->getName() : $node->getProperty('uriPathSegment');
$i = 1;
while ($q->siblings('[instanceof Neos.Neos:Document][uriPathSegment="' . $possibleUriPathSegment . '"]')->count() > 0) {
$possibleUriPathSegment = $initialUriPathSegment . '-' . $i++;
}
$node->setProperty('uriPathSegment', $possibleUriPathSegment);
}
} | [
"public",
"static",
"function",
"setUniqueUriPathSegment",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"->",
"getNodeType",
"(",
")",
"->",
"isOfType",
"(",
"'Neos.Neos:Document'",
")",
")",
"{",
"$",
"q",
"=",
"new",
"FlowQuery",
... | Sets the best possible uriPathSegment for the given Node.
Will use an already set uriPathSegment or alternatively the node name as base,
then checks if the uriPathSegment already exists on the same level and appends a counter until a unique path segment was found.
@param NodeInterface $node
@return void | [
"Sets",
"the",
"best",
"possible",
"uriPathSegment",
"for",
"the",
"given",
"Node",
".",
"Will",
"use",
"an",
"already",
"set",
"uriPathSegment",
"or",
"alternatively",
"the",
"node",
"name",
"as",
"base",
"then",
"checks",
"if",
"the",
"uriPathSegment",
"alre... | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Utility/NodeUriPathSegmentGenerator.php#L43-L56 | train |
neos/neos-development-collection | Neos.Neos/Classes/Utility/NodeUriPathSegmentGenerator.php | NodeUriPathSegmentGenerator.generateUriPathSegment | public function generateUriPathSegment(NodeInterface $node = null, $text = null)
{
if ($node) {
$text = $text ?: $node->getLabel() ?: $node->getName();
$dimensions = $node->getContext()->getDimensions();
if (array_key_exists('language', $dimensions) && $dimensions['language'] !== []) {
$locale = new Locale($dimensions['language'][0]);
$language = $locale->getLanguage();
}
} elseif (strlen($text) === 0) {
throw new Exception('Given text was empty.', 1457591815);
}
$text = $this->transliterationService->transliterate($text, isset($language) ? $language : null);
return Transliterator::urlize($text);
} | php | public function generateUriPathSegment(NodeInterface $node = null, $text = null)
{
if ($node) {
$text = $text ?: $node->getLabel() ?: $node->getName();
$dimensions = $node->getContext()->getDimensions();
if (array_key_exists('language', $dimensions) && $dimensions['language'] !== []) {
$locale = new Locale($dimensions['language'][0]);
$language = $locale->getLanguage();
}
} elseif (strlen($text) === 0) {
throw new Exception('Given text was empty.', 1457591815);
}
$text = $this->transliterationService->transliterate($text, isset($language) ? $language : null);
return Transliterator::urlize($text);
} | [
"public",
"function",
"generateUriPathSegment",
"(",
"NodeInterface",
"$",
"node",
"=",
"null",
",",
"$",
"text",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"node",
")",
"{",
"$",
"text",
"=",
"$",
"text",
"?",
":",
"$",
"node",
"->",
"getLabel",
"(",
... | Generates a URI path segment for a given node taking it's language dimension into account
@param NodeInterface $node Optional node to determine language dimension
@param string $text Optional text
@return string | [
"Generates",
"a",
"URI",
"path",
"segment",
"for",
"a",
"given",
"node",
"taking",
"it",
"s",
"language",
"dimension",
"into",
"account"
] | 9062fb5e8e9217bc99324b7eba0378e9274fc051 | https://github.com/neos/neos-development-collection/blob/9062fb5e8e9217bc99324b7eba0378e9274fc051/Neos.Neos/Classes/Utility/NodeUriPathSegmentGenerator.php#L65-L79 | train |
aws/aws-php-sns-message-validator | src/Message.php | Message.fromJsonString | private static function fromJsonString($requestBody)
{
$data = json_decode($requestBody, true);
if (JSON_ERROR_NONE !== json_last_error() || !is_array($data)) {
throw new \RuntimeException('Invalid POST data.');
}
return new Message($data);
} | php | private static function fromJsonString($requestBody)
{
$data = json_decode($requestBody, true);
if (JSON_ERROR_NONE !== json_last_error() || !is_array($data)) {
throw new \RuntimeException('Invalid POST data.');
}
return new Message($data);
} | [
"private",
"static",
"function",
"fromJsonString",
"(",
"$",
"requestBody",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"requestBody",
",",
"true",
")",
";",
"if",
"(",
"JSON_ERROR_NONE",
"!==",
"json_last_error",
"(",
")",
"||",
"!",
"is_array",
... | Creates a Message object from a JSON-decodable string.
@param string $requestBody
@return Message | [
"Creates",
"a",
"Message",
"object",
"from",
"a",
"JSON",
"-",
"decodable",
"string",
"."
] | 58949c84b4731a31e01183fe9d9d764267694562 | https://github.com/aws/aws-php-sns-message-validator/blob/58949c84b4731a31e01183fe9d9d764267694562/src/Message.php#L64-L72 | train |
aws/aws-php-sns-message-validator | src/MessageValidator.php | MessageValidator.validate | public function validate(Message $message)
{
if (self::isLambdaStyle($message)) {
$message = self::convertLambdaMessage($message);
}
// Get the certificate.
$this->validateUrl($message['SigningCertURL']);
$certificate = call_user_func($this->certClient, $message['SigningCertURL']);
if ($certificate === false) {
throw new InvalidSnsMessageException(
"Cannot get the certificate from \"{$message['SigningCertURL']}\"."
);
}
// Extract the public key.
$key = openssl_get_publickey($certificate);
if (!$key) {
throw new InvalidSnsMessageException(
'Cannot get the public key from the certificate.'
);
}
// Verify the signature of the message.
$content = $this->getStringToSign($message);
$signature = base64_decode($message['Signature']);
if (openssl_verify($content, $signature, $key, OPENSSL_ALGO_SHA1) != 1) {
throw new InvalidSnsMessageException(
'The message signature is invalid.'
);
}
} | php | public function validate(Message $message)
{
if (self::isLambdaStyle($message)) {
$message = self::convertLambdaMessage($message);
}
// Get the certificate.
$this->validateUrl($message['SigningCertURL']);
$certificate = call_user_func($this->certClient, $message['SigningCertURL']);
if ($certificate === false) {
throw new InvalidSnsMessageException(
"Cannot get the certificate from \"{$message['SigningCertURL']}\"."
);
}
// Extract the public key.
$key = openssl_get_publickey($certificate);
if (!$key) {
throw new InvalidSnsMessageException(
'Cannot get the public key from the certificate.'
);
}
// Verify the signature of the message.
$content = $this->getStringToSign($message);
$signature = base64_decode($message['Signature']);
if (openssl_verify($content, $signature, $key, OPENSSL_ALGO_SHA1) != 1) {
throw new InvalidSnsMessageException(
'The message signature is invalid.'
);
}
} | [
"public",
"function",
"validate",
"(",
"Message",
"$",
"message",
")",
"{",
"if",
"(",
"self",
"::",
"isLambdaStyle",
"(",
"$",
"message",
")",
")",
"{",
"$",
"message",
"=",
"self",
"::",
"convertLambdaMessage",
"(",
"$",
"message",
")",
";",
"}",
"//... | Validates a message from SNS to ensure that it was delivered by AWS.
@param Message $message Message to validate.
@throws InvalidSnsMessageException If the cert cannot be retrieved or its
source verified, or the message
signature is invalid. | [
"Validates",
"a",
"message",
"from",
"SNS",
"to",
"ensure",
"that",
"it",
"was",
"delivered",
"by",
"AWS",
"."
] | 58949c84b4731a31e01183fe9d9d764267694562 | https://github.com/aws/aws-php-sns-message-validator/blob/58949c84b4731a31e01183fe9d9d764267694562/src/MessageValidator.php#L80-L111 | train |
aws/aws-php-sns-message-validator | src/MessageValidator.php | MessageValidator.isValid | public function isValid(Message $message)
{
try {
$this->validate($message);
return true;
} catch (InvalidSnsMessageException $e) {
return false;
}
} | php | public function isValid(Message $message)
{
try {
$this->validate($message);
return true;
} catch (InvalidSnsMessageException $e) {
return false;
}
} | [
"public",
"function",
"isValid",
"(",
"Message",
"$",
"message",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"validate",
"(",
"$",
"message",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"InvalidSnsMessageException",
"$",
"e",
")",
"{",
"return",
"... | Determines if a message is valid and that is was delivered by AWS. This
method does not throw exceptions and returns a simple boolean value.
@param Message $message The message to validate
@return bool | [
"Determines",
"if",
"a",
"message",
"is",
"valid",
"and",
"that",
"is",
"was",
"delivered",
"by",
"AWS",
".",
"This",
"method",
"does",
"not",
"throw",
"exceptions",
"and",
"returns",
"a",
"simple",
"boolean",
"value",
"."
] | 58949c84b4731a31e01183fe9d9d764267694562 | https://github.com/aws/aws-php-sns-message-validator/blob/58949c84b4731a31e01183fe9d9d764267694562/src/MessageValidator.php#L121-L129 | train |
aws/aws-php-sns-message-validator | src/MessageValidator.php | MessageValidator.getStringToSign | public function getStringToSign(Message $message)
{
static $signableKeys = [
'Message',
'MessageId',
'Subject',
'SubscribeURL',
'Timestamp',
'Token',
'TopicArn',
'Type',
];
if ($message['SignatureVersion'] !== self::SIGNATURE_VERSION_1) {
throw new InvalidSnsMessageException(
"The SignatureVersion \"{$message['SignatureVersion']}\" is not supported."
);
}
$stringToSign = '';
foreach ($signableKeys as $key) {
if (isset($message[$key])) {
$stringToSign .= "{$key}\n{$message[$key]}\n";
}
}
return $stringToSign;
} | php | public function getStringToSign(Message $message)
{
static $signableKeys = [
'Message',
'MessageId',
'Subject',
'SubscribeURL',
'Timestamp',
'Token',
'TopicArn',
'Type',
];
if ($message['SignatureVersion'] !== self::SIGNATURE_VERSION_1) {
throw new InvalidSnsMessageException(
"The SignatureVersion \"{$message['SignatureVersion']}\" is not supported."
);
}
$stringToSign = '';
foreach ($signableKeys as $key) {
if (isset($message[$key])) {
$stringToSign .= "{$key}\n{$message[$key]}\n";
}
}
return $stringToSign;
} | [
"public",
"function",
"getStringToSign",
"(",
"Message",
"$",
"message",
")",
"{",
"static",
"$",
"signableKeys",
"=",
"[",
"'Message'",
",",
"'MessageId'",
",",
"'Subject'",
",",
"'SubscribeURL'",
",",
"'Timestamp'",
",",
"'Token'",
",",
"'TopicArn'",
",",
"'... | Builds string-to-sign according to the SNS message spec.
@param Message $message Message for which to build the string-to-sign.
@return string
@link http://docs.aws.amazon.com/sns/latest/gsg/SendMessageToHttp.verify.signature.html | [
"Builds",
"string",
"-",
"to",
"-",
"sign",
"according",
"to",
"the",
"SNS",
"message",
"spec",
"."
] | 58949c84b4731a31e01183fe9d9d764267694562 | https://github.com/aws/aws-php-sns-message-validator/blob/58949c84b4731a31e01183fe9d9d764267694562/src/MessageValidator.php#L139-L166 | train |
aws/aws-php-sns-message-validator | src/MessageValidator.php | MessageValidator.validateUrl | private function validateUrl($url)
{
$parsed = parse_url($url);
if (empty($parsed['scheme'])
|| empty($parsed['host'])
|| $parsed['scheme'] !== 'https'
|| substr($url, -4) !== '.pem'
|| !preg_match($this->hostPattern, $parsed['host'])
) {
throw new InvalidSnsMessageException(
'The certificate is located on an invalid domain.'
);
}
} | php | private function validateUrl($url)
{
$parsed = parse_url($url);
if (empty($parsed['scheme'])
|| empty($parsed['host'])
|| $parsed['scheme'] !== 'https'
|| substr($url, -4) !== '.pem'
|| !preg_match($this->hostPattern, $parsed['host'])
) {
throw new InvalidSnsMessageException(
'The certificate is located on an invalid domain.'
);
}
} | [
"private",
"function",
"validateUrl",
"(",
"$",
"url",
")",
"{",
"$",
"parsed",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"parsed",
"[",
"'scheme'",
"]",
")",
"||",
"empty",
"(",
"$",
"parsed",
"[",
"'host'",
"]",
... | Ensures that the URL of the certificate is one belonging to AWS, and not
just something from the amazonaws domain, which could include S3 buckets.
@param string $url Certificate URL
@throws InvalidSnsMessageException if the cert url is invalid. | [
"Ensures",
"that",
"the",
"URL",
"of",
"the",
"certificate",
"is",
"one",
"belonging",
"to",
"AWS",
"and",
"not",
"just",
"something",
"from",
"the",
"amazonaws",
"domain",
"which",
"could",
"include",
"S3",
"buckets",
"."
] | 58949c84b4731a31e01183fe9d9d764267694562 | https://github.com/aws/aws-php-sns-message-validator/blob/58949c84b4731a31e01183fe9d9d764267694562/src/MessageValidator.php#L176-L189 | train |
SiftScience/sift-php | lib/SiftClient.php | SiftClient.track | public function track($event, $properties, $opts = array()) {
$this->mergeArguments($opts, array(
'return_score' => false,
'return_action' => false,
'return_workflow_status' => false,
'force_workflow_run' => false,
'abuse_types' => array(),
'path' => null,
'timeout' => $this->timeout,
'version' => $this->version
));
$this->validateArgument($event, 'event', 'string');
$this->validateArgument($properties, 'properties', 'array');
$path = $opts['path'];
if (!$path) {
$path = self::restApiUrl($opts['version']);
}
$properties['$api_key'] = $this->api_key;
$properties['$type'] = $event;
$params = array();
if ($opts['return_score']) $params['return_score'] = 'true';
if ($opts['return_action']) $params['return_action'] = 'true';
if ($opts['return_workflow_status']) $params['return_workflow_status'] = 'true';
if ($opts['force_workflow_run']) $params['force_workflow_run'] = 'true';
if ($opts['abuse_types']) $params['abuse_types'] = implode(',', $opts['abuse_types']);
try {
$request = new SiftRequest(
$path, SiftRequest::POST, $opts['timeout'], $opts['version'], array(
'body' => $properties,
'params' => $params
),
$this->curl_opts
);
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | php | public function track($event, $properties, $opts = array()) {
$this->mergeArguments($opts, array(
'return_score' => false,
'return_action' => false,
'return_workflow_status' => false,
'force_workflow_run' => false,
'abuse_types' => array(),
'path' => null,
'timeout' => $this->timeout,
'version' => $this->version
));
$this->validateArgument($event, 'event', 'string');
$this->validateArgument($properties, 'properties', 'array');
$path = $opts['path'];
if (!$path) {
$path = self::restApiUrl($opts['version']);
}
$properties['$api_key'] = $this->api_key;
$properties['$type'] = $event;
$params = array();
if ($opts['return_score']) $params['return_score'] = 'true';
if ($opts['return_action']) $params['return_action'] = 'true';
if ($opts['return_workflow_status']) $params['return_workflow_status'] = 'true';
if ($opts['force_workflow_run']) $params['force_workflow_run'] = 'true';
if ($opts['abuse_types']) $params['abuse_types'] = implode(',', $opts['abuse_types']);
try {
$request = new SiftRequest(
$path, SiftRequest::POST, $opts['timeout'], $opts['version'], array(
'body' => $properties,
'params' => $params
),
$this->curl_opts
);
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | [
"public",
"function",
"track",
"(",
"$",
"event",
",",
"$",
"properties",
",",
"$",
"opts",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeArguments",
"(",
"$",
"opts",
",",
"array",
"(",
"'return_score'",
"=>",
"false",
",",
"'return_actio... | Tracks an event and associated properties through the Sift Science API.
See https://siftscience.com/resources/references/events_api.html for valid $event values
and $properties fields.
@param string $event The type of the event to send. This can be either a reserved event name,
like $transaction or $label or a custom event name (that does not start with a $). This
parameter is required.
@param array $properties An array of name-value pairs that specify the event-specific
attributes to track. This parameter is required.
@param array $opts Array of optional parameters for this request:
- bool 'return_score': Whether to return the user's score as part of the API response. The
score will include the posted event.
- bool 'return_action': Whether to return any actions triggered by this event as part of the
API response.
- bool 'return_workflow_status': Whether to return the status of any workflow run as a
result of the posted event in the API response.
- bool 'force_workflow_run': Whether to request an asynchronous workflow run if the
workflow is configured to only run with API request.
- array 'abuse_types': List of abuse types, specifying for which abuse types a score
should be returned (if scores were requested). If not specified, a score will
be returned for every abuse_type to which you are subscribed.
- int 'timeout': By default, this client's timeout is used.
- string 'version': By default, this client's version is used.
- string 'path': The URL path to use for this call. By default, the path for the requested
version of the Events API is used.
@return null|SiftResponse | [
"Tracks",
"an",
"event",
"and",
"associated",
"properties",
"through",
"the",
"Sift",
"Science",
"API",
"."
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftClient.php#L110-L152 | train |
SiftScience/sift-php | lib/SiftClient.php | SiftClient.label | public function label($userId, $properties, $opts = array()) {
$this->mergeArguments($opts, array(
'timeout' => $this->timeout,
'version' => $this->version
));
$this->validateArgument($userId, 'user id', 'string');
$this->validateArgument($properties, 'properties', 'array');
return $this->track('$label', $properties, array(
'timeout' => $opts['timeout'],
'version' => $opts['version'],
'path' => $this->userLabelApiUrl($userId, $opts['version'])
));
} | php | public function label($userId, $properties, $opts = array()) {
$this->mergeArguments($opts, array(
'timeout' => $this->timeout,
'version' => $this->version
));
$this->validateArgument($userId, 'user id', 'string');
$this->validateArgument($properties, 'properties', 'array');
return $this->track('$label', $properties, array(
'timeout' => $opts['timeout'],
'version' => $opts['version'],
'path' => $this->userLabelApiUrl($userId, $opts['version'])
));
} | [
"public",
"function",
"label",
"(",
"$",
"userId",
",",
"$",
"properties",
",",
"$",
"opts",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeArguments",
"(",
"$",
"opts",
",",
"array",
"(",
"'timeout'",
"=>",
"$",
"this",
"->",
"timeout",
... | Labels a user as either good or bad through the Sift Science API.
See https://siftscience.com/resources/references/labels_api.html for valid $properties
fields.
@param string $userId The ID of a user. This parameter is required.
@param array $properties An array of name-value pairs that specify the label attributes.
This parameter is required.
@param array $opts Array of optional parameters for this request:
- int 'timeout': By default, this client's timeout is used.
- string 'version': By default, this client's version is used.
@return null|SiftResponse | [
"Labels",
"a",
"user",
"as",
"either",
"good",
"or",
"bad",
"through",
"the",
"Sift",
"Science",
"API",
"."
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftClient.php#L292-L306 | train |
SiftScience/sift-php | lib/SiftClient.php | SiftClient.unlabel | public function unlabel($userId, $opts = array()) {
$this->mergeArguments($opts, array(
'abuse_type' => null,
'timeout' => $this->timeout,
'version' => $this->version
));
$this->validateArgument($userId, 'user id', 'string');
$params = array('api_key' => $this->api_key);
if ($opts['abuse_type']) $params['abuse_type'] = $opts['abuse_type'];
try {
$request = new SiftRequest(self::userLabelApiUrl($userId, $opts['version']),
SiftRequest::DELETE, $opts['timeout'], $opts['version'], array('params' => $params));
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | php | public function unlabel($userId, $opts = array()) {
$this->mergeArguments($opts, array(
'abuse_type' => null,
'timeout' => $this->timeout,
'version' => $this->version
));
$this->validateArgument($userId, 'user id', 'string');
$params = array('api_key' => $this->api_key);
if ($opts['abuse_type']) $params['abuse_type'] = $opts['abuse_type'];
try {
$request = new SiftRequest(self::userLabelApiUrl($userId, $opts['version']),
SiftRequest::DELETE, $opts['timeout'], $opts['version'], array('params' => $params));
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | [
"public",
"function",
"unlabel",
"(",
"$",
"userId",
",",
"$",
"opts",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeArguments",
"(",
"$",
"opts",
",",
"array",
"(",
"'abuse_type'",
"=>",
"null",
",",
"'timeout'",
"=>",
"$",
"this",
"->"... | Removes a label from a user
@param string $userId The ID of a user. This parameter is required.
@param array $opts Array of optional parameters for this request:
- string 'abuse_type': The abuse type for which the user should be unlabeled.
If omitted, the user is unlabeled for all abuse types.
- int 'timeout': By default, this client's timeout is used.
- string 'version': By default, this client's version is used.
@return null|SiftResponse | [
"Removes",
"a",
"label",
"from",
"a",
"user"
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftClient.php#L322-L342 | train |
SiftScience/sift-php | lib/SiftClient.php | SiftClient.getContentDecisions | public function getContentDecisions($user_id, $content_id, $opts = array()) {
$this->mergeArguments($opts, array(
'account_id' => $this->account_id,
'timeout' => $this->timeout
));
$this->validateArgument($content_id, 'content id', 'string');
$url = ($this->api_endpoint .
'/v3/accounts/' . rawurlencode($opts['account_id']) .
'/users/' . rawurlencode($user_id) .
'/content/' . rawurlencode($content_id) .
'/decisions');
try {
$request = new SiftRequest($url, SiftRequest::GET, $opts['timeout'], self::API3_VERSION,
array('auth' => $this->api_key . ':'));
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | php | public function getContentDecisions($user_id, $content_id, $opts = array()) {
$this->mergeArguments($opts, array(
'account_id' => $this->account_id,
'timeout' => $this->timeout
));
$this->validateArgument($content_id, 'content id', 'string');
$url = ($this->api_endpoint .
'/v3/accounts/' . rawurlencode($opts['account_id']) .
'/users/' . rawurlencode($user_id) .
'/content/' . rawurlencode($content_id) .
'/decisions');
try {
$request = new SiftRequest($url, SiftRequest::GET, $opts['timeout'], self::API3_VERSION,
array('auth' => $this->api_key . ':'));
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | [
"public",
"function",
"getContentDecisions",
"(",
"$",
"user_id",
",",
"$",
"content_id",
",",
"$",
"opts",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeArguments",
"(",
"$",
"opts",
",",
"array",
"(",
"'account_id'",
"=>",
"$",
"this",
"... | Gets the latest decision for a piece of content.
@param string $content_id The ID of a piece of content.
@param string $user_id The ID of the owner of the content.
@param array $opts Array of optional parameters for this request:
- string 'account_id': by default, this client's account ID is used.
- int 'timeout': By default, this client's timeout is used. | [
"Gets",
"the",
"latest",
"decision",
"for",
"a",
"piece",
"of",
"content",
"."
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftClient.php#L486-L508 | train |
SiftScience/sift-php | lib/SiftClient.php | SiftClient.getDecisions | public function getDecisions($opts = array()) {
$this->mergeArguments($opts, array(
'account_id' => $this->account_id,
'timeout' => $this->timeout,
'abuse_types' => null,
'entity_type' => null,
'next_ref' => null,
'limit' => null,
'from' => null
));
$params = array();
if ($opts['next_ref']) {
$url = $opts['next_ref'];
} else {
$url = ($this->api_endpoint .
'/v3/accounts/' . rawurlencode($opts['account_id']) .
'/decisions');
if ($opts['abuse_types']) $params['abuse_types'] = implode(',', $opts['abuse_types']);
if ($opts['entity_type']) $params['entity_type'] = $opts['entity_type'];
if ($opts['limit']) $params['limit'] = $opts['limit'];
if ($opts['from']) $params['from'] = $opts['from'];
}
try {
$request = new SiftRequest($url, SiftRequest::GET, $opts['timeout'],
self::API3_VERSION,
array('auth' => $this->api_key . ':'));
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | php | public function getDecisions($opts = array()) {
$this->mergeArguments($opts, array(
'account_id' => $this->account_id,
'timeout' => $this->timeout,
'abuse_types' => null,
'entity_type' => null,
'next_ref' => null,
'limit' => null,
'from' => null
));
$params = array();
if ($opts['next_ref']) {
$url = $opts['next_ref'];
} else {
$url = ($this->api_endpoint .
'/v3/accounts/' . rawurlencode($opts['account_id']) .
'/decisions');
if ($opts['abuse_types']) $params['abuse_types'] = implode(',', $opts['abuse_types']);
if ($opts['entity_type']) $params['entity_type'] = $opts['entity_type'];
if ($opts['limit']) $params['limit'] = $opts['limit'];
if ($opts['from']) $params['from'] = $opts['from'];
}
try {
$request = new SiftRequest($url, SiftRequest::GET, $opts['timeout'],
self::API3_VERSION,
array('auth' => $this->api_key . ':'));
return $request->send();
} catch (Exception $e) {
$this->logError($e->getMessage());
return null;
}
} | [
"public",
"function",
"getDecisions",
"(",
"$",
"opts",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeArguments",
"(",
"$",
"opts",
",",
"array",
"(",
"'account_id'",
"=>",
"$",
"this",
"->",
"account_id",
",",
"'timeout'",
"=>",
"$",
"thi... | Gets a list of configured decisions.
@param array $opts Array of optional parameters for this request:
- string 'account_id': by default, this client's account ID is used.
- int 'timeout': By default, this client's timeout is used.
- array 'abuse_types': filters decisions which can be appiled to
listed abuse types
- string 'entity_type': filters on decisions which can be applied to
a specified entity_type
- string 'next_ref': url that will fetch the next page of decisions
- int 'limit': sets the max number of decisions returned
- int 'from': will return the next decision from the index given up
to the limit. | [
"Gets",
"a",
"list",
"of",
"configured",
"decisions",
"."
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftClient.php#L525-L561 | train |
SiftScience/sift-php | lib/SiftClient.php | SiftClient.applyDecisionToUser | public function applyDecisionToUser($user_id, $decision_id, $source, $opts = array()) {
$this->mergeArguments($opts, array(
'account_id' => $this->account_id,
'timeout' => $this->timeout,
'decision_id' => $decision_id,
'source' => $source,
'analyst' => null,
'description' => null,
'time' => null
));
$this->validateArgument($user_id, 'user_id', 'string');
$url = ($this->api_endpoint .
'/v3/accounts/' . rawurlencode($opts['account_id']) .
'/users/'. rawurlencode($user_id) .
'/decisions');
return $this->applyDecision($url, $opts);
} | php | public function applyDecisionToUser($user_id, $decision_id, $source, $opts = array()) {
$this->mergeArguments($opts, array(
'account_id' => $this->account_id,
'timeout' => $this->timeout,
'decision_id' => $decision_id,
'source' => $source,
'analyst' => null,
'description' => null,
'time' => null
));
$this->validateArgument($user_id, 'user_id', 'string');
$url = ($this->api_endpoint .
'/v3/accounts/' . rawurlencode($opts['account_id']) .
'/users/'. rawurlencode($user_id) .
'/decisions');
return $this->applyDecision($url, $opts);
} | [
"public",
"function",
"applyDecisionToUser",
"(",
"$",
"user_id",
",",
"$",
"decision_id",
",",
"$",
"source",
",",
"$",
"opts",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mergeArguments",
"(",
"$",
"opts",
",",
"array",
"(",
"'account_id'",
... | Apply a decision to a user. Builds url to apply decision to user and
delegates to applyDecision
@param string $user_id the id of the user that will get this decision
@param string $decision_id The decision that will be applied to a user
@param string $source the source of the decision, i.e. MANUAL_REVIEW,
AUTOMATED_RULE, CHARGEBACK
@param array $opts Array of optional parameters for this request:
- string 'account_id': by default, this client's account ID is used.
- int 'timeout': By default, this client's timeout is used.
- string 'analyst': when the source is MANUAL_REVIEW, an analyst
identifier must be passed.
- string 'description': free form text adding context to why this
decision is being applied.
- int 'time': Timestamp of when a decision was applied, mainly used
for backfilling | [
"Apply",
"a",
"decision",
"to",
"a",
"user",
".",
"Builds",
"url",
"to",
"apply",
"decision",
"to",
"user",
"and",
"delegates",
"to",
"applyDecision"
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftClient.php#L581-L600 | train |
SiftScience/sift-php | lib/SiftClient.php | SiftClient.mergeArguments | private function mergeArguments(&$opts, $defaults) {
if (!is_array($opts)) {
throw new InvalidArgumentException("Argument 'opts' must be an array.");
}
foreach ($opts as $key => $value) {
if (!array_key_exists($key, $defaults)) {
throw new InvalidArgumentException("${key} is not a valid argument.");
}
}
$opts += $defaults;
} | php | private function mergeArguments(&$opts, $defaults) {
if (!is_array($opts)) {
throw new InvalidArgumentException("Argument 'opts' must be an array.");
}
foreach ($opts as $key => $value) {
if (!array_key_exists($key, $defaults)) {
throw new InvalidArgumentException("${key} is not a valid argument.");
}
}
$opts += $defaults;
} | [
"private",
"function",
"mergeArguments",
"(",
"&",
"$",
"opts",
",",
"$",
"defaults",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"opts",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Argument 'opts' must be an array.\"",
")",
";",
"... | Merges a function's default parameter values into an array of arguments.
In particular, this method:
1. Validates that $opts only contains allowed keys -- i.e., those in $defaults.
2. Modifies $opts in-place by $opts += $defaults.
@param array &$opts The array of arguments passed to a function.
@param array $defaults The array of default parameter values for a function.
@throws InvalidArgumentException if $opts contains any keys not in $defaults. | [
"Merges",
"a",
"function",
"s",
"default",
"parameter",
"values",
"into",
"an",
"array",
"of",
"arguments",
"."
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftClient.php#L777-L787 | train |
SiftScience/sift-php | lib/SiftRequest.php | SiftRequest.send | public function send() {
$curlUrl = $this->url;
if ($this->params) {
$queryString = http_build_query($this->params);
$separator = parse_url($curlUrl, PHP_URL_QUERY) ? '&' : '?';
$curlUrl .= $separator . $queryString;
}
// Mock the request if self::$mock exists
if (self::$mock) {
if (self::$mock['url'] == $curlUrl && self::$mock['method'] == $this->method) {
return self::$mock['response'];
}
return null;
}
// Open and configure curl connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$headers = array(
'User-Agent: SiftScience/v' . $this->version . ' sift-php/' . Sift::VERSION
);
if ($this->auth) {
curl_setopt($ch, CURLOPT_USERPWD, $this->auth);
}
// HTTP-method-specific configuration.
if ($this->method == self::POST) {
if (function_exists('json_encode')) {
$jsonString = json_encode($this->body);
} else {
require_once(dirname(__FILE__) . '/Services_JSON-1.0.3/JSON.php');
$json = new Services_JSON();
$jsonString = $json->encodeUnsafe($this->body);
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
array_push($headers, 'Content-Type: application/json',
'Content-Length: ' . strlen($jsonString)
);
} else if ($this->method == self::DELETE) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
}
foreach ($this->curl_opts as $option => $value) {
if ($option !== CURLOPT_HTTPHEADER) {
curl_setopt($ch, $option, $value);
} else {
$headers = array_merge($headers, $value);
}
}
// Send the request using curl and parse result
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErrno = curl_errno($ch);
$curlError = curl_error($ch);
curl_close($ch);
return new SiftResponse($result, $httpStatusCode, $this, $curlErrno, $curlError);
} | php | public function send() {
$curlUrl = $this->url;
if ($this->params) {
$queryString = http_build_query($this->params);
$separator = parse_url($curlUrl, PHP_URL_QUERY) ? '&' : '?';
$curlUrl .= $separator . $queryString;
}
// Mock the request if self::$mock exists
if (self::$mock) {
if (self::$mock['url'] == $curlUrl && self::$mock['method'] == $this->method) {
return self::$mock['response'];
}
return null;
}
// Open and configure curl connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$headers = array(
'User-Agent: SiftScience/v' . $this->version . ' sift-php/' . Sift::VERSION
);
if ($this->auth) {
curl_setopt($ch, CURLOPT_USERPWD, $this->auth);
}
// HTTP-method-specific configuration.
if ($this->method == self::POST) {
if (function_exists('json_encode')) {
$jsonString = json_encode($this->body);
} else {
require_once(dirname(__FILE__) . '/Services_JSON-1.0.3/JSON.php');
$json = new Services_JSON();
$jsonString = $json->encodeUnsafe($this->body);
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
array_push($headers, 'Content-Type: application/json',
'Content-Length: ' . strlen($jsonString)
);
} else if ($this->method == self::DELETE) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
}
foreach ($this->curl_opts as $option => $value) {
if ($option !== CURLOPT_HTTPHEADER) {
curl_setopt($ch, $option, $value);
} else {
$headers = array_merge($headers, $value);
}
}
// Send the request using curl and parse result
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErrno = curl_errno($ch);
$curlError = curl_error($ch);
curl_close($ch);
return new SiftResponse($result, $httpStatusCode, $this, $curlErrno, $curlError);
} | [
"public",
"function",
"send",
"(",
")",
"{",
"$",
"curlUrl",
"=",
"$",
"this",
"->",
"url",
";",
"if",
"(",
"$",
"this",
"->",
"params",
")",
"{",
"$",
"queryString",
"=",
"http_build_query",
"(",
"$",
"this",
"->",
"params",
")",
";",
"$",
"separa... | Send the HTTP request via cURL
@return SiftResponse | [
"Send",
"the",
"HTTP",
"request",
"via",
"cURL"
] | 7718f5d351dde036e1b4fa366602c378a8c930e3 | https://github.com/SiftScience/sift-php/blob/7718f5d351dde036e1b4fa366602c378a8c930e3/lib/SiftRequest.php#L54-L119 | train |
Eden-PHP/Mail | src/Pop3.php | Pop3.getEmailTotal | public function getEmailTotal()
{
@list($messages, $octets) = explode(' ', $this->call('STAT'));
$messages = is_numeric($messages) ? $messages : 0;
return $messages;
} | php | public function getEmailTotal()
{
@list($messages, $octets) = explode(' ', $this->call('STAT'));
$messages = is_numeric($messages) ? $messages : 0;
return $messages;
} | [
"public",
"function",
"getEmailTotal",
"(",
")",
"{",
"@",
"list",
"(",
"$",
"messages",
",",
"$",
"octets",
")",
"=",
"explode",
"(",
"' '",
",",
"$",
"this",
"->",
"call",
"(",
"'STAT'",
")",
")",
";",
"$",
"messages",
"=",
"is_numeric",
"(",
"$"... | Returns the total number of emails in a mailbox
@return number | [
"Returns",
"the",
"total",
"number",
"of",
"emails",
"in",
"a",
"mailbox"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Pop3.php#L288-L294 | train |
Eden-PHP/Mail | src/Pop3.php | Pop3.getHeaders | private function getHeaders($rawData)
{
if (is_string($rawData)) {
$rawData = explode("\n", $rawData);
}
$key = null;
$headers = array();
foreach ($rawData as $line) {
$line = trim($line);
if (preg_match("/^([a-zA-Z0-9-]+):/i", $line, $matches)) {
$key = strtolower($matches[1]);
if (isset($headers[$key])) {
if (!is_array($headers[$key])) {
$headers[$key] = array($headers[$key]);
}
$headers[$key][] = trim(str_replace($matches[0], '', $line));
continue;
}
$headers[$key] = trim(str_replace($matches[0], '', $line));
continue;
}
if (!is_null($key) && isset($headers[$key])) {
if (is_array($headers[$key])) {
$headers[$key][count($headers[$key])-1] .= ' '.$line;
continue;
}
$headers[$key] .= ' '.$line;
}
}
return $headers;
} | php | private function getHeaders($rawData)
{
if (is_string($rawData)) {
$rawData = explode("\n", $rawData);
}
$key = null;
$headers = array();
foreach ($rawData as $line) {
$line = trim($line);
if (preg_match("/^([a-zA-Z0-9-]+):/i", $line, $matches)) {
$key = strtolower($matches[1]);
if (isset($headers[$key])) {
if (!is_array($headers[$key])) {
$headers[$key] = array($headers[$key]);
}
$headers[$key][] = trim(str_replace($matches[0], '', $line));
continue;
}
$headers[$key] = trim(str_replace($matches[0], '', $line));
continue;
}
if (!is_null($key) && isset($headers[$key])) {
if (is_array($headers[$key])) {
$headers[$key][count($headers[$key])-1] .= ' '.$line;
continue;
}
$headers[$key] .= ' '.$line;
}
}
return $headers;
} | [
"private",
"function",
"getHeaders",
"(",
"$",
"rawData",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"rawData",
")",
")",
"{",
"$",
"rawData",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"rawData",
")",
";",
"}",
"$",
"key",
"=",
"null",
";",
"$",
... | Returns email reponse headers
array key value format
@param *string $rawData The data to parse
@return array | [
"Returns",
"email",
"reponse",
"headers",
"array",
"key",
"value",
"format"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Pop3.php#L613-L649 | train |
Eden-PHP/Mail | src/Imap.php | Imap.getUniqueEmails | public function getUniqueEmails($uid, $body = false)
{
Argument::i()
->test(1, 'int', 'string', 'array')
->test(2, 'bool');
//if not connected
if (!$this->socket) {
//then connect
$this->connect();
}
//if the total in this mailbox is 0
//it means they probably didn't select a mailbox
//or the mailbox selected is empty
if ($this->total == 0) {
//we might as well return an empty array
return array();
}
//if uid is an array
if (is_array($uid)) {
$uid = implode(',', $uid);
}
//lets call it
$items = array('UID', 'FLAGS', 'BODY[HEADER]');
if ($body) {
$items = array('UID', 'FLAGS', 'BODY[]');
}
$first = is_numeric($uid) ? true : false;
return $this->getEmailResponse('UID FETCH', array($uid, $this->getList($items)), $first);
} | php | public function getUniqueEmails($uid, $body = false)
{
Argument::i()
->test(1, 'int', 'string', 'array')
->test(2, 'bool');
//if not connected
if (!$this->socket) {
//then connect
$this->connect();
}
//if the total in this mailbox is 0
//it means they probably didn't select a mailbox
//or the mailbox selected is empty
if ($this->total == 0) {
//we might as well return an empty array
return array();
}
//if uid is an array
if (is_array($uid)) {
$uid = implode(',', $uid);
}
//lets call it
$items = array('UID', 'FLAGS', 'BODY[HEADER]');
if ($body) {
$items = array('UID', 'FLAGS', 'BODY[]');
}
$first = is_numeric($uid) ? true : false;
return $this->getEmailResponse('UID FETCH', array($uid, $this->getList($items)), $first);
} | [
"public",
"function",
"getUniqueEmails",
"(",
"$",
"uid",
",",
"$",
"body",
"=",
"false",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1",
",",
"'int'",
",",
"'string'",
",",
"'array'",
")",
"->",
"test",
"(",
"2",
",",
"'bool'",
... | Returns a list of emails given a uid or set of uids
@param *number|array $uid A list of uid/s
@param bool $body Whether to also include the body
@return array | [
"Returns",
"a",
"list",
"of",
"emails",
"given",
"a",
"uid",
"or",
"set",
"of",
"uids"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L400-L435 | train |
Eden-PHP/Mail | src/Imap.php | Imap.move | public function move($uid, $mailbox)
{
Argument::i()->test(1, 'int', 'string')->test(2, 'string');
if (!$this->socket) {
$this->connect();
}
return $this->call('UID MOVE '.$uid.' '.$mailbox);
} | php | public function move($uid, $mailbox)
{
Argument::i()->test(1, 'int', 'string')->test(2, 'string');
if (!$this->socket) {
$this->connect();
}
return $this->call('UID MOVE '.$uid.' '.$mailbox);
} | [
"public",
"function",
"move",
"(",
"$",
"uid",
",",
"$",
"mailbox",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1",
",",
"'int'",
",",
"'string'",
")",
"->",
"test",
"(",
"2",
",",
"'string'",
")",
";",
"if",
"(",
"!",
"$",
... | Moves an email from folder to other folder
@param *number $uid The mail unique ID
@param *string $mailbox The mailbox destination
@return Eden\Mail\Imap | [
"Moves",
"an",
"email",
"from",
"folder",
"to",
"other",
"folder"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L445-L454 | train |
Eden-PHP/Mail | src/Imap.php | Imap.copy | public function copy($uid, $mailbox)
{
Argument::i()->test(1, 'int', 'string')->test(2, 'string');
if (!$this->socket) {
$this->connect();
}
$this->call('UID COPY '.$uid.' '.$mailbox);
return $this->remove($uid);
} | php | public function copy($uid, $mailbox)
{
Argument::i()->test(1, 'int', 'string')->test(2, 'string');
if (!$this->socket) {
$this->connect();
}
$this->call('UID COPY '.$uid.' '.$mailbox);
return $this->remove($uid);
} | [
"public",
"function",
"copy",
"(",
"$",
"uid",
",",
"$",
"mailbox",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1",
",",
"'int'",
",",
"'string'",
")",
"->",
"test",
"(",
"2",
",",
"'string'",
")",
";",
"if",
"(",
"!",
"$",
... | Copy an email to another mailbox
@param *number $uid The mail unique ID
@param *string $mailbox The mailbox destination
@return Eden\Mail\Imap | [
"Copy",
"an",
"email",
"to",
"another",
"mailbox"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L464-L475 | train |
Eden-PHP/Mail | src/Imap.php | Imap.searchTotal | public function searchTotal(array $filter, $or = false)
{
Argument::i()->test(2, 'bool');
if (!$this->socket) {
$this->connect();
}
//build a search criteria
$search = array();
foreach ($filter as $where) {
$item = $where[0].' "'.$where[1].'"';
if (isset($where[2])) {
$item .= ' "'.$where[2].'"';
}
$search[] = $item;
}
//if this is an or search
if ($or) {
$search = 'OR ('.implode(') (', $search).')';
} else {
//this is an and search
$search = implode(' ', $search);
}
$response = $this->call('UID SEARCH '.$search);
//get the result
$result = array_pop($response);
//if we got some results
if (strpos($result, 'OK') !== false) {
//parse out the uids
$uids = explode(' ', $response[0]);
array_shift($uids);
array_shift($uids);
return count($uids);
}
//it's not okay just return 0
return 0;
} | php | public function searchTotal(array $filter, $or = false)
{
Argument::i()->test(2, 'bool');
if (!$this->socket) {
$this->connect();
}
//build a search criteria
$search = array();
foreach ($filter as $where) {
$item = $where[0].' "'.$where[1].'"';
if (isset($where[2])) {
$item .= ' "'.$where[2].'"';
}
$search[] = $item;
}
//if this is an or search
if ($or) {
$search = 'OR ('.implode(') (', $search).')';
} else {
//this is an and search
$search = implode(' ', $search);
}
$response = $this->call('UID SEARCH '.$search);
//get the result
$result = array_pop($response);
//if we got some results
if (strpos($result, 'OK') !== false) {
//parse out the uids
$uids = explode(' ', $response[0]);
array_shift($uids);
array_shift($uids);
return count($uids);
}
//it's not okay just return 0
return 0;
} | [
"public",
"function",
"searchTotal",
"(",
"array",
"$",
"filter",
",",
"$",
"or",
"=",
"false",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"2",
",",
"'bool'",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"socket",
")",
"{",
"... | Returns the total amount of emails
@param *array $filter Search filters
@param bool $or Is this an OR search ?
@return number | [
"Returns",
"the",
"total",
"amount",
"of",
"emails"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L638-L682 | train |
Eden-PHP/Mail | src/Imap.php | Imap.setActiveMailbox | public function setActiveMailbox($mailbox)
{
Argument::i()->test(1, 'string');
if (!$this->socket) {
$this->connect();
}
$response = $this->call('SELECT', $this->escape($mailbox));
$result = array_pop($response);
foreach ($response as $line) {
if (strpos($line, 'EXISTS') !== false) {
list($star, $this->total, $type) = explode(' ', $line, 3);
} else if (strpos($line, 'UIDNEXT') !== false) {
list($star, $ok, $next, $this->next, $type) = explode(' ', $line, 5);
$this->next = substr($this->next, 0, -1);
}
if ($this->total && $this->next) {
break;
}
}
if (strpos($result, 'OK') !== false) {
$this->mailbox = $mailbox;
return $this;
}
return false;
} | php | public function setActiveMailbox($mailbox)
{
Argument::i()->test(1, 'string');
if (!$this->socket) {
$this->connect();
}
$response = $this->call('SELECT', $this->escape($mailbox));
$result = array_pop($response);
foreach ($response as $line) {
if (strpos($line, 'EXISTS') !== false) {
list($star, $this->total, $type) = explode(' ', $line, 3);
} else if (strpos($line, 'UIDNEXT') !== false) {
list($star, $ok, $next, $this->next, $type) = explode(' ', $line, 5);
$this->next = substr($this->next, 0, -1);
}
if ($this->total && $this->next) {
break;
}
}
if (strpos($result, 'OK') !== false) {
$this->mailbox = $mailbox;
return $this;
}
return false;
} | [
"public",
"function",
"setActiveMailbox",
"(",
"$",
"mailbox",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1",
",",
"'string'",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"socket",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
... | IMAP requires setting an active mailbox
before getting a list of mails
@param string $mailbox Name of mailbox
@return false|Eden\Mail\Imap | [
"IMAP",
"requires",
"setting",
"an",
"active",
"mailbox",
"before",
"getting",
"a",
"list",
"of",
"mails"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L692-L723 | train |
Eden-PHP/Mail | src/Imap.php | Imap.getLine | protected function getLine()
{
$line = fgets($this->socket);
if ($line === false) {
$this->disconnect();
}
$this->debug('Receiving: '.$line);
return $line;
} | php | protected function getLine()
{
$line = fgets($this->socket);
if ($line === false) {
$this->disconnect();
}
$this->debug('Receiving: '.$line);
return $line;
} | [
"protected",
"function",
"getLine",
"(",
")",
"{",
"$",
"line",
"=",
"fgets",
"(",
"$",
"this",
"->",
"socket",
")",
";",
"if",
"(",
"$",
"line",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"disconnect",
"(",
")",
";",
"}",
"$",
"this",
"->",
... | Returns the response one line at a time
@return string | [
"Returns",
"the",
"response",
"one",
"line",
"at",
"a",
"time"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L747-L758 | train |
Eden-PHP/Mail | src/Imap.php | Imap.send | protected function send($command, $parameters = array())
{
$this->tag ++;
$line = 'TAG' . $this->tag . ' ' . $command;
if (!is_array($parameters)) {
$parameters = array($parameters);
}
foreach ($parameters as $parameter) {
if (is_array($parameter)) {
if (fputs($this->socket, $line . ' ' . $parameter[0] . "\r\n") === false) {
return false;
}
if (strpos($this->getLine(), '+ ') === false) {
return false;
}
$line = $parameter[1];
} else {
$line .= ' ' . $parameter;
}
}
$this->debug('Sending: '.$line);
return fputs($this->socket, $line . "\r\n");
} | php | protected function send($command, $parameters = array())
{
$this->tag ++;
$line = 'TAG' . $this->tag . ' ' . $command;
if (!is_array($parameters)) {
$parameters = array($parameters);
}
foreach ($parameters as $parameter) {
if (is_array($parameter)) {
if (fputs($this->socket, $line . ' ' . $parameter[0] . "\r\n") === false) {
return false;
}
if (strpos($this->getLine(), '+ ') === false) {
return false;
}
$line = $parameter[1];
} else {
$line .= ' ' . $parameter;
}
}
$this->debug('Sending: '.$line);
return fputs($this->socket, $line . "\r\n");
} | [
"protected",
"function",
"send",
"(",
"$",
"command",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"tag",
"++",
";",
"$",
"line",
"=",
"'TAG'",
".",
"$",
"this",
"->",
"tag",
".",
"' '",
".",
"$",
"command",
";",
... | Sends out the command
@param *string $command The raw IMAP command
@param array $parameter Parameters to include
@return bool | [
"Sends",
"out",
"the",
"command"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L792-L821 | train |
Eden-PHP/Mail | src/Imap.php | Imap.getEmailResponse | private function getEmailResponse($command, $parameters = array(), $first = false)
{
//send out the command
if (!$this->send($command, $parameters)) {
return false;
}
$messageId = $uniqueId = $count = 0;
$emails = $email = array();
$start = time();
//while there is no hang
while (time() < ($start + self::TIMEOUT)) {
//get a response line
$line = str_replace("\n", '', $this->getLine());
//if the line starts with a fetch
//it means it's the end of getting an email
if (strpos($line, 'FETCH') !== false && strpos($line, 'TAG'.$this->tag) === false) {
//if there is email data
if (!empty($email)) {
//create the email format and add it to emails
$emails[$uniqueId] = $this->getEmailFormat($email, $uniqueId, $flags);
//if all we want is the first one
if ($first) {
//just return this
return $emails[$uniqueId];
}
//make email data empty again
$email = array();
}
//if just okay
if (strpos($line, 'OK') !== false) {
//then skip the rest
continue;
}
//if it's not just ok
//it will contain the message id and the unique id and flags
$flags = array();
if (strpos($line, '\Answered') !== false) {
$flags[] = 'answered';
}
if (strpos($line, '\Flagged') !== false) {
$flags[] = 'flagged';
}
if (strpos($line, '\Deleted') !== false) {
$flags[] = 'deleted';
}
if (strpos($line, '\Seen') !== false) {
$flags[] = 'seen';
}
if (strpos($line, '\Draft') !== false) {
$flags[] = 'draft';
}
$findUid = explode(' ', $line);
foreach ($findUid as $i => $uid) {
if (is_numeric($uid)) {
$uniqueId = $uid;
}
if (strpos(strtolower($uid), 'uid') !== false) {
$uniqueId = $findUid[$i+1];
break;
}
}
//skip the rest
continue;
}
//if there is a tag it means we are at the end
if (strpos($line, 'TAG'.$this->tag) !== false) {
//if email details are not empty and the last line is just a )
if (!empty($email) && strpos(trim($email[count($email) -1]), ')') === 0) {
//take it out because that is not part of the details
array_pop($email);
}
//if there is email data
if (!empty($email)) {
//create the email format and add it to emails
$emails[$uniqueId] = $this->getEmailFormat($email, $uniqueId, $flags);
//if all we want is the first one
if ($first) {
//just return this
return $emails[$uniqueId];
}
}
//break out of this loop
break;
}
//so at this point we are getting raw data
//capture this data in email details
$email[] = $line;
}
return $emails;
} | php | private function getEmailResponse($command, $parameters = array(), $first = false)
{
//send out the command
if (!$this->send($command, $parameters)) {
return false;
}
$messageId = $uniqueId = $count = 0;
$emails = $email = array();
$start = time();
//while there is no hang
while (time() < ($start + self::TIMEOUT)) {
//get a response line
$line = str_replace("\n", '', $this->getLine());
//if the line starts with a fetch
//it means it's the end of getting an email
if (strpos($line, 'FETCH') !== false && strpos($line, 'TAG'.$this->tag) === false) {
//if there is email data
if (!empty($email)) {
//create the email format and add it to emails
$emails[$uniqueId] = $this->getEmailFormat($email, $uniqueId, $flags);
//if all we want is the first one
if ($first) {
//just return this
return $emails[$uniqueId];
}
//make email data empty again
$email = array();
}
//if just okay
if (strpos($line, 'OK') !== false) {
//then skip the rest
continue;
}
//if it's not just ok
//it will contain the message id and the unique id and flags
$flags = array();
if (strpos($line, '\Answered') !== false) {
$flags[] = 'answered';
}
if (strpos($line, '\Flagged') !== false) {
$flags[] = 'flagged';
}
if (strpos($line, '\Deleted') !== false) {
$flags[] = 'deleted';
}
if (strpos($line, '\Seen') !== false) {
$flags[] = 'seen';
}
if (strpos($line, '\Draft') !== false) {
$flags[] = 'draft';
}
$findUid = explode(' ', $line);
foreach ($findUid as $i => $uid) {
if (is_numeric($uid)) {
$uniqueId = $uid;
}
if (strpos(strtolower($uid), 'uid') !== false) {
$uniqueId = $findUid[$i+1];
break;
}
}
//skip the rest
continue;
}
//if there is a tag it means we are at the end
if (strpos($line, 'TAG'.$this->tag) !== false) {
//if email details are not empty and the last line is just a )
if (!empty($email) && strpos(trim($email[count($email) -1]), ')') === 0) {
//take it out because that is not part of the details
array_pop($email);
}
//if there is email data
if (!empty($email)) {
//create the email format and add it to emails
$emails[$uniqueId] = $this->getEmailFormat($email, $uniqueId, $flags);
//if all we want is the first one
if ($first) {
//just return this
return $emails[$uniqueId];
}
}
//break out of this loop
break;
}
//so at this point we are getting raw data
//capture this data in email details
$email[] = $line;
}
return $emails;
} | [
"private",
"function",
"getEmailResponse",
"(",
"$",
"command",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
",",
"$",
"first",
"=",
"false",
")",
"{",
"//send out the command",
"if",
"(",
"!",
"$",
"this",
"->",
"send",
"(",
"$",
"command",
",",
"$... | Splits emails into arrays
@param *string $command The IMAP command
@param array $parameters Any extra parameters
@param bool $first Whether the return should just be the first
@return array | [
"Splits",
"emails",
"into",
"arrays"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L1074-L1182 | train |
Eden-PHP/Mail | src/Imap.php | Imap.getList | private function getList($array)
{
$list = array();
foreach ($array as $key => $value) {
$list[] = !is_array($value) ? $value : $this->getList($v);
}
return '(' . implode(' ', $list) . ')';
} | php | private function getList($array)
{
$list = array();
foreach ($array as $key => $value) {
$list[] = !is_array($value) ? $value : $this->getList($v);
}
return '(' . implode(' ', $list) . ')';
} | [
"private",
"function",
"getList",
"(",
"$",
"array",
")",
"{",
"$",
"list",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"list",
"[",
"]",
"=",
"!",
"is_array",
"(",
"$",
"value... | Returns stringified list
considering arrays inside of arrays
@param array $array The list to transform
@return string | [
"Returns",
"stringified",
"list",
"considering",
"arrays",
"inside",
"of",
"arrays"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Imap.php#L1238-L1246 | train |
Eden-PHP/Mail | src/Index.php | Index.smtp | public function smtp($host, $user, $pass, $port = null, $ssl = false, $tls = false)
{
Argument::i()
->test(1, 'string')
->test(2, 'string')
->test(3, 'string')
->test(4, 'int', 'null')
->test(5, 'bool')
->test(6, 'bool');
return Smtp::i($host, $user, $pass, $port, $ssl, $tls);
} | php | public function smtp($host, $user, $pass, $port = null, $ssl = false, $tls = false)
{
Argument::i()
->test(1, 'string')
->test(2, 'string')
->test(3, 'string')
->test(4, 'int', 'null')
->test(5, 'bool')
->test(6, 'bool');
return Smtp::i($host, $user, $pass, $port, $ssl, $tls);
} | [
"public",
"function",
"smtp",
"(",
"$",
"host",
",",
"$",
"user",
",",
"$",
"pass",
",",
"$",
"port",
"=",
"null",
",",
"$",
"ssl",
"=",
"false",
",",
"$",
"tls",
"=",
"false",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1"... | Returns Mail SMTP
@param *string $host The SMTP host
@param *string $user The mailbox user name
@param *string $pass The mailbox password
@param int|null $port The SMTP port
@param bool $ssl Whether to use SSL
@param bool $tls Whether to use TLS
@return Eden\Mail\Smtp | [
"Returns",
"Mail",
"SMTP"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Index.php#L89-L100 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.addBCC | public function addBCC($email, $name = null)
{
Argument::i()
->test(1, 'string')
->test(2, 'string', 'null');
$this->bcc[$email] = $name;
return $this;
} | php | public function addBCC($email, $name = null)
{
Argument::i()
->test(1, 'string')
->test(2, 'string', 'null');
$this->bcc[$email] = $name;
return $this;
} | [
"public",
"function",
"addBCC",
"(",
"$",
"email",
",",
"$",
"name",
"=",
"null",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1",
",",
"'string'",
")",
"->",
"test",
"(",
"2",
",",
"'string'",
",",
"'null'",
")",
";",
"$",
"t... | Adds an email to the bcc list
@param *string $email Email address
@param string $name Name of person
@return Eden\Mail\Smtp | [
"Adds",
"an",
"email",
"to",
"the",
"bcc",
"list"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L172-L180 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.addCC | public function addCC($email, $name = null)
{
Argument::i()
->test(1, 'string')
->test(2, 'string', 'null');
$this->cc[$email] = $name;
return $this;
} | php | public function addCC($email, $name = null)
{
Argument::i()
->test(1, 'string')
->test(2, 'string', 'null');
$this->cc[$email] = $name;
return $this;
} | [
"public",
"function",
"addCC",
"(",
"$",
"email",
",",
"$",
"name",
"=",
"null",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1",
",",
"'string'",
")",
"->",
"test",
"(",
"2",
",",
"'string'",
",",
"'null'",
")",
";",
"$",
"th... | Adds an email to the cc list
@param *string $email Email address
@param string $name Name of person
@return Eden\Mail\Smtp | [
"Adds",
"an",
"email",
"to",
"the",
"cc",
"list"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L190-L198 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.addTo | public function addTo($email, $name = null)
{
Argument::i()
->test(1, 'string')
->test(2, 'string', 'null');
$this->to[$email] = $name;
return $this;
} | php | public function addTo($email, $name = null)
{
Argument::i()
->test(1, 'string')
->test(2, 'string', 'null');
$this->to[$email] = $name;
return $this;
} | [
"public",
"function",
"addTo",
"(",
"$",
"email",
",",
"$",
"name",
"=",
"null",
")",
"{",
"Argument",
"::",
"i",
"(",
")",
"->",
"test",
"(",
"1",
",",
"'string'",
")",
"->",
"test",
"(",
"2",
",",
"'string'",
",",
"'null'",
")",
";",
"$",
"th... | Adds an email to the to list
@param *string $email Email address
@param string $name Name of person
@return Eden\Mail\Smtp | [
"Adds",
"an",
"email",
"to",
"the",
"to",
"list"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L208-L216 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.reset | public function reset()
{
$this->subject = null;
$this->body = array();
$this->to = array();
$this->cc = array();
$this->bcc = array();
$this->attachments = array();
$this->disconnect();
return $this;
} | php | public function reset()
{
$this->subject = null;
$this->body = array();
$this->to = array();
$this->cc = array();
$this->bcc = array();
$this->attachments = array();
$this->disconnect();
return $this;
} | [
"public",
"function",
"reset",
"(",
")",
"{",
"$",
"this",
"->",
"subject",
"=",
"null",
";",
"$",
"this",
"->",
"body",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"to",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"cc",
"=",
"array",
... | Resets the class
@return Eden\Mail\Smtp | [
"Resets",
"the",
"class"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L447-L459 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getAlternativeAttachmentBody | protected function getAlternativeAttachmentBody()
{
$alternative = $this->getAlternativeBody();
$body = array();
$body[] = 'Content-Type: multipart/mixed; boundary="'.$this->boundary[1].'"';
$body[] = null;
$body[] = '--'.$this->boundary[1];
foreach ($alternative as $line) {
$body[] = $line;
}
return $this->addAttachmentBody($body);
} | php | protected function getAlternativeAttachmentBody()
{
$alternative = $this->getAlternativeBody();
$body = array();
$body[] = 'Content-Type: multipart/mixed; boundary="'.$this->boundary[1].'"';
$body[] = null;
$body[] = '--'.$this->boundary[1];
foreach ($alternative as $line) {
$body[] = $line;
}
return $this->addAttachmentBody($body);
} | [
"protected",
"function",
"getAlternativeAttachmentBody",
"(",
")",
"{",
"$",
"alternative",
"=",
"$",
"this",
"->",
"getAlternativeBody",
"(",
")",
";",
"$",
"body",
"=",
"array",
"(",
")",
";",
"$",
"body",
"[",
"]",
"=",
"'Content-Type: multipart/mixed; boun... | Adds the attachment string body
for HTML formatted emails
@return array | [
"Adds",
"the",
"attachment",
"string",
"body",
"for",
"HTML",
"formatted",
"emails"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L669-L683 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getAlternativeBody | protected function getAlternativeBody()
{
$plain = $this->getPlainBody();
$html = $this->getHtmlBody();
$body = array();
$body[] = 'Content-Type: multipart/alternative; boundary="'.$this->boundary[0].'"';
$body[] = null;
$body[] = '--'.$this->boundary[0];
foreach ($plain as $line) {
$body[] = $line;
}
$body[] = '--'.$this->boundary[0];
foreach ($html as $line) {
$body[] = $line;
}
$body[] = '--'.$this->boundary[0].'--';
$body[] = null;
$body[] = null;
return $body;
} | php | protected function getAlternativeBody()
{
$plain = $this->getPlainBody();
$html = $this->getHtmlBody();
$body = array();
$body[] = 'Content-Type: multipart/alternative; boundary="'.$this->boundary[0].'"';
$body[] = null;
$body[] = '--'.$this->boundary[0];
foreach ($plain as $line) {
$body[] = $line;
}
$body[] = '--'.$this->boundary[0];
foreach ($html as $line) {
$body[] = $line;
}
$body[] = '--'.$this->boundary[0].'--';
$body[] = null;
$body[] = null;
return $body;
} | [
"protected",
"function",
"getAlternativeBody",
"(",
")",
"{",
"$",
"plain",
"=",
"$",
"this",
"->",
"getPlainBody",
"(",
")",
";",
"$",
"html",
"=",
"$",
"this",
"->",
"getHtmlBody",
"(",
")",
";",
"$",
"body",
"=",
"array",
"(",
")",
";",
"$",
"bo... | Adds the string body
for HTML formatted emails
@return array | [
"Adds",
"the",
"string",
"body",
"for",
"HTML",
"formatted",
"emails"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L691-L716 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getBody | protected function getBody()
{
$type = 'Plain';
if (count($this->body) > 1) {
$type = 'Alternative';
} else if (isset($this->body['text/html'])) {
$type = 'Html';
}
$method = 'get%sBody';
if (!empty($this->attachments)) {
$method = 'get%sAttachmentBody';
}
$method = sprintf($method, $type);
return $this->$method();
} | php | protected function getBody()
{
$type = 'Plain';
if (count($this->body) > 1) {
$type = 'Alternative';
} else if (isset($this->body['text/html'])) {
$type = 'Html';
}
$method = 'get%sBody';
if (!empty($this->attachments)) {
$method = 'get%sAttachmentBody';
}
$method = sprintf($method, $type);
return $this->$method();
} | [
"protected",
"function",
"getBody",
"(",
")",
"{",
"$",
"type",
"=",
"'Plain'",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"body",
")",
">",
"1",
")",
"{",
"$",
"type",
"=",
"'Alternative'",
";",
"}",
"else",
"if",
"(",
"isset",
"(",
"$",
... | Returns the body
@return array | [
"Returns",
"the",
"body"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L723-L740 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getHtmlAttachmentBody | protected function getHtmlAttachmentBody()
{
$html = $this->getHtmlBody();
$body = array();
$body[] = 'Content-Type: multipart/mixed; boundary="'.$this->boundary[1].'"';
$body[] = null;
$body[] = '--'.$this->boundary[1];
foreach ($html as $line) {
$body[] = $line;
}
return $this->addAttachmentBody($body);
} | php | protected function getHtmlAttachmentBody()
{
$html = $this->getHtmlBody();
$body = array();
$body[] = 'Content-Type: multipart/mixed; boundary="'.$this->boundary[1].'"';
$body[] = null;
$body[] = '--'.$this->boundary[1];
foreach ($html as $line) {
$body[] = $line;
}
return $this->addAttachmentBody($body);
} | [
"protected",
"function",
"getHtmlAttachmentBody",
"(",
")",
"{",
"$",
"html",
"=",
"$",
"this",
"->",
"getHtmlBody",
"(",
")",
";",
"$",
"body",
"=",
"array",
"(",
")",
";",
"$",
"body",
"[",
"]",
"=",
"'Content-Type: multipart/mixed; boundary=\"'",
".",
"... | Returns the HTML + Attachment version body
@return array | [
"Returns",
"the",
"HTML",
"+",
"Attachment",
"version",
"body"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L803-L817 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getHtmlBody | protected function getHtmlBody()
{
$charset = $this->isUtf8($this->body['text/html']) ? 'utf-8' : 'US-ASCII';
$html = str_replace("\r", '', trim($this->body['text/html']));
$encoded = explode("\n", $this->quotedPrintableEncode($html));
$body = array();
$body[] = 'Content-Type: text/html; charset='.$charset;
$body[] = 'Content-Transfer-Encoding: quoted-printable'."\n";
foreach ($encoded as $line) {
$body[] = $line;
}
$body[] = null;
$body[] = null;
return $body;
} | php | protected function getHtmlBody()
{
$charset = $this->isUtf8($this->body['text/html']) ? 'utf-8' : 'US-ASCII';
$html = str_replace("\r", '', trim($this->body['text/html']));
$encoded = explode("\n", $this->quotedPrintableEncode($html));
$body = array();
$body[] = 'Content-Type: text/html; charset='.$charset;
$body[] = 'Content-Transfer-Encoding: quoted-printable'."\n";
foreach ($encoded as $line) {
$body[] = $line;
}
$body[] = null;
$body[] = null;
return $body;
} | [
"protected",
"function",
"getHtmlBody",
"(",
")",
"{",
"$",
"charset",
"=",
"$",
"this",
"->",
"isUtf8",
"(",
"$",
"this",
"->",
"body",
"[",
"'text/html'",
"]",
")",
"?",
"'utf-8'",
":",
"'US-ASCII'",
";",
"$",
"html",
"=",
"str_replace",
"(",
"\"\\r\... | Returns the HTML version body
@return array | [
"Returns",
"the",
"HTML",
"version",
"body"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L824-L842 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getPlainAttachmentBody | protected function getPlainAttachmentBody()
{
$plain = $this->getPlainBody();
$body = array();
$body[] = 'Content-Type: multipart/mixed; boundary="'.$this->boundary[1].'"';
$body[] = null;
$body[] = '--'.$this->boundary[1];
foreach ($plain as $line) {
$body[] = $line;
}
return $this->addAttachmentBody($body);
} | php | protected function getPlainAttachmentBody()
{
$plain = $this->getPlainBody();
$body = array();
$body[] = 'Content-Type: multipart/mixed; boundary="'.$this->boundary[1].'"';
$body[] = null;
$body[] = '--'.$this->boundary[1];
foreach ($plain as $line) {
$body[] = $line;
}
return $this->addAttachmentBody($body);
} | [
"protected",
"function",
"getPlainAttachmentBody",
"(",
")",
"{",
"$",
"plain",
"=",
"$",
"this",
"->",
"getPlainBody",
"(",
")",
";",
"$",
"body",
"=",
"array",
"(",
")",
";",
"$",
"body",
"[",
"]",
"=",
"'Content-Type: multipart/mixed; boundary=\"'",
".",
... | Returns the Plain + Attachment version body
@return array | [
"Returns",
"the",
"Plain",
"+",
"Attachment",
"version",
"body"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L849-L863 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getPlainBody | protected function getPlainBody()
{
$charset = $this->isUtf8($this->body['text/plain']) ? 'utf-8' : 'US-ASCII';
$plane = str_replace("\r", '', trim($this->body['text/plain']));
$count = ceil(strlen($plane) / 998);
$body = array();
$body[] = 'Content-Type: text/plain; charset='.$charset;
$body[] = 'Content-Transfer-Encoding: 7bit';
$body[] = null;
for ($i = 0; $i < $count; $i++) {
$body[] = substr($plane, ($i * 998), 998);
}
$body[] = null;
$body[] = null;
return $body;
} | php | protected function getPlainBody()
{
$charset = $this->isUtf8($this->body['text/plain']) ? 'utf-8' : 'US-ASCII';
$plane = str_replace("\r", '', trim($this->body['text/plain']));
$count = ceil(strlen($plane) / 998);
$body = array();
$body[] = 'Content-Type: text/plain; charset='.$charset;
$body[] = 'Content-Transfer-Encoding: 7bit';
$body[] = null;
for ($i = 0; $i < $count; $i++) {
$body[] = substr($plane, ($i * 998), 998);
}
$body[] = null;
$body[] = null;
return $body;
} | [
"protected",
"function",
"getPlainBody",
"(",
")",
"{",
"$",
"charset",
"=",
"$",
"this",
"->",
"isUtf8",
"(",
"$",
"this",
"->",
"body",
"[",
"'text/plain'",
"]",
")",
"?",
"'utf-8'",
":",
"'US-ASCII'",
";",
"$",
"plane",
"=",
"str_replace",
"(",
"\"\... | Returns the Plain version body
@return array | [
"Returns",
"the",
"Plain",
"version",
"body"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L870-L889 | train |
Eden-PHP/Mail | src/Smtp.php | Smtp.getTimestamp | private function getTimestamp()
{
$zone = date('Z');
$sign = ($zone < 0) ? '-' : '+';
$zone = abs($zone);
$zone = (int)($zone / 3600) * 100 + ($zone % 3600) / 60;
return sprintf("%s %s%04d", date('D, j M Y H:i:s'), $sign, $zone);
} | php | private function getTimestamp()
{
$zone = date('Z');
$sign = ($zone < 0) ? '-' : '+';
$zone = abs($zone);
$zone = (int)($zone / 3600) * 100 + ($zone % 3600) / 60;
return sprintf("%s %s%04d", date('D, j M Y H:i:s'), $sign, $zone);
} | [
"private",
"function",
"getTimestamp",
"(",
")",
"{",
"$",
"zone",
"=",
"date",
"(",
"'Z'",
")",
";",
"$",
"sign",
"=",
"(",
"$",
"zone",
"<",
"0",
")",
"?",
"'-'",
":",
"'+'",
";",
"$",
"zone",
"=",
"abs",
"(",
"$",
"zone",
")",
";",
"$",
... | Returns timestamp, formatted to what SMTP expects
@return string | [
"Returns",
"timestamp",
"formatted",
"to",
"what",
"SMTP",
"expects"
] | ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67 | https://github.com/Eden-PHP/Mail/blob/ae34e7ba2c3e4bb116ab2824ffc0b7843d63fb67/src/Smtp.php#L952-L959 | train |
FriendsOfCake/cakephp-upload | src/Validation/Traits/ImageValidationTrait.php | ImageValidationTrait.isAboveMinWidth | public static function isAboveMinWidth($check, $width)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list($imgWidth) = getimagesize($check['tmp_name']);
return $width > 0 && $imgWidth >= $width;
} | php | public static function isAboveMinWidth($check, $width)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list($imgWidth) = getimagesize($check['tmp_name']);
return $width > 0 && $imgWidth >= $width;
} | [
"public",
"static",
"function",
"isAboveMinWidth",
"(",
"$",
"check",
",",
"$",
"width",
")",
"{",
"// Non-file uploads also mean the height is too big",
"if",
"(",
"!",
"isset",
"(",
"$",
"check",
"[",
"'tmp_name'",
"]",
")",
"||",
"!",
"strlen",
"(",
"$",
... | Check that the file is above the minimum width requirement
@param mixed $check Value to check
@param int $width Width of Image
@return bool Success | [
"Check",
"that",
"the",
"file",
"is",
"above",
"the",
"minimum",
"width",
"requirement"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Validation/Traits/ImageValidationTrait.php#L14-L23 | train |
FriendsOfCake/cakephp-upload | src/Validation/Traits/ImageValidationTrait.php | ImageValidationTrait.isAboveMinHeight | public static function isAboveMinHeight($check, $height)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list(, $imgHeight) = getimagesize($check['tmp_name']);
return $height > 0 && $imgHeight >= $height;
} | php | public static function isAboveMinHeight($check, $height)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list(, $imgHeight) = getimagesize($check['tmp_name']);
return $height > 0 && $imgHeight >= $height;
} | [
"public",
"static",
"function",
"isAboveMinHeight",
"(",
"$",
"check",
",",
"$",
"height",
")",
"{",
"// Non-file uploads also mean the height is too big",
"if",
"(",
"!",
"isset",
"(",
"$",
"check",
"[",
"'tmp_name'",
"]",
")",
"||",
"!",
"strlen",
"(",
"$",
... | Check that the file is above the minimum height requirement
@param mixed $check Value to check
@param int $height Height of Image
@return bool Success | [
"Check",
"that",
"the",
"file",
"is",
"above",
"the",
"minimum",
"height",
"requirement"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Validation/Traits/ImageValidationTrait.php#L50-L59 | train |
FriendsOfCake/cakephp-upload | src/Validation/Traits/UploadValidationTrait.php | UploadValidationTrait.isAboveMinSize | public static function isAboveMinSize($check, $size)
{
// Non-file uploads also mean the size is too small
if (!isset($check['size']) || !strlen($check['size'])) {
return false;
}
return $check['size'] >= $size;
} | php | public static function isAboveMinSize($check, $size)
{
// Non-file uploads also mean the size is too small
if (!isset($check['size']) || !strlen($check['size'])) {
return false;
}
return $check['size'] >= $size;
} | [
"public",
"static",
"function",
"isAboveMinSize",
"(",
"$",
"check",
",",
"$",
"size",
")",
"{",
"// Non-file uploads also mean the size is too small",
"if",
"(",
"!",
"isset",
"(",
"$",
"check",
"[",
"'size'",
"]",
")",
"||",
"!",
"strlen",
"(",
"$",
"check... | Check that the file is above the minimum file upload size
@param mixed $check Value to check
@param int $size Minimum file size
@return bool Success | [
"Check",
"that",
"the",
"file",
"is",
"above",
"the",
"minimum",
"file",
"upload",
"size"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Validation/Traits/UploadValidationTrait.php#L73-L81 | train |
FriendsOfCake/cakephp-upload | src/Validation/Traits/UploadValidationTrait.php | UploadValidationTrait.isBelowMaxSize | public static function isBelowMaxSize($check, $size)
{
// Non-file uploads also mean the size is too small
if (!isset($check['size']) || !strlen($check['size'])) {
return false;
}
return $check['size'] <= $size;
} | php | public static function isBelowMaxSize($check, $size)
{
// Non-file uploads also mean the size is too small
if (!isset($check['size']) || !strlen($check['size'])) {
return false;
}
return $check['size'] <= $size;
} | [
"public",
"static",
"function",
"isBelowMaxSize",
"(",
"$",
"check",
",",
"$",
"size",
")",
"{",
"// Non-file uploads also mean the size is too small",
"if",
"(",
"!",
"isset",
"(",
"$",
"check",
"[",
"'size'",
"]",
")",
"||",
"!",
"strlen",
"(",
"$",
"check... | Check that the file is below the maximum file upload size
@param mixed $check Value to check
@param int $size Maximum file size
@return bool Success | [
"Check",
"that",
"the",
"file",
"is",
"below",
"the",
"maximum",
"file",
"upload",
"size"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Validation/Traits/UploadValidationTrait.php#L90-L98 | train |
FriendsOfCake/cakephp-upload | src/File/Writer/DefaultWriter.php | DefaultWriter.delete | public function delete(array $files)
{
$filesystem = $this->getFilesystem($this->field, $this->settings);
$results = [];
foreach ($files as $path) {
$results[] = $this->deletePath($filesystem, $path);
}
return $results;
} | php | public function delete(array $files)
{
$filesystem = $this->getFilesystem($this->field, $this->settings);
$results = [];
foreach ($files as $path) {
$results[] = $this->deletePath($filesystem, $path);
}
return $results;
} | [
"public",
"function",
"delete",
"(",
"array",
"$",
"files",
")",
"{",
"$",
"filesystem",
"=",
"$",
"this",
"->",
"getFilesystem",
"(",
"$",
"this",
"->",
"field",
",",
"$",
"this",
"->",
"settings",
")",
";",
"$",
"results",
"=",
"[",
"]",
";",
"fo... | Deletes a set of files to an output
@param array $files the files being written out
@return array array of results | [
"Deletes",
"a",
"set",
"of",
"files",
"to",
"an",
"output"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/File/Writer/DefaultWriter.php#L93-L102 | train |
FriendsOfCake/cakephp-upload | src/File/Writer/DefaultWriter.php | DefaultWriter.deletePath | public function deletePath(FilesystemInterface $filesystem, $path)
{
$success = false;
try {
$success = $filesystem->delete($path);
} catch (FileNotFoundException $e) {
// TODO: log this?
}
return $success;
} | php | public function deletePath(FilesystemInterface $filesystem, $path)
{
$success = false;
try {
$success = $filesystem->delete($path);
} catch (FileNotFoundException $e) {
// TODO: log this?
}
return $success;
} | [
"public",
"function",
"deletePath",
"(",
"FilesystemInterface",
"$",
"filesystem",
",",
"$",
"path",
")",
"{",
"$",
"success",
"=",
"false",
";",
"try",
"{",
"$",
"success",
"=",
"$",
"filesystem",
"->",
"delete",
"(",
"$",
"path",
")",
";",
"}",
"catc... | Deletes a path from a filesystem
@param \League\Flysystem\FilesystemInterface $filesystem a filesystem writer
@param string $path the path that should be deleted
@return bool | [
"Deletes",
"a",
"path",
"from",
"a",
"filesystem"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/File/Writer/DefaultWriter.php#L139-L149 | train |
FriendsOfCake/cakephp-upload | src/File/Writer/DefaultWriter.php | DefaultWriter.getFilesystem | public function getFilesystem($field, array $settings = [])
{
$adapter = new Local(Hash::get($settings, 'filesystem.root', ROOT . DS));
$adapter = Hash::get($settings, 'filesystem.adapter', $adapter);
if (is_callable($adapter)) {
$adapter = $adapter();
}
if ($adapter instanceof AdapterInterface) {
return new Filesystem($adapter, Hash::get($settings, 'filesystem.options', [
'visibility' => AdapterInterface::VISIBILITY_PUBLIC
]));
}
throw new UnexpectedValueException(sprintf("Invalid Adapter for field %s", $field));
} | php | public function getFilesystem($field, array $settings = [])
{
$adapter = new Local(Hash::get($settings, 'filesystem.root', ROOT . DS));
$adapter = Hash::get($settings, 'filesystem.adapter', $adapter);
if (is_callable($adapter)) {
$adapter = $adapter();
}
if ($adapter instanceof AdapterInterface) {
return new Filesystem($adapter, Hash::get($settings, 'filesystem.options', [
'visibility' => AdapterInterface::VISIBILITY_PUBLIC
]));
}
throw new UnexpectedValueException(sprintf("Invalid Adapter for field %s", $field));
} | [
"public",
"function",
"getFilesystem",
"(",
"$",
"field",
",",
"array",
"$",
"settings",
"=",
"[",
"]",
")",
"{",
"$",
"adapter",
"=",
"new",
"Local",
"(",
"Hash",
"::",
"get",
"(",
"$",
"settings",
",",
"'filesystem.root'",
",",
"ROOT",
".",
"DS",
"... | Retrieves a configured filesystem for the given field
@param string $field the field for which data will be saved
@param array $settings the settings for the current field
@return \League\Flysystem\FilesystemInterface | [
"Retrieves",
"a",
"configured",
"filesystem",
"for",
"the",
"given",
"field"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/File/Writer/DefaultWriter.php#L158-L173 | train |
FriendsOfCake/cakephp-upload | src/Model/Behavior/UploadBehavior.php | UploadBehavior.beforeMarshal | public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
$validator = $this->_table->getValidator();
$dataArray = $data->getArrayCopy();
foreach (array_keys($this->getConfig(null, [])) as $field) {
if (!$validator->isEmptyAllowed($field, false)) {
continue;
}
if (Hash::get($dataArray, $field . '.error') !== UPLOAD_ERR_NO_FILE) {
continue;
}
unset($data[$field]);
}
} | php | public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
$validator = $this->_table->getValidator();
$dataArray = $data->getArrayCopy();
foreach (array_keys($this->getConfig(null, [])) as $field) {
if (!$validator->isEmptyAllowed($field, false)) {
continue;
}
if (Hash::get($dataArray, $field . '.error') !== UPLOAD_ERR_NO_FILE) {
continue;
}
unset($data[$field]);
}
} | [
"public",
"function",
"beforeMarshal",
"(",
"Event",
"$",
"event",
",",
"ArrayObject",
"$",
"data",
",",
"ArrayObject",
"$",
"options",
")",
"{",
"$",
"validator",
"=",
"$",
"this",
"->",
"_table",
"->",
"getValidator",
"(",
")",
";",
"$",
"dataArray",
"... | Modifies the data being marshalled to ensure invalid upload data is not inserted
@param \Cake\Event\Event $event an event instance
@param \ArrayObject $data data being marshalled
@param \ArrayObject $options options for the current event
@return void | [
"Modifies",
"the",
"data",
"being",
"marshalled",
"to",
"ensure",
"invalid",
"upload",
"data",
"is",
"not",
"inserted"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Model/Behavior/UploadBehavior.php#L59-L72 | train |
FriendsOfCake/cakephp-upload | src/Model/Behavior/UploadBehavior.php | UploadBehavior.beforeSave | public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
{
foreach ($this->getConfig(null, []) as $field => $settings) {
if (in_array($field, $this->protectedFieldNames)) {
continue;
}
if (Hash::get((array)$entity->get($field), 'error') !== UPLOAD_ERR_OK) {
if (Hash::get($settings, 'restoreValueOnFailure', true)) {
$entity->set($field, $entity->getOriginal($field));
$entity->setDirty($field, false);
}
continue;
}
$data = $entity->get($field);
$path = $this->getPathProcessor($entity, $data, $field, $settings);
$basepath = $path->basepath();
$filename = $path->filename();
$data['name'] = $filename;
$files = $this->constructFiles($entity, $data, $field, $settings, $basepath);
$writer = $this->getWriter($entity, $data, $field, $settings);
$success = $writer->write($files);
if ((new Collection($success))->contains(false)) {
return false;
}
$entity->set($field, $filename);
$entity->set(Hash::get($settings, 'fields.dir', 'dir'), $basepath);
$entity->set(Hash::get($settings, 'fields.size', 'size'), $data['size']);
$entity->set(Hash::get($settings, 'fields.type', 'type'), $data['type']);
}
} | php | public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
{
foreach ($this->getConfig(null, []) as $field => $settings) {
if (in_array($field, $this->protectedFieldNames)) {
continue;
}
if (Hash::get((array)$entity->get($field), 'error') !== UPLOAD_ERR_OK) {
if (Hash::get($settings, 'restoreValueOnFailure', true)) {
$entity->set($field, $entity->getOriginal($field));
$entity->setDirty($field, false);
}
continue;
}
$data = $entity->get($field);
$path = $this->getPathProcessor($entity, $data, $field, $settings);
$basepath = $path->basepath();
$filename = $path->filename();
$data['name'] = $filename;
$files = $this->constructFiles($entity, $data, $field, $settings, $basepath);
$writer = $this->getWriter($entity, $data, $field, $settings);
$success = $writer->write($files);
if ((new Collection($success))->contains(false)) {
return false;
}
$entity->set($field, $filename);
$entity->set(Hash::get($settings, 'fields.dir', 'dir'), $basepath);
$entity->set(Hash::get($settings, 'fields.size', 'size'), $data['size']);
$entity->set(Hash::get($settings, 'fields.type', 'type'), $data['type']);
}
} | [
"public",
"function",
"beforeSave",
"(",
"Event",
"$",
"event",
",",
"Entity",
"$",
"entity",
",",
"ArrayObject",
"$",
"options",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"null",
",",
"[",
"]",
")",
"as",
"$",
"field",
"=>",
"$"... | Modifies the entity before it is saved so that uploaded file data is persisted
in the database too.
@param \Cake\Event\Event $event The beforeSave event that was fired
@param \Cake\ORM\Entity $entity The entity that is going to be saved
@param \ArrayObject $options the options passed to the save method
@return void|false | [
"Modifies",
"the",
"entity",
"before",
"it",
"is",
"saved",
"so",
"that",
"uploaded",
"file",
"data",
"is",
"persisted",
"in",
"the",
"database",
"too",
"."
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Model/Behavior/UploadBehavior.php#L83-L117 | train |
FriendsOfCake/cakephp-upload | src/Model/Behavior/UploadBehavior.php | UploadBehavior.afterDelete | public function afterDelete(Event $event, Entity $entity, ArrayObject $options)
{
$result = true;
foreach ($this->getConfig(null, []) as $field => $settings) {
if (in_array($field, $this->protectedFieldNames) || Hash::get($settings, 'keepFilesOnDelete', true)) {
continue;
}
$dirField = Hash::get($settings, 'fields.dir', 'dir');
if ($entity->has($dirField)) {
$path = $entity->get($dirField);
} else {
$path = $this->getPathProcessor($entity, $entity->get($field), $field, $settings)->basepath();
}
$callback = Hash::get($settings, 'deleteCallback', null);
if ($callback && is_callable($callback)) {
$files = $callback($path, $entity, $field, $settings);
} else {
$files = [$path . $entity->get($field)];
}
$writer = $this->getWriter($entity, [], $field, $settings);
$success = $writer->delete($files);
if ($result && (new Collection($success))->contains(false)) {
$result = false;
}
}
return $result;
} | php | public function afterDelete(Event $event, Entity $entity, ArrayObject $options)
{
$result = true;
foreach ($this->getConfig(null, []) as $field => $settings) {
if (in_array($field, $this->protectedFieldNames) || Hash::get($settings, 'keepFilesOnDelete', true)) {
continue;
}
$dirField = Hash::get($settings, 'fields.dir', 'dir');
if ($entity->has($dirField)) {
$path = $entity->get($dirField);
} else {
$path = $this->getPathProcessor($entity, $entity->get($field), $field, $settings)->basepath();
}
$callback = Hash::get($settings, 'deleteCallback', null);
if ($callback && is_callable($callback)) {
$files = $callback($path, $entity, $field, $settings);
} else {
$files = [$path . $entity->get($field)];
}
$writer = $this->getWriter($entity, [], $field, $settings);
$success = $writer->delete($files);
if ($result && (new Collection($success))->contains(false)) {
$result = false;
}
}
return $result;
} | [
"public",
"function",
"afterDelete",
"(",
"Event",
"$",
"event",
",",
"Entity",
"$",
"entity",
",",
"ArrayObject",
"$",
"options",
")",
"{",
"$",
"result",
"=",
"true",
";",
"foreach",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"null",
",",
"[",
"]",
... | Deletes the files after the entity is deleted
@param \Cake\Event\Event $event The afterDelete event that was fired
@param \Cake\ORM\Entity $entity The entity that was deleted
@param \ArrayObject $options the options passed to the delete method
@return void|false | [
"Deletes",
"the",
"files",
"after",
"the",
"entity",
"is",
"deleted"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Model/Behavior/UploadBehavior.php#L127-L159 | train |
FriendsOfCake/cakephp-upload | src/Model/Behavior/UploadBehavior.php | UploadBehavior.getPathProcessor | public function getPathProcessor(Entity $entity, $data, $field, $settings)
{
$default = 'Josegonzalez\Upload\File\Path\DefaultProcessor';
$processorClass = Hash::get($settings, 'pathProcessor', $default);
if (is_subclass_of($processorClass, 'Josegonzalez\Upload\File\Path\ProcessorInterface')) {
return new $processorClass($this->_table, $entity, $data, $field, $settings);
}
throw new UnexpectedValueException(sprintf(
"'pathProcessor' not set to instance of ProcessorInterface: %s",
$processorClass
));
} | php | public function getPathProcessor(Entity $entity, $data, $field, $settings)
{
$default = 'Josegonzalez\Upload\File\Path\DefaultProcessor';
$processorClass = Hash::get($settings, 'pathProcessor', $default);
if (is_subclass_of($processorClass, 'Josegonzalez\Upload\File\Path\ProcessorInterface')) {
return new $processorClass($this->_table, $entity, $data, $field, $settings);
}
throw new UnexpectedValueException(sprintf(
"'pathProcessor' not set to instance of ProcessorInterface: %s",
$processorClass
));
} | [
"public",
"function",
"getPathProcessor",
"(",
"Entity",
"$",
"entity",
",",
"$",
"data",
",",
"$",
"field",
",",
"$",
"settings",
")",
"{",
"$",
"default",
"=",
"'Josegonzalez\\Upload\\File\\Path\\DefaultProcessor'",
";",
"$",
"processorClass",
"=",
"Hash",
"::... | Retrieves an instance of a path processor which knows how to build paths
for a given file upload
@param \Cake\ORM\Entity $entity an entity
@param array $data the data being submitted for a save
@param string $field the field for which data will be saved
@param array $settings the settings for the current field
@return \Josegonzalez\Upload\File\Path\AbstractProcessor | [
"Retrieves",
"an",
"instance",
"of",
"a",
"path",
"processor",
"which",
"knows",
"how",
"to",
"build",
"paths",
"for",
"a",
"given",
"file",
"upload"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Model/Behavior/UploadBehavior.php#L171-L183 | train |
FriendsOfCake/cakephp-upload | src/Model/Behavior/UploadBehavior.php | UploadBehavior.getWriter | public function getWriter(Entity $entity, $data, $field, $settings)
{
$default = 'Josegonzalez\Upload\File\Writer\DefaultWriter';
$writerClass = Hash::get($settings, 'writer', $default);
if (is_subclass_of($writerClass, 'Josegonzalez\Upload\File\Writer\WriterInterface')) {
return new $writerClass($this->_table, $entity, $data, $field, $settings);
}
throw new UnexpectedValueException(sprintf(
"'writer' not set to instance of WriterInterface: %s",
$writerClass
));
} | php | public function getWriter(Entity $entity, $data, $field, $settings)
{
$default = 'Josegonzalez\Upload\File\Writer\DefaultWriter';
$writerClass = Hash::get($settings, 'writer', $default);
if (is_subclass_of($writerClass, 'Josegonzalez\Upload\File\Writer\WriterInterface')) {
return new $writerClass($this->_table, $entity, $data, $field, $settings);
}
throw new UnexpectedValueException(sprintf(
"'writer' not set to instance of WriterInterface: %s",
$writerClass
));
} | [
"public",
"function",
"getWriter",
"(",
"Entity",
"$",
"entity",
",",
"$",
"data",
",",
"$",
"field",
",",
"$",
"settings",
")",
"{",
"$",
"default",
"=",
"'Josegonzalez\\Upload\\File\\Writer\\DefaultWriter'",
";",
"$",
"writerClass",
"=",
"Hash",
"::",
"get",... | Retrieves an instance of a file writer which knows how to write files to disk
@param \Cake\ORM\Entity $entity an entity
@param array $data the data being submitted for a save
@param string $field the field for which data will be saved
@param array $settings the settings for the current field
@return \Josegonzalez\Upload\File\Path\AbstractProcessor | [
"Retrieves",
"an",
"instance",
"of",
"a",
"file",
"writer",
"which",
"knows",
"how",
"to",
"write",
"files",
"to",
"disk"
] | 7d21c546bbf718e95b011c1c9a42a689d076ea6f | https://github.com/FriendsOfCake/cakephp-upload/blob/7d21c546bbf718e95b011c1c9a42a689d076ea6f/src/Model/Behavior/UploadBehavior.php#L194-L206 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.