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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Behat/Gherkin | src/Behat/Gherkin/Parser.php | Parser.parseBackground | protected function parseBackground()
{
$token = $this->expectTokenType('Background');
$title = trim($token['value']);
$keyword = $token['keyword'];
$line = $token['line'];
if (count($this->popTags())) {
throw new ParserException(sprintf(
'Background can not be tagged, but it is on line: %d%s',
$line,
$this->file ? ' in file: ' . $this->file : ''
));
}
// Parse description and steps
$steps = array();
$allowedTokenTypes = array('Step', 'Newline', 'Text', 'Comment');
while (in_array($this->predictTokenType(), $allowedTokenTypes)) {
$node = $this->parseExpression();
if ($node instanceof StepNode) {
$steps[] = $this->normalizeStepNodeKeywordType($node, $steps);
continue;
}
if (!count($steps) && is_string($node)) {
$text = preg_replace('/^\s{0,' . ($token['indent'] + 2) . '}|\s*$/', '', $node);
$title .= "\n" . $text;
continue;
}
if ("\n" === $node) {
continue;
}
if (is_string($node)) {
throw new ParserException(sprintf(
'Expected Step, but got text: "%s"%s',
$node,
$this->file ? ' in file: ' . $this->file : ''
));
}
if (!$node instanceof StepNode) {
throw new ParserException(sprintf(
'Expected Step, but got %s on line: %d%s',
$node->getNodeType(),
$node->getLine(),
$this->file ? ' in file: ' . $this->file : ''
));
}
}
return new BackgroundNode(rtrim($title) ?: null, $steps, $keyword, $line);
} | php | protected function parseBackground()
{
$token = $this->expectTokenType('Background');
$title = trim($token['value']);
$keyword = $token['keyword'];
$line = $token['line'];
if (count($this->popTags())) {
throw new ParserException(sprintf(
'Background can not be tagged, but it is on line: %d%s',
$line,
$this->file ? ' in file: ' . $this->file : ''
));
}
// Parse description and steps
$steps = array();
$allowedTokenTypes = array('Step', 'Newline', 'Text', 'Comment');
while (in_array($this->predictTokenType(), $allowedTokenTypes)) {
$node = $this->parseExpression();
if ($node instanceof StepNode) {
$steps[] = $this->normalizeStepNodeKeywordType($node, $steps);
continue;
}
if (!count($steps) && is_string($node)) {
$text = preg_replace('/^\s{0,' . ($token['indent'] + 2) . '}|\s*$/', '', $node);
$title .= "\n" . $text;
continue;
}
if ("\n" === $node) {
continue;
}
if (is_string($node)) {
throw new ParserException(sprintf(
'Expected Step, but got text: "%s"%s',
$node,
$this->file ? ' in file: ' . $this->file : ''
));
}
if (!$node instanceof StepNode) {
throw new ParserException(sprintf(
'Expected Step, but got %s on line: %d%s',
$node->getNodeType(),
$node->getLine(),
$this->file ? ' in file: ' . $this->file : ''
));
}
}
return new BackgroundNode(rtrim($title) ?: null, $steps, $keyword, $line);
} | [
"protected",
"function",
"parseBackground",
"(",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"expectTokenType",
"(",
"'Background'",
")",
";",
"$",
"title",
"=",
"trim",
"(",
"$",
"token",
"[",
"'value'",
"]",
")",
";",
"$",
"keyword",
"=",
"$",
... | Parses background token & returns it's node.
@return BackgroundNode
@throws ParserException | [
"Parses",
"background",
"token",
"&",
"returns",
"it",
"s",
"node",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Parser.php#L298-L354 | train |
Behat/Gherkin | src/Behat/Gherkin/Parser.php | Parser.parseStep | protected function parseStep()
{
$token = $this->expectTokenType('Step');
$keyword = $token['value'];
$keywordType = $token['keyword_type'];
$text = trim($token['text']);
$line = $token['line'];
$arguments = array();
while (in_array($predicted = $this->predictTokenType(), array('PyStringOp', 'TableRow', 'Newline', 'Comment'))) {
if ('Comment' === $predicted || 'Newline' === $predicted) {
$this->acceptTokenType($predicted);
continue;
}
$node = $this->parseExpression();
if ($node instanceof PyStringNode || $node instanceof TableNode) {
$arguments[] = $node;
}
}
return new StepNode($keyword, $text, $arguments, $line, $keywordType);
} | php | protected function parseStep()
{
$token = $this->expectTokenType('Step');
$keyword = $token['value'];
$keywordType = $token['keyword_type'];
$text = trim($token['text']);
$line = $token['line'];
$arguments = array();
while (in_array($predicted = $this->predictTokenType(), array('PyStringOp', 'TableRow', 'Newline', 'Comment'))) {
if ('Comment' === $predicted || 'Newline' === $predicted) {
$this->acceptTokenType($predicted);
continue;
}
$node = $this->parseExpression();
if ($node instanceof PyStringNode || $node instanceof TableNode) {
$arguments[] = $node;
}
}
return new StepNode($keyword, $text, $arguments, $line, $keywordType);
} | [
"protected",
"function",
"parseStep",
"(",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"expectTokenType",
"(",
"'Step'",
")",
";",
"$",
"keyword",
"=",
"$",
"token",
"[",
"'value'",
"]",
";",
"$",
"keywordType",
"=",
"$",
"token",
"[",
"'keyword_ty... | Parses step token & returns it's node.
@return StepNode | [
"Parses",
"step",
"token",
"&",
"returns",
"it",
"s",
"node",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Parser.php#L490-L514 | train |
Behat/Gherkin | src/Behat/Gherkin/Parser.php | Parser.parseExamples | protected function parseExamples()
{
$token = $this->expectTokenType('Examples');
$keyword = $token['keyword'];
return new ExampleTableNode($this->parseTableRows(), $keyword);
} | php | protected function parseExamples()
{
$token = $this->expectTokenType('Examples');
$keyword = $token['keyword'];
return new ExampleTableNode($this->parseTableRows(), $keyword);
} | [
"protected",
"function",
"parseExamples",
"(",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"expectTokenType",
"(",
"'Examples'",
")",
";",
"$",
"keyword",
"=",
"$",
"token",
"[",
"'keyword'",
"]",
";",
"return",
"new",
"ExampleTableNode",
"(",
"$",
"... | Parses examples table node.
@return ExampleTableNode | [
"Parses",
"examples",
"table",
"node",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Parser.php#L521-L528 | train |
Behat/Gherkin | src/Behat/Gherkin/Parser.php | Parser.parsePyString | protected function parsePyString()
{
$token = $this->expectTokenType('PyStringOp');
$line = $token['line'];
$strings = array();
while ('PyStringOp' !== ($predicted = $this->predictTokenType()) && 'Text' === $predicted) {
$token = $this->expectTokenType('Text');
$strings[] = $token['value'];
}
$this->expectTokenType('PyStringOp');
return new PyStringNode($strings, $line);
} | php | protected function parsePyString()
{
$token = $this->expectTokenType('PyStringOp');
$line = $token['line'];
$strings = array();
while ('PyStringOp' !== ($predicted = $this->predictTokenType()) && 'Text' === $predicted) {
$token = $this->expectTokenType('Text');
$strings[] = $token['value'];
}
$this->expectTokenType('PyStringOp');
return new PyStringNode($strings, $line);
} | [
"protected",
"function",
"parsePyString",
"(",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"expectTokenType",
"(",
"'PyStringOp'",
")",
";",
"$",
"line",
"=",
"$",
"token",
"[",
"'line'",
"]",
";",
"$",
"strings",
"=",
"array",
"(",
")",
";",
"wh... | Parses PyString token & returns it's node.
@return PyStringNode | [
"Parses",
"PyString",
"token",
"&",
"returns",
"it",
"s",
"node",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Parser.php#L545-L561 | train |
Behat/Gherkin | src/Behat/Gherkin/Parser.php | Parser.parseLanguage | protected function parseLanguage()
{
$token = $this->expectTokenType('Language');
if (null === $this->languageSpecifierLine) {
$this->lexer->analyse($this->input, $token['value']);
$this->languageSpecifierLine = $token['line'];
} elseif ($token['line'] !== $this->languageSpecifierLine) {
throw new ParserException(sprintf(
'Ambiguous language specifiers on lines: %d and %d%s',
$this->languageSpecifierLine,
$token['line'],
$this->file ? ' in file: ' . $this->file : ''
));
}
return $this->parseExpression();
} | php | protected function parseLanguage()
{
$token = $this->expectTokenType('Language');
if (null === $this->languageSpecifierLine) {
$this->lexer->analyse($this->input, $token['value']);
$this->languageSpecifierLine = $token['line'];
} elseif ($token['line'] !== $this->languageSpecifierLine) {
throw new ParserException(sprintf(
'Ambiguous language specifiers on lines: %d and %d%s',
$this->languageSpecifierLine,
$token['line'],
$this->file ? ' in file: ' . $this->file : ''
));
}
return $this->parseExpression();
} | [
"protected",
"function",
"parseLanguage",
"(",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"expectTokenType",
"(",
"'Language'",
")",
";",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"languageSpecifierLine",
")",
"{",
"$",
"this",
"->",
"lexer",
"->... | Parses language block and updates lexer configuration based on it.
@return BackgroundNode|FeatureNode|OutlineNode|ScenarioNode|StepNode|TableNode|string
@throws ParserException | [
"Parses",
"language",
"block",
"and",
"updates",
"lexer",
"configuration",
"based",
"on",
"it",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Parser.php#L632-L649 | train |
Behat/Gherkin | src/Behat/Gherkin/Parser.php | Parser.parseTableRows | private function parseTableRows()
{
$table = array();
while (in_array($predicted = $this->predictTokenType(), array('TableRow', 'Newline', 'Comment'))) {
if ('Comment' === $predicted || 'Newline' === $predicted) {
$this->acceptTokenType($predicted);
continue;
}
$token = $this->expectTokenType('TableRow');
$table[$token['line']] = $token['columns'];
}
return $table;
} | php | private function parseTableRows()
{
$table = array();
while (in_array($predicted = $this->predictTokenType(), array('TableRow', 'Newline', 'Comment'))) {
if ('Comment' === $predicted || 'Newline' === $predicted) {
$this->acceptTokenType($predicted);
continue;
}
$token = $this->expectTokenType('TableRow');
$table[$token['line']] = $token['columns'];
}
return $table;
} | [
"private",
"function",
"parseTableRows",
"(",
")",
"{",
"$",
"table",
"=",
"array",
"(",
")",
";",
"while",
"(",
"in_array",
"(",
"$",
"predicted",
"=",
"$",
"this",
"->",
"predictTokenType",
"(",
")",
",",
"array",
"(",
"'TableRow'",
",",
"'Newline'",
... | Parses the rows of a table
@return string[][] | [
"Parses",
"the",
"rows",
"of",
"a",
"table"
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Parser.php#L656-L671 | train |
Behat/Gherkin | src/Behat/Gherkin/Parser.php | Parser.normalizeStepNodeKeywordType | private function normalizeStepNodeKeywordType(StepNode $node, array $steps = array())
{
if (in_array($node->getKeywordType(), array('And', 'But'))) {
if (($prev = end($steps))) {
$keywordType = $prev->getKeywordType();
} else {
$keywordType = 'Given';
}
$node = new StepNode(
$node->getKeyword(),
$node->getText(),
$node->getArguments(),
$node->getLine(),
$keywordType
);
}
return $node;
} | php | private function normalizeStepNodeKeywordType(StepNode $node, array $steps = array())
{
if (in_array($node->getKeywordType(), array('And', 'But'))) {
if (($prev = end($steps))) {
$keywordType = $prev->getKeywordType();
} else {
$keywordType = 'Given';
}
$node = new StepNode(
$node->getKeyword(),
$node->getText(),
$node->getArguments(),
$node->getLine(),
$keywordType
);
}
return $node;
} | [
"private",
"function",
"normalizeStepNodeKeywordType",
"(",
"StepNode",
"$",
"node",
",",
"array",
"$",
"steps",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"node",
"->",
"getKeywordType",
"(",
")",
",",
"array",
"(",
"'And'",
",",... | Changes step node type for types But, And to type of previous step if it exists else sets to Given
@param StepNode $node
@param StepNode[] $steps
@return StepNode | [
"Changes",
"step",
"node",
"type",
"for",
"types",
"But",
"And",
"to",
"type",
"of",
"previous",
"step",
"if",
"it",
"exists",
"else",
"sets",
"to",
"Given"
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Parser.php#L680-L698 | train |
Behat/Gherkin | src/Behat/Gherkin/Cache/FileCache.php | FileCache.read | public function read($path)
{
$cachePath = $this->getCachePathFor($path);
$feature = unserialize(file_get_contents($cachePath));
if (!$feature instanceof FeatureNode) {
throw new CacheException(sprintf('Can not load cache for a feature "%s" from "%s".', $path, $cachePath ));
}
return $feature;
} | php | public function read($path)
{
$cachePath = $this->getCachePathFor($path);
$feature = unserialize(file_get_contents($cachePath));
if (!$feature instanceof FeatureNode) {
throw new CacheException(sprintf('Can not load cache for a feature "%s" from "%s".', $path, $cachePath ));
}
return $feature;
} | [
"public",
"function",
"read",
"(",
"$",
"path",
")",
"{",
"$",
"cachePath",
"=",
"$",
"this",
"->",
"getCachePathFor",
"(",
"$",
"path",
")",
";",
"$",
"feature",
"=",
"unserialize",
"(",
"file_get_contents",
"(",
"$",
"cachePath",
")",
")",
";",
"if",... | Reads feature cache from path.
@param string $path Feature path
@return FeatureNode
@throws CacheException | [
"Reads",
"feature",
"cache",
"from",
"path",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Cache/FileCache.php#L75-L85 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/OutlineNode.php | OutlineNode.createExamples | protected function createExamples()
{
$examples = array();
foreach ($this->table->getColumnsHash() as $rowNum => $row) {
$examples[] = new ExampleNode(
$this->table->getRowAsString($rowNum + 1),
$this->tags,
$this->getSteps(),
$row,
$this->table->getRowLine($rowNum + 1),
$this->getTitle()
);
}
return $examples;
} | php | protected function createExamples()
{
$examples = array();
foreach ($this->table->getColumnsHash() as $rowNum => $row) {
$examples[] = new ExampleNode(
$this->table->getRowAsString($rowNum + 1),
$this->tags,
$this->getSteps(),
$row,
$this->table->getRowLine($rowNum + 1),
$this->getTitle()
);
}
return $examples;
} | [
"protected",
"function",
"createExamples",
"(",
")",
"{",
"$",
"examples",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"table",
"->",
"getColumnsHash",
"(",
")",
"as",
"$",
"rowNum",
"=>",
"$",
"row",
")",
"{",
"$",
"examples",
"[... | Creates examples for this outline using examples table.
@return ExampleNode[] | [
"Creates",
"examples",
"for",
"this",
"outline",
"using",
"examples",
"table",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/OutlineNode.php#L202-L217 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/TableNode.php | TableNode.fromList | public static function fromList(array $list)
{
if (count($list) !== count($list, COUNT_RECURSIVE)) {
throw new NodeException('List is not a one-dimensional array.');
}
array_walk($list, function (&$item) {
$item = array($item);
});
return new self($list);
} | php | public static function fromList(array $list)
{
if (count($list) !== count($list, COUNT_RECURSIVE)) {
throw new NodeException('List is not a one-dimensional array.');
}
array_walk($list, function (&$item) {
$item = array($item);
});
return new self($list);
} | [
"public",
"static",
"function",
"fromList",
"(",
"array",
"$",
"list",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"list",
")",
"!==",
"count",
"(",
"$",
"list",
",",
"COUNT_RECURSIVE",
")",
")",
"{",
"throw",
"new",
"NodeException",
"(",
"'List is not a one... | Creates a table from a given list.
@param array $list One-dimensional array
@return TableNode
@throws NodeException If the given list is not a one-dimensional array | [
"Creates",
"a",
"table",
"from",
"a",
"given",
"list",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/TableNode.php#L87-L97 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/TableNode.php | TableNode.getColumnsHash | public function getColumnsHash()
{
$rows = $this->getRows();
$keys = array_shift($rows);
$hash = array();
foreach ($rows as $row) {
$hash[] = array_combine($keys, $row);
}
return $hash;
} | php | public function getColumnsHash()
{
$rows = $this->getRows();
$keys = array_shift($rows);
$hash = array();
foreach ($rows as $row) {
$hash[] = array_combine($keys, $row);
}
return $hash;
} | [
"public",
"function",
"getColumnsHash",
"(",
")",
"{",
"$",
"rows",
"=",
"$",
"this",
"->",
"getRows",
"(",
")",
";",
"$",
"keys",
"=",
"array_shift",
"(",
"$",
"rows",
")",
";",
"$",
"hash",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"row... | Returns table hash, formed by columns.
@return array | [
"Returns",
"table",
"hash",
"formed",
"by",
"columns",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/TableNode.php#L124-L135 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/TableNode.php | TableNode.getRowsHash | public function getRowsHash()
{
$hash = array();
foreach ($this->getRows() as $row) {
$hash[array_shift($row)] = (1 == count($row)) ? $row[0] : $row;
}
return $hash;
} | php | public function getRowsHash()
{
$hash = array();
foreach ($this->getRows() as $row) {
$hash[array_shift($row)] = (1 == count($row)) ? $row[0] : $row;
}
return $hash;
} | [
"public",
"function",
"getRowsHash",
"(",
")",
"{",
"$",
"hash",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getRows",
"(",
")",
"as",
"$",
"row",
")",
"{",
"$",
"hash",
"[",
"array_shift",
"(",
"$",
"row",
")",
"]",
"=",
"... | Returns table hash, formed by rows.
@return array | [
"Returns",
"table",
"hash",
"formed",
"by",
"rows",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/TableNode.php#L142-L151 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/TableNode.php | TableNode.getRow | public function getRow($index)
{
$rows = $this->getRows();
if (!isset($rows[$index])) {
throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
}
return $rows[$index];
} | php | public function getRow($index)
{
$rows = $this->getRows();
if (!isset($rows[$index])) {
throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
}
return $rows[$index];
} | [
"public",
"function",
"getRow",
"(",
"$",
"index",
")",
"{",
"$",
"rows",
"=",
"$",
"this",
"->",
"getRows",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"rows",
"[",
"$",
"index",
"]",
")",
")",
"{",
"throw",
"new",
"NodeException",
"(",
... | Returns specific row in a table.
@param integer $index Row number
@return array
@throws NodeException If row with specified index does not exist | [
"Returns",
"specific",
"row",
"in",
"a",
"table",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/TableNode.php#L193-L202 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/TableNode.php | TableNode.getColumn | public function getColumn($index)
{
if ($index >= count($this->getRow(0))) {
throw new NodeException(sprintf('Column #%d does not exist in table.', $index));
}
$rows = $this->getRows();
$column = array();
foreach ($rows as $row) {
$column[] = $row[$index];
}
return $column;
} | php | public function getColumn($index)
{
if ($index >= count($this->getRow(0))) {
throw new NodeException(sprintf('Column #%d does not exist in table.', $index));
}
$rows = $this->getRows();
$column = array();
foreach ($rows as $row) {
$column[] = $row[$index];
}
return $column;
} | [
"public",
"function",
"getColumn",
"(",
"$",
"index",
")",
"{",
"if",
"(",
"$",
"index",
">=",
"count",
"(",
"$",
"this",
"->",
"getRow",
"(",
"0",
")",
")",
")",
"{",
"throw",
"new",
"NodeException",
"(",
"sprintf",
"(",
"'Column #%d does not exist in t... | Returns specific column in a table.
@param integer $index Column number
@return array
@throws NodeException If column with specified index does not exist | [
"Returns",
"specific",
"column",
"in",
"a",
"table",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/TableNode.php#L213-L227 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/TableNode.php | TableNode.getRowLine | public function getRowLine($index)
{
$lines = array_keys($this->table);
if (!isset($lines[$index])) {
throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
}
return $lines[$index];
} | php | public function getRowLine($index)
{
$lines = array_keys($this->table);
if (!isset($lines[$index])) {
throw new NodeException(sprintf('Rows #%d does not exist in table.', $index));
}
return $lines[$index];
} | [
"public",
"function",
"getRowLine",
"(",
"$",
"index",
")",
"{",
"$",
"lines",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"table",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"lines",
"[",
"$",
"index",
"]",
")",
")",
"{",
"throw",
"new",
"NodeE... | Returns line number at which specific row was defined.
@param integer $index
@return integer
@throws NodeException If row with specified index does not exist | [
"Returns",
"line",
"number",
"at",
"which",
"specific",
"row",
"was",
"defined",
"."
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/TableNode.php#L238-L247 | train |
Behat/Gherkin | src/Behat/Gherkin/Node/TableNode.php | TableNode.getTableAsString | public function getTableAsString()
{
$lines = array();
for ($i = 0; $i < count($this->getRows()); $i++) {
$lines[] = $this->getRowAsString($i);
}
return implode("\n", $lines);
} | php | public function getTableAsString()
{
$lines = array();
for ($i = 0; $i < count($this->getRows()); $i++) {
$lines[] = $this->getRowAsString($i);
}
return implode("\n", $lines);
} | [
"public",
"function",
"getTableAsString",
"(",
")",
"{",
"$",
"lines",
"=",
"array",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"count",
"(",
"$",
"this",
"->",
"getRows",
"(",
")",
")",
";",
"$",
"i",
"++",
")",
"{",
... | Converts entire table into string
@return string | [
"Converts",
"entire",
"table",
"into",
"string"
] | 749be1ff9ed4265a4465c90c3900bdebad6b008e | https://github.com/Behat/Gherkin/blob/749be1ff9ed4265a4465c90c3900bdebad6b008e/src/Behat/Gherkin/Node/TableNode.php#L291-L299 | train |
php-http/client-common | spec/HttpMethodsClientSpec.php | HttpMethodsClientSpec.assert | private function assert(HttpClient $client, RequestFactory $requestFactory, RequestInterface $request, ResponseInterface $response, string $method, string $body = null)
{
$client->sendRequest($request)->shouldBeCalled()->willReturn($response);
$this->mockFactory($requestFactory, $request, strtoupper($method), $body);
$this->$method(self::$requestData['uri'], self::$requestData['headers'], self::$requestData['body'])->shouldReturnAnInstanceOf(ResponseInterface::class);
} | php | private function assert(HttpClient $client, RequestFactory $requestFactory, RequestInterface $request, ResponseInterface $response, string $method, string $body = null)
{
$client->sendRequest($request)->shouldBeCalled()->willReturn($response);
$this->mockFactory($requestFactory, $request, strtoupper($method), $body);
$this->$method(self::$requestData['uri'], self::$requestData['headers'], self::$requestData['body'])->shouldReturnAnInstanceOf(ResponseInterface::class);
} | [
"private",
"function",
"assert",
"(",
"HttpClient",
"$",
"client",
",",
"RequestFactory",
"$",
"requestFactory",
",",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
",",
"string",
"$",
"method",
",",
"string",
"$",
"body",
"=",
... | Run the actual test.
As there is no data provider in phpspec, we keep separate methods to get new mocks for each test. | [
"Run",
"the",
"actual",
"test",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/spec/HttpMethodsClientSpec.php#L77-L83 | train |
php-http/client-common | src/HttpClientPool/HttpClientPoolItem.php | HttpClientPoolItem.isDisabled | public function isDisabled(): bool
{
if (null !== $this->reenableAfter && null !== $this->disabledAt) {
// Reenable after a certain time
$now = new \DateTime();
if (($now->getTimestamp() - $this->disabledAt->getTimestamp()) >= $this->reenableAfter) {
$this->enable();
return false;
}
return true;
}
return null !== $this->disabledAt;
} | php | public function isDisabled(): bool
{
if (null !== $this->reenableAfter && null !== $this->disabledAt) {
// Reenable after a certain time
$now = new \DateTime();
if (($now->getTimestamp() - $this->disabledAt->getTimestamp()) >= $this->reenableAfter) {
$this->enable();
return false;
}
return true;
}
return null !== $this->disabledAt;
} | [
"public",
"function",
"isDisabled",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"reenableAfter",
"&&",
"null",
"!==",
"$",
"this",
"->",
"disabledAt",
")",
"{",
"// Reenable after a certain time",
"$",
"now",
"=",
"new",
"\\",
... | Whether this client is disabled or not.
If the client was disabled, calling this method checks if the client can
be reenabled and if so enables it. | [
"Whether",
"this",
"client",
"is",
"disabled",
"or",
"not",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/HttpClientPool/HttpClientPoolItem.php#L118-L134 | train |
php-http/client-common | src/Plugin/AddPathPlugin.php | AddPathPlugin.handleRequest | public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
{
$prepend = $this->uri->getPath();
$path = $request->getUri()->getPath();
if (substr($path, 0, strlen($prepend)) !== $prepend) {
$request = $request->withUri($request->getUri()
->withPath($prepend.$path)
);
}
return $next($request);
} | php | public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
{
$prepend = $this->uri->getPath();
$path = $request->getUri()->getPath();
if (substr($path, 0, strlen($prepend)) !== $prepend) {
$request = $request->withUri($request->getUri()
->withPath($prepend.$path)
);
}
return $next($request);
} | [
"public",
"function",
"handleRequest",
"(",
"RequestInterface",
"$",
"request",
",",
"callable",
"$",
"next",
",",
"callable",
"$",
"first",
")",
":",
"Promise",
"{",
"$",
"prepend",
"=",
"$",
"this",
"->",
"uri",
"->",
"getPath",
"(",
")",
";",
"$",
"... | Adds a prefix in the beginning of the URL's path.
The prefix is not added if that prefix is already on the URL's path. This will fail on the edge
case of the prefix being repeated, for example if `https://example.com/api/api/foo` is a valid
URL on the server and the configured prefix is `/api`.
We looked at other solutions, but they are all much more complicated, while still having edge
cases:
- Doing an spl_object_hash on `$first` will lead to collisions over time because over time the
hash can collide.
- Have the PluginClient provide a magic header to identify the request chain and only apply
this plugin once.
There are 2 reasons for the AddPathPlugin to be executed twice on the same request:
- A plugin can restart the chain by calling `$first`, e.g. redirect
- A plugin can call `$next` more than once, e.g. retry
Depending on the scenario, the path should or should not be added. E.g. `$first` could
be called after a redirect response from the server. The server likely already has the
correct path.
No solution fits all use cases. This implementation will work fine for the common use cases.
If you have a specific situation where this is not the right thing, you can build a custom plugin
that does exactly what you need.
{@inheritdoc} | [
"Adds",
"a",
"prefix",
"in",
"the",
"beginning",
"of",
"the",
"URL",
"s",
"path",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/Plugin/AddPathPlugin.php#L65-L77 | train |
php-http/client-common | src/Plugin/DecoderPlugin.php | DecoderPlugin.decodeResponse | private function decodeResponse(ResponseInterface $response): ResponseInterface
{
$response = $this->decodeOnEncodingHeader('Transfer-Encoding', $response);
if ($this->useContentEncoding) {
$response = $this->decodeOnEncodingHeader('Content-Encoding', $response);
}
return $response;
} | php | private function decodeResponse(ResponseInterface $response): ResponseInterface
{
$response = $this->decodeOnEncodingHeader('Transfer-Encoding', $response);
if ($this->useContentEncoding) {
$response = $this->decodeOnEncodingHeader('Content-Encoding', $response);
}
return $response;
} | [
"private",
"function",
"decodeResponse",
"(",
"ResponseInterface",
"$",
"response",
")",
":",
"ResponseInterface",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"decodeOnEncodingHeader",
"(",
"'Transfer-Encoding'",
",",
"$",
"response",
")",
";",
"if",
"(",
"$",... | Decode a response body given its Transfer-Encoding or Content-Encoding value. | [
"Decode",
"a",
"response",
"body",
"given",
"its",
"Transfer",
"-",
"Encoding",
"or",
"Content",
"-",
"Encoding",
"value",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/Plugin/DecoderPlugin.php#L72-L81 | train |
php-http/client-common | src/Deferred.php | Deferred.resolve | public function resolve(ResponseInterface $response): void
{
if (Promise::PENDING !== $this->state) {
return;
}
$this->value = $response;
$this->state = Promise::FULFILLED;
foreach ($this->onFulfilledCallbacks as $onFulfilledCallback) {
$onFulfilledCallback($response);
}
} | php | public function resolve(ResponseInterface $response): void
{
if (Promise::PENDING !== $this->state) {
return;
}
$this->value = $response;
$this->state = Promise::FULFILLED;
foreach ($this->onFulfilledCallbacks as $onFulfilledCallback) {
$onFulfilledCallback($response);
}
} | [
"public",
"function",
"resolve",
"(",
"ResponseInterface",
"$",
"response",
")",
":",
"void",
"{",
"if",
"(",
"Promise",
"::",
"PENDING",
"!==",
"$",
"this",
"->",
"state",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"value",
"=",
"$",
"response",... | Resolve this deferred with a Response. | [
"Resolve",
"this",
"deferred",
"with",
"a",
"Response",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/Deferred.php#L100-L112 | train |
php-http/client-common | src/Deferred.php | Deferred.reject | public function reject(ClientExceptionInterface $exception): void
{
if (Promise::PENDING !== $this->state) {
return;
}
$this->failure = $exception;
$this->state = Promise::REJECTED;
foreach ($this->onRejectedCallbacks as $onRejectedCallback) {
$onRejectedCallback($exception);
}
} | php | public function reject(ClientExceptionInterface $exception): void
{
if (Promise::PENDING !== $this->state) {
return;
}
$this->failure = $exception;
$this->state = Promise::REJECTED;
foreach ($this->onRejectedCallbacks as $onRejectedCallback) {
$onRejectedCallback($exception);
}
} | [
"public",
"function",
"reject",
"(",
"ClientExceptionInterface",
"$",
"exception",
")",
":",
"void",
"{",
"if",
"(",
"Promise",
"::",
"PENDING",
"!==",
"$",
"this",
"->",
"state",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"failure",
"=",
"$",
"e... | Reject this deferred with an Exception. | [
"Reject",
"this",
"deferred",
"with",
"an",
"Exception",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/Deferred.php#L117-L129 | train |
php-http/client-common | src/HttpClientPool/HttpClientPool.php | HttpClientPool.addHttpClient | public function addHttpClient($client): void
{
if (!$client instanceof HttpClientPoolItem) {
$client = new HttpClientPoolItem($client);
}
$this->clientPool[] = $client;
} | php | public function addHttpClient($client): void
{
if (!$client instanceof HttpClientPoolItem) {
$client = new HttpClientPoolItem($client);
}
$this->clientPool[] = $client;
} | [
"public",
"function",
"addHttpClient",
"(",
"$",
"client",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"client",
"instanceof",
"HttpClientPoolItem",
")",
"{",
"$",
"client",
"=",
"new",
"HttpClientPoolItem",
"(",
"$",
"client",
")",
";",
"}",
"$",
"this"... | Add a client to the pool.
@param ClientInterface|HttpAsyncClient|HttpClientPoolItem $client | [
"Add",
"a",
"client",
"to",
"the",
"pool",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/HttpClientPool/HttpClientPool.php#L30-L37 | train |
php-http/client-common | src/BatchResult.php | BatchResult.getResponses | public function getResponses(): array
{
$responses = [];
foreach ($this->responses as $request) {
$responses[] = $this->responses[$request];
}
return $responses;
} | php | public function getResponses(): array
{
$responses = [];
foreach ($this->responses as $request) {
$responses[] = $this->responses[$request];
}
return $responses;
} | [
"public",
"function",
"getResponses",
"(",
")",
":",
"array",
"{",
"$",
"responses",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"responses",
"as",
"$",
"request",
")",
"{",
"$",
"responses",
"[",
"]",
"=",
"$",
"this",
"->",
"responses",
... | Returns all successful responses.
@return ResponseInterface[] | [
"Returns",
"all",
"successful",
"responses",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/BatchResult.php#L47-L56 | train |
php-http/client-common | src/BatchResult.php | BatchResult.getResponseFor | public function getResponseFor(RequestInterface $request): ResponseInterface
{
try {
return $this->responses[$request];
} catch (\UnexpectedValueException $e) {
throw new \UnexpectedValueException('Request not found', $e->getCode(), $e);
}
} | php | public function getResponseFor(RequestInterface $request): ResponseInterface
{
try {
return $this->responses[$request];
} catch (\UnexpectedValueException $e) {
throw new \UnexpectedValueException('Request not found', $e->getCode(), $e);
}
} | [
"public",
"function",
"getResponseFor",
"(",
"RequestInterface",
"$",
"request",
")",
":",
"ResponseInterface",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"responses",
"[",
"$",
"request",
"]",
";",
"}",
"catch",
"(",
"\\",
"UnexpectedValueException",
"$",
... | Returns the response for a successful request.
@throws \UnexpectedValueException If request was not part of the batch or failed | [
"Returns",
"the",
"response",
"for",
"a",
"successful",
"request",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/BatchResult.php#L72-L79 | train |
php-http/client-common | src/BatchResult.php | BatchResult.addResponse | public function addResponse(RequestInterface $request, ResponseInterface $response): self
{
$new = clone $this;
$new->responses->attach($request, $response);
return $new;
} | php | public function addResponse(RequestInterface $request, ResponseInterface $response): self
{
$new = clone $this;
$new->responses->attach($request, $response);
return $new;
} | [
"public",
"function",
"addResponse",
"(",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
":",
"self",
"{",
"$",
"new",
"=",
"clone",
"$",
"this",
";",
"$",
"new",
"->",
"responses",
"->",
"attach",
"(",
"$",
"request",
... | Adds a response in an immutable way.
@return BatchResult the new BatchResult with this request-response pair added to it | [
"Adds",
"a",
"response",
"in",
"an",
"immutable",
"way",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/BatchResult.php#L86-L92 | train |
php-http/client-common | src/BatchResult.php | BatchResult.getExceptions | public function getExceptions(): array
{
$exceptions = [];
foreach ($this->exceptions as $request) {
$exceptions[] = $this->exceptions[$request];
}
return $exceptions;
} | php | public function getExceptions(): array
{
$exceptions = [];
foreach ($this->exceptions as $request) {
$exceptions[] = $this->exceptions[$request];
}
return $exceptions;
} | [
"public",
"function",
"getExceptions",
"(",
")",
":",
"array",
"{",
"$",
"exceptions",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"exceptions",
"as",
"$",
"request",
")",
"{",
"$",
"exceptions",
"[",
"]",
"=",
"$",
"this",
"->",
"exceptio... | Returns all exceptions for the unsuccessful requests.
@return ClientExceptionInterface[] | [
"Returns",
"all",
"exceptions",
"for",
"the",
"unsuccessful",
"requests",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/BatchResult.php#L107-L116 | train |
php-http/client-common | src/BatchResult.php | BatchResult.getExceptionFor | public function getExceptionFor(RequestInterface $request): ClientExceptionInterface
{
try {
return $this->exceptions[$request];
} catch (\UnexpectedValueException $e) {
throw new \UnexpectedValueException('Request not found', $e->getCode(), $e);
}
} | php | public function getExceptionFor(RequestInterface $request): ClientExceptionInterface
{
try {
return $this->exceptions[$request];
} catch (\UnexpectedValueException $e) {
throw new \UnexpectedValueException('Request not found', $e->getCode(), $e);
}
} | [
"public",
"function",
"getExceptionFor",
"(",
"RequestInterface",
"$",
"request",
")",
":",
"ClientExceptionInterface",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"exceptions",
"[",
"$",
"request",
"]",
";",
"}",
"catch",
"(",
"\\",
"UnexpectedValueException"... | Returns the exception for a failed request.
@throws \UnexpectedValueException If request was not part of the batch or was successful | [
"Returns",
"the",
"exception",
"for",
"a",
"failed",
"request",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/BatchResult.php#L132-L139 | train |
php-http/client-common | src/BatchResult.php | BatchResult.addException | public function addException(RequestInterface $request, ClientExceptionInterface $exception): self
{
$new = clone $this;
$new->exceptions->attach($request, $exception);
return $new;
} | php | public function addException(RequestInterface $request, ClientExceptionInterface $exception): self
{
$new = clone $this;
$new->exceptions->attach($request, $exception);
return $new;
} | [
"public",
"function",
"addException",
"(",
"RequestInterface",
"$",
"request",
",",
"ClientExceptionInterface",
"$",
"exception",
")",
":",
"self",
"{",
"$",
"new",
"=",
"clone",
"$",
"this",
";",
"$",
"new",
"->",
"exceptions",
"->",
"attach",
"(",
"$",
"... | Adds an exception in an immutable way.
@return BatchResult the new BatchResult with this request-exception pair added to it | [
"Adds",
"an",
"exception",
"in",
"an",
"immutable",
"way",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/BatchResult.php#L146-L152 | train |
php-http/client-common | src/PluginClient.php | PluginClient.configure | private function configure(array $options = []): array
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'max_restarts' => 10,
]);
$resolver->setAllowedTypes('max_restarts', 'int');
return $resolver->resolve($options);
} | php | private function configure(array $options = []): array
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'max_restarts' => 10,
]);
$resolver->setAllowedTypes('max_restarts', 'int');
return $resolver->resolve($options);
} | [
"private",
"function",
"configure",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"array",
"{",
"$",
"resolver",
"=",
"new",
"OptionsResolver",
"(",
")",
";",
"$",
"resolver",
"->",
"setDefaults",
"(",
"[",
"'max_restarts'",
"=>",
"10",
",",
"... | Configure the plugin client. | [
"Configure",
"the",
"plugin",
"client",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/PluginClient.php#L108-L118 | train |
php-http/client-common | src/HttpClientRouter.php | HttpClientRouter.addClient | public function addClient($client, RequestMatcher $requestMatcher): void
{
$this->clients[] = [
'matcher' => $requestMatcher,
'client' => new FlexibleHttpClient($client),
];
} | php | public function addClient($client, RequestMatcher $requestMatcher): void
{
$this->clients[] = [
'matcher' => $requestMatcher,
'client' => new FlexibleHttpClient($client),
];
} | [
"public",
"function",
"addClient",
"(",
"$",
"client",
",",
"RequestMatcher",
"$",
"requestMatcher",
")",
":",
"void",
"{",
"$",
"this",
"->",
"clients",
"[",
"]",
"=",
"[",
"'matcher'",
"=>",
"$",
"requestMatcher",
",",
"'client'",
"=>",
"new",
"FlexibleH... | Add a client to the router.
@param ClientInterface|HttpAsyncClient $client | [
"Add",
"a",
"client",
"to",
"the",
"router",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/HttpClientRouter.php#L47-L53 | train |
php-http/client-common | src/HttpClientRouter.php | HttpClientRouter.chooseHttpClient | private function chooseHttpClient(RequestInterface $request)
{
foreach ($this->clients as $client) {
if ($client['matcher']->matches($request)) {
return $client['client'];
}
}
throw new HttpClientNoMatchException('No client found for the specified request', $request);
} | php | private function chooseHttpClient(RequestInterface $request)
{
foreach ($this->clients as $client) {
if ($client['matcher']->matches($request)) {
return $client['client'];
}
}
throw new HttpClientNoMatchException('No client found for the specified request', $request);
} | [
"private",
"function",
"chooseHttpClient",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"clients",
"as",
"$",
"client",
")",
"{",
"if",
"(",
"$",
"client",
"[",
"'matcher'",
"]",
"->",
"matches",
"(",
"$",
"reques... | Choose an HTTP client given a specific request.
@return ClientInterface|HttpAsyncClient | [
"Choose",
"an",
"HTTP",
"client",
"given",
"a",
"specific",
"request",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/src/HttpClientRouter.php#L60-L69 | train |
php-http/client-common | spec/Plugin/RedirectPluginSpec.php | RedirectPluginSpec.it_throws_circular_redirection_exception_on_redirect_that_does_not_change_url | public function it_throws_circular_redirection_exception_on_redirect_that_does_not_change_url(
UriInterface $redirectUri,
RequestInterface $request,
ResponseInterface $redirectResponse
) {
$redirectResponse->getStatusCode()->willReturn(302);
$redirectResponse->hasHeader('Location')->willReturn(true);
$redirectResponse->getHeaderLine('Location')->willReturn('/redirect');
$next = function () use ($redirectResponse): Promise {
return new HttpFulfilledPromise($redirectResponse->getWrappedObject());
};
$first = function () {
throw new \Exception('First should never be called');
};
$request->getUri()->willReturn($redirectUri);
$redirectUri->__toString()->willReturn('/redirect');
$redirectUri->withPath('/redirect')->willReturn($redirectUri);
$redirectUri->withFragment('')->willReturn($redirectUri);
$redirectUri->withQuery('')->willReturn($redirectUri);
$request->withUri($redirectUri)->willReturn($request);
$redirectUri->__toString()->willReturn('/redirect');
$request->getMethod()->willReturn('GET');
$promise = $this->handleRequest($request, $next, $first);
$promise->shouldReturnAnInstanceOf(HttpRejectedPromise::class);
$promise->shouldThrow(CircularRedirectionException::class)->duringWait();
} | php | public function it_throws_circular_redirection_exception_on_redirect_that_does_not_change_url(
UriInterface $redirectUri,
RequestInterface $request,
ResponseInterface $redirectResponse
) {
$redirectResponse->getStatusCode()->willReturn(302);
$redirectResponse->hasHeader('Location')->willReturn(true);
$redirectResponse->getHeaderLine('Location')->willReturn('/redirect');
$next = function () use ($redirectResponse): Promise {
return new HttpFulfilledPromise($redirectResponse->getWrappedObject());
};
$first = function () {
throw new \Exception('First should never be called');
};
$request->getUri()->willReturn($redirectUri);
$redirectUri->__toString()->willReturn('/redirect');
$redirectUri->withPath('/redirect')->willReturn($redirectUri);
$redirectUri->withFragment('')->willReturn($redirectUri);
$redirectUri->withQuery('')->willReturn($redirectUri);
$request->withUri($redirectUri)->willReturn($request);
$redirectUri->__toString()->willReturn('/redirect');
$request->getMethod()->willReturn('GET');
$promise = $this->handleRequest($request, $next, $first);
$promise->shouldReturnAnInstanceOf(HttpRejectedPromise::class);
$promise->shouldThrow(CircularRedirectionException::class)->duringWait();
} | [
"public",
"function",
"it_throws_circular_redirection_exception_on_redirect_that_does_not_change_url",
"(",
"UriInterface",
"$",
"redirectUri",
",",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"redirectResponse",
")",
"{",
"$",
"redirectResponse",
"->",
... | This is the "redirection does not redirect case. | [
"This",
"is",
"the",
"redirection",
"does",
"not",
"redirect",
"case",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/spec/Plugin/RedirectPluginSpec.php#L366-L397 | train |
php-http/client-common | spec/Plugin/RedirectPluginSpec.php | RedirectPluginSpec.it_throws_circular_redirection_exception_on_alternating_redirect | public function it_throws_circular_redirection_exception_on_alternating_redirect(
UriInterface $uri,
UriInterface $redirectUri,
RequestInterface $request,
ResponseInterface $redirectResponse1,
ResponseInterface $redirectResponse2,
RequestInterface $modifiedRequest
) {
$redirectResponse1->getStatusCode()->willReturn(302);
$redirectResponse1->hasHeader('Location')->willReturn(true);
$redirectResponse1->getHeaderLine('Location')->willReturn('/redirect');
$redirectResponse2->getStatusCode()->willReturn(302);
$redirectResponse2->hasHeader('Location')->willReturn(true);
$redirectResponse2->getHeaderLine('Location')->willReturn('/original');
$next = function (RequestInterface $currentRequest) use ($request, $redirectResponse1, $redirectResponse2): Promise {
return ($currentRequest === $request->getWrappedObject())
? new HttpFulfilledPromise($redirectResponse1->getWrappedObject())
: new HttpFulfilledPromise($redirectResponse2->getWrappedObject())
;
};
$redirectPlugin = $this;
$firstCalled = false;
$first = function (RequestInterface $request) use (&$firstCalled, $redirectPlugin, $next, &$first) {
if ($firstCalled) {
throw new \Exception('only one redirect expected');
}
$firstCalled = true;
return $redirectPlugin->getWrappedObject()->handleRequest($request, $next, $first);
};
$request->getUri()->willReturn($uri);
$uri->__toString()->willReturn('/original');
$modifiedRequest->getUri()->willReturn($redirectUri);
$redirectUri->__toString()->willReturn('/redirect');
$uri->withPath('/redirect')->willReturn($redirectUri);
$redirectUri->withFragment('')->willReturn($redirectUri);
$redirectUri->withQuery('')->willReturn($redirectUri);
$redirectUri->withPath('/original')->willReturn($uri);
$uri->withFragment('')->willReturn($uri);
$uri->withQuery('')->willReturn($uri);
$request->withUri($redirectUri)->willReturn($modifiedRequest);
$request->getMethod()->willReturn('GET');
$modifiedRequest->withUri($uri)->willReturn($request);
$modifiedRequest->getMethod()->willReturn('GET');
$promise = $this->handleRequest($request, $next, $first);
$promise->shouldReturnAnInstanceOf(HttpRejectedPromise::class);
$promise->shouldThrow(CircularRedirectionException::class)->duringWait();
} | php | public function it_throws_circular_redirection_exception_on_alternating_redirect(
UriInterface $uri,
UriInterface $redirectUri,
RequestInterface $request,
ResponseInterface $redirectResponse1,
ResponseInterface $redirectResponse2,
RequestInterface $modifiedRequest
) {
$redirectResponse1->getStatusCode()->willReturn(302);
$redirectResponse1->hasHeader('Location')->willReturn(true);
$redirectResponse1->getHeaderLine('Location')->willReturn('/redirect');
$redirectResponse2->getStatusCode()->willReturn(302);
$redirectResponse2->hasHeader('Location')->willReturn(true);
$redirectResponse2->getHeaderLine('Location')->willReturn('/original');
$next = function (RequestInterface $currentRequest) use ($request, $redirectResponse1, $redirectResponse2): Promise {
return ($currentRequest === $request->getWrappedObject())
? new HttpFulfilledPromise($redirectResponse1->getWrappedObject())
: new HttpFulfilledPromise($redirectResponse2->getWrappedObject())
;
};
$redirectPlugin = $this;
$firstCalled = false;
$first = function (RequestInterface $request) use (&$firstCalled, $redirectPlugin, $next, &$first) {
if ($firstCalled) {
throw new \Exception('only one redirect expected');
}
$firstCalled = true;
return $redirectPlugin->getWrappedObject()->handleRequest($request, $next, $first);
};
$request->getUri()->willReturn($uri);
$uri->__toString()->willReturn('/original');
$modifiedRequest->getUri()->willReturn($redirectUri);
$redirectUri->__toString()->willReturn('/redirect');
$uri->withPath('/redirect')->willReturn($redirectUri);
$redirectUri->withFragment('')->willReturn($redirectUri);
$redirectUri->withQuery('')->willReturn($redirectUri);
$redirectUri->withPath('/original')->willReturn($uri);
$uri->withFragment('')->willReturn($uri);
$uri->withQuery('')->willReturn($uri);
$request->withUri($redirectUri)->willReturn($modifiedRequest);
$request->getMethod()->willReturn('GET');
$modifiedRequest->withUri($uri)->willReturn($request);
$modifiedRequest->getMethod()->willReturn('GET');
$promise = $this->handleRequest($request, $next, $first);
$promise->shouldReturnAnInstanceOf(HttpRejectedPromise::class);
$promise->shouldThrow(CircularRedirectionException::class)->duringWait();
} | [
"public",
"function",
"it_throws_circular_redirection_exception_on_alternating_redirect",
"(",
"UriInterface",
"$",
"uri",
",",
"UriInterface",
"$",
"redirectUri",
",",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"redirectResponse1",
",",
"ResponseInter... | This is a redirection flipping back and forth between two paths.
There could be a larger loop but the logic in the plugin stays the same with as many redirects as needed. | [
"This",
"is",
"a",
"redirection",
"flipping",
"back",
"and",
"forth",
"between",
"two",
"paths",
"."
] | 9a2a4c1735ee00eac3e6939a8e2ea29321ae2593 | https://github.com/php-http/client-common/blob/9a2a4c1735ee00eac3e6939a8e2ea29321ae2593/spec/Plugin/RedirectPluginSpec.php#L404-L460 | train |
botman/driver-slack | src/SlackDriver.php | SlackDriver.hasMatchingEvent | public function hasMatchingEvent()
{
// Retrieve the 'event' part of the payload
$eventData = $this->payload->get('event');
// If the event type isn't 'message' (which should go through BotMan::hears),
// build a GenericEvent and return it
if (isset($eventData['type']) && $eventData['type'] !== 'message') {
$eventPayload = json_encode($eventData);
if ($eventPayload !== false) {
$event = new GenericEvent($eventPayload);
$event->setName($eventData['type']);
return $event;
}
}
// Otherwise, fall back to the parent implementation
return parent::hasMatchingEvent();
} | php | public function hasMatchingEvent()
{
// Retrieve the 'event' part of the payload
$eventData = $this->payload->get('event');
// If the event type isn't 'message' (which should go through BotMan::hears),
// build a GenericEvent and return it
if (isset($eventData['type']) && $eventData['type'] !== 'message') {
$eventPayload = json_encode($eventData);
if ($eventPayload !== false) {
$event = new GenericEvent($eventPayload);
$event->setName($eventData['type']);
return $event;
}
}
// Otherwise, fall back to the parent implementation
return parent::hasMatchingEvent();
} | [
"public",
"function",
"hasMatchingEvent",
"(",
")",
"{",
"// Retrieve the 'event' part of the payload",
"$",
"eventData",
"=",
"$",
"this",
"->",
"payload",
"->",
"get",
"(",
"'event'",
")",
";",
"// If the event type isn't 'message' (which should go through BotMan::hears),",... | Determine whether a non-message event is matching the current request, and if so,
build and return a GenericEvent instance from it.
@return GenericEvent|bool|mixed A GenericEvent instance, or the result from
the parent class' method (likely false). | [
"Determine",
"whether",
"a",
"non",
"-",
"message",
"event",
"is",
"matching",
"the",
"current",
"request",
"and",
"if",
"so",
"build",
"and",
"return",
"a",
"GenericEvent",
"instance",
"from",
"it",
"."
] | a832671a0bc2a42b083ebaea60ea7a4efee96045 | https://github.com/botman/driver-slack/blob/a832671a0bc2a42b083ebaea60ea7a4efee96045/src/SlackDriver.php#L93-L112 | train |
botman/driver-slack | src/SlackDriver.php | SlackDriver.convertQuestion | private function convertQuestion(Question $question)
{
$questionData = $question->toArray();
$buttons = Collection::make($question->getButtons())->map(function ($button) {
if ($button['type'] === 'select') {
return $button;
}
return array_merge([
'name' => $button['name'],
'text' => $button['text'],
'image_url' => $button['image_url'],
'type' => $button['type'],
'value' => $button['value'],
], $button['additional']);
})->toArray();
$questionData['actions'] = $buttons;
return $questionData;
} | php | private function convertQuestion(Question $question)
{
$questionData = $question->toArray();
$buttons = Collection::make($question->getButtons())->map(function ($button) {
if ($button['type'] === 'select') {
return $button;
}
return array_merge([
'name' => $button['name'],
'text' => $button['text'],
'image_url' => $button['image_url'],
'type' => $button['type'],
'value' => $button['value'],
], $button['additional']);
})->toArray();
$questionData['actions'] = $buttons;
return $questionData;
} | [
"private",
"function",
"convertQuestion",
"(",
"Question",
"$",
"question",
")",
"{",
"$",
"questionData",
"=",
"$",
"question",
"->",
"toArray",
"(",
")",
";",
"$",
"buttons",
"=",
"Collection",
"::",
"make",
"(",
"$",
"question",
"->",
"getButtons",
"(",... | Convert a Question object into a valid Slack response.
@param \BotMan\BotMan\Messages\Outgoing\Question $question
@return array | [
"Convert",
"a",
"Question",
"object",
"into",
"a",
"valid",
"Slack",
"response",
"."
] | a832671a0bc2a42b083ebaea60ea7a4efee96045 | https://github.com/botman/driver-slack/blob/a832671a0bc2a42b083ebaea60ea7a4efee96045/src/SlackDriver.php#L209-L229 | train |
botman/driver-slack | src/SlackDriver.php | SlackDriver.getBotUserId | public function getBotUserId()
{
$botUserIdRequest = $this->http->post('https://slack.com/api/auth.test', [], [
'token' => $this->config->get('token'),
]);
$botUserIdPayload = new ParameterBag((array) json_decode($botUserIdRequest->getContent(), true));
if ($botUserIdPayload->get('user_id')) {
$this->botUserID = $botUserIdPayload->get('user_id');
$this->getBotId();
}
} | php | public function getBotUserId()
{
$botUserIdRequest = $this->http->post('https://slack.com/api/auth.test', [], [
'token' => $this->config->get('token'),
]);
$botUserIdPayload = new ParameterBag((array) json_decode($botUserIdRequest->getContent(), true));
if ($botUserIdPayload->get('user_id')) {
$this->botUserID = $botUserIdPayload->get('user_id');
$this->getBotId();
}
} | [
"public",
"function",
"getBotUserId",
"(",
")",
"{",
"$",
"botUserIdRequest",
"=",
"$",
"this",
"->",
"http",
"->",
"post",
"(",
"'https://slack.com/api/auth.test'",
",",
"[",
"]",
",",
"[",
"'token'",
"=>",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
... | Get bot userID. | [
"Get",
"bot",
"userID",
"."
] | a832671a0bc2a42b083ebaea60ea7a4efee96045 | https://github.com/botman/driver-slack/blob/a832671a0bc2a42b083ebaea60ea7a4efee96045/src/SlackDriver.php#L437-L448 | train |
botman/driver-slack | src/SlackDriver.php | SlackDriver.getBotId | private function getBotId()
{
$botUserRequest = $this->http->post('https://slack.com/api/users.info', [], [
'user' => $this->botUserID,
'token' => $this->config->get('token'),
]);
$botUserPayload = (array) json_decode($botUserRequest->getContent(), true);
if ($botUserPayload['user']['is_bot']) {
$this->botID = $botUserPayload['user']['profile']['bot_id'];
}
} | php | private function getBotId()
{
$botUserRequest = $this->http->post('https://slack.com/api/users.info', [], [
'user' => $this->botUserID,
'token' => $this->config->get('token'),
]);
$botUserPayload = (array) json_decode($botUserRequest->getContent(), true);
if ($botUserPayload['user']['is_bot']) {
$this->botID = $botUserPayload['user']['profile']['bot_id'];
}
} | [
"private",
"function",
"getBotId",
"(",
")",
"{",
"$",
"botUserRequest",
"=",
"$",
"this",
"->",
"http",
"->",
"post",
"(",
"'https://slack.com/api/users.info'",
",",
"[",
"]",
",",
"[",
"'user'",
"=>",
"$",
"this",
"->",
"botUserID",
",",
"'token'",
"=>",... | Get bot ID. | [
"Get",
"bot",
"ID",
"."
] | a832671a0bc2a42b083ebaea60ea7a4efee96045 | https://github.com/botman/driver-slack/blob/a832671a0bc2a42b083ebaea60ea7a4efee96045/src/SlackDriver.php#L453-L464 | train |
botman/driver-slack | src/SlackDriver.php | SlackDriver.extendConversation | public function extendConversation()
{
Conversation::macro('sendDialog', function (Dialog $dialog, $next, $additionalParameters = []) {
$response = $this->bot->replyDialog($dialog, $additionalParameters);
$validation = function ($answer) use ($dialog, $next, $additionalParameters) {
$errors = $dialog->errors(Collection::make($answer->getValue()));
if (count($errors)) {
$this->bot->touchCurrentConversation();
return Response::create(json_encode(['errors' => $errors]), 200, ['ContentType' => 'application/json'])->send();
} else {
if ($next instanceof \Closure) {
$next = $next->bindTo($this, $this);
}
$next($answer);
}
};
$this->bot->storeConversation($this, $validation, $dialog, $additionalParameters);
return $response;
});
} | php | public function extendConversation()
{
Conversation::macro('sendDialog', function (Dialog $dialog, $next, $additionalParameters = []) {
$response = $this->bot->replyDialog($dialog, $additionalParameters);
$validation = function ($answer) use ($dialog, $next, $additionalParameters) {
$errors = $dialog->errors(Collection::make($answer->getValue()));
if (count($errors)) {
$this->bot->touchCurrentConversation();
return Response::create(json_encode(['errors' => $errors]), 200, ['ContentType' => 'application/json'])->send();
} else {
if ($next instanceof \Closure) {
$next = $next->bindTo($this, $this);
}
$next($answer);
}
};
$this->bot->storeConversation($this, $validation, $dialog, $additionalParameters);
return $response;
});
} | [
"public",
"function",
"extendConversation",
"(",
")",
"{",
"Conversation",
"::",
"macro",
"(",
"'sendDialog'",
",",
"function",
"(",
"Dialog",
"$",
"dialog",
",",
"$",
"next",
",",
"$",
"additionalParameters",
"=",
"[",
"]",
")",
"{",
"$",
"response",
"=",... | Extend BotMan conversation class. | [
"Extend",
"BotMan",
"conversation",
"class",
"."
] | a832671a0bc2a42b083ebaea60ea7a4efee96045 | https://github.com/botman/driver-slack/blob/a832671a0bc2a42b083ebaea60ea7a4efee96045/src/SlackDriver.php#L469-L491 | train |
botman/driver-slack | src/SlackRTMDriver.php | SlackRTMDriver.connected | public function connected()
{
$this->client->getAuthedUser()->then(function ($user) {
$this->botUserID = $user->getId();
$data = $user->getRawUser();
if (isset($data['is_bot']) && $data['is_bot']) {
$this->bot_id = $data['profile']['bot_id'];
}
});
} | php | public function connected()
{
$this->client->getAuthedUser()->then(function ($user) {
$this->botUserID = $user->getId();
$data = $user->getRawUser();
if (isset($data['is_bot']) && $data['is_bot']) {
$this->bot_id = $data['profile']['bot_id'];
}
});
} | [
"public",
"function",
"connected",
"(",
")",
"{",
"$",
"this",
"->",
"client",
"->",
"getAuthedUser",
"(",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"botUserID",
"=",
"$",
"user",
"->",
"getId",
"(",
")",
";... | Connected event. | [
"Connected",
"event",
"."
] | a832671a0bc2a42b083ebaea60ea7a4efee96045 | https://github.com/botman/driver-slack/blob/a832671a0bc2a42b083ebaea60ea7a4efee96045/src/SlackRTMDriver.php#L72-L81 | train |
botman/driver-slack | src/SlackRTMDriver.php | SlackRTMDriver.types | public function types(IncomingMessage $matchingMessage)
{
$channel = null;
$this->getChannelGroupOrDM($matchingMessage)->then(function ($_channel) use (&$channel) {
$channel = $_channel;
});
if (! is_null($channel)) {
$this->client->setAsTyping($channel, false);
}
} | php | public function types(IncomingMessage $matchingMessage)
{
$channel = null;
$this->getChannelGroupOrDM($matchingMessage)->then(function ($_channel) use (&$channel) {
$channel = $_channel;
});
if (! is_null($channel)) {
$this->client->setAsTyping($channel, false);
}
} | [
"public",
"function",
"types",
"(",
"IncomingMessage",
"$",
"matchingMessage",
")",
"{",
"$",
"channel",
"=",
"null",
";",
"$",
"this",
"->",
"getChannelGroupOrDM",
"(",
"$",
"matchingMessage",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"_channel",
")",
... | Send a typing indicator.
@param IncomingMessage $matchingMessage
@return mixed | [
"Send",
"a",
"typing",
"indicator",
"."
] | a832671a0bc2a42b083ebaea60ea7a4efee96045 | https://github.com/botman/driver-slack/blob/a832671a0bc2a42b083ebaea60ea7a4efee96045/src/SlackRTMDriver.php#L328-L338 | train |
jenssegers/date | src/Date.php | Date.parse | public static function parse($time = null, $timezone = null)
{
if ($time instanceof Carbon) {
return new static(
$time->toDateTimeString(),
$timezone ?: $time->getTimezone()
);
}
if (!is_int($time)) {
$time = static::translateTimeString($time);
}
return new static($time, $timezone);
} | php | public static function parse($time = null, $timezone = null)
{
if ($time instanceof Carbon) {
return new static(
$time->toDateTimeString(),
$timezone ?: $time->getTimezone()
);
}
if (!is_int($time)) {
$time = static::translateTimeString($time);
}
return new static($time, $timezone);
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"time",
"=",
"null",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"time",
"instanceof",
"Carbon",
")",
"{",
"return",
"new",
"static",
"(",
"$",
"time",
"->",
"toDateTimeString",
"(",
... | Create a Date instance from a string.
@param string $time
@param string|DateTimeZone $timezone
@return Date | [
"Create",
"a",
"Date",
"instance",
"from",
"a",
"string",
"."
] | 4a7768372b1a0eb4e8db4ca5524b9828b2884310 | https://github.com/jenssegers/date/blob/4a7768372b1a0eb4e8db4ca5524b9828b2884310/src/Date.php#L77-L91 | train |
jenssegers/date | src/Date.php | Date.ago | public function ago($since = null, $syntax = null, $short = false, $parts = 1, $options = null)
{
return $this->diffForHumans($since, $syntax, $short, $parts, $options);
} | php | public function ago($since = null, $syntax = null, $short = false, $parts = 1, $options = null)
{
return $this->diffForHumans($since, $syntax, $short, $parts, $options);
} | [
"public",
"function",
"ago",
"(",
"$",
"since",
"=",
"null",
",",
"$",
"syntax",
"=",
"null",
",",
"$",
"short",
"=",
"false",
",",
"$",
"parts",
"=",
"1",
",",
"$",
"options",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"diffForHumans",
... | Alias for diffForHumans.
@param Date $since
@param bool $syntax Removes time difference modifiers ago, after, etc
@param bool $short (Carbon 2 only) displays short format of time units
@param int $parts (Carbon 2 only) maximum number of parts to display (default value: 1: single unit)
@param int $options (Carbon 2 only) human diff options
@return string | [
"Alias",
"for",
"diffForHumans",
"."
] | 4a7768372b1a0eb4e8db4ca5524b9828b2884310 | https://github.com/jenssegers/date/blob/4a7768372b1a0eb4e8db4ca5524b9828b2884310/src/Date.php#L113-L116 | train |
jenssegers/date | src/Date.php | Date.timespan | public function timespan($time = null, $timezone = null)
{
// Get translator
$lang = $this->getTranslator();
// Create Date instance if needed
if (!$time instanceof static) {
$time = Date::parse($time, $timezone);
}
$units = [
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
// Get DateInterval and cast to array
$interval = (array) $this->diff($time);
// Get weeks
$interval['w'] = (int) ($interval['d'] / 7);
$interval['d'] = $interval['d'] % 7;
// Get ready to build
$str = [];
// Loop all units and build string
foreach ($units as $k => $unit) {
if ($interval[$k]) {
$str[] = $lang->transChoice($unit, $interval[$k], [':count' => $interval[$k]]);
}
}
return implode(', ', $str);
} | php | public function timespan($time = null, $timezone = null)
{
// Get translator
$lang = $this->getTranslator();
// Create Date instance if needed
if (!$time instanceof static) {
$time = Date::parse($time, $timezone);
}
$units = [
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
// Get DateInterval and cast to array
$interval = (array) $this->diff($time);
// Get weeks
$interval['w'] = (int) ($interval['d'] / 7);
$interval['d'] = $interval['d'] % 7;
// Get ready to build
$str = [];
// Loop all units and build string
foreach ($units as $k => $unit) {
if ($interval[$k]) {
$str[] = $lang->transChoice($unit, $interval[$k], [':count' => $interval[$k]]);
}
}
return implode(', ', $str);
} | [
"public",
"function",
"timespan",
"(",
"$",
"time",
"=",
"null",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"// Get translator",
"$",
"lang",
"=",
"$",
"this",
"->",
"getTranslator",
"(",
")",
";",
"// Create Date instance if needed",
"if",
"(",
"!",
"$"... | Gets the timespan between this date and another date.
@param Date|int $time
@param string|DateTimeZone $timezone
@return string | [
"Gets",
"the",
"timespan",
"between",
"this",
"date",
"and",
"another",
"date",
"."
] | 4a7768372b1a0eb4e8db4ca5524b9828b2884310 | https://github.com/jenssegers/date/blob/4a7768372b1a0eb4e8db4ca5524b9828b2884310/src/Date.php#L214-L252 | train |
jenssegers/date | src/Date.php | Date.add | public function add($interval, $value = 1, $overflow = null)
{
if (is_string($interval)) {
// Check for ISO 8601
if (strtoupper(substr($interval, 0, 1)) == 'P') {
$interval = new DateInterval($interval);
} else {
$interval = DateInterval::createFromDateString($interval);
}
}
$method = new ReflectionMethod(parent::class, 'add');
$result = $method->getNumberOfRequiredParameters() === 1
? parent::add($interval)
: parent::add($interval, $value, $overflow);
return $result ? $this : false;
} | php | public function add($interval, $value = 1, $overflow = null)
{
if (is_string($interval)) {
// Check for ISO 8601
if (strtoupper(substr($interval, 0, 1)) == 'P') {
$interval = new DateInterval($interval);
} else {
$interval = DateInterval::createFromDateString($interval);
}
}
$method = new ReflectionMethod(parent::class, 'add');
$result = $method->getNumberOfRequiredParameters() === 1
? parent::add($interval)
: parent::add($interval, $value, $overflow);
return $result ? $this : false;
} | [
"public",
"function",
"add",
"(",
"$",
"interval",
",",
"$",
"value",
"=",
"1",
",",
"$",
"overflow",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"interval",
")",
")",
"{",
"// Check for ISO 8601",
"if",
"(",
"strtoupper",
"(",
"substr",
... | Adds an amount of days, months, years, hours, minutes and seconds to a Date object.
@param DateInterval|string $interval
@param int $value (only effective if using Carbon 2)
@param bool|null $overflow (only effective if using Carbon 2)
@return Date|bool | [
"Adds",
"an",
"amount",
"of",
"days",
"months",
"years",
"hours",
"minutes",
"and",
"seconds",
"to",
"a",
"Date",
"object",
"."
] | 4a7768372b1a0eb4e8db4ca5524b9828b2884310 | https://github.com/jenssegers/date/blob/4a7768372b1a0eb4e8db4ca5524b9828b2884310/src/Date.php#L262-L279 | train |
jenssegers/date | src/Date.php | Date.translateTimeString | public static function translateTimeString($time, $from = null, $to = null, $mode = -1)
{
// Don't run translations for english.
if (static::getLocale() == 'en') {
return $time;
}
// All the language file items we can translate.
$keys = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december',
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday',
];
// Get all the language lines of the current locale.
$all = static::getTranslator()->getCatalogue()->all();
$terms = array_intersect_key($all['messages'], array_flip((array) $keys));
// Split terms with a | sign.
foreach ($terms as $i => $term) {
if (strpos($term, '|') === false) {
continue;
}
// Split term options.
$options = explode('|', $term);
// Remove :count and {count} placeholders.
$options = array_map(function ($option) {
$option = trim(str_replace(':count', '', $option));
$option = preg_replace('/({\d+(,(\d+|Inf))?}|\[\d+(,(\d+|Inf))?\])/', '', $option);
return $option;
}, $options);
$terms[$i] = $options;
}
// Replace the localized words with English words.
$translated = $time;
foreach ($terms as $english => $localized) {
$translated = str_ireplace($localized, $english, $translated);
}
return $translated;
} | php | public static function translateTimeString($time, $from = null, $to = null, $mode = -1)
{
// Don't run translations for english.
if (static::getLocale() == 'en') {
return $time;
}
// All the language file items we can translate.
$keys = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december',
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday',
];
// Get all the language lines of the current locale.
$all = static::getTranslator()->getCatalogue()->all();
$terms = array_intersect_key($all['messages'], array_flip((array) $keys));
// Split terms with a | sign.
foreach ($terms as $i => $term) {
if (strpos($term, '|') === false) {
continue;
}
// Split term options.
$options = explode('|', $term);
// Remove :count and {count} placeholders.
$options = array_map(function ($option) {
$option = trim(str_replace(':count', '', $option));
$option = preg_replace('/({\d+(,(\d+|Inf))?}|\[\d+(,(\d+|Inf))?\])/', '', $option);
return $option;
}, $options);
$terms[$i] = $options;
}
// Replace the localized words with English words.
$translated = $time;
foreach ($terms as $english => $localized) {
$translated = str_ireplace($localized, $english, $translated);
}
return $translated;
} | [
"public",
"static",
"function",
"translateTimeString",
"(",
"$",
"time",
",",
"$",
"from",
"=",
"null",
",",
"$",
"to",
"=",
"null",
",",
"$",
"mode",
"=",
"-",
"1",
")",
"{",
"// Don't run translations for english.",
"if",
"(",
"static",
"::",
"getLocale"... | Translate a locale based time string to its english equivalent.
@param string $time
@return string | [
"Translate",
"a",
"locale",
"based",
"time",
"string",
"to",
"its",
"english",
"equivalent",
"."
] | 4a7768372b1a0eb4e8db4ca5524b9828b2884310 | https://github.com/jenssegers/date/blob/4a7768372b1a0eb4e8db4ca5524b9828b2884310/src/Date.php#L402-L463 | train |
meyfa/php-svg | src/Utilities/Colors/ColorLookup.php | ColorLookup.get | public static function get($keyword)
{
$keywordLower = strtolower($keyword);
if (!isset(self::$values[$keywordLower])) {
return null;
}
return self::$values[$keywordLower];
} | php | public static function get($keyword)
{
$keywordLower = strtolower($keyword);
if (!isset(self::$values[$keywordLower])) {
return null;
}
return self::$values[$keywordLower];
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"keyword",
")",
"{",
"$",
"keywordLower",
"=",
"strtolower",
"(",
"$",
"keyword",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"values",
"[",
"$",
"keywordLower",
"]",
")",
")",
"{",
"r... | Obtains the RGBA component array for the given color keyword. If a string
that is NOT a valid keyword is given, or if the color is unknown, null is
returned.
@param string $keyword The color keyword to look up.
@return int[]|null The RGBA components, or null. | [
"Obtains",
"the",
"RGBA",
"component",
"array",
"for",
"the",
"given",
"color",
"keyword",
".",
"If",
"a",
"string",
"that",
"is",
"NOT",
"a",
"valid",
"keyword",
"is",
"given",
"or",
"if",
"the",
"color",
"is",
"unknown",
"null",
"is",
"returned",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Utilities/Colors/ColorLookup.php#L15-L24 | train |
meyfa/php-svg | src/Utilities/SVGStyleParser.php | SVGStyleParser.parseStyles | public static function parseStyles($string)
{
$styles = array();
if (empty($string)) {
return $styles;
}
$declarations = preg_split('/\s*;\s*/', $string);
foreach ($declarations as $declaration) {
$declaration = trim($declaration);
if ($declaration === '') {
continue;
}
$split = preg_split('/\s*:\s*/', $declaration);
$styles[$split[0]] = $split[1];
}
return $styles;
} | php | public static function parseStyles($string)
{
$styles = array();
if (empty($string)) {
return $styles;
}
$declarations = preg_split('/\s*;\s*/', $string);
foreach ($declarations as $declaration) {
$declaration = trim($declaration);
if ($declaration === '') {
continue;
}
$split = preg_split('/\s*:\s*/', $declaration);
$styles[$split[0]] = $split[1];
}
return $styles;
} | [
"public",
"static",
"function",
"parseStyles",
"(",
"$",
"string",
")",
"{",
"$",
"styles",
"=",
"array",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"string",
")",
")",
"{",
"return",
"$",
"styles",
";",
"}",
"$",
"declarations",
"=",
"preg_split",... | Parses a string of CSS declarations into an associative array.
@param string $string The CSS declarations.
@return string[] An associative array of all declarations. | [
"Parses",
"a",
"string",
"of",
"CSS",
"declarations",
"into",
"an",
"associative",
"array",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Utilities/SVGStyleParser.php#L17-L36 | train |
meyfa/php-svg | src/Utilities/SVGStyleParser.php | SVGStyleParser.parseCss | public static function parseCss($css)
{
$result = array();
preg_match_all('/(?ims)([a-z0-9\s\,\.\:#_\-@^*()\[\]\"\'=]+)\{([^\}]*)\}/', $css, $arr);
foreach ($arr[0] as $i => $x) {
$selectors = explode(',', trim($arr[1][$i]));
if (in_array($selectors[0], array('@font-face', '@keyframes', '@media'))) {
continue;
}
$rules = self::parseStyles(trim($arr[2][$i]));
foreach ($selectors as $selector) {
$result[trim($selector)] = $rules;
}
}
return $result;
} | php | public static function parseCss($css)
{
$result = array();
preg_match_all('/(?ims)([a-z0-9\s\,\.\:#_\-@^*()\[\]\"\'=]+)\{([^\}]*)\}/', $css, $arr);
foreach ($arr[0] as $i => $x) {
$selectors = explode(',', trim($arr[1][$i]));
if (in_array($selectors[0], array('@font-face', '@keyframes', '@media'))) {
continue;
}
$rules = self::parseStyles(trim($arr[2][$i]));
foreach ($selectors as $selector) {
$result[trim($selector)] = $rules;
}
}
return $result;
} | [
"public",
"static",
"function",
"parseCss",
"(",
"$",
"css",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"preg_match_all",
"(",
"'/(?ims)([a-z0-9\\s\\,\\.\\:#_\\-@^*()\\[\\]\\\"\\'=]+)\\{([^\\}]*)\\}/'",
",",
"$",
"css",
",",
"$",
"arr",
")",
";",
"for... | Parses CSS content into an associative 2D array of all selectors and
their respective style declarations.
@SuppressWarnings(PHPMD.UnusedLocalVariable)
@param string $css The CSS style rules.
@return string[][] A 2D associative array with style declarations. | [
"Parses",
"CSS",
"content",
"into",
"an",
"associative",
"2D",
"array",
"of",
"all",
"selectors",
"and",
"their",
"respective",
"style",
"declarations",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Utilities/SVGStyleParser.php#L48-L65 | train |
meyfa/php-svg | src/Nodes/SVGNode.php | SVGNode.setValue | public function setValue($value)
{
if (!isset($value)) {
unset($this->value);
return $this;
}
$this->value = (string) $value;
return $this;
} | php | public function setValue($value)
{
if (!isset($value)) {
unset($this->value);
return $this;
}
$this->value = (string) $value;
return $this;
} | [
"public",
"function",
"setValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"value",
")",
";",
"return",
"$",
"this",
";",
"}",
"$",
"this",
"->",
"value",
"=",
"(",... | Defines the value on this node.
@param string $value The new node's value.
@return $this This node instance, for call chaining. | [
"Defines",
"the",
"value",
"on",
"this",
"node",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNode.php#L80-L88 | train |
meyfa/php-svg | src/Nodes/SVGNode.php | SVGNode.setStyle | public function setStyle($name, $value)
{
$value = (string) $value;
if (strlen($value) === 0) {
unset($this->styles[$name]);
return $this;
}
$this->styles[$name] = $value;
return $this;
} | php | public function setStyle($name, $value)
{
$value = (string) $value;
if (strlen($value) === 0) {
unset($this->styles[$name]);
return $this;
}
$this->styles[$name] = $value;
return $this;
} | [
"public",
"function",
"setStyle",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"(",
"string",
")",
"$",
"value",
";",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
"===",
"0",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"styl... | Defines a style on this node. A value of null or the empty string will
unset the property.
@param string $name The name of the style to set.
@param string|null $value The new style value.
@return $this This node instance, for call chaining. | [
"Defines",
"a",
"style",
"on",
"this",
"node",
".",
"A",
"value",
"of",
"null",
"or",
"the",
"empty",
"string",
"will",
"unset",
"the",
"property",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNode.php#L111-L120 | train |
meyfa/php-svg | src/Nodes/SVGNode.php | SVGNode.getComputedStyle | public function getComputedStyle($name)
{
$style = $this->getStyle($name);
// If no immediate style then get style from container/global style rules
if ($style === null && isset($this->parent)) {
$containerStyles = $this->parent->getContainerStyleForNode($this);
$style = isset($containerStyles[$name]) ? $containerStyles[$name] : null;
}
// If still no style then get parent's style
if (($style === null || $style === 'inherit') && isset($this->parent)) {
return $this->parent->getComputedStyle($name);
}
// 'inherit' is not what we want. Either get the real style, or
// nothing at all.
return $style !== 'inherit' ? $style : null;
} | php | public function getComputedStyle($name)
{
$style = $this->getStyle($name);
// If no immediate style then get style from container/global style rules
if ($style === null && isset($this->parent)) {
$containerStyles = $this->parent->getContainerStyleForNode($this);
$style = isset($containerStyles[$name]) ? $containerStyles[$name] : null;
}
// If still no style then get parent's style
if (($style === null || $style === 'inherit') && isset($this->parent)) {
return $this->parent->getComputedStyle($name);
}
// 'inherit' is not what we want. Either get the real style, or
// nothing at all.
return $style !== 'inherit' ? $style : null;
} | [
"public",
"function",
"getComputedStyle",
"(",
"$",
"name",
")",
"{",
"$",
"style",
"=",
"$",
"this",
"->",
"getStyle",
"(",
"$",
"name",
")",
";",
"// If no immediate style then get style from container/global style rules",
"if",
"(",
"$",
"style",
"===",
"null",... | Obtains the computed style with the given name. The 'computed style' is
the one in effect; taking inheritance and default styles into account.
@param string $name The name of the style to compute.
@return string|null The style value if specified anywhere, else null. | [
"Obtains",
"the",
"computed",
"style",
"with",
"the",
"given",
"name",
".",
"The",
"computed",
"style",
"is",
"the",
"one",
"in",
"effect",
";",
"taking",
"inheritance",
"and",
"default",
"styles",
"into",
"account",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNode.php#L143-L161 | train |
meyfa/php-svg | src/Nodes/SVGNode.php | SVGNode.setAttribute | public function setAttribute($name, $value)
{
if (!isset($value)) {
unset($this->attributes[$name]);
return $this;
}
$this->attributes[$name] = (string) $value;
return $this;
} | php | public function setAttribute($name, $value)
{
if (!isset($value)) {
unset($this->attributes[$name]);
return $this;
}
$this->attributes[$name] = (string) $value;
return $this;
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"name",
"]",
")",
";",
"return",
"$",
"this",... | Defines an attribute on this node. A value of null will unset the
attribute. Note that the empty string is perfectly valid.
@param string $name The name of the attribute to set.
@param string|null $value The new attribute value.
@return $this This node instance, for call chaining. | [
"Defines",
"an",
"attribute",
"on",
"this",
"node",
".",
"A",
"value",
"of",
"null",
"will",
"unset",
"the",
"attribute",
".",
"Note",
"that",
"the",
"empty",
"string",
"is",
"perfectly",
"valid",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNode.php#L185-L193 | train |
meyfa/php-svg | src/Nodes/SVGNode.php | SVGNode.getIdAndClassPattern | public function getIdAndClassPattern()
{
$id = $this->getAttribute('id');
$class = $this->getAttribute('class');
$pattern = '';
if (!empty($id)) {
$pattern = '#'.$id.'|#'.$id;
}
if (!empty($class)) {
if (!empty($pattern)) {
$pattern .= '.'.$class.'|';
}
$pattern .= '.'.$class;
}
return empty($pattern) ? null : '/('.$pattern.')/';
} | php | public function getIdAndClassPattern()
{
$id = $this->getAttribute('id');
$class = $this->getAttribute('class');
$pattern = '';
if (!empty($id)) {
$pattern = '#'.$id.'|#'.$id;
}
if (!empty($class)) {
if (!empty($pattern)) {
$pattern .= '.'.$class.'|';
}
$pattern .= '.'.$class;
}
return empty($pattern) ? null : '/('.$pattern.')/';
} | [
"public",
"function",
"getIdAndClassPattern",
"(",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"'id'",
")",
";",
"$",
"class",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"'class'",
")",
";",
"$",
"pattern",
"=",
"''",
";",
"if... | Constructs a regex pattern to use as the key to retrieve styles for this
node from its container.
@return string|null The generated pattern. | [
"Constructs",
"a",
"regex",
"pattern",
"to",
"use",
"as",
"the",
"key",
"to",
"retrieve",
"styles",
"for",
"this",
"node",
"from",
"its",
"container",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNode.php#L240-L257 | train |
meyfa/php-svg | src/Rasterization/Path/SVGBezierApproximator.php | SVGBezierApproximator.getDistanceSquared | private static function getDistanceSquared($p1, $p2)
{
$dx = $p2[0] - $p1[0];
$dy = $p2[1] - $p1[1];
return $dx * $dx + $dy * $dy;
} | php | private static function getDistanceSquared($p1, $p2)
{
$dx = $p2[0] - $p1[0];
$dy = $p2[1] - $p1[1];
return $dx * $dx + $dy * $dy;
} | [
"private",
"static",
"function",
"getDistanceSquared",
"(",
"$",
"p1",
",",
"$",
"p2",
")",
"{",
"$",
"dx",
"=",
"$",
"p2",
"[",
"0",
"]",
"-",
"$",
"p1",
"[",
"0",
"]",
";",
"$",
"dy",
"=",
"$",
"p2",
"[",
"1",
"]",
"-",
"$",
"p1",
"[",
... | Calculates the squared distance between two points.
The squared distance is defined as d = (x1 - x0)^2 + (y1 - y0)^2.
@param float[] $p1 The first point (0 => x, 1 => y).
@param float[] $p2 The second point (0 => x, 1 => y).
@return float The squared distance between the two points. | [
"Calculates",
"the",
"squared",
"distance",
"between",
"two",
"points",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGBezierApproximator.php#L152-L158 | train |
meyfa/php-svg | src/SVG.php | SVG.toRasterImage | public function toRasterImage($width, $height)
{
$docWidth = $this->document->getWidth();
$docHeight = $this->document->getHeight();
$viewBox = $this->document->getViewBox();
$rasterizer = new SVGRasterizer($docWidth, $docHeight, $viewBox, $width, $height);
$this->document->rasterize($rasterizer);
return $rasterizer->finish();
} | php | public function toRasterImage($width, $height)
{
$docWidth = $this->document->getWidth();
$docHeight = $this->document->getHeight();
$viewBox = $this->document->getViewBox();
$rasterizer = new SVGRasterizer($docWidth, $docHeight, $viewBox, $width, $height);
$this->document->rasterize($rasterizer);
return $rasterizer->finish();
} | [
"public",
"function",
"toRasterImage",
"(",
"$",
"width",
",",
"$",
"height",
")",
"{",
"$",
"docWidth",
"=",
"$",
"this",
"->",
"document",
"->",
"getWidth",
"(",
")",
";",
"$",
"docHeight",
"=",
"$",
"this",
"->",
"document",
"->",
"getHeight",
"(",
... | Converts this image into a rasterized GD resource of the given size.
The resulting image resource supports transparency and represents the
SVG as accurately as possible (with PHP's limited imaging functions).
Note that, since images in SVG have an innate size, the given size only
scales the output canvas and does not influence element positions.
@param int $width The target canvas's width, in pixels.
@param int $height The target canvas's height, in pixels.
@return resource The rasterized image as a GD resource (with alpha). | [
"Converts",
"this",
"image",
"into",
"a",
"rasterized",
"GD",
"resource",
"of",
"the",
"given",
"size",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/SVG.php#L53-L63 | train |
meyfa/php-svg | src/SVG.php | SVG.toXMLString | public function toXMLString($standalone = true)
{
$writer = new SVGWriter($standalone);
$writer->writeNode($this->document);
return $writer->getString();
} | php | public function toXMLString($standalone = true)
{
$writer = new SVGWriter($standalone);
$writer->writeNode($this->document);
return $writer->getString();
} | [
"public",
"function",
"toXMLString",
"(",
"$",
"standalone",
"=",
"true",
")",
"{",
"$",
"writer",
"=",
"new",
"SVGWriter",
"(",
"$",
"standalone",
")",
";",
"$",
"writer",
"->",
"writeNode",
"(",
"$",
"this",
"->",
"document",
")",
";",
"return",
"$",... | Converts this image's document tree into an XML source code string.
Note that an image parsed from an XML string might not have the exact
same XML string generated by this method, since the output is optimized
and formatted according to specific rules.
@param bool $standalone optional, false omits the leading <?xml tag
@return string This image's document tree as an XML string. | [
"Converts",
"this",
"image",
"s",
"document",
"tree",
"into",
"an",
"XML",
"source",
"code",
"string",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/SVG.php#L84-L90 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGRenderer.php | SVGRenderer.render | public function render(SVGRasterizer $rasterizer, array $options, SVGNode $context)
{
$params = $this->prepareRenderParams($rasterizer, $options);
$paintOrder = $this->getPaintOrder($context);
foreach ($paintOrder as $paint) {
if ($paint === 'fill') {
$this->paintFill($rasterizer, $context, $params);
} elseif ($paint === 'stroke') {
$this->paintStroke($rasterizer, $context, $params);
}
}
} | php | public function render(SVGRasterizer $rasterizer, array $options, SVGNode $context)
{
$params = $this->prepareRenderParams($rasterizer, $options);
$paintOrder = $this->getPaintOrder($context);
foreach ($paintOrder as $paint) {
if ($paint === 'fill') {
$this->paintFill($rasterizer, $context, $params);
} elseif ($paint === 'stroke') {
$this->paintStroke($rasterizer, $context, $params);
}
}
} | [
"public",
"function",
"render",
"(",
"SVGRasterizer",
"$",
"rasterizer",
",",
"array",
"$",
"options",
",",
"SVGNode",
"$",
"context",
")",
"{",
"$",
"params",
"=",
"$",
"this",
"->",
"prepareRenderParams",
"(",
"$",
"rasterizer",
",",
"$",
"options",
")",... | Renders the shape to the rasterizer, using the given options and node
context.
The node is required for access to things like the opacity as well as
stroke/fill attributes etc.
The options array is subclass-specific; for example, ellipse renderers
might require the center and the radiuses while polygon renderers might
require an array of points. For details, see the respective subclasses.
Note that as part of the renderer contract, every option that is passed
in must not be offset, scaled or even validated beforehand. Such things
are dealt with by the `SVGRenderer::prepareRenderParams()` method.
@param SVGRasterizer $rasterizer The rasterizer to render to.
@param mixed[] $options Associative array of renderer options.
@param SVGNode $context The SVGNode serving as the context.
@return void | [
"Renders",
"the",
"shape",
"to",
"the",
"rasterizer",
"using",
"the",
"given",
"options",
"and",
"node",
"context",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGRenderer.php#L40-L52 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGRenderer.php | SVGRenderer.prepareColor | private static function prepareColor($color, SVGNode $context)
{
$color = Color::parse($color);
$rgb = ($color[0] << 16) + ($color[1] << 8) + ($color[2]);
$opacity = self::calculateTotalOpacity($context);
$a = 127 - $opacity * intval($color[3] * 127 / 255);
return $rgb | ($a << 24);
} | php | private static function prepareColor($color, SVGNode $context)
{
$color = Color::parse($color);
$rgb = ($color[0] << 16) + ($color[1] << 8) + ($color[2]);
$opacity = self::calculateTotalOpacity($context);
$a = 127 - $opacity * intval($color[3] * 127 / 255);
return $rgb | ($a << 24);
} | [
"private",
"static",
"function",
"prepareColor",
"(",
"$",
"color",
",",
"SVGNode",
"$",
"context",
")",
"{",
"$",
"color",
"=",
"Color",
"::",
"parse",
"(",
"$",
"color",
")",
";",
"$",
"rgb",
"=",
"(",
"$",
"color",
"[",
"0",
"]",
"<<",
"16",
"... | Parses the color string and applies the node's total opacity to it,
then returns it as a GD color int.
@param string $color The CSS color value.
@param SVGNode $context The node serving as the opacity reference.
@return int The prepared color as a GD color integer. | [
"Parses",
"the",
"color",
"string",
"and",
"applies",
"the",
"node",
"s",
"total",
"opacity",
"to",
"it",
"then",
"returns",
"it",
"as",
"a",
"GD",
"color",
"int",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGRenderer.php#L116-L125 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGRenderer.php | SVGRenderer.getNodeOpacity | private static function getNodeOpacity(SVGNode $node)
{
$opacity = $node->getStyle('opacity');
if (is_numeric($opacity)) {
return floatval($opacity);
} elseif ($opacity === 'inherit') {
$parent = $node->getParent();
if (isset($parent)) {
return self::getNodeOpacity($parent);
}
}
return 1;
} | php | private static function getNodeOpacity(SVGNode $node)
{
$opacity = $node->getStyle('opacity');
if (is_numeric($opacity)) {
return floatval($opacity);
} elseif ($opacity === 'inherit') {
$parent = $node->getParent();
if (isset($parent)) {
return self::getNodeOpacity($parent);
}
}
return 1;
} | [
"private",
"static",
"function",
"getNodeOpacity",
"(",
"SVGNode",
"$",
"node",
")",
"{",
"$",
"opacity",
"=",
"$",
"node",
"->",
"getStyle",
"(",
"'opacity'",
")",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"opacity",
")",
")",
"{",
"return",
"floatval",
... | Obtains the node's very own opacity value, as specified in its styles,
taking care of 'inherit' and defaulting to 1.
@param SVGNode $node The node to get the opacity value of.
@return float The node's own opacity value. | [
"Obtains",
"the",
"node",
"s",
"very",
"own",
"opacity",
"value",
"as",
"specified",
"in",
"its",
"styles",
"taking",
"care",
"of",
"inherit",
"and",
"defaulting",
"to",
"1",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGRenderer.php#L135-L149 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGRenderer.php | SVGRenderer.calculateTotalOpacity | private static function calculateTotalOpacity(SVGNode $node)
{
$opacity = self::getNodeOpacity($node);
$parent = $node->getParent();
if (isset($parent)) {
return $opacity * self::calculateTotalOpacity($parent);
}
return $opacity;
} | php | private static function calculateTotalOpacity(SVGNode $node)
{
$opacity = self::getNodeOpacity($node);
$parent = $node->getParent();
if (isset($parent)) {
return $opacity * self::calculateTotalOpacity($parent);
}
return $opacity;
} | [
"private",
"static",
"function",
"calculateTotalOpacity",
"(",
"SVGNode",
"$",
"node",
")",
"{",
"$",
"opacity",
"=",
"self",
"::",
"getNodeOpacity",
"(",
"$",
"node",
")",
";",
"$",
"parent",
"=",
"$",
"node",
"->",
"getParent",
"(",
")",
";",
"if",
"... | Calculates the node's total opacity by multiplying its own with all of
its parents' ones.
@param SVGNode $node The node of which to calculate the opacity.
@return float The node's total opacity. | [
"Calculates",
"the",
"node",
"s",
"total",
"opacity",
"by",
"multiplying",
"its",
"own",
"with",
"all",
"of",
"its",
"parents",
"ones",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGRenderer.php#L159-L169 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGRenderer.php | SVGRenderer.prepareLengthX | protected static function prepareLengthX($len, SVGRasterizer $ras)
{
$doc = $ras->getDocumentWidth();
$scale = $ras->getScaleX();
return Length::convert($len, $doc) * $scale;
} | php | protected static function prepareLengthX($len, SVGRasterizer $ras)
{
$doc = $ras->getDocumentWidth();
$scale = $ras->getScaleX();
return Length::convert($len, $doc) * $scale;
} | [
"protected",
"static",
"function",
"prepareLengthX",
"(",
"$",
"len",
",",
"SVGRasterizer",
"$",
"ras",
")",
"{",
"$",
"doc",
"=",
"$",
"ras",
"->",
"getDocumentWidth",
"(",
")",
";",
"$",
"scale",
"=",
"$",
"ras",
"->",
"getScaleX",
"(",
")",
";",
"... | Parses the length string in relation to the rasterizer's X dimension.
@param string $len The CSS length string.
@param SVGRasterizer $ras The rasterizer for scaling the length.
@return float The parsed and scaled length, in pixels. | [
"Parses",
"the",
"length",
"string",
"in",
"relation",
"to",
"the",
"rasterizer",
"s",
"X",
"dimension",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGRenderer.php#L179-L185 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGRenderer.php | SVGRenderer.prepareLengthY | protected static function prepareLengthY($len, SVGRasterizer $ras)
{
$doc = $ras->getDocumentWidth();
$scale = $ras->getScaleY();
return Length::convert($len, $doc) * $scale;
} | php | protected static function prepareLengthY($len, SVGRasterizer $ras)
{
$doc = $ras->getDocumentWidth();
$scale = $ras->getScaleY();
return Length::convert($len, $doc) * $scale;
} | [
"protected",
"static",
"function",
"prepareLengthY",
"(",
"$",
"len",
",",
"SVGRasterizer",
"$",
"ras",
")",
"{",
"$",
"doc",
"=",
"$",
"ras",
"->",
"getDocumentWidth",
"(",
")",
";",
"$",
"scale",
"=",
"$",
"ras",
"->",
"getScaleY",
"(",
")",
";",
"... | Parses the length string in relation to the rasterizer's Y dimension.
@param string $len The CSS length string.
@param SVGRasterizer $ras The rasterizer for scaling the length.
@return float The parsed and scaled length, in pixels. | [
"Parses",
"the",
"length",
"string",
"in",
"relation",
"to",
"the",
"rasterizer",
"s",
"Y",
"dimension",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGRenderer.php#L195-L201 | train |
meyfa/php-svg | src/Rasterization/SVGRasterizer.php | SVGRasterizer.createImage | private static function createImage($width, $height)
{
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, true);
imagesavealpha($img, true);
imagefill($img, 0, 0, 0x7F000000);
return $img;
} | php | private static function createImage($width, $height)
{
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, true);
imagesavealpha($img, true);
imagefill($img, 0, 0, 0x7F000000);
return $img;
} | [
"private",
"static",
"function",
"createImage",
"(",
"$",
"width",
",",
"$",
"height",
")",
"{",
"$",
"img",
"=",
"imagecreatetruecolor",
"(",
"$",
"width",
",",
"$",
"height",
")",
";",
"imagealphablending",
"(",
"$",
"img",
",",
"true",
")",
";",
"im... | Sets up a new truecolor GD image resource with the given dimensions.
The returned image supports and is filled with transparency.
@param int $width The output image width, in pixels.
@param int $height The output image height, in pixels.
@return resource The created GD image resource. | [
"Sets",
"up",
"a",
"new",
"truecolor",
"GD",
"image",
"resource",
"with",
"the",
"given",
"dimensions",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/SVGRasterizer.php#L78-L88 | train |
meyfa/php-svg | src/Rasterization/SVGRasterizer.php | SVGRasterizer.createDependencies | private static function createDependencies()
{
if (isset(self::$renderers)) {
return;
}
self::$renderers = array(
'rect' => new Renderers\SVGRectRenderer(),
'line' => new Renderers\SVGLineRenderer(),
'ellipse' => new Renderers\SVGEllipseRenderer(),
'polygon' => new Renderers\SVGPolygonRenderer(),
'image' => new Renderers\SVGImageRenderer(),
'text' => new Renderers\SVGTextRenderer(),
);
self::$pathParser = new Path\SVGPathParser();
self::$pathApproximator = new Path\SVGPathApproximator();
} | php | private static function createDependencies()
{
if (isset(self::$renderers)) {
return;
}
self::$renderers = array(
'rect' => new Renderers\SVGRectRenderer(),
'line' => new Renderers\SVGLineRenderer(),
'ellipse' => new Renderers\SVGEllipseRenderer(),
'polygon' => new Renderers\SVGPolygonRenderer(),
'image' => new Renderers\SVGImageRenderer(),
'text' => new Renderers\SVGTextRenderer(),
);
self::$pathParser = new Path\SVGPathParser();
self::$pathApproximator = new Path\SVGPathApproximator();
} | [
"private",
"static",
"function",
"createDependencies",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"renderers",
")",
")",
"{",
"return",
";",
"}",
"self",
"::",
"$",
"renderers",
"=",
"array",
"(",
"'rect'",
"=>",
"new",
"Renderers",
"\\... | Makes sure the singleton static variables are all instantiated.
This includes registering all of the standard renderers, as well as
preparing the path parser and the path approximator.
@return void | [
"Makes",
"sure",
"the",
"singleton",
"static",
"variables",
"are",
"all",
"instantiated",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/SVGRasterizer.php#L98-L115 | train |
meyfa/php-svg | src/Rasterization/SVGRasterizer.php | SVGRasterizer.getRenderer | private static function getRenderer($id)
{
if (!isset(self::$renderers[$id])) {
throw new \InvalidArgumentException("no such renderer: ".$id);
}
return self::$renderers[$id];
} | php | private static function getRenderer($id)
{
if (!isset(self::$renderers[$id])) {
throw new \InvalidArgumentException("no such renderer: ".$id);
}
return self::$renderers[$id];
} | [
"private",
"static",
"function",
"getRenderer",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"renderers",
"[",
"$",
"id",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"no such renderer: \"",
"... | Finds the renderer registered with the given id.
@param string $id The id of a registered renderer instance.
@return Renderers\SVGRenderer The requested renderer.
@throws \InvalidArgumentException If no such renderer exists. | [
"Finds",
"the",
"renderer",
"registered",
"with",
"the",
"given",
"id",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/SVGRasterizer.php#L125-L131 | train |
meyfa/php-svg | src/Rasterization/SVGRasterizer.php | SVGRasterizer.render | public function render($rendererId, array $params, SVGNode $context)
{
$renderer = self::getRenderer($rendererId);
return $renderer->render($this, $params, $context);
} | php | public function render($rendererId, array $params, SVGNode $context)
{
$renderer = self::getRenderer($rendererId);
return $renderer->render($this, $params, $context);
} | [
"public",
"function",
"render",
"(",
"$",
"rendererId",
",",
"array",
"$",
"params",
",",
"SVGNode",
"$",
"context",
")",
"{",
"$",
"renderer",
"=",
"self",
"::",
"getRenderer",
"(",
"$",
"rendererId",
")",
";",
"return",
"$",
"renderer",
"->",
"render",... | Uses the specified renderer to draw an object, as described via the
params attribute, and by utilizing the provided node context.
The node is required for access to things like the opacity as well as
stroke/fill attributes etc.
@param string $rendererId The id of the renderer to use.
@param mixed[] $params An array of options to pass to the renderer.
@param SVGNode $context The SVGNode that serves as drawing context.
@return mixed Whatever the renderer returned (in most cases void).
@throws \InvalidArgumentException If no such renderer exists. | [
"Uses",
"the",
"specified",
"renderer",
"to",
"draw",
"an",
"object",
"as",
"described",
"via",
"the",
"params",
"attribute",
"and",
"by",
"utilizing",
"the",
"provided",
"node",
"context",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/SVGRasterizer.php#L166-L170 | train |
meyfa/php-svg | src/Writing/SVGWriter.php | SVGWriter.writeNode | public function writeNode(SVGNode $node)
{
$this->outString .= '<'.$node->getName();
$this->appendAttributes($node->getSerializableAttributes());
$this->appendStyles($node->getSerializableStyles());
$textContent = htmlspecialchars($node->getValue());
if ($node instanceof SVGNodeContainer) {
$this->outString .= '>';
for ($i = 0, $n = $node->countChildren(); $i < $n; ++$i) {
$this->writeNode($node->getChild($i));
}
$this->outString .= $textContent.'</'.$node->getName().'>';
return;
}
if ($node instanceof SVGStyle) {
$this->outString .= '>';
$this->writeCdata($node->getCss());
$this->outString .= $textContent.'</'.$node->getName().'>';
return;
}
if (!empty($textContent)) {
$this->outString .= '>' . $textContent . '</'.$node->getName().'>';
return;
}
$this->outString .= ' />';
} | php | public function writeNode(SVGNode $node)
{
$this->outString .= '<'.$node->getName();
$this->appendAttributes($node->getSerializableAttributes());
$this->appendStyles($node->getSerializableStyles());
$textContent = htmlspecialchars($node->getValue());
if ($node instanceof SVGNodeContainer) {
$this->outString .= '>';
for ($i = 0, $n = $node->countChildren(); $i < $n; ++$i) {
$this->writeNode($node->getChild($i));
}
$this->outString .= $textContent.'</'.$node->getName().'>';
return;
}
if ($node instanceof SVGStyle) {
$this->outString .= '>';
$this->writeCdata($node->getCss());
$this->outString .= $textContent.'</'.$node->getName().'>';
return;
}
if (!empty($textContent)) {
$this->outString .= '>' . $textContent . '</'.$node->getName().'>';
return;
}
$this->outString .= ' />';
} | [
"public",
"function",
"writeNode",
"(",
"SVGNode",
"$",
"node",
")",
"{",
"$",
"this",
"->",
"outString",
".=",
"'<'",
".",
"$",
"node",
"->",
"getName",
"(",
")",
";",
"$",
"this",
"->",
"appendAttributes",
"(",
"$",
"node",
"->",
"getSerializableAttrib... | Converts the given node into its XML representation and appends that to
this writer's output string.
The generated string contains the attributes defined via
SVGNode::getSerializableAttributes() and the styles defined via
SVGNode::getSerializableStyles().
Container nodes (<g></g>) and self-closing tags (<rect />) are
distinguished correctly.
@param SVGNode $node The node to write.
@return void | [
"Converts",
"the",
"given",
"node",
"into",
"its",
"XML",
"representation",
"and",
"appends",
"that",
"to",
"this",
"writer",
"s",
"output",
"string",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Writing/SVGWriter.php#L47-L78 | train |
meyfa/php-svg | src/Writing/SVGWriter.php | SVGWriter.appendStyles | private function appendStyles(array $styles)
{
if (empty($styles)) {
return;
}
$string = '';
$prependSemicolon = false;
foreach ($styles as $key => $value) {
if ($prependSemicolon) {
$string .= '; ';
}
$prependSemicolon = true;
$string .= $key.': '.$value;
}
$this->appendAttribute('style', $string);
} | php | private function appendStyles(array $styles)
{
if (empty($styles)) {
return;
}
$string = '';
$prependSemicolon = false;
foreach ($styles as $key => $value) {
if ($prependSemicolon) {
$string .= '; ';
}
$prependSemicolon = true;
$string .= $key.': '.$value;
}
$this->appendAttribute('style', $string);
} | [
"private",
"function",
"appendStyles",
"(",
"array",
"$",
"styles",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"styles",
")",
")",
"{",
"return",
";",
"}",
"$",
"string",
"=",
"''",
";",
"$",
"prependSemicolon",
"=",
"false",
";",
"foreach",
"(",
"$",
... | Converts the given styles into a CSS string, then appends a 'style'
attribute with the value set to that string to this writer's output.
@param string[] $styles An associative array of styles for the attribute.
@return void | [
"Converts",
"the",
"given",
"styles",
"into",
"a",
"CSS",
"string",
"then",
"appends",
"a",
"style",
"attribute",
"with",
"the",
"value",
"set",
"to",
"that",
"string",
"to",
"this",
"writer",
"s",
"output",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Writing/SVGWriter.php#L88-L105 | train |
meyfa/php-svg | src/Writing/SVGWriter.php | SVGWriter.appendAttributes | private function appendAttributes(array $attrs)
{
foreach ($attrs as $key => $value) {
$this->appendAttribute($key, $value);
}
} | php | private function appendAttributes(array $attrs)
{
foreach ($attrs as $key => $value) {
$this->appendAttribute($key, $value);
}
} | [
"private",
"function",
"appendAttributes",
"(",
"array",
"$",
"attrs",
")",
"{",
"foreach",
"(",
"$",
"attrs",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"appendAttribute",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
... | Appends all attributes defined in the given associative array to this
writer's output.
@param string[] $attrs An associative array of attribute strings.
@return void | [
"Appends",
"all",
"attributes",
"defined",
"in",
"the",
"given",
"associative",
"array",
"to",
"this",
"writer",
"s",
"output",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Writing/SVGWriter.php#L115-L120 | train |
meyfa/php-svg | src/Writing/SVGWriter.php | SVGWriter.appendAttribute | private function appendAttribute($attrName, $attrValue)
{
$xml1 = defined('ENT_XML1') ? ENT_XML1 : 16;
$attrName = htmlspecialchars($attrName, $xml1 | ENT_COMPAT);
$attrValue = htmlspecialchars($attrValue, $xml1 | ENT_COMPAT);
$this->outString .= ' '.$attrName.'="'.$attrValue.'"';
} | php | private function appendAttribute($attrName, $attrValue)
{
$xml1 = defined('ENT_XML1') ? ENT_XML1 : 16;
$attrName = htmlspecialchars($attrName, $xml1 | ENT_COMPAT);
$attrValue = htmlspecialchars($attrValue, $xml1 | ENT_COMPAT);
$this->outString .= ' '.$attrName.'="'.$attrValue.'"';
} | [
"private",
"function",
"appendAttribute",
"(",
"$",
"attrName",
",",
"$",
"attrValue",
")",
"{",
"$",
"xml1",
"=",
"defined",
"(",
"'ENT_XML1'",
")",
"?",
"ENT_XML1",
":",
"16",
";",
"$",
"attrName",
"=",
"htmlspecialchars",
"(",
"$",
"attrName",
",",
"$... | Appends a single attribute given by key and value to this writer's
output.
@param string $attrName The attribute name.
@param string $attrValue The attribute value.
@return void | [
"Appends",
"a",
"single",
"attribute",
"given",
"by",
"key",
"and",
"value",
"to",
"this",
"writer",
"s",
"output",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Writing/SVGWriter.php#L131-L139 | train |
meyfa/php-svg | src/Nodes/Structures/SVGDocumentFragment.php | SVGDocumentFragment.rasterize | public function rasterize(SVGRasterizer $rasterizer)
{
if ($this->isRoot()) {
parent::rasterize($rasterizer);
return;
}
// create new rasterizer for nested viewport
$subRasterizer = new SVGRasterizer(
$this->getWidth(), // document width
$this->getHeight(), // document height
$this->getViewBox(), // viewBox
Length::convert($this->getWidth() ?: '100%', $rasterizer->getWidth()),
Length::convert($this->getHeight() ?: '100%', $rasterizer->getHeight())
);
// perform rasterization as usual
parent::rasterize($subRasterizer);
$img = $subRasterizer->finish();
// copy nested viewport onto parent viewport
imagecopy(
$rasterizer->getImage(), // destination
$img, // source
0, 0, // dst_x, dst_y
0, 0, // src_x, src_y
$subRasterizer->getWidth(), // src_w
$subRasterizer->getHeight() // src_h
);
imagedestroy($img);
} | php | public function rasterize(SVGRasterizer $rasterizer)
{
if ($this->isRoot()) {
parent::rasterize($rasterizer);
return;
}
// create new rasterizer for nested viewport
$subRasterizer = new SVGRasterizer(
$this->getWidth(), // document width
$this->getHeight(), // document height
$this->getViewBox(), // viewBox
Length::convert($this->getWidth() ?: '100%', $rasterizer->getWidth()),
Length::convert($this->getHeight() ?: '100%', $rasterizer->getHeight())
);
// perform rasterization as usual
parent::rasterize($subRasterizer);
$img = $subRasterizer->finish();
// copy nested viewport onto parent viewport
imagecopy(
$rasterizer->getImage(), // destination
$img, // source
0, 0, // dst_x, dst_y
0, 0, // src_x, src_y
$subRasterizer->getWidth(), // src_w
$subRasterizer->getHeight() // src_h
);
imagedestroy($img);
} | [
"public",
"function",
"rasterize",
"(",
"SVGRasterizer",
"$",
"rasterizer",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isRoot",
"(",
")",
")",
"{",
"parent",
"::",
"rasterize",
"(",
"$",
"rasterizer",
")",
";",
"return",
";",
"}",
"// create new rasterizer f... | Draws this node to the given rasterizer.
@param SVGRasterizer $rasterizer The rasterizer to draw to.
@return void | [
"Draws",
"this",
"node",
"to",
"the",
"given",
"rasterizer",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/Structures/SVGDocumentFragment.php#L110-L140 | train |
meyfa/php-svg | src/Nodes/Structures/SVGDocumentFragment.php | SVGDocumentFragment.getElementById | public function getElementById($id)
{
// start with document
$stack = array($this);
while (!empty($stack)) {
$elem = array_pop($stack);
// check current node
if ($elem->getAttribute('id') === $id) {
return $elem;
}
// add children to stack (tree order traversal)
if ($elem instanceof SVGNodeContainer) {
for ($i = $elem->countChildren() - 1; $i >= 0; --$i) {
array_push($stack, $elem->getChild($i));
}
}
}
return null;
} | php | public function getElementById($id)
{
// start with document
$stack = array($this);
while (!empty($stack)) {
$elem = array_pop($stack);
// check current node
if ($elem->getAttribute('id') === $id) {
return $elem;
}
// add children to stack (tree order traversal)
if ($elem instanceof SVGNodeContainer) {
for ($i = $elem->countChildren() - 1; $i >= 0; --$i) {
array_push($stack, $elem->getChild($i));
}
}
}
return null;
} | [
"public",
"function",
"getElementById",
"(",
"$",
"id",
")",
"{",
"// start with document",
"$",
"stack",
"=",
"array",
"(",
"$",
"this",
")",
";",
"while",
"(",
"!",
"empty",
"(",
"$",
"stack",
")",
")",
"{",
"$",
"elem",
"=",
"array_pop",
"(",
"$",... | Returns the node with the given id, or null if no such node exists in the
document.
@param string $id The id to search for.
@return \SVG\Nodes\SVGNode|null The node with the given id if it exists. | [
"Returns",
"the",
"node",
"with",
"the",
"given",
"id",
"or",
"null",
"if",
"no",
"such",
"node",
"exists",
"in",
"the",
"document",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/Structures/SVGDocumentFragment.php#L192-L212 | train |
meyfa/php-svg | src/Rasterization/Path/SVGPolygonBuilder.php | SVGPolygonBuilder.getLastPoint | public function getLastPoint()
{
if (empty($this->points)) {
return null;
}
return $this->points[count($this->points) - 1];
} | php | public function getLastPoint()
{
if (empty($this->points)) {
return null;
}
return $this->points[count($this->points) - 1];
} | [
"public",
"function",
"getLastPoint",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"points",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"points",
"[",
"count",
"(",
"$",
"this",
"->",
"points",
")",
"-",
... | Finds the very last point in this polygon, or null if none exist.
@return float[]|null The last point, or null. | [
"Finds",
"the",
"very",
"last",
"point",
"in",
"this",
"polygon",
"or",
"null",
"if",
"none",
"exist",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGPolygonBuilder.php#L61-L67 | train |
meyfa/php-svg | src/Rasterization/Path/SVGPolygonBuilder.php | SVGPolygonBuilder.addPoint | public function addPoint($x, $y)
{
$x = isset($x) ? $x : $this->posX;
$y = isset($y) ? $y : $this->posY;
$this->points[] = array($x, $y);
$this->posX = $x;
$this->posY = $y;
} | php | public function addPoint($x, $y)
{
$x = isset($x) ? $x : $this->posX;
$y = isset($y) ? $y : $this->posY;
$this->points[] = array($x, $y);
$this->posX = $x;
$this->posY = $y;
} | [
"public",
"function",
"addPoint",
"(",
"$",
"x",
",",
"$",
"y",
")",
"{",
"$",
"x",
"=",
"isset",
"(",
"$",
"x",
")",
"?",
"$",
"x",
":",
"$",
"this",
"->",
"posX",
";",
"$",
"y",
"=",
"isset",
"(",
"$",
"y",
")",
"?",
"$",
"y",
":",
"$... | Appends a point with ABSOLUTE coordinates to the end of this polygon.
Provide null for a coordinate to use the current position for that
coordinate.
@param float|null $x The point's absolute x coordinate.
@param float|null $y The point's absolute y coordinate.
@return void | [
"Appends",
"a",
"point",
"with",
"ABSOLUTE",
"coordinates",
"to",
"the",
"end",
"of",
"this",
"polygon",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGPolygonBuilder.php#L94-L103 | train |
meyfa/php-svg | src/Rasterization/Path/SVGPolygonBuilder.php | SVGPolygonBuilder.addPointRelative | public function addPointRelative($x, $y)
{
$this->posX += $x ?: 0;
$this->posY += $y ?: 0;
$this->points[] = array($this->posX, $this->posY);
} | php | public function addPointRelative($x, $y)
{
$this->posX += $x ?: 0;
$this->posY += $y ?: 0;
$this->points[] = array($this->posX, $this->posY);
} | [
"public",
"function",
"addPointRelative",
"(",
"$",
"x",
",",
"$",
"y",
")",
"{",
"$",
"this",
"->",
"posX",
"+=",
"$",
"x",
"?",
":",
"0",
";",
"$",
"this",
"->",
"posY",
"+=",
"$",
"y",
"?",
":",
"0",
";",
"$",
"this",
"->",
"points",
"[",
... | Appends a point with RELATIVE coordinates to the end of this polygon.
The coordinates are resolved against the current position.
Providing null for a coordinate is the same as providing a value of 0.
@see SVGPolygonBuilder::getPosition() For more info on relative points.
@param float|null $x The point's relative x coordinate.
@param float|null $y The point's relative y coordinate.
@return void | [
"Appends",
"a",
"point",
"with",
"RELATIVE",
"coordinates",
"to",
"the",
"end",
"of",
"this",
"polygon",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGPolygonBuilder.php#L118-L124 | train |
meyfa/php-svg | src/Rasterization/Path/SVGPolygonBuilder.php | SVGPolygonBuilder.addPoints | public function addPoints(array $points)
{
$this->points = array_merge($this->points, $points);
$endPoint = $this->points[count($this->points) - 1];
$this->posX = $endPoint[0];
$this->posY = $endPoint[1];
} | php | public function addPoints(array $points)
{
$this->points = array_merge($this->points, $points);
$endPoint = $this->points[count($this->points) - 1];
$this->posX = $endPoint[0];
$this->posY = $endPoint[1];
} | [
"public",
"function",
"addPoints",
"(",
"array",
"$",
"points",
")",
"{",
"$",
"this",
"->",
"points",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"points",
",",
"$",
"points",
")",
";",
"$",
"endPoint",
"=",
"$",
"this",
"->",
"points",
"[",
"count"... | Appends multiple points with ABSOLUTE coordinates to this polygon.
@param array[] $points A point array (array of float 2-tuples).
@return void | [
"Appends",
"multiple",
"points",
"with",
"ABSOLUTE",
"coordinates",
"to",
"this",
"polygon",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGPolygonBuilder.php#L133-L140 | train |
meyfa/php-svg | src/Rasterization/Path/SVGArcApproximator.php | SVGArcApproximator.calculatePoint | private static function calculatePoint($center, $rx, $ry, $xa, $angle)
{
$a = $rx * cos($angle);
$b = $ry * sin($angle);
return array(
cos($xa) * $a - sin($xa) * $b + $center[0],
sin($xa) * $a + cos($xa) * $b + $center[1],
);
} | php | private static function calculatePoint($center, $rx, $ry, $xa, $angle)
{
$a = $rx * cos($angle);
$b = $ry * sin($angle);
return array(
cos($xa) * $a - sin($xa) * $b + $center[0],
sin($xa) * $a + cos($xa) * $b + $center[1],
);
} | [
"private",
"static",
"function",
"calculatePoint",
"(",
"$",
"center",
",",
"$",
"rx",
",",
"$",
"ry",
",",
"$",
"xa",
",",
"$",
"angle",
")",
"{",
"$",
"a",
"=",
"$",
"rx",
"*",
"cos",
"(",
"$",
"angle",
")",
";",
"$",
"b",
"=",
"$",
"ry",
... | Calculates a single point on an ellipsis described by its center
parameterization.
@param float[] $center The ellipse's center point (x, y).
@param float $rx The radius along the ellipse's x-axis.
@param float $ry The radius along the ellipse's y-axis.
@param float $xa The x-axis angle / the ellipse's rotation (radians).
@param float $angle The point's position on the ellipse.
@return float[] The calculated point as an (x, y) tuple. | [
"Calculates",
"a",
"single",
"point",
"on",
"an",
"ellipsis",
"described",
"by",
"its",
"center",
"parameterization",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGArcApproximator.php#L79-L88 | train |
meyfa/php-svg | src/Rasterization/Path/SVGArcApproximator.php | SVGArcApproximator.vectorAngle | private static function vectorAngle($ux, $uy, $vx, $vy)
{
$ta = atan2($uy, $ux);
$tb = atan2($vy, $vx);
if ($tb >= $ta) {
return $tb - $ta;
}
return 2 * M_PI - ($ta - $tb);
} | php | private static function vectorAngle($ux, $uy, $vx, $vy)
{
$ta = atan2($uy, $ux);
$tb = atan2($vy, $vx);
if ($tb >= $ta) {
return $tb - $ta;
}
return 2 * M_PI - ($ta - $tb);
} | [
"private",
"static",
"function",
"vectorAngle",
"(",
"$",
"ux",
",",
"$",
"uy",
",",
"$",
"vx",
",",
"$",
"vy",
")",
"{",
"$",
"ta",
"=",
"atan2",
"(",
"$",
"uy",
",",
"$",
"ux",
")",
";",
"$",
"tb",
"=",
"atan2",
"(",
"$",
"vy",
",",
"$",
... | Computes the angle between two given vectors.
@param float $ux First vector's x coordinate.
@param float $uy First vector's y coordinate.
@param float $vx Second vector's x coordinate.
@param float $vy Second vector's y coordinate.
@return float The angle, in radians. | [
"Computes",
"the",
"angle",
"between",
"two",
"given",
"vectors",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGArcApproximator.php#L171-L181 | train |
meyfa/php-svg | src/Utilities/Colors/Color.php | Color.parse | public static function parse($color)
{
$lookupResult = ColorLookup::get($color);
if (isset($lookupResult)) {
return $lookupResult;
}
// pass on to dedicated functions depending on notation
if (preg_match('/^#([0-9A-F]+)$/i', $color, $matches)) {
list($r, $g, $b, $a) = self::parseHexComponents($matches[1]);
} elseif (preg_match('/^rgba?\((.*)\)$/', $color, $matches)) {
list($r, $g, $b, $a) = self::parseRGBAComponents($matches[1]);
} elseif (preg_match('/^hsla?\((.*)\)$/', $color, $matches)) {
list($r, $g, $b, $a) = self::parseHSLAComponents($matches[1]);
}
// any illegal component invalidates all components
if (!isset($r) || !isset($g) || !isset($b) || !isset($a)) {
return array(0, 0, 0, 0);
}
return self::clamp($r, $g, $b, $a);
} | php | public static function parse($color)
{
$lookupResult = ColorLookup::get($color);
if (isset($lookupResult)) {
return $lookupResult;
}
// pass on to dedicated functions depending on notation
if (preg_match('/^#([0-9A-F]+)$/i', $color, $matches)) {
list($r, $g, $b, $a) = self::parseHexComponents($matches[1]);
} elseif (preg_match('/^rgba?\((.*)\)$/', $color, $matches)) {
list($r, $g, $b, $a) = self::parseRGBAComponents($matches[1]);
} elseif (preg_match('/^hsla?\((.*)\)$/', $color, $matches)) {
list($r, $g, $b, $a) = self::parseHSLAComponents($matches[1]);
}
// any illegal component invalidates all components
if (!isset($r) || !isset($g) || !isset($b) || !isset($a)) {
return array(0, 0, 0, 0);
}
return self::clamp($r, $g, $b, $a);
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"color",
")",
"{",
"$",
"lookupResult",
"=",
"ColorLookup",
"::",
"get",
"(",
"$",
"color",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"lookupResult",
")",
")",
"{",
"return",
"$",
"lookupResult",
";",
... | Converts any valid SVG color string into an array of RGBA components.
All of the components are ints 0-255.
@param string $color The color string to convert, as specified in SVG.
@return int[] The color converted to RGBA components. | [
"Converts",
"any",
"valid",
"SVG",
"color",
"string",
"into",
"an",
"array",
"of",
"RGBA",
"components",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Utilities/Colors/Color.php#L18-L40 | train |
meyfa/php-svg | src/Utilities/Colors/Color.php | Color.parseHexComponents | private static function parseHexComponents($str)
{
$len = strlen($str);
$r = $g = $b = $a = null;
if ($len === 6 || $len === 8) {
$r = hexdec($str[0].$str[1]);
$g = hexdec($str[2].$str[3]);
$b = hexdec($str[4].$str[5]);
$a = $len === 8 ? hexdec($str[6].$str[7]) : 255;
} elseif ($len === 3 || $len == 4) {
$r = hexdec($str[0].$str[0]);
$g = hexdec($str[1].$str[1]);
$b = hexdec($str[2].$str[2]);
$a = $len === 4 ? hexdec($str[3].$str[3]) : 255;
}
return array($r, $g, $b, $a);
} | php | private static function parseHexComponents($str)
{
$len = strlen($str);
$r = $g = $b = $a = null;
if ($len === 6 || $len === 8) {
$r = hexdec($str[0].$str[1]);
$g = hexdec($str[2].$str[3]);
$b = hexdec($str[4].$str[5]);
$a = $len === 8 ? hexdec($str[6].$str[7]) : 255;
} elseif ($len === 3 || $len == 4) {
$r = hexdec($str[0].$str[0]);
$g = hexdec($str[1].$str[1]);
$b = hexdec($str[2].$str[2]);
$a = $len === 4 ? hexdec($str[3].$str[3]) : 255;
}
return array($r, $g, $b, $a);
} | [
"private",
"static",
"function",
"parseHexComponents",
"(",
"$",
"str",
")",
"{",
"$",
"len",
"=",
"strlen",
"(",
"$",
"str",
")",
";",
"$",
"r",
"=",
"$",
"g",
"=",
"$",
"b",
"=",
"$",
"a",
"=",
"null",
";",
"if",
"(",
"$",
"len",
"===",
"6"... | Takes a hex string of length 3, 4, 6 or 8 and converts it into an array
of floating-point RGBA components.
For strings of invalid length, all components will be null.
@param string $str The hexadecimal color string to convert.
@return float[] The RGBA components (0 - 255). | [
"Takes",
"a",
"hex",
"string",
"of",
"length",
"3",
"4",
"6",
"or",
"8",
"and",
"converts",
"it",
"into",
"an",
"array",
"of",
"floating",
"-",
"point",
"RGBA",
"components",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Utilities/Colors/Color.php#L72-L91 | train |
meyfa/php-svg | src/Rasterization/Path/SVGPathParser.php | SVGPathParser.parse | public function parse($description)
{
$commands = array();
$matches = array();
$idString = implode('', array_keys(self::$commandLengths));
preg_match_all('/(['.$idString.'])([^'.$idString.']*)/', $description, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$id = $match[1];
$args = $this->splitArguments($match[2]);
$success = $this->parseCommandChain($id, $args, $commands);
if (!$success) {
break;
}
}
return $commands;
} | php | public function parse($description)
{
$commands = array();
$matches = array();
$idString = implode('', array_keys(self::$commandLengths));
preg_match_all('/(['.$idString.'])([^'.$idString.']*)/', $description, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$id = $match[1];
$args = $this->splitArguments($match[2]);
$success = $this->parseCommandChain($id, $args, $commands);
if (!$success) {
break;
}
}
return $commands;
} | [
"public",
"function",
"parse",
"(",
"$",
"description",
")",
"{",
"$",
"commands",
"=",
"array",
"(",
")",
";",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"$",
"idString",
"=",
"implode",
"(",
"''",
",",
"array_keys",
"(",
"self",
"::",
"$",
"com... | Parses a path description into a consecutive array of commands.
The commands themselves are associative arrays with 2 keys:
- string 'id': the command's id, e.g. 'M' or 'c' or ...
- float[] 'args': consecutive array of command arguments
@param string $description The SVG path description to parse.
@return array[] An array of commands (structure: see above). | [
"Parses",
"a",
"path",
"description",
"into",
"a",
"consecutive",
"array",
"of",
"commands",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGPathParser.php#L38-L57 | train |
meyfa/php-svg | src/Rasterization/Path/SVGPathParser.php | SVGPathParser.splitArguments | private function splitArguments($str)
{
$str = trim($str);
$args = array();
if (!empty($str)) {
preg_match_all('/[+-]?(\d*\.\d+|\d+)(e[+-]?\d+)?/', $str, $args);
$args = $args[0];
}
return $args;
} | php | private function splitArguments($str)
{
$str = trim($str);
$args = array();
if (!empty($str)) {
preg_match_all('/[+-]?(\d*\.\d+|\d+)(e[+-]?\d+)?/', $str, $args);
$args = $args[0];
}
return $args;
} | [
"private",
"function",
"splitArguments",
"(",
"$",
"str",
")",
"{",
"$",
"str",
"=",
"trim",
"(",
"$",
"str",
")",
";",
"$",
"args",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"str",
")",
")",
"{",
"preg_match_all",
"(",
"'... | Splits the given arguments string into an array of strings.
@param string $str The string to split.
@return string[] The splitted arguments. | [
"Splits",
"the",
"given",
"arguments",
"string",
"into",
"an",
"array",
"of",
"strings",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGPathParser.php#L66-L77 | train |
meyfa/php-svg | src/Rasterization/Path/SVGPathParser.php | SVGPathParser.parseCommandChain | private function parseCommandChain($id, array $args, array &$commands)
{
if (!isset(self::$commandLengths[$id])) {
// unknown command
return false;
}
$length = self::$commandLengths[$id];
if ($length === 0) {
if (count($args) > 0) {
return false;
}
$commands[] = array(
'id' => $id,
'args' => $args,
);
return true;
}
foreach (array_chunk($args, $length) as $subArgs) {
if (count($subArgs) !== $length) {
return false;
}
$commands[] = array(
'id' => $id,
'args' => array_map('floatval', $subArgs),
);
// If a MoveTo command is followed by additional coordinate pairs,
// those are interpreted as implicit LineTo commands
if ($id === 'M') {
$id = 'L';
} elseif ($id === 'm') {
$id = 'l';
}
}
return true;
} | php | private function parseCommandChain($id, array $args, array &$commands)
{
if (!isset(self::$commandLengths[$id])) {
// unknown command
return false;
}
$length = self::$commandLengths[$id];
if ($length === 0) {
if (count($args) > 0) {
return false;
}
$commands[] = array(
'id' => $id,
'args' => $args,
);
return true;
}
foreach (array_chunk($args, $length) as $subArgs) {
if (count($subArgs) !== $length) {
return false;
}
$commands[] = array(
'id' => $id,
'args' => array_map('floatval', $subArgs),
);
// If a MoveTo command is followed by additional coordinate pairs,
// those are interpreted as implicit LineTo commands
if ($id === 'M') {
$id = 'L';
} elseif ($id === 'm') {
$id = 'l';
}
}
return true;
} | [
"private",
"function",
"parseCommandChain",
"(",
"$",
"id",
",",
"array",
"$",
"args",
",",
"array",
"&",
"$",
"commands",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"commandLengths",
"[",
"$",
"id",
"]",
")",
")",
"{",
"// unknown co... | Groups the given argument chain into sets and constructs a command array
for every set, which is then pushed to the given array reference.
@param string $id The command id that the arguments belong to.
@param string[] $args All of the arguments following the command.
@param array[] $commands The array to add all parsed commands to.
@return bool Whether the command is known AND the arg count is correct. | [
"Groups",
"the",
"given",
"argument",
"chain",
"into",
"sets",
"and",
"constructs",
"a",
"command",
"array",
"for",
"every",
"set",
"which",
"is",
"then",
"pushed",
"to",
"the",
"given",
"array",
"reference",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Path/SVGPathParser.php#L89-L127 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGImageRenderer.php | SVGImageRenderer.loadImage | private function loadImage($href, $w, $h)
{
$content = $this->loadImageContent($href);
if (strpos($content, '<svg') !== false && strrpos($content, '</svg>') !== false) {
$svg = SVG::fromString($content);
return $svg->toRasterImage($w, $h);
}
return imagecreatefromstring($content);
} | php | private function loadImage($href, $w, $h)
{
$content = $this->loadImageContent($href);
if (strpos($content, '<svg') !== false && strrpos($content, '</svg>') !== false) {
$svg = SVG::fromString($content);
return $svg->toRasterImage($w, $h);
}
return imagecreatefromstring($content);
} | [
"private",
"function",
"loadImage",
"(",
"$",
"href",
",",
"$",
"w",
",",
"$",
"h",
")",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"loadImageContent",
"(",
"$",
"href",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"content",
",",
"'<svg'",
")",
"!... | Loads the image locatable via the given HREF and creates a GD resource
for it.
This method supports data URIs, as well as SVG files (they are rasterized
through this very library). As such, the dimensions given are the
dimensions the rasterized SVG would have.
@param string $href The image URI.
@param int $w The width that the rasterized image should have.
@param int $h The height that the rasterized image should have.
@return resource The loaded image. | [
"Loads",
"the",
"image",
"locatable",
"via",
"the",
"given",
"HREF",
"and",
"creates",
"a",
"GD",
"resource",
"for",
"it",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGImageRenderer.php#L83-L93 | train |
meyfa/php-svg | src/Rasterization/Renderers/SVGImageRenderer.php | SVGImageRenderer.loadImageContent | private function loadImageContent($href)
{
$dataPrefix = 'data:';
// check if $href is data URI
if (substr($href, 0, strlen($dataPrefix)) === $dataPrefix) {
$commaPos = strpos($href, ',');
$metadata = substr($href, 0, $commaPos);
$content = substr($href, $commaPos + 1);
if (strpos($metadata, ';base64') !== false) {
$content = base64_decode($content);
}
return $content;
}
return file_get_contents($href);
} | php | private function loadImageContent($href)
{
$dataPrefix = 'data:';
// check if $href is data URI
if (substr($href, 0, strlen($dataPrefix)) === $dataPrefix) {
$commaPos = strpos($href, ',');
$metadata = substr($href, 0, $commaPos);
$content = substr($href, $commaPos + 1);
if (strpos($metadata, ';base64') !== false) {
$content = base64_decode($content);
}
return $content;
}
return file_get_contents($href);
} | [
"private",
"function",
"loadImageContent",
"(",
"$",
"href",
")",
"{",
"$",
"dataPrefix",
"=",
"'data:'",
";",
"// check if $href is data URI",
"if",
"(",
"substr",
"(",
"$",
"href",
",",
"0",
",",
"strlen",
"(",
"$",
"dataPrefix",
")",
")",
"===",
"$",
... | Loads the data of an image locatable via the given HREF into a string.
@param string $href The image URI.
@return string The image content. | [
"Loads",
"the",
"data",
"of",
"an",
"image",
"locatable",
"via",
"the",
"given",
"HREF",
"into",
"a",
"string",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Rasterization/Renderers/SVGImageRenderer.php#L102-L120 | train |
meyfa/php-svg | src/Nodes/Embedded/SVGImage.php | SVGImage.fromFile | public static function fromFile($path, $mimeType, $x = null, $y = null, $width = null, $height = null)
{
$imageContent = file_get_contents($path);
if ($imageContent === false) {
throw new \RuntimeException('Image file "' . $path . '" could not be read.');
}
return self::fromString(
$imageContent,
$mimeType,
$x,
$y,
$width,
$height
);
} | php | public static function fromFile($path, $mimeType, $x = null, $y = null, $width = null, $height = null)
{
$imageContent = file_get_contents($path);
if ($imageContent === false) {
throw new \RuntimeException('Image file "' . $path . '" could not be read.');
}
return self::fromString(
$imageContent,
$mimeType,
$x,
$y,
$width,
$height
);
} | [
"public",
"static",
"function",
"fromFile",
"(",
"$",
"path",
",",
"$",
"mimeType",
",",
"$",
"x",
"=",
"null",
",",
"$",
"y",
"=",
"null",
",",
"$",
"width",
"=",
"null",
",",
"$",
"height",
"=",
"null",
")",
"{",
"$",
"imageContent",
"=",
"file... | Creates a new SVGImage directly from file
@param string $path
@param string $mimeType
@param float|null $x
@param float|null $y
@param float|null $width
@param float|null $height
@return self | [
"Creates",
"a",
"new",
"SVGImage",
"directly",
"from",
"file"
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/Embedded/SVGImage.php#L46-L61 | train |
meyfa/php-svg | src/Nodes/Embedded/SVGImage.php | SVGImage.fromString | public static function fromString(
$imageContent,
$mimeType,
$x = null,
$y = null,
$width = null,
$height = null
) {
return new self(
sprintf(
'data:%s;base64,%s',
$mimeType,
base64_encode($imageContent)
),
$x,
$y,
$width,
$height
);
} | php | public static function fromString(
$imageContent,
$mimeType,
$x = null,
$y = null,
$width = null,
$height = null
) {
return new self(
sprintf(
'data:%s;base64,%s',
$mimeType,
base64_encode($imageContent)
),
$x,
$y,
$width,
$height
);
} | [
"public",
"static",
"function",
"fromString",
"(",
"$",
"imageContent",
",",
"$",
"mimeType",
",",
"$",
"x",
"=",
"null",
",",
"$",
"y",
"=",
"null",
",",
"$",
"width",
"=",
"null",
",",
"$",
"height",
"=",
"null",
")",
"{",
"return",
"new",
"self"... | Creates a new SVGImage directly from a raw binary image string
@param string $imageContent
@param string $mimeType
@param float|null $x
@param float|null $y
@param float|null $width
@param float|null $height
@return self | [
"Creates",
"a",
"new",
"SVGImage",
"directly",
"from",
"a",
"raw",
"binary",
"image",
"string"
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/Embedded/SVGImage.php#L75-L94 | train |
meyfa/php-svg | src/Reading/SVGReader.php | SVGReader.parseXML | public function parseXML(\SimpleXMLElement $xml)
{
$name = $xml->getName();
if ($name !== 'svg') {
return null;
}
$width = isset($xml['width']) ? $xml['width'] : null;
$height = isset($xml['height']) ? $xml['height'] : null;
$namespaces = $xml->getNamespaces(true);
$img = new SVG($width, $height, $namespaces);
$nsKeys = array_keys($namespaces);
$doc = $img->getDocument();
$this->applyAttributes($doc, $xml, $nsKeys);
$this->applyStyles($doc, $xml);
$this->addChildren($doc, $xml, $nsKeys);
return $img;
} | php | public function parseXML(\SimpleXMLElement $xml)
{
$name = $xml->getName();
if ($name !== 'svg') {
return null;
}
$width = isset($xml['width']) ? $xml['width'] : null;
$height = isset($xml['height']) ? $xml['height'] : null;
$namespaces = $xml->getNamespaces(true);
$img = new SVG($width, $height, $namespaces);
$nsKeys = array_keys($namespaces);
$doc = $img->getDocument();
$this->applyAttributes($doc, $xml, $nsKeys);
$this->applyStyles($doc, $xml);
$this->addChildren($doc, $xml, $nsKeys);
return $img;
} | [
"public",
"function",
"parseXML",
"(",
"\\",
"SimpleXMLElement",
"$",
"xml",
")",
"{",
"$",
"name",
"=",
"$",
"xml",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"$",
"name",
"!==",
"'svg'",
")",
"{",
"return",
"null",
";",
"}",
"$",
"width",
"=",
... | Parses the given XML document into an instance of SVG.
Returns null when parsing fails.
@param \SimpleXMLElement $xml The root node of the SVG document to parse.
@return SVG|null An image object representing the parse result. | [
"Parses",
"the",
"given",
"XML",
"document",
"into",
"an",
"instance",
"of",
"SVG",
".",
"Returns",
"null",
"when",
"parsing",
"fails",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Reading/SVGReader.php#L115-L136 | train |
meyfa/php-svg | src/Reading/SVGReader.php | SVGReader.applyAttributes | private function applyAttributes(SVGNode $node, \SimpleXMLElement $xml,
array $namespaces)
{
foreach ($namespaces as $ns) {
foreach ($xml->attributes($ns, true) as $key => $value) {
if ($key === 'style') {
continue;
}
if (in_array($key, self::$styleAttributes)) {
$node->setStyle($key, $value);
continue;
}
if (!empty($ns) && $ns !== 'svg') {
$key = $ns . ':' . $key;
}
$node->setAttribute($key, $value);
}
}
} | php | private function applyAttributes(SVGNode $node, \SimpleXMLElement $xml,
array $namespaces)
{
foreach ($namespaces as $ns) {
foreach ($xml->attributes($ns, true) as $key => $value) {
if ($key === 'style') {
continue;
}
if (in_array($key, self::$styleAttributes)) {
$node->setStyle($key, $value);
continue;
}
if (!empty($ns) && $ns !== 'svg') {
$key = $ns . ':' . $key;
}
$node->setAttribute($key, $value);
}
}
} | [
"private",
"function",
"applyAttributes",
"(",
"SVGNode",
"$",
"node",
",",
"\\",
"SimpleXMLElement",
"$",
"xml",
",",
"array",
"$",
"namespaces",
")",
"{",
"foreach",
"(",
"$",
"namespaces",
"as",
"$",
"ns",
")",
"{",
"foreach",
"(",
"$",
"xml",
"->",
... | Iterates over all XML attributes and applies them to the given node.
Since styles in SVG can also be expressed with attributes, this method
checks the name of each attribute and, if it matches that of a style,
applies it as a style instead. The actual 'style' attribute is ignored.
@see SVGReader::$styleAttributes The attributes considered styles.
@param SVGNode $node The node to apply the attributes to.
@param \SimpleXMLElement $xml The attribute source.
@param string[] $namespaces Array of allowed namespace prefixes.
@return void | [
"Iterates",
"over",
"all",
"XML",
"attributes",
"and",
"applies",
"them",
"to",
"the",
"given",
"node",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Reading/SVGReader.php#L153-L171 | train |
meyfa/php-svg | src/Reading/SVGReader.php | SVGReader.addChildren | private function addChildren(SVGNodeContainer $node, \SimpleXMLElement $xml,
array $namespaces)
{
foreach ($xml->children() as $child) {
$node->addChild($this->parseNode($child, $namespaces));
}
} | php | private function addChildren(SVGNodeContainer $node, \SimpleXMLElement $xml,
array $namespaces)
{
foreach ($xml->children() as $child) {
$node->addChild($this->parseNode($child, $namespaces));
}
} | [
"private",
"function",
"addChildren",
"(",
"SVGNodeContainer",
"$",
"node",
",",
"\\",
"SimpleXMLElement",
"$",
"xml",
",",
"array",
"$",
"namespaces",
")",
"{",
"foreach",
"(",
"$",
"xml",
"->",
"children",
"(",
")",
"as",
"$",
"child",
")",
"{",
"$",
... | Iterates over all children, parses them into library class instances,
and adds them to the given node container.
@param SVGNodeContainer $node The node to add the children to.
@param \SimpleXMLElement $xml The XML node containing the children.
@param string[] $namespaces Array of allowed namespace prefixes.
@return void | [
"Iterates",
"over",
"all",
"children",
"parses",
"them",
"into",
"library",
"class",
"instances",
"and",
"adds",
"them",
"to",
"the",
"given",
"node",
"container",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Reading/SVGReader.php#L207-L213 | train |
meyfa/php-svg | src/Reading/SVGReader.php | SVGReader.parseNode | private function parseNode(\SimpleXMLElement $xml, array $namespaces)
{
$type = $xml->getName();
if (isset(self::$nodeTypes[$type])) {
$call = array(self::$nodeTypes[$type], 'constructFromAttributes');
$node = call_user_func($call, $xml);
} else {
$node = new SVGGenericNodeType($type);
}
$this->applyAttributes($node, $xml, $namespaces);
$this->applyStyles($node, $xml);
$node->setValue($xml);
if ($node instanceof SVGNodeContainer) {
$this->addChildren($node, $xml, $namespaces);
}
return $node;
} | php | private function parseNode(\SimpleXMLElement $xml, array $namespaces)
{
$type = $xml->getName();
if (isset(self::$nodeTypes[$type])) {
$call = array(self::$nodeTypes[$type], 'constructFromAttributes');
$node = call_user_func($call, $xml);
} else {
$node = new SVGGenericNodeType($type);
}
$this->applyAttributes($node, $xml, $namespaces);
$this->applyStyles($node, $xml);
$node->setValue($xml);
if ($node instanceof SVGNodeContainer) {
$this->addChildren($node, $xml, $namespaces);
}
return $node;
} | [
"private",
"function",
"parseNode",
"(",
"\\",
"SimpleXMLElement",
"$",
"xml",
",",
"array",
"$",
"namespaces",
")",
"{",
"$",
"type",
"=",
"$",
"xml",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"nodeTypes",
"[",
"$",... | Parses the given XML element into an instance of a SVGNode subclass.
Unknown node types use a generic implementation.
@param \SimpleXMLElement $xml The XML element to parse.
@param string[] $namespaces Array of allowed namespace prefixes.
@return SVGNode The parsed node.
@SuppressWarnings(PHPMD.ElseExpression) | [
"Parses",
"the",
"given",
"XML",
"element",
"into",
"an",
"instance",
"of",
"a",
"SVGNode",
"subclass",
".",
"Unknown",
"node",
"types",
"use",
"a",
"generic",
"implementation",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Reading/SVGReader.php#L226-L246 | train |
meyfa/php-svg | src/Nodes/SVGNodeContainer.php | SVGNodeContainer.addChild | public function addChild(SVGNode $node, $index = null)
{
if ($node === $this || $node->parent === $this) {
return $this;
}
if (isset($node->parent)) {
$node->parent->removeChild($node);
}
$index = ($index !== null) ? $index : count($this->children);
// insert and set new parent
array_splice($this->children, $index, 0, array($node));
$node->parent = $this;
if ($node instanceof SVGStyle) {
// if node is SVGStyle then add rules to container's style
$this->addContainerStyle($node);
}
return $this;
} | php | public function addChild(SVGNode $node, $index = null)
{
if ($node === $this || $node->parent === $this) {
return $this;
}
if (isset($node->parent)) {
$node->parent->removeChild($node);
}
$index = ($index !== null) ? $index : count($this->children);
// insert and set new parent
array_splice($this->children, $index, 0, array($node));
$node->parent = $this;
if ($node instanceof SVGStyle) {
// if node is SVGStyle then add rules to container's style
$this->addContainerStyle($node);
}
return $this;
} | [
"public",
"function",
"addChild",
"(",
"SVGNode",
"$",
"node",
",",
"$",
"index",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"node",
"===",
"$",
"this",
"||",
"$",
"node",
"->",
"parent",
"===",
"$",
"this",
")",
"{",
"return",
"$",
"this",
";",
"}",... | Inserts an SVGNode instance at the given index, or, if no index is given,
at the end of the child list.
Does nothing if the node already exists in this container.
@param SVGNode $node The node to add to this container's children.
@param int $index The position to insert at (optional).
@return $this This node instance, for call chaining. | [
"Inserts",
"an",
"SVGNode",
"instance",
"at",
"the",
"given",
"index",
"or",
"if",
"no",
"index",
"is",
"given",
"at",
"the",
"end",
"of",
"the",
"child",
"list",
".",
"Does",
"nothing",
"if",
"the",
"node",
"already",
"exists",
"in",
"this",
"container"... | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNodeContainer.php#L40-L62 | train |
meyfa/php-svg | src/Nodes/SVGNodeContainer.php | SVGNodeContainer.removeChild | public function removeChild($child)
{
$index = $this->resolveChildIndex($child);
if ($index === false) {
return $this;
}
$node = $this->children[$index];
$node->parent = null;
array_splice($this->children, $index, 1);
return $this;
} | php | public function removeChild($child)
{
$index = $this->resolveChildIndex($child);
if ($index === false) {
return $this;
}
$node = $this->children[$index];
$node->parent = null;
array_splice($this->children, $index, 1);
return $this;
} | [
"public",
"function",
"removeChild",
"(",
"$",
"child",
")",
"{",
"$",
"index",
"=",
"$",
"this",
"->",
"resolveChildIndex",
"(",
"$",
"child",
")",
";",
"if",
"(",
"$",
"index",
"===",
"false",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"node... | Removes a child node, given either as its instance or as the index it's
located at, from this container.
@param SVGNode|int $child The node (or respective index) to remove.
@return $this This node instance, for call chaining. | [
"Removes",
"a",
"child",
"node",
"given",
"either",
"as",
"its",
"instance",
"or",
"as",
"the",
"index",
"it",
"s",
"located",
"at",
"from",
"this",
"container",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNodeContainer.php#L72-L85 | train |
meyfa/php-svg | src/Nodes/SVGNodeContainer.php | SVGNodeContainer.setChild | public function setChild($child, SVGNode $node)
{
$index = $this->resolveChildIndex($child);
if ($index === false) {
return $this;
}
$this->removeChild($index);
$this->addChild($node, $index);
return $this;
} | php | public function setChild($child, SVGNode $node)
{
$index = $this->resolveChildIndex($child);
if ($index === false) {
return $this;
}
$this->removeChild($index);
$this->addChild($node, $index);
return $this;
} | [
"public",
"function",
"setChild",
"(",
"$",
"child",
",",
"SVGNode",
"$",
"node",
")",
"{",
"$",
"index",
"=",
"$",
"this",
"->",
"resolveChildIndex",
"(",
"$",
"child",
")",
";",
"if",
"(",
"$",
"index",
"===",
"false",
")",
"{",
"return",
"$",
"t... | Replaces a child node with another node.
@param SVGNode|int $child The node (or respective index) to replace.
@param SVGNode $node The replacement node.
@return $this This node instance, for call chaining. | [
"Replaces",
"a",
"child",
"node",
"with",
"another",
"node",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNodeContainer.php#L95-L106 | train |
meyfa/php-svg | src/Nodes/SVGNodeContainer.php | SVGNodeContainer.resolveChildIndex | private function resolveChildIndex($nodeOrIndex)
{
if (is_int($nodeOrIndex)) {
return $nodeOrIndex;
} elseif ($nodeOrIndex instanceof SVGNode) {
return array_search($nodeOrIndex, $this->children, true);
}
return false;
} | php | private function resolveChildIndex($nodeOrIndex)
{
if (is_int($nodeOrIndex)) {
return $nodeOrIndex;
} elseif ($nodeOrIndex instanceof SVGNode) {
return array_search($nodeOrIndex, $this->children, true);
}
return false;
} | [
"private",
"function",
"resolveChildIndex",
"(",
"$",
"nodeOrIndex",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"nodeOrIndex",
")",
")",
"{",
"return",
"$",
"nodeOrIndex",
";",
"}",
"elseif",
"(",
"$",
"nodeOrIndex",
"instanceof",
"SVGNode",
")",
"{",
"retur... | Resolves a child node to its index. If an index is given, it is returned
without modification.
@param SVGNode|int $nodeOrIndex The node (or respective index).
@return int|false The index, or false if argument invalid or not a child. | [
"Resolves",
"a",
"child",
"node",
"to",
"its",
"index",
".",
"If",
"an",
"index",
"is",
"given",
"it",
"is",
"returned",
"without",
"modification",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNodeContainer.php#L116-L125 | train |
meyfa/php-svg | src/Nodes/SVGNodeContainer.php | SVGNodeContainer.addContainerStyle | public function addContainerStyle(SVGStyle $styleNode)
{
$newStyles = SVGStyleParser::parseCss($styleNode->getCss());
$this->containerStyles = array_merge($this->containerStyles, $newStyles);
return $this;
} | php | public function addContainerStyle(SVGStyle $styleNode)
{
$newStyles = SVGStyleParser::parseCss($styleNode->getCss());
$this->containerStyles = array_merge($this->containerStyles, $newStyles);
return $this;
} | [
"public",
"function",
"addContainerStyle",
"(",
"SVGStyle",
"$",
"styleNode",
")",
"{",
"$",
"newStyles",
"=",
"SVGStyleParser",
"::",
"parseCss",
"(",
"$",
"styleNode",
"->",
"getCss",
"(",
")",
")",
";",
"$",
"this",
"->",
"containerStyles",
"=",
"array_me... | Adds the SVGStyle element rules to container's styles.
@param SVGStyle $styleNode The style node to add rules from.
@return $this This node instance, for call chaining. | [
"Adds",
"the",
"SVGStyle",
"element",
"rules",
"to",
"container",
"s",
"styles",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNodeContainer.php#L150-L156 | train |
meyfa/php-svg | src/Nodes/SVGNodeContainer.php | SVGNodeContainer.getContainerStyleByPattern | public function getContainerStyleByPattern($pattern)
{
if ($pattern === null) {
return array();
}
$nodeStyles = array();
if (!empty($this->parent)) {
$nodeStyles = $this->parent->getContainerStyleByPattern($pattern);
}
$keys = $this->pregGrepStyle($pattern);
foreach ($keys as $key) {
$nodeStyles = array_merge($nodeStyles, $this->containerStyles[$key]);
}
return $nodeStyles;
} | php | public function getContainerStyleByPattern($pattern)
{
if ($pattern === null) {
return array();
}
$nodeStyles = array();
if (!empty($this->parent)) {
$nodeStyles = $this->parent->getContainerStyleByPattern($pattern);
}
$keys = $this->pregGrepStyle($pattern);
foreach ($keys as $key) {
$nodeStyles = array_merge($nodeStyles, $this->containerStyles[$key]);
}
return $nodeStyles;
} | [
"public",
"function",
"getContainerStyleByPattern",
"(",
"$",
"pattern",
")",
"{",
"if",
"(",
"$",
"pattern",
"===",
"null",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"nodeStyles",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"("... | Returns style rules for the given node id + class pattern.
@param string $pattern The node's pattern.
@return string[] The style rules to be applied. | [
"Returns",
"style",
"rules",
"for",
"the",
"given",
"node",
"id",
"+",
"class",
"pattern",
"."
] | 1cb26a2f2207c736ff07e3297e5c0921bacaa1ee | https://github.com/meyfa/php-svg/blob/1cb26a2f2207c736ff07e3297e5c0921bacaa1ee/src/Nodes/SVGNodeContainer.php#L194-L211 | train |
rainlab/builder-plugin | classes/ControlLibrary.php | ControlLibrary.listControls | public function listControls($returnGrouped = true)
{
if ($this->groupedControls !== null) {
return $returnGrouped ? $this->groupedControls : $this->controls;
}
$this->groupedControls = [
$this->resolveControlGroupName(self::GROUP_STANDARD) => [],
$this->resolveControlGroupName(self::GROUP_WIDGETS) => []
];
Event::fire('pages.builder.registerControls', [$this]);
foreach ($this->controls as $controlType=>$controlInfo) {
$controlGroup = $this->resolveControlGroupName($controlInfo['group']);
if (!array_key_exists($controlGroup, $this->groupedControls)) {
$this->groupedControls[$controlGroup] = [];
}
$this->groupedControls[$controlGroup][$controlType] = $controlInfo;
}
return $returnGrouped ? $this->groupedControls : $this->controls;
} | php | public function listControls($returnGrouped = true)
{
if ($this->groupedControls !== null) {
return $returnGrouped ? $this->groupedControls : $this->controls;
}
$this->groupedControls = [
$this->resolveControlGroupName(self::GROUP_STANDARD) => [],
$this->resolveControlGroupName(self::GROUP_WIDGETS) => []
];
Event::fire('pages.builder.registerControls', [$this]);
foreach ($this->controls as $controlType=>$controlInfo) {
$controlGroup = $this->resolveControlGroupName($controlInfo['group']);
if (!array_key_exists($controlGroup, $this->groupedControls)) {
$this->groupedControls[$controlGroup] = [];
}
$this->groupedControls[$controlGroup][$controlType] = $controlInfo;
}
return $returnGrouped ? $this->groupedControls : $this->controls;
} | [
"public",
"function",
"listControls",
"(",
"$",
"returnGrouped",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"groupedControls",
"!==",
"null",
")",
"{",
"return",
"$",
"returnGrouped",
"?",
"$",
"this",
"->",
"groupedControls",
":",
"$",
"this",
... | Returns a list of all known form controls grouped by control groups.
@param boolean $returnGrouped Indicates whether controls should be grouped in the result.
@return array | [
"Returns",
"a",
"list",
"of",
"all",
"known",
"form",
"controls",
"grouped",
"by",
"control",
"groups",
"."
] | e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf | https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ControlLibrary.php#L29-L53 | train |
rainlab/builder-plugin | classes/ControlLibrary.php | ControlLibrary.getControlInfo | public function getControlInfo($code)
{
$controls = $this->listControls(false);
if (array_key_exists($code, $controls)) {
return $controls[$code];
}
return [
'properties' => [],
'designTimeProvider' => self::DEFAULT_DESIGN_TIME_PROVIDER,
'name' => $code,
'description' => null,
'unknownControl' => true
];
} | php | public function getControlInfo($code)
{
$controls = $this->listControls(false);
if (array_key_exists($code, $controls)) {
return $controls[$code];
}
return [
'properties' => [],
'designTimeProvider' => self::DEFAULT_DESIGN_TIME_PROVIDER,
'name' => $code,
'description' => null,
'unknownControl' => true
];
} | [
"public",
"function",
"getControlInfo",
"(",
"$",
"code",
")",
"{",
"$",
"controls",
"=",
"$",
"this",
"->",
"listControls",
"(",
"false",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"code",
",",
"$",
"controls",
")",
")",
"{",
"return",
"$",
... | Returns information about a control by its code.
@param string $code Specifies the control code.
@return array Returns an associative array or null if the control is not registered. | [
"Returns",
"information",
"about",
"a",
"control",
"by",
"its",
"code",
"."
] | e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf | https://github.com/rainlab/builder-plugin/blob/e50640a30cc3d80d0b18bcb97dfeeef25d59dbaf/classes/ControlLibrary.php#L60-L75 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.