repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
phptal/PHPTAL
classes/PHPTAL/Dom/Element.php
PHPTAL_Dom_Element.setAttributeNS
public function setAttributeNS($namespace_uri, $qname, $value) { $localname = preg_replace('/^[^:]*:/', '', $qname); if (!($n = $this->getAttributeNodeNS($namespace_uri, $localname))) { $this->attribute_nodes[] = $n = new PHPTAL_Dom_Attr($qname, $namespace_uri, null, 'UTF-8'); // FIXME: find encoding } $n->setValue($value); }
php
public function setAttributeNS($namespace_uri, $qname, $value) { $localname = preg_replace('/^[^:]*:/', '', $qname); if (!($n = $this->getAttributeNodeNS($namespace_uri, $localname))) { $this->attribute_nodes[] = $n = new PHPTAL_Dom_Attr($qname, $namespace_uri, null, 'UTF-8'); // FIXME: find encoding } $n->setValue($value); }
[ "public", "function", "setAttributeNS", "(", "$", "namespace_uri", ",", "$", "qname", ",", "$", "value", ")", "{", "$", "localname", "=", "preg_replace", "(", "'/^[^:]*:/'", ",", "''", ",", "$", "qname", ")", ";", "if", "(", "!", "(", "$", "n", "=", ...
Set attribute value. Creates new attribute if it doesn't exist yet. @param string $namespace_uri full namespace URI. "" for default namespace @param string $qname prefixed qualified name (e.g. "atom:feed") or local name (e.g. "p") @param string $value unescaped value @return void
[ "Set", "attribute", "value", ".", "Creates", "new", "attribute", "if", "it", "doesn", "t", "exist", "yet", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Element.php#L280-L287
phptal/PHPTAL
classes/PHPTAL/Dom/Element.php
PHPTAL_Dom_Element.hasRealContent
public function hasRealContent() { if (count($this->contentAttributes) > 0) return true; foreach ($this->childNodes as $node) { if (!$node instanceof PHPTAL_Dom_Text || $node->getValueEscaped() !== '') return true; } return false; }
php
public function hasRealContent() { if (count($this->contentAttributes) > 0) return true; foreach ($this->childNodes as $node) { if (!$node instanceof PHPTAL_Dom_Text || $node->getValueEscaped() !== '') return true; } return false; }
[ "public", "function", "hasRealContent", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "contentAttributes", ")", ">", "0", ")", "return", "true", ";", "foreach", "(", "$", "this", "->", "childNodes", "as", "$", "node", ")", "{", "if", "("...
Returns true if this element or one of its PHPTAL attributes has some content to print (an empty text node child does not count). @return bool
[ "Returns", "true", "if", "this", "element", "or", "one", "of", "its", "PHPTAL", "attributes", "has", "some", "content", "to", "print", "(", "an", "empty", "text", "node", "child", "does", "not", "count", ")", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Element.php#L295-L303
phptal/PHPTAL
classes/PHPTAL/Dom/Element.php
PHPTAL_Dom_Element.generateSurroundHead
public function generateSurroundHead(PHPTAL_Php_CodeWriter $codewriter) { foreach ($this->surroundAttributes as $att) { $att->before($codewriter); } }
php
public function generateSurroundHead(PHPTAL_Php_CodeWriter $codewriter) { foreach ($this->surroundAttributes as $att) { $att->before($codewriter); } }
[ "public", "function", "generateSurroundHead", "(", "PHPTAL_Php_CodeWriter", "$", "codewriter", ")", "{", "foreach", "(", "$", "this", "->", "surroundAttributes", "as", "$", "att", ")", "{", "$", "att", "->", "before", "(", "$", "codewriter", ")", ";", "}", ...
~~~~~ Generation methods may be called by some PHPTAL attributes ~~~~~
[ "~~~~~", "Generation", "methods", "may", "be", "called", "by", "some", "PHPTAL", "attributes", "~~~~~" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Element.php#L316-L321
phptal/PHPTAL
classes/PHPTAL/Dom/Element.php
PHPTAL_Dom_Element.generateAttributes
private function generateAttributes(PHPTAL_Php_CodeWriter $codewriter) { $html5mode = ($codewriter->getOutputMode() === PHPTAL::HTML5); foreach ($this->getAttributeNodes() as $attr) { // xmlns:foo is not allowed in text/html if ($html5mode && $attr->isNamespaceDeclaration()) { continue; } switch ($attr->getReplacedState()) { case PHPTAL_Dom_Attr::NOT_REPLACED: $codewriter->pushHTML(' '.$attr->getQualifiedName()); if ($codewriter->getOutputMode() !== PHPTAL::HTML5 || !PHPTAL_Dom_Defs::getInstance()->isBooleanAttribute($attr->getQualifiedName())) { $html = $codewriter->interpolateHTML($attr->getValueEscaped()); $codewriter->pushHTML('='.$codewriter->quoteAttributeValue($html)); } break; case PHPTAL_Dom_Attr::HIDDEN: break; case PHPTAL_Dom_Attr::FULLY_REPLACED: $codewriter->pushHTML($attr->getValueEscaped()); break; case PHPTAL_Dom_Attr::VALUE_REPLACED: $codewriter->pushHTML(' '.$attr->getQualifiedName().'="'); $codewriter->pushHTML($attr->getValueEscaped()); $codewriter->pushHTML('"'); break; } } }
php
private function generateAttributes(PHPTAL_Php_CodeWriter $codewriter) { $html5mode = ($codewriter->getOutputMode() === PHPTAL::HTML5); foreach ($this->getAttributeNodes() as $attr) { // xmlns:foo is not allowed in text/html if ($html5mode && $attr->isNamespaceDeclaration()) { continue; } switch ($attr->getReplacedState()) { case PHPTAL_Dom_Attr::NOT_REPLACED: $codewriter->pushHTML(' '.$attr->getQualifiedName()); if ($codewriter->getOutputMode() !== PHPTAL::HTML5 || !PHPTAL_Dom_Defs::getInstance()->isBooleanAttribute($attr->getQualifiedName())) { $html = $codewriter->interpolateHTML($attr->getValueEscaped()); $codewriter->pushHTML('='.$codewriter->quoteAttributeValue($html)); } break; case PHPTAL_Dom_Attr::HIDDEN: break; case PHPTAL_Dom_Attr::FULLY_REPLACED: $codewriter->pushHTML($attr->getValueEscaped()); break; case PHPTAL_Dom_Attr::VALUE_REPLACED: $codewriter->pushHTML(' '.$attr->getQualifiedName().'="'); $codewriter->pushHTML($attr->getValueEscaped()); $codewriter->pushHTML('"'); break; } } }
[ "private", "function", "generateAttributes", "(", "PHPTAL_Php_CodeWriter", "$", "codewriter", ")", "{", "$", "html5mode", "=", "(", "$", "codewriter", "->", "getOutputMode", "(", ")", "===", "PHPTAL", "::", "HTML5", ")", ";", "foreach", "(", "$", "this", "->...
~~~~~ Private members ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[ "~~~~~", "Private", "members", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Element.php#L397-L432
phptal/PHPTAL
classes/PHPTAL/Php/Attribute/METAL/FillSlot.php
PHPTAL_Php_Attribute_METAL_FillSlot.estimateNumberOfBytesOutput
private function estimateNumberOfBytesOutput(PHPTAL_Dom_Element $element, $is_nested_in_repeat) { // macros don't output anything on their own if ($element->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'define-macro')) { return 0; } $estimated_bytes = 2*(3+strlen($element->getQualifiedName())); foreach ($element->getAttributeNodes() as $attr) { $estimated_bytes += 4+strlen($attr->getQualifiedName()); if ($attr->getReplacedState() === PHPTAL_Dom_Attr::NOT_REPLACED) { $estimated_bytes += strlen($attr->getValueEscaped()); // this is shoddy for replaced attributes } } $has_repeat_attr = $element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'repeat'); if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'content') || $element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'replace')) { // assume that output in loops is shorter (e.g. table rows) than outside (main content) $estimated_bytes += ($has_repeat_attr || $is_nested_in_repeat) ? 500 : 2000; } else { foreach ($element->childNodes as $node) { if ($node instanceof PHPTAL_Dom_Element) { $estimated_bytes += $this->estimateNumberOfBytesOutput($node, $has_repeat_attr || $is_nested_in_repeat); } else { $estimated_bytes += strlen($node->getValueEscaped()); } } } if ($element->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'use-macro')) { $estimated_bytes += ($has_repeat_attr || $is_nested_in_repeat) ? 500 : 2000; } if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'condition')) { $estimated_bytes /= 2; // naively assuming 50% chance, that works well with if/else pattern } if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'repeat')) { // assume people don't write big nested loops $estimated_bytes *= $is_nested_in_repeat ? 5 : 10; } return $estimated_bytes; }
php
private function estimateNumberOfBytesOutput(PHPTAL_Dom_Element $element, $is_nested_in_repeat) { // macros don't output anything on their own if ($element->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'define-macro')) { return 0; } $estimated_bytes = 2*(3+strlen($element->getQualifiedName())); foreach ($element->getAttributeNodes() as $attr) { $estimated_bytes += 4+strlen($attr->getQualifiedName()); if ($attr->getReplacedState() === PHPTAL_Dom_Attr::NOT_REPLACED) { $estimated_bytes += strlen($attr->getValueEscaped()); // this is shoddy for replaced attributes } } $has_repeat_attr = $element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'repeat'); if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'content') || $element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'replace')) { // assume that output in loops is shorter (e.g. table rows) than outside (main content) $estimated_bytes += ($has_repeat_attr || $is_nested_in_repeat) ? 500 : 2000; } else { foreach ($element->childNodes as $node) { if ($node instanceof PHPTAL_Dom_Element) { $estimated_bytes += $this->estimateNumberOfBytesOutput($node, $has_repeat_attr || $is_nested_in_repeat); } else { $estimated_bytes += strlen($node->getValueEscaped()); } } } if ($element->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'use-macro')) { $estimated_bytes += ($has_repeat_attr || $is_nested_in_repeat) ? 500 : 2000; } if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'condition')) { $estimated_bytes /= 2; // naively assuming 50% chance, that works well with if/else pattern } if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'repeat')) { // assume people don't write big nested loops $estimated_bytes *= $is_nested_in_repeat ? 5 : 10; } return $estimated_bytes; }
[ "private", "function", "estimateNumberOfBytesOutput", "(", "PHPTAL_Dom_Element", "$", "element", ",", "$", "is_nested_in_repeat", ")", "{", "// macros don't output anything on their own", "if", "(", "$", "element", "->", "hasAttributeNS", "(", "'http://xml.zope.org/namespaces...
@param bool $is_nested_in_repeat true if any parent element has tal:repeat @return rough guess
[ "@param", "bool", "$is_nested_in_repeat", "true", "if", "any", "parent", "element", "has", "tal", ":", "repeat" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/Attribute/METAL/FillSlot.php#L101-L147
phptal/PHPTAL
classes/PHPTAL/Php/Attribute.php
PHPTAL_Php_Attribute.extractEchoType
protected function extractEchoType($expression) { $echoType = self::ECHO_TEXT; $expression = trim($expression); if (preg_match('/^(text|structure)\s+(.*?)$/ism', $expression, $m)) { list(, $echoType, $expression) = $m; } $this->_echoType = strtolower($echoType); return trim($expression); }
php
protected function extractEchoType($expression) { $echoType = self::ECHO_TEXT; $expression = trim($expression); if (preg_match('/^(text|structure)\s+(.*?)$/ism', $expression, $m)) { list(, $echoType, $expression) = $m; } $this->_echoType = strtolower($echoType); return trim($expression); }
[ "protected", "function", "extractEchoType", "(", "$", "expression", ")", "{", "$", "echoType", "=", "self", "::", "ECHO_TEXT", ";", "$", "expression", "=", "trim", "(", "$", "expression", ")", ";", "if", "(", "preg_match", "(", "'/^(text|structure)\\s+(.*?)$/i...
Remove structure|text keyword from expression and stores it for later doEcho() usage. $expression = 'stucture my/path'; $expression = $this->extractEchoType($expression); ... $this->doEcho($code);
[ "Remove", "structure|text", "keyword", "from", "expression", "and", "stores", "it", "for", "later", "doEcho", "()", "usage", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/Attribute.php#L66-L75
phptal/PHPTAL
classes/PHPTAL/TemplateException.php
PHPTAL_TemplateException.hintSrcPosition
public function hintSrcPosition($srcFile, $srcLine) { if ($srcFile && $srcLine) { if (!$this->is_src_accurate) { $this->srcFile = $srcFile; $this->srcLine = $srcLine; $this->is_src_accurate = true; } else if ($this->srcLine <= 1 && $this->srcFile === $srcFile) { $this->srcLine = $srcLine; } } if ($this->is_src_accurate) { $this->file = $this->srcFile; $this->line = (int)$this->srcLine; } }
php
public function hintSrcPosition($srcFile, $srcLine) { if ($srcFile && $srcLine) { if (!$this->is_src_accurate) { $this->srcFile = $srcFile; $this->srcLine = $srcLine; $this->is_src_accurate = true; } else if ($this->srcLine <= 1 && $this->srcFile === $srcFile) { $this->srcLine = $srcLine; } } if ($this->is_src_accurate) { $this->file = $this->srcFile; $this->line = (int)$this->srcLine; } }
[ "public", "function", "hintSrcPosition", "(", "$", "srcFile", ",", "$", "srcLine", ")", "{", "if", "(", "$", "srcFile", "&&", "$", "srcLine", ")", "{", "if", "(", "!", "$", "this", "->", "is_src_accurate", ")", "{", "$", "this", "->", "srcFile", "=",...
Set new TAL source file/line if it isn't known already
[ "Set", "new", "TAL", "source", "file", "/", "line", "if", "it", "isn", "t", "known", "already" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/TemplateException.php#L62-L78
phptal/PHPTAL
classes/PHPTAL/TemplateException.php
PHPTAL_TemplateException.setTemplateSource
private function setTemplateSource() { // not accurate, but better than null $this->srcFile = $this->file; $this->srcLine = $this->line; list($file,$line) = $this->findFileAndLine(); if (NULL === $file) { return false; } // this is not accurate yet, hopefully will be overwritten later $this->srcFile = $file; $this->srcLine = $line; $lines = @file($file); if (!$lines) { return false; } $found_line=false; $found_file=false; // scan lines backwards looking for "from line" comments $end = min(count($lines), $line)-1; for($i=$end; $i >= 0; $i--) { if (preg_match('/tag "[^"]*" from line (\d+)/', $lines[$i], $m)) { $this->srcLine = intval($m[1]); $found_line=true; break; } } foreach(preg_grep('/Generated by PHPTAL from/',$lines) as $line) { if (preg_match('/Generated by PHPTAL from (.*) \(/', $line, $m)) { $this->srcFile = $m[1]; $found_file=true; break; } } return $found_line && $found_file; }
php
private function setTemplateSource() { // not accurate, but better than null $this->srcFile = $this->file; $this->srcLine = $this->line; list($file,$line) = $this->findFileAndLine(); if (NULL === $file) { return false; } // this is not accurate yet, hopefully will be overwritten later $this->srcFile = $file; $this->srcLine = $line; $lines = @file($file); if (!$lines) { return false; } $found_line=false; $found_file=false; // scan lines backwards looking for "from line" comments $end = min(count($lines), $line)-1; for($i=$end; $i >= 0; $i--) { if (preg_match('/tag "[^"]*" from line (\d+)/', $lines[$i], $m)) { $this->srcLine = intval($m[1]); $found_line=true; break; } } foreach(preg_grep('/Generated by PHPTAL from/',$lines) as $line) { if (preg_match('/Generated by PHPTAL from (.*) \(/', $line, $m)) { $this->srcFile = $m[1]; $found_file=true; break; } } return $found_line && $found_file; }
[ "private", "function", "setTemplateSource", "(", ")", "{", "// not accurate, but better than null", "$", "this", "->", "srcFile", "=", "$", "this", "->", "file", ";", "$", "this", "->", "srcLine", "=", "$", "this", "->", "line", ";", "list", "(", "$", "fil...
sets srcLine and srcFile to template path and source line by checking error backtrace and scanning PHP code file @return bool true if found accurate data
[ "sets", "srcLine", "and", "srcFile", "to", "template", "path", "and", "source", "line", "by", "checking", "error", "backtrace", "and", "scanning", "PHP", "code", "file" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/TemplateException.php#L122-L165
phptal/PHPTAL
classes/PHPTAL/Php/CodeWriter.php
PHPTAL_Php_CodeWriter.doDoctype
public function doDoctype($called_from_macro = false) { if ($this->_doctype) { $code = '$ctx->setDocType('.$this->str($this->_doctype).','.($called_from_macro?'true':'false').')'; $this->pushCode($code); } }
php
public function doDoctype($called_from_macro = false) { if ($this->_doctype) { $code = '$ctx->setDocType('.$this->str($this->_doctype).','.($called_from_macro?'true':'false').')'; $this->pushCode($code); } }
[ "public", "function", "doDoctype", "(", "$", "called_from_macro", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_doctype", ")", "{", "$", "code", "=", "'$ctx->setDocType('", ".", "$", "this", "->", "str", "(", "$", "this", "->", "_doctype", ")...
Generate code for setting DOCTYPE @param bool $called_from_macro for error checking: unbuffered output doesn't support that
[ "Generate", "code", "for", "setting", "DOCTYPE" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/CodeWriter.php#L207-L213
phptal/PHPTAL
classes/PHPTAL/Php/CodeWriter.php
PHPTAL_Php_CodeWriter.doXmlDeclaration
public function doXmlDeclaration($called_from_macro = false) { if ($this->_xmldeclaration && $this->getOutputMode() !== PHPTAL::HTML5) { $code = '$ctx->setXmlDeclaration('.$this->str($this->_xmldeclaration).','.($called_from_macro?'true':'false').')'; $this->pushCode($code); } }
php
public function doXmlDeclaration($called_from_macro = false) { if ($this->_xmldeclaration && $this->getOutputMode() !== PHPTAL::HTML5) { $code = '$ctx->setXmlDeclaration('.$this->str($this->_xmldeclaration).','.($called_from_macro?'true':'false').')'; $this->pushCode($code); } }
[ "public", "function", "doXmlDeclaration", "(", "$", "called_from_macro", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_xmldeclaration", "&&", "$", "this", "->", "getOutputMode", "(", ")", "!==", "PHPTAL", "::", "HTML5", ")", "{", "$", "code", "...
Generate XML declaration @param bool $called_from_macro for error checking: unbuffered output doesn't support that
[ "Generate", "XML", "declaration" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/CodeWriter.php#L220-L226
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setTemplate
public function setTemplate($path) { $this->_prepared = false; $this->_functionName = null; $this->_codeFile = null; $this->_path = $path; $this->_source = null; $this->_context->_docType = null; $this->_context->_xmlDeclaration = null; return $this; }
php
public function setTemplate($path) { $this->_prepared = false; $this->_functionName = null; $this->_codeFile = null; $this->_path = $path; $this->_source = null; $this->_context->_docType = null; $this->_context->_xmlDeclaration = null; return $this; }
[ "public", "function", "setTemplate", "(", "$", "path", ")", "{", "$", "this", "->", "_prepared", "=", "false", ";", "$", "this", "->", "_functionName", "=", "null", ";", "$", "this", "->", "_codeFile", "=", "null", ";", "$", "this", "->", "_path", "=...
Set template from file path. @param string $path filesystem path, or any path that will be accepted by source resolver @return $this
[ "Set", "template", "from", "file", "path", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L229-L239
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setSource
public function setSource($src, $path = null) { $this->_prepared = false; $this->_functionName = null; $this->_codeFile = null; $this->_source = new PHPTAL_StringSource($src, $path); $this->_path = $this->_source->getRealPath(); $this->_context->_docType = null; $this->_context->_xmlDeclaration = null; return $this; }
php
public function setSource($src, $path = null) { $this->_prepared = false; $this->_functionName = null; $this->_codeFile = null; $this->_source = new PHPTAL_StringSource($src, $path); $this->_path = $this->_source->getRealPath(); $this->_context->_docType = null; $this->_context->_xmlDeclaration = null; return $this; }
[ "public", "function", "setSource", "(", "$", "src", ",", "$", "path", "=", "null", ")", "{", "$", "this", "->", "_prepared", "=", "false", ";", "$", "this", "->", "_functionName", "=", "null", ";", "$", "this", "->", "_codeFile", "=", "null", ";", ...
Set template from source. Should be used only with temporary template sources. Use setTemplate() or addSourceResolver() whenever possible. @param string $src The phptal template source. @param string $path Fake and 'unique' template path. @return $this
[ "Set", "template", "from", "source", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L252-L262
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setTemplateRepository
public function setTemplateRepository($rep) { if (is_array($rep)) { $this->_repositories = $rep; } else { $this->_repositories[] = $rep; } return $this; }
php
public function setTemplateRepository($rep) { if (is_array($rep)) { $this->_repositories = $rep; } else { $this->_repositories[] = $rep; } return $this; }
[ "public", "function", "setTemplateRepository", "(", "$", "rep", ")", "{", "if", "(", "is_array", "(", "$", "rep", ")", ")", "{", "$", "this", "->", "_repositories", "=", "$", "rep", ";", "}", "else", "{", "$", "this", "->", "_repositories", "[", "]",...
Specify where to look for templates. @param mixed $rep string or Array of repositories @return $this
[ "Specify", "where", "to", "look", "for", "templates", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L271-L279
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.stripComments
public function stripComments($bool) { $this->resetPrepared(); if ($bool) { $this->prefilters['_phptal_strip_comments_'] = new PHPTAL_PreFilter_StripComments(); } else { unset($this->prefilters['_phptal_strip_comments_']); } return $this; }
php
public function stripComments($bool) { $this->resetPrepared(); if ($bool) { $this->prefilters['_phptal_strip_comments_'] = new PHPTAL_PreFilter_StripComments(); } else { unset($this->prefilters['_phptal_strip_comments_']); } return $this; }
[ "public", "function", "stripComments", "(", "$", "bool", ")", "{", "$", "this", "->", "resetPrepared", "(", ")", ";", "if", "(", "$", "bool", ")", "{", "$", "this", "->", "prefilters", "[", "'_phptal_strip_comments_'", "]", "=", "new", "PHPTAL_PreFilter_St...
Ignore XML/XHTML comments on parsing. Comments starting with <!--! are always stripped. @param bool $bool if true all comments are stripped during parse @return $this
[ "Ignore", "XML", "/", "XHTML", "comments", "on", "parsing", ".", "Comments", "starting", "with", "<!", "--", "!", "are", "always", "stripped", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L323-L333
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setOutputMode
public function setOutputMode($mode) { $this->resetPrepared(); if ($mode != PHPTAL::XHTML && $mode != PHPTAL::XML && $mode != PHPTAL::HTML5) { throw new PHPTAL_ConfigurationException('Unsupported output mode '.$mode); } $this->_outputMode = $mode; return $this; }
php
public function setOutputMode($mode) { $this->resetPrepared(); if ($mode != PHPTAL::XHTML && $mode != PHPTAL::XML && $mode != PHPTAL::HTML5) { throw new PHPTAL_ConfigurationException('Unsupported output mode '.$mode); } $this->_outputMode = $mode; return $this; }
[ "public", "function", "setOutputMode", "(", "$", "mode", ")", "{", "$", "this", "->", "resetPrepared", "(", ")", ";", "if", "(", "$", "mode", "!=", "PHPTAL", "::", "XHTML", "&&", "$", "mode", "!=", "PHPTAL", "::", "XML", "&&", "$", "mode", "!=", "P...
Set output mode XHTML output mode will force elements like <link/>, <meta/> and <img/>, etc. to be empty and threats attributes like selected, checked to be boolean attributes. XML output mode outputs XML without such modifications and is neccessary to generate RSS feeds properly. @param int $mode (PHPTAL::XML, PHPTAL::XHTML or PHPTAL::HTML5). @return $this
[ "Set", "output", "mode", "XHTML", "output", "mode", "will", "force", "elements", "like", "<link", "/", ">", "<meta", "/", ">", "and", "<img", "/", ">", "etc", ".", "to", "be", "empty", "and", "threats", "attributes", "like", "selected", "checked", "to", ...
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L348-L357
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setEncoding
public function setEncoding($enc) { $enc = strtoupper($enc); if ($enc != $this->_encoding) { $this->_encoding = $enc; if ($this->_translator) $this->_translator->setEncoding($enc); $this->resetPrepared(); } return $this; }
php
public function setEncoding($enc) { $enc = strtoupper($enc); if ($enc != $this->_encoding) { $this->_encoding = $enc; if ($this->_translator) $this->_translator->setEncoding($enc); $this->resetPrepared(); } return $this; }
[ "public", "function", "setEncoding", "(", "$", "enc", ")", "{", "$", "enc", "=", "strtoupper", "(", "$", "enc", ")", ";", "if", "(", "$", "enc", "!=", "$", "this", "->", "_encoding", ")", "{", "$", "this", "->", "_encoding", "=", "$", "enc", ";",...
Set input and ouput encoding. Encoding is case-insensitive. @param string $enc example: 'UTF-8' @return $this
[ "Set", "input", "and", "ouput", "encoding", ".", "Encoding", "is", "case", "-", "insensitive", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L377-L387
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setPhpCodeDestination
public function setPhpCodeDestination($path) { $this->_phpCodeDestination = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $this->resetPrepared(); return $this; }
php
public function setPhpCodeDestination($path) { $this->_phpCodeDestination = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $this->resetPrepared(); return $this; }
[ "public", "function", "setPhpCodeDestination", "(", "$", "path", ")", "{", "$", "this", "->", "_phpCodeDestination", "=", "rtrim", "(", "$", "path", ",", "DIRECTORY_SEPARATOR", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "this", "->", "resetPrepared", "(", ")",...
Set the storage location for intermediate PHP files. The path cannot contain characters that would be interpreted by glob() (e.g. *[]?) @param string $path Intermediate file path. @return $this
[ "Set", "the", "storage", "location", "for", "intermediate", "PHP", "files", ".", "The", "path", "cannot", "contain", "characters", "that", "would", "be", "interpreted", "by", "glob", "()", "(", "e", ".", "g", ".", "*", "[]", "?", ")" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L409-L414
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setTranslator
public function setTranslator(PHPTAL_TranslationService $t) { $this->_translator = $t; $t->setEncoding($this->getEncoding()); return $this; }
php
public function setTranslator(PHPTAL_TranslationService $t) { $this->_translator = $t; $t->setEncoding($this->getEncoding()); return $this; }
[ "public", "function", "setTranslator", "(", "PHPTAL_TranslationService", "$", "t", ")", "{", "$", "this", "->", "_translator", "=", "$", "t", ";", "$", "t", "->", "setEncoding", "(", "$", "this", "->", "getEncoding", "(", ")", ")", ";", "return", "$", ...
Set I18N translator. This sets encoding used by the translator, so be sure to use encoding-dependent features of the translator (e.g. addDomain) _after_ calling setTranslator. @param PHPTAL_TranslationService $t instance @return $this
[ "Set", "I18N", "translator", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L482-L487
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.addPreFilter
final public function addPreFilter($filter) { $this->resetPrepared(); if (!$filter instanceof PHPTAL_PreFilter) { throw new PHPTAL_ConfigurationException("addPreFilter expects PHPTAL_PreFilter object"); } $this->prefilters[] = $filter; return $this; }
php
final public function addPreFilter($filter) { $this->resetPrepared(); if (!$filter instanceof PHPTAL_PreFilter) { throw new PHPTAL_ConfigurationException("addPreFilter expects PHPTAL_PreFilter object"); } $this->prefilters[] = $filter; return $this; }
[ "final", "public", "function", "addPreFilter", "(", "$", "filter", ")", "{", "$", "this", "->", "resetPrepared", "(", ")", ";", "if", "(", "!", "$", "filter", "instanceof", "PHPTAL_PreFilter", ")", "{", "throw", "new", "PHPTAL_ConfigurationException", "(", "...
Add new prefilter to filter chain. Prefilters are called only once template is compiled. PreFilters must inherit PHPTAL_PreFilter class. (in future this method will allow string with filter name instead of object) @param mixed $filter PHPTAL_PreFilter object or name of prefilter to add @return PHPTAL
[ "Add", "new", "prefilter", "to", "filter", "chain", ".", "Prefilters", "are", "called", "only", "once", "template", "is", "compiled", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L515-L525
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.getPreFiltersCacheId
private function getPreFiltersCacheId() { $cacheid = ''; foreach($this->getPreFilters() as $key => $prefilter) { if ($prefilter instanceof PHPTAL_PreFilter) { $cacheid .= $key.$prefilter->getCacheId(); } elseif ($prefilter instanceof PHPTAL_Filter) { $cacheid .= $key.get_class($prefilter); } else { $cacheid .= $key.$prefilter; } } return $cacheid; }
php
private function getPreFiltersCacheId() { $cacheid = ''; foreach($this->getPreFilters() as $key => $prefilter) { if ($prefilter instanceof PHPTAL_PreFilter) { $cacheid .= $key.$prefilter->getCacheId(); } elseif ($prefilter instanceof PHPTAL_Filter) { $cacheid .= $key.get_class($prefilter); } else { $cacheid .= $key.$prefilter; } } return $cacheid; }
[ "private", "function", "getPreFiltersCacheId", "(", ")", "{", "$", "cacheid", "=", "''", ";", "foreach", "(", "$", "this", "->", "getPreFilters", "(", ")", "as", "$", "key", "=>", "$", "prefilter", ")", "{", "if", "(", "$", "prefilter", "instanceof", "...
Returns string that is unique for every different configuration of prefilters. Result of prefilters may be cached until this string changes. You can override this function. @return string
[ "Returns", "string", "that", "is", "unique", "for", "every", "different", "configuration", "of", "prefilters", ".", "Result", "of", "prefilters", "may", "be", "cached", "until", "this", "string", "changes", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L548-L561
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.getPreFilterInstances
private function getPreFilterInstances() { $prefilters = $this->getPreFilters(); foreach($prefilters as $prefilter) { if ($prefilter instanceof PHPTAL_PreFilter) { $prefilter->setPHPTAL($this); } } return $prefilters; }
php
private function getPreFilterInstances() { $prefilters = $this->getPreFilters(); foreach($prefilters as $prefilter) { if ($prefilter instanceof PHPTAL_PreFilter) { $prefilter->setPHPTAL($this); } } return $prefilters; }
[ "private", "function", "getPreFilterInstances", "(", ")", "{", "$", "prefilters", "=", "$", "this", "->", "getPreFilters", "(", ")", ";", "foreach", "(", "$", "prefilters", "as", "$", "prefilter", ")", "{", "if", "(", "$", "prefilter", "instanceof", "PHPTA...
Instantiate prefilters @return array of PHPTAL_[Pre]Filter objects
[ "Instantiate", "prefilters" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L568-L578
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.getTrigger
public function getTrigger($id) { if (array_key_exists($id, $this->_triggers)) { return $this->_triggers[$id]; } return null; }
php
public function getTrigger($id) { if (array_key_exists($id, $this->_triggers)) { return $this->_triggers[$id]; } return null; }
[ "public", "function", "getTrigger", "(", "$", "id", ")", "{", "if", "(", "array_key_exists", "(", "$", "id", ",", "$", "this", "->", "_triggers", ")", ")", "{", "return", "$", "this", "->", "_triggers", "[", "$", "id", "]", ";", "}", "return", "nul...
Returns trigger for specified phptal:id. @param string $id phptal:id @return PHPTAL_Trigger or NULL
[ "Returns", "trigger", "for", "specified", "phptal", ":", "id", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L611-L617
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.execute
public function execute() { try { if (!$this->_prepared) { // includes generated template PHP code $this->prepare(); } $this->_context->echoDeclarations(false); $templateFunction = $this->getFunctionName(); try { ob_start(); $templateFunction($this, $this->_context); $res = ob_get_clean(); } catch (Exception $e) { ob_end_clean(); throw $e; } // unshift doctype if ($this->_context->_docType) { $res = $this->_context->_docType . $res; } // unshift xml declaration if ($this->_context->_xmlDeclaration) { $res = $this->_context->_xmlDeclaration . "\n" . $res; } if ($this->_postfilter) { return $this->_postfilter->filter($res); } } catch (Exception $e) { PHPTAL_ExceptionHandler::handleException($e, $this->getEncoding()); } return $res; }
php
public function execute() { try { if (!$this->_prepared) { // includes generated template PHP code $this->prepare(); } $this->_context->echoDeclarations(false); $templateFunction = $this->getFunctionName(); try { ob_start(); $templateFunction($this, $this->_context); $res = ob_get_clean(); } catch (Exception $e) { ob_end_clean(); throw $e; } // unshift doctype if ($this->_context->_docType) { $res = $this->_context->_docType . $res; } // unshift xml declaration if ($this->_context->_xmlDeclaration) { $res = $this->_context->_xmlDeclaration . "\n" . $res; } if ($this->_postfilter) { return $this->_postfilter->filter($res); } } catch (Exception $e) { PHPTAL_ExceptionHandler::handleException($e, $this->getEncoding()); } return $res; }
[ "public", "function", "execute", "(", ")", "{", "try", "{", "if", "(", "!", "$", "this", "->", "_prepared", ")", "{", "// includes generated template PHP code", "$", "this", "->", "prepare", "(", ")", ";", "}", "$", "this", "->", "_context", "->", "echoD...
Execute the template code and return generated markup. @return string
[ "Execute", "the", "template", "code", "and", "return", "generated", "markup", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L653-L696
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.echoExecute
public function echoExecute() { try { if (!$this->_prepared) { // includes generated template PHP code $this->prepare(); } if ($this->_postfilter) { throw new PHPTAL_ConfigurationException("echoExecute() does not support postfilters"); } $this->_context->echoDeclarations(true); $templateFunction = $this->getFunctionName(); $templateFunction($this, $this->_context); } catch (Exception $e) { PHPTAL_ExceptionHandler::handleException($e, $this->getEncoding()); } }
php
public function echoExecute() { try { if (!$this->_prepared) { // includes generated template PHP code $this->prepare(); } if ($this->_postfilter) { throw new PHPTAL_ConfigurationException("echoExecute() does not support postfilters"); } $this->_context->echoDeclarations(true); $templateFunction = $this->getFunctionName(); $templateFunction($this, $this->_context); } catch (Exception $e) { PHPTAL_ExceptionHandler::handleException($e, $this->getEncoding()); } }
[ "public", "function", "echoExecute", "(", ")", "{", "try", "{", "if", "(", "!", "$", "this", "->", "_prepared", ")", "{", "// includes generated template PHP code", "$", "this", "->", "prepare", "(", ")", ";", "}", "if", "(", "$", "this", "->", "_postfil...
Execute and echo template without buffering of the output. This function does not allow postfilters nor DOCTYPE/XML declaration. @return NULL
[ "Execute", "and", "echo", "template", "without", "buffering", "of", "the", "output", ".", "This", "function", "does", "not", "allow", "postfilters", "nor", "DOCTYPE", "/", "XML", "declaration", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L704-L725
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL._executeMacroOfTemplate
final public function _executeMacroOfTemplate($path, PHPTAL $local_tpl) { // extract macro source file from macro name, if macro path does not // contain filename, then the macro is assumed to be local if (preg_match('/^(.*?)\/([a-z0-9_-]*)$/i', $path, $m)) { list(, $file, $macroName) = $m; if (isset($this->externalMacroTemplatesCache[$file])) { $tpl = $this->externalMacroTemplatesCache[$file]; } else { $tpl = clone $this; array_unshift($tpl->_repositories, dirname($this->_source->getRealPath())); $tpl->setTemplate($file); $tpl->prepare(); // keep it small (typically only 1 or 2 external files are used) if (count($this->externalMacroTemplatesCache) > 10) { $this->externalMacroTemplatesCache = array(); } $this->externalMacroTemplatesCache[$file] = $tpl; } $fun = $tpl->getFunctionName() . '_' . strtr($macroName, "-", "_"); if (!function_exists($fun)) { throw new PHPTAL_MacroMissingException("Macro '$macroName' is not defined in $file", $this->_source->getRealPath()); } $fun($tpl, $this); } else { // call local macro $fun = $local_tpl->getFunctionName() . '_' . strtr($path, "-", "_"); if (!function_exists($fun)) { throw new PHPTAL_MacroMissingException("Macro '$path' is not defined", $local_tpl->_source->getRealPath()); } $fun( $local_tpl, $this); } }
php
final public function _executeMacroOfTemplate($path, PHPTAL $local_tpl) { // extract macro source file from macro name, if macro path does not // contain filename, then the macro is assumed to be local if (preg_match('/^(.*?)\/([a-z0-9_-]*)$/i', $path, $m)) { list(, $file, $macroName) = $m; if (isset($this->externalMacroTemplatesCache[$file])) { $tpl = $this->externalMacroTemplatesCache[$file]; } else { $tpl = clone $this; array_unshift($tpl->_repositories, dirname($this->_source->getRealPath())); $tpl->setTemplate($file); $tpl->prepare(); // keep it small (typically only 1 or 2 external files are used) if (count($this->externalMacroTemplatesCache) > 10) { $this->externalMacroTemplatesCache = array(); } $this->externalMacroTemplatesCache[$file] = $tpl; } $fun = $tpl->getFunctionName() . '_' . strtr($macroName, "-", "_"); if (!function_exists($fun)) { throw new PHPTAL_MacroMissingException("Macro '$macroName' is not defined in $file", $this->_source->getRealPath()); } $fun($tpl, $this); } else { // call local macro $fun = $local_tpl->getFunctionName() . '_' . strtr($path, "-", "_"); if (!function_exists($fun)) { throw new PHPTAL_MacroMissingException("Macro '$path' is not defined", $local_tpl->_source->getRealPath()); } $fun( $local_tpl, $this); } }
[ "final", "public", "function", "_executeMacroOfTemplate", "(", "$", "path", ",", "PHPTAL", "$", "local_tpl", ")", "{", "// extract macro source file from macro name, if macro path does not", "// contain filename, then the macro is assumed to be local", "if", "(", "preg_match", "(...
This is PHPTAL's internal function that handles execution of macros from templates. $this is caller's context (the file where execution had originally started) @param PHPTAL $local_tpl is PHPTAL instance of the file in which macro is defined (it will be different from $this if it's external macro call) @access private
[ "This", "is", "PHPTAL", "s", "internal", "function", "that", "handles", "execution", "of", "macros", "from", "templates", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L748-L786
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.setCodeFile
private function setCodeFile() { $this->findTemplate(); $this->_codeFile = $this->getPhpCodeDestination() . $this->getFunctionName() . '.' . $this->getPhpCodeExtension(); }
php
private function setCodeFile() { $this->findTemplate(); $this->_codeFile = $this->getPhpCodeDestination() . $this->getFunctionName() . '.' . $this->getPhpCodeExtension(); }
[ "private", "function", "setCodeFile", "(", ")", "{", "$", "this", "->", "findTemplate", "(", ")", ";", "$", "this", "->", "_codeFile", "=", "$", "this", "->", "getPhpCodeDestination", "(", ")", ".", "$", "this", "->", "getFunctionName", "(", ")", ".", ...
ensure that getCodePath will return up-to-date path
[ "ensure", "that", "getCodePath", "will", "return", "up", "-", "to", "-", "date", "path" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L791-L795
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.prepare
public function prepare() { // clear just in case settings changed and cache is out of date $this->externalMacroTemplatesCache = array(); // find the template source file and update function name $this->setCodeFile(); if (!function_exists($this->getFunctionName())) { // parse template if php generated code does not exists or template // source file modified since last generation or force reparse is set if ($this->getForceReparse() || !file_exists($this->getCodePath())) { // i'm not sure where that belongs, but not in normal path of execution // because some sites have _a lot_ of files in temp if ($this->getCachePurgeFrequency() && mt_rand()%$this->getCachePurgeFrequency() == 0) { $this->cleanUpGarbage(); } $result = $this->parse(); if (!file_put_contents($this->getCodePath(), $result)) { throw new PHPTAL_IOException('Unable to open '.$this->getCodePath().' for writing'); } // the awesome thing about eval() is that parse errors don't stop PHP. // when PHP dies during eval, fatal error is printed and // can be captured with output buffering ob_start(); try { eval("?>\n".$result); } catch(ParseError $parseError) { ob_end_clean(); throw new PHPTAL_TemplateException( 'Parse error: ' . $parseError->getMessage(), $this->getCodePath(), $parseError->getLine(), $parseError ); } catch(Exception $e) { ob_end_clean(); throw $e; } if (!function_exists($this->getFunctionName())) { $msg = str_replace('eval()\'d code', $this->getCodePath(), ob_get_clean()); // greedy .* ensures last match if (preg_match('/.*on line (\d+)$/m', $msg, $m)) $line=$m[1]; else $line=0; throw new PHPTAL_TemplateException(trim($msg), $this->getCodePath(), $line); } ob_end_clean(); } else { // eval trick is used only on first run, // just in case it causes any problems with opcode accelerators require $this->getCodePath(); } } $this->_prepared = true; return $this; }
php
public function prepare() { // clear just in case settings changed and cache is out of date $this->externalMacroTemplatesCache = array(); // find the template source file and update function name $this->setCodeFile(); if (!function_exists($this->getFunctionName())) { // parse template if php generated code does not exists or template // source file modified since last generation or force reparse is set if ($this->getForceReparse() || !file_exists($this->getCodePath())) { // i'm not sure where that belongs, but not in normal path of execution // because some sites have _a lot_ of files in temp if ($this->getCachePurgeFrequency() && mt_rand()%$this->getCachePurgeFrequency() == 0) { $this->cleanUpGarbage(); } $result = $this->parse(); if (!file_put_contents($this->getCodePath(), $result)) { throw new PHPTAL_IOException('Unable to open '.$this->getCodePath().' for writing'); } // the awesome thing about eval() is that parse errors don't stop PHP. // when PHP dies during eval, fatal error is printed and // can be captured with output buffering ob_start(); try { eval("?>\n".$result); } catch(ParseError $parseError) { ob_end_clean(); throw new PHPTAL_TemplateException( 'Parse error: ' . $parseError->getMessage(), $this->getCodePath(), $parseError->getLine(), $parseError ); } catch(Exception $e) { ob_end_clean(); throw $e; } if (!function_exists($this->getFunctionName())) { $msg = str_replace('eval()\'d code', $this->getCodePath(), ob_get_clean()); // greedy .* ensures last match if (preg_match('/.*on line (\d+)$/m', $msg, $m)) $line=$m[1]; else $line=0; throw new PHPTAL_TemplateException(trim($msg), $this->getCodePath(), $line); } ob_end_clean(); } else { // eval trick is used only on first run, // just in case it causes any problems with opcode accelerators require $this->getCodePath(); } } $this->_prepared = true; return $this; }
[ "public", "function", "prepare", "(", ")", "{", "// clear just in case settings changed and cache is out of date", "$", "this", "->", "externalMacroTemplatesCache", "=", "array", "(", ")", ";", "// find the template source file and update function name", "$", "this", "->", "s...
Prepare template without executing it.
[ "Prepare", "template", "without", "executing", "it", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L807-L871
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.cleanUpGarbage
public function cleanUpGarbage() { $cacheFilesExpire = time() - $this->getCacheLifetime() * 3600 * 24; // relies on templates sorting order being related to their modification dates $upperLimit = $this->getPhpCodeDestination() . $this->getFunctionNamePrefix($cacheFilesExpire) . '_'; $lowerLimit = $this->getPhpCodeDestination() . $this->getFunctionNamePrefix(0); // second * gets phptal:cache $cacheFiles = glob($this->getPhpCodeDestination() . 'tpl_????????_*.' . $this->getPhpCodeExtension() . '*'); if ($cacheFiles) { foreach ($cacheFiles as $index => $file) { // comparison here skips filenames that are certainly too new if (strcmp($file, $upperLimit) <= 0 || substr($file, 0, strlen($lowerLimit)) === $lowerLimit) { $time = filemtime($file); if ($time && $time < $cacheFilesExpire) { @unlink($file); } } } } }
php
public function cleanUpGarbage() { $cacheFilesExpire = time() - $this->getCacheLifetime() * 3600 * 24; // relies on templates sorting order being related to their modification dates $upperLimit = $this->getPhpCodeDestination() . $this->getFunctionNamePrefix($cacheFilesExpire) . '_'; $lowerLimit = $this->getPhpCodeDestination() . $this->getFunctionNamePrefix(0); // second * gets phptal:cache $cacheFiles = glob($this->getPhpCodeDestination() . 'tpl_????????_*.' . $this->getPhpCodeExtension() . '*'); if ($cacheFiles) { foreach ($cacheFiles as $index => $file) { // comparison here skips filenames that are certainly too new if (strcmp($file, $upperLimit) <= 0 || substr($file, 0, strlen($lowerLimit)) === $lowerLimit) { $time = filemtime($file); if ($time && $time < $cacheFilesExpire) { @unlink($file); } } } } }
[ "public", "function", "cleanUpGarbage", "(", ")", "{", "$", "cacheFilesExpire", "=", "time", "(", ")", "-", "$", "this", "->", "getCacheLifetime", "(", ")", "*", "3600", "*", "24", ";", "// relies on templates sorting order being related to their modification dates", ...
Removes all compiled templates from cache that are older than getCacheLifetime() days
[ "Removes", "all", "compiled", "templates", "from", "cache", "that", "are", "older", "than", "getCacheLifetime", "()", "days" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L916-L939
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.cleanUpCache
public function cleanUpCache() { $filename = $this->getCodePath(); $cacheFiles = glob($filename . '?*'); if ($cacheFiles) { foreach ($cacheFiles as $file) { if (substr($file, 0, strlen($filename)) !== $filename) continue; // safety net @unlink($file); } } $this->_prepared = false; }
php
public function cleanUpCache() { $filename = $this->getCodePath(); $cacheFiles = glob($filename . '?*'); if ($cacheFiles) { foreach ($cacheFiles as $file) { if (substr($file, 0, strlen($filename)) !== $filename) continue; // safety net @unlink($file); } } $this->_prepared = false; }
[ "public", "function", "cleanUpCache", "(", ")", "{", "$", "filename", "=", "$", "this", "->", "getCodePath", "(", ")", ";", "$", "cacheFiles", "=", "glob", "(", "$", "filename", ".", "'?*'", ")", ";", "if", "(", "$", "cacheFiles", ")", "{", "foreach"...
Removes content cached with phptal:cache for currently set template Must be called after setSource/setTemplate.
[ "Removes", "content", "cached", "with", "phptal", ":", "cache", "for", "currently", "set", "template", "Must", "be", "called", "after", "setSource", "/", "setTemplate", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L945-L956
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.getFunctionName
public function getFunctionName() { // function name is used as base for caching, so it must be unique for // every combination of settings that changes code in compiled template if (!$this->_functionName) { // just to make tempalte name recognizable $basename = preg_replace('/\.[a-z]{3,5}$/', '', basename($this->_source->getRealPath())); $basename = substr(trim(preg_replace('/[^a-zA-Z0-9]+/', '_', $basename), "_"), 0, 20); $hash = md5(PHPTAL_VERSION . PHP_VERSION . $this->_source->getRealPath() . $this->getEncoding() . $this->getPrefiltersCacheId() . $this->getOutputMode(), true ); // uses base64 rather than hex to make filename shorter. // there is loss of some bits due to name constraints and case-insensivity, // but that's still over 110 bits in addition to basename and timestamp. $hash = strtr(rtrim(base64_encode($hash),"="),"+/=","_A_"); $this->_functionName = $this->getFunctionNamePrefix($this->_source->getLastModifiedTime()) . $basename . '__' . $hash; } return $this->_functionName; }
php
public function getFunctionName() { // function name is used as base for caching, so it must be unique for // every combination of settings that changes code in compiled template if (!$this->_functionName) { // just to make tempalte name recognizable $basename = preg_replace('/\.[a-z]{3,5}$/', '', basename($this->_source->getRealPath())); $basename = substr(trim(preg_replace('/[^a-zA-Z0-9]+/', '_', $basename), "_"), 0, 20); $hash = md5(PHPTAL_VERSION . PHP_VERSION . $this->_source->getRealPath() . $this->getEncoding() . $this->getPrefiltersCacheId() . $this->getOutputMode(), true ); // uses base64 rather than hex to make filename shorter. // there is loss of some bits due to name constraints and case-insensivity, // but that's still over 110 bits in addition to basename and timestamp. $hash = strtr(rtrim(base64_encode($hash),"="),"+/=","_A_"); $this->_functionName = $this->getFunctionNamePrefix($this->_source->getLastModifiedTime()) . $basename . '__' . $hash; } return $this->_functionName; }
[ "public", "function", "getFunctionName", "(", ")", "{", "// function name is used as base for caching, so it must be unique for", "// every combination of settings that changes code in compiled template", "if", "(", "!", "$", "this", "->", "_functionName", ")", "{", "// just to mak...
Returns the generated template function name. @return string
[ "Returns", "the", "generated", "template", "function", "name", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L976-L1004
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.parse
protected function parse() { $data = $this->_source->getData(); $prefilters = $this->getPreFilterInstances(); foreach($prefilters as $prefilter) { $data = $prefilter->filter($data); } $realpath = $this->_source->getRealPath(); $parser = new PHPTAL_Dom_SaxXmlParser($this->_encoding); $builder = new PHPTAL_Dom_PHPTALDocumentBuilder(); $tree = $parser->parseString($builder, $data, $realpath)->getResult(); foreach($prefilters as $prefilter) { if ($prefilter instanceof PHPTAL_PreFilter) { if ($prefilter->filterDOM($tree) !== NULL) { throw new PHPTAL_ConfigurationException("Don't return value from filterDOM()"); } } } $state = new PHPTAL_Php_State($this); $codewriter = new PHPTAL_Php_CodeWriter($state); $codewriter->doTemplateFile($this->getFunctionName(), $tree); return $codewriter->getResult(); }
php
protected function parse() { $data = $this->_source->getData(); $prefilters = $this->getPreFilterInstances(); foreach($prefilters as $prefilter) { $data = $prefilter->filter($data); } $realpath = $this->_source->getRealPath(); $parser = new PHPTAL_Dom_SaxXmlParser($this->_encoding); $builder = new PHPTAL_Dom_PHPTALDocumentBuilder(); $tree = $parser->parseString($builder, $data, $realpath)->getResult(); foreach($prefilters as $prefilter) { if ($prefilter instanceof PHPTAL_PreFilter) { if ($prefilter->filterDOM($tree) !== NULL) { throw new PHPTAL_ConfigurationException("Don't return value from filterDOM()"); } } } $state = new PHPTAL_Php_State($this); $codewriter = new PHPTAL_Php_CodeWriter($state); $codewriter->doTemplateFile($this->getFunctionName(), $tree); return $codewriter->getResult(); }
[ "protected", "function", "parse", "(", ")", "{", "$", "data", "=", "$", "this", "->", "_source", "->", "getData", "(", ")", ";", "$", "prefilters", "=", "$", "this", "->", "getPreFilterInstances", "(", ")", ";", "foreach", "(", "$", "prefilters", "as",...
Parse currently set template, prefilter and generate PHP code. @return string (compiled PHP code)
[ "Parse", "currently", "set", "template", "prefilter", "and", "generate", "PHP", "code", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L1099-L1128
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.findTemplate
protected function findTemplate() { if ($this->_path == false) { throw new PHPTAL_ConfigurationException('No template file specified'); } // template source already defined if ($this->_source) { return; } if (!$this->resolvers && !$this->_repositories) { $this->_source = new PHPTAL_FileSource($this->_path); } else { foreach ($this->resolvers as $resolver) { $source = $resolver->resolve($this->_path); if ($source) { $this->_source = $source; return; } } $resolver = new PHPTAL_FileSourceResolver($this->_repositories); $this->_source = $resolver->resolve($this->_path); } if (!$this->_source) { throw new PHPTAL_IOException('Unable to locate template file '.$this->_path); } }
php
protected function findTemplate() { if ($this->_path == false) { throw new PHPTAL_ConfigurationException('No template file specified'); } // template source already defined if ($this->_source) { return; } if (!$this->resolvers && !$this->_repositories) { $this->_source = new PHPTAL_FileSource($this->_path); } else { foreach ($this->resolvers as $resolver) { $source = $resolver->resolve($this->_path); if ($source) { $this->_source = $source; return; } } $resolver = new PHPTAL_FileSourceResolver($this->_repositories); $this->_source = $resolver->resolve($this->_path); } if (!$this->_source) { throw new PHPTAL_IOException('Unable to locate template file '.$this->_path); } }
[ "protected", "function", "findTemplate", "(", ")", "{", "if", "(", "$", "this", "->", "_path", "==", "false", ")", "{", "throw", "new", "PHPTAL_ConfigurationException", "(", "'No template file specified'", ")", ";", "}", "// template source already defined", "if", ...
Search template source location. @return void
[ "Search", "template", "source", "location", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L1134-L1163
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.autoload
final public static function autoload($class) { if (version_compare(PHP_VERSION, '5.3', '>=') && __NAMESPACE__) { $class = str_replace(__NAMESPACE__, 'PHPTAL', $class); $class = strtr($class, '\\', '_'); } if (substr($class, 0, 7) !== 'PHPTAL_') return; $path = dirname(__FILE__) . strtr("_".$class, "_", DIRECTORY_SEPARATOR) . '.php'; require $path; }
php
final public static function autoload($class) { if (version_compare(PHP_VERSION, '5.3', '>=') && __NAMESPACE__) { $class = str_replace(__NAMESPACE__, 'PHPTAL', $class); $class = strtr($class, '\\', '_'); } if (substr($class, 0, 7) !== 'PHPTAL_') return; $path = dirname(__FILE__) . strtr("_".$class, "_", DIRECTORY_SEPARATOR) . '.php'; require $path; }
[ "final", "public", "static", "function", "autoload", "(", "$", "class", ")", "{", "if", "(", "version_compare", "(", "PHP_VERSION", ",", "'5.3'", ",", "'>='", ")", "&&", "__NAMESPACE__", ")", "{", "$", "class", "=", "str_replace", "(", "__NAMESPACE__", ","...
Suitable for callbacks from SPL autoload @param string $class class name to load @return void
[ "Suitable", "for", "callbacks", "from", "SPL", "autoload" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L1192-L1204
phptal/PHPTAL
classes/PHPTAL.php
PHPTAL.autoloadRegister
final public static function autoloadRegister() { // spl_autoload_register disables oldschool autoload // even if it was added using spl_autoload_register! // this is intended to preserve old autoloader $uses_autoload = function_exists('__autoload') && (!($tmp = spl_autoload_functions()) || ($tmp[0] === '__autoload')); // Prepending PHPTAL's autoloader helps if there are other autoloaders // that throw/die when file is not found. Only >5.3 though. if (version_compare(PHP_VERSION, '5.3', '>=')) { spl_autoload_register(array(__CLASS__,'autoload'), false, true); } else { spl_autoload_register(array(__CLASS__,'autoload')); } if ($uses_autoload) { spl_autoload_register('__autoload'); } }
php
final public static function autoloadRegister() { // spl_autoload_register disables oldschool autoload // even if it was added using spl_autoload_register! // this is intended to preserve old autoloader $uses_autoload = function_exists('__autoload') && (!($tmp = spl_autoload_functions()) || ($tmp[0] === '__autoload')); // Prepending PHPTAL's autoloader helps if there are other autoloaders // that throw/die when file is not found. Only >5.3 though. if (version_compare(PHP_VERSION, '5.3', '>=')) { spl_autoload_register(array(__CLASS__,'autoload'), false, true); } else { spl_autoload_register(array(__CLASS__,'autoload')); } if ($uses_autoload) { spl_autoload_register('__autoload'); } }
[ "final", "public", "static", "function", "autoloadRegister", "(", ")", "{", "// spl_autoload_register disables oldschool autoload", "// even if it was added using spl_autoload_register!", "// this is intended to preserve old autoloader", "$", "uses_autoload", "=", "function_exists", "(...
Sets up PHPTAL's autoloader. If you have to use your own autoloader to load PHPTAL files, use spl_autoload_unregister(array('PHPTAL','autoload')); @return void
[ "Sets", "up", "PHPTAL", "s", "autoloader", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL.php#L1214-L1234
phptal/PHPTAL
classes/PHPTAL/ExceptionHandler.php
PHPTAL_ExceptionHandler.handleException
public static function handleException(Exception $e, $encoding) { // PHPTAL's handler is only useful on fresh HTTP response if (PHP_SAPI !== 'cli' && !headers_sent()) { $old_exception_handler = set_exception_handler(array(new PHPTAL_ExceptionHandler($encoding), '_defaultExceptionHandler')); if ($old_exception_handler !== NULL) { restore_exception_handler(); // if there's user's exception handler, let it work } } throw $e; // throws instead of outputting immediately to support user's try/catch }
php
public static function handleException(Exception $e, $encoding) { // PHPTAL's handler is only useful on fresh HTTP response if (PHP_SAPI !== 'cli' && !headers_sent()) { $old_exception_handler = set_exception_handler(array(new PHPTAL_ExceptionHandler($encoding), '_defaultExceptionHandler')); if ($old_exception_handler !== NULL) { restore_exception_handler(); // if there's user's exception handler, let it work } } throw $e; // throws instead of outputting immediately to support user's try/catch }
[ "public", "static", "function", "handleException", "(", "Exception", "$", "e", ",", "$", "encoding", ")", "{", "// PHPTAL's handler is only useful on fresh HTTP response", "if", "(", "PHP_SAPI", "!==", "'cli'", "&&", "!", "headers_sent", "(", ")", ")", "{", "$", ...
PHP's default exception handler allows error pages to be indexed and can reveal too much information, so if possible PHPTAL sets up its own handler to fix this. Doesn't change exception handler if non-default one is set. @param Exception e exception to re-throw and display @return void @throws Exception
[ "PHP", "s", "default", "exception", "handler", "allows", "error", "pages", "to", "be", "indexed", "and", "can", "reveal", "too", "much", "information", "so", "if", "possible", "PHPTAL", "sets", "up", "its", "own", "handler", "to", "fix", "this", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/ExceptionHandler.php#L34-L45
phptal/PHPTAL
classes/PHPTAL/ExceptionHandler.php
PHPTAL_ExceptionHandler._defaultExceptionHandler
public function _defaultExceptionHandler($e) { if (!headers_sent()) { header('HTTP/1.1 500 PHPTAL Exception'); header('Content-Type:text/html;charset='.$this->encoding); } $line = $e->getFile(); if ($e->getLine()) { $line .= ' line '.$e->getLine(); } if (ini_get('display_errors')) { $title = get_class($e).': '.htmlspecialchars($e->getMessage()); $body = "<p><strong>\n".htmlspecialchars($e->getMessage()).'</strong></p>' . '<p>In '.htmlspecialchars($line)."</p><pre>\n".htmlspecialchars($e->getTraceAsString()).'</pre>'; } else { $title = "PHPTAL Exception"; $body = "<p>This page cannot be displayed.</p><hr/>" . "<p><small>Enable <code>display_errors</code> to see detailed message.</small></p>"; } echo "<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head><style>body{font-family:sans-serif}</style><title>\n"; echo $title.'</title></head><body><h1>PHPTAL Exception</h1>'.$body; error_log($e->getMessage().' in '.$line); echo '</body></html>'.str_repeat(' ', 100)."\n"; // IE won't display error pages < 512b exit(1); }
php
public function _defaultExceptionHandler($e) { if (!headers_sent()) { header('HTTP/1.1 500 PHPTAL Exception'); header('Content-Type:text/html;charset='.$this->encoding); } $line = $e->getFile(); if ($e->getLine()) { $line .= ' line '.$e->getLine(); } if (ini_get('display_errors')) { $title = get_class($e).': '.htmlspecialchars($e->getMessage()); $body = "<p><strong>\n".htmlspecialchars($e->getMessage()).'</strong></p>' . '<p>In '.htmlspecialchars($line)."</p><pre>\n".htmlspecialchars($e->getTraceAsString()).'</pre>'; } else { $title = "PHPTAL Exception"; $body = "<p>This page cannot be displayed.</p><hr/>" . "<p><small>Enable <code>display_errors</code> to see detailed message.</small></p>"; } echo "<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head><style>body{font-family:sans-serif}</style><title>\n"; echo $title.'</title></head><body><h1>PHPTAL Exception</h1>'.$body; error_log($e->getMessage().' in '.$line); echo '</body></html>'.str_repeat(' ', 100)."\n"; // IE won't display error pages < 512b exit(1); }
[ "public", "function", "_defaultExceptionHandler", "(", "$", "e", ")", "{", "if", "(", "!", "headers_sent", "(", ")", ")", "{", "header", "(", "'HTTP/1.1 500 PHPTAL Exception'", ")", ";", "header", "(", "'Content-Type:text/html;charset='", ".", "$", "this", "->",...
Generates simple error page. Sets appropriate HTTP status to prevent page being indexed. @param Exception e exception to display
[ "Generates", "simple", "error", "page", ".", "Sets", "appropriate", "HTTP", "status", "to", "prevent", "page", "being", "indexed", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/ExceptionHandler.php#L53-L80
phptal/PHPTAL
classes/PHPTAL/Php/Attribute/TAL/Replace.php
PHPTAL_Php_Attribute_TAL_Replace.generateDefault
private function generateDefault(PHPTAL_Php_CodeWriter $codewriter) { $this->phpelement->generateSurroundHead($codewriter); $this->phpelement->generateHead($codewriter); $this->phpelement->generateContent($codewriter); $this->phpelement->generateFoot($codewriter); $this->phpelement->generateSurroundFoot($codewriter); }
php
private function generateDefault(PHPTAL_Php_CodeWriter $codewriter) { $this->phpelement->generateSurroundHead($codewriter); $this->phpelement->generateHead($codewriter); $this->phpelement->generateContent($codewriter); $this->phpelement->generateFoot($codewriter); $this->phpelement->generateSurroundFoot($codewriter); }
[ "private", "function", "generateDefault", "(", "PHPTAL_Php_CodeWriter", "$", "codewriter", ")", "{", "$", "this", "->", "phpelement", "->", "generateSurroundHead", "(", "$", "codewriter", ")", ";", "$", "this", "->", "phpelement", "->", "generateHead", "(", "$",...
don't replace - re-generate default content
[ "don", "t", "replace", "-", "re", "-", "generate", "default", "content" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/Attribute/TAL/Replace.php#L108-L115
phptal/PHPTAL
classes/PHPTAL/Php/Transformer.php
PHPTAL_Php_Transformer.transform
public static function transform($str, $prefix='$') { $len = strlen($str); $state = self::ST_WHITE; $result = ''; $i = 0; $inString = false; $backslashed = false; $instanceof = false; $eval = false; for ($i = 0; $i <= $len; $i++) { if ($i == $len) $c = "\0"; else $c = $str[$i]; switch ($state) { // after whitespace a variable-variable may start, ${var} → $ctx->{$ctx->var} case self::ST_WHITE: if ($c === '$' && $i+1 < $len && $str[$i+1] === '{') { $result .= $prefix; $state = self::ST_NONE; break; } /* NO BREAK - ST_WHITE is almost the same as ST_NONE */ // no specific state defined, just eat char and see what to do with it. case self::ST_NONE: // begin of eval without { if ($c === '$' && $i+1 < $len && self::isAlpha($str[$i+1])) { $state = self::ST_EVAL; $mark = $i+1; $result .= $prefix.'{'; } elseif (self::isDigit($c)) { $state = self::ST_NUM; $mark = $i; } // that an alphabetic char, then it should be the begining // of a var or static // && !self::isDigit($c) checked earlier elseif (self::isVarNameChar($c)) { $state = self::ST_VAR; $mark = $i; } // begining of double quoted string elseif ($c === '"') { $state = self::ST_ESTR; $mark = $i; $inString = true; } // begining of single quoted string elseif ($c === '\'') { $state = self::ST_STR; $mark = $i; $inString = true; } // closing a method, an array access or an evaluation elseif ($c === ')' || $c === ']' || $c === '}') { $result .= $c; // if next char is dot then an object member must // follow if ($i+1 < $len && $str[$i+1] === '.') { $result .= '->'; $state = self::ST_MEMBER; $mark = $i+2; $i+=2; } } // @ is an access to some defined variable elseif ($c === '@') { $state = self::ST_DEFINE; $mark = $i+1; } elseif (ctype_space($c)) { $state = self::ST_WHITE; $result .= $c; } // character we don't mind about else { $result .= $c; } break; // $xxx case self::ST_EVAL: if (!self::isVarNameChar($c)) { $result .= $prefix . substr($str, $mark, $i-$mark); $result .= '}'; $state = self::ST_NONE; } break; // single quoted string case self::ST_STR: if ($c === '\\') { $backslashed = true; } elseif ($backslashed) { $backslashed = false; } // end of string, back to none state elseif ($c === '\'') { $result .= substr($str, $mark, $i-$mark+1); $inString = false; $state = self::ST_NONE; } break; // double quoted string case self::ST_ESTR: if ($c === '\\') { $backslashed = true; } elseif ($backslashed) { $backslashed = false; } // end of string, back to none state elseif ($c === '"') { $result .= substr($str, $mark, $i-$mark+1); $inString = false; $state = self::ST_NONE; } // instring interpolation, search } and transform the // interpollation to insert it into the string elseif ($c === '$' && $i+1 < $len && $str[$i+1] === '{') { $result .= substr($str, $mark, $i-$mark) . '{'; $sub = 0; for ($j = $i; $j<$len; $j++) { if ($str[$j] === '{') { $sub++; } elseif ($str[$j] === '}' && (--$sub) == 0) { $part = substr($str, $i+2, $j-$i-2); $result .= self::transform($part, $prefix); $i = $j; $mark = $i; } } } break; // var state case self::ST_VAR: if (self::isVarNameChar($c)) { } // end of var, begin of member (method or var) elseif ($c === '.') { $result .= $prefix . substr($str, $mark, $i-$mark); $result .= '->'; $state = self::ST_MEMBER; $mark = $i+1; } // static call, the var is a class name elseif ($c === ':' && $i+1 < $len && $str[$i+1] === ':') { $result .= substr($str, $mark, $i-$mark+1); $mark = $i+1; $i++; $state = self::ST_STATIC; break; } // function invocation, the var is a function name elseif ($c === '(') { $result .= substr($str, $mark, $i-$mark+1); $state = self::ST_NONE; } // array index, the var is done elseif ($c === '[') { if ($str[$mark]==='_') { // superglobal? $result .= '$' . substr($str, $mark, $i-$mark+1); } else { $result .= $prefix . substr($str, $mark, $i-$mark+1); } $state = self::ST_NONE; } // end of var with non-var-name character, handle keywords // and populate the var name else { $var = substr($str, $mark, $i-$mark); $low = strtolower($var); // boolean and null if ($low === 'true' || $low === 'false' || $low === 'null') { $result .= $var; } // lt, gt, ge, eq, ... elseif (array_key_exists($low, self::$TranslationTable)) { $result .= self::$TranslationTable[$low]; } // instanceof keyword elseif ($low === 'instanceof') { $result .= $var; $instanceof = true; } // previous was instanceof elseif ($instanceof) { // last was instanceof, this var is a class name $result .= $var; $instanceof = false; } // regular variable else { $result .= $prefix . $var; } $i--; $state = self::ST_NONE; } break; // object member case self::ST_MEMBER: if (self::isVarNameChar($c)) { } // eval mode ${foo} elseif ($c === '$' && ($i >= $len-2 || $str[$i+1] !== '{')) { $result .= '{' . $prefix; $mark++; $eval = true; } // x.${foo} x->{foo} elseif ($c === '$') { $mark++; } // end of var member var, begin of new member elseif ($c === '.') { $result .= substr($str, $mark, $i-$mark); if ($eval) { $result .='}'; $eval = false; } $result .= '->'; $mark = $i+1; $state = self::ST_MEMBER; } // begin of static access elseif ($c === ':') { $result .= substr($str, $mark, $i-$mark+1); if ($eval) { $result .='}'; $eval = false; } $state = self::ST_STATIC; break; } // the member is a method or an array elseif ($c === '(' || $c === '[') { $result .= substr($str, $mark, $i-$mark+1); if ($eval) { $result .='}'; $eval = false; } $state = self::ST_NONE; } // regular end of member, it is a var else { $var = substr($str, $mark, $i-$mark); if ($var !== '' && !preg_match('/^[a-z][a-z0-9_\x7f-\xff]*$/i',$var)) { throw new PHPTAL_ParserException("Invalid field name '$var' in expression php:$str"); } $result .= $var; if ($eval) { $result .='}'; $eval = false; } $state = self::ST_NONE; $i--; } break; // wait for separator case self::ST_DEFINE: if (self::isVarNameChar($c)) { } else { $state = self::ST_NONE; $result .= substr($str, $mark, $i-$mark); $i--; } break; // static call, can be const, static var, static method // Klass::$static // Klass::const // Kclass::staticMethod() // case self::ST_STATIC: if (self::isVarNameChar($c)) { } // static var elseif ($c === '$') { } // end of static var which is an object and begin of member elseif ($c === '.') { $result .= substr($str, $mark, $i-$mark); $result .= '->'; $mark = $i+1; $state = self::ST_MEMBER; } // end of static var which is a class name elseif ($c === ':') { $result .= substr($str, $mark, $i-$mark+1); $state = self::ST_STATIC; break; } // static method or array elseif ($c === '(' || $c === '[') { $result .= substr($str, $mark, $i-$mark+1); $state = self::ST_NONE; } // end of static var or const else { $result .= substr($str, $mark, $i-$mark); $state = self::ST_NONE; $i--; } break; // numeric value case self::ST_NUM: if (!self::isDigitCompound($c)) { $var = substr($str, $mark, $i-$mark); if (self::isAlpha($c) || $c === '_') { throw new PHPTAL_ParserException("Syntax error in number '$var$c' in expression php:$str"); } if (!is_numeric($var)) { throw new PHPTAL_ParserException("Syntax error in number '$var' in expression php:$str"); } $result .= $var; $state = self::ST_NONE; $i--; } break; } } $result = trim($result); // CodeWriter doesn't like expressions that look like blocks if ($result[strlen($result)-1] === '}') return '('.$result.')'; return $result; }
php
public static function transform($str, $prefix='$') { $len = strlen($str); $state = self::ST_WHITE; $result = ''; $i = 0; $inString = false; $backslashed = false; $instanceof = false; $eval = false; for ($i = 0; $i <= $len; $i++) { if ($i == $len) $c = "\0"; else $c = $str[$i]; switch ($state) { // after whitespace a variable-variable may start, ${var} → $ctx->{$ctx->var} case self::ST_WHITE: if ($c === '$' && $i+1 < $len && $str[$i+1] === '{') { $result .= $prefix; $state = self::ST_NONE; break; } /* NO BREAK - ST_WHITE is almost the same as ST_NONE */ // no specific state defined, just eat char and see what to do with it. case self::ST_NONE: // begin of eval without { if ($c === '$' && $i+1 < $len && self::isAlpha($str[$i+1])) { $state = self::ST_EVAL; $mark = $i+1; $result .= $prefix.'{'; } elseif (self::isDigit($c)) { $state = self::ST_NUM; $mark = $i; } // that an alphabetic char, then it should be the begining // of a var or static // && !self::isDigit($c) checked earlier elseif (self::isVarNameChar($c)) { $state = self::ST_VAR; $mark = $i; } // begining of double quoted string elseif ($c === '"') { $state = self::ST_ESTR; $mark = $i; $inString = true; } // begining of single quoted string elseif ($c === '\'') { $state = self::ST_STR; $mark = $i; $inString = true; } // closing a method, an array access or an evaluation elseif ($c === ')' || $c === ']' || $c === '}') { $result .= $c; // if next char is dot then an object member must // follow if ($i+1 < $len && $str[$i+1] === '.') { $result .= '->'; $state = self::ST_MEMBER; $mark = $i+2; $i+=2; } } // @ is an access to some defined variable elseif ($c === '@') { $state = self::ST_DEFINE; $mark = $i+1; } elseif (ctype_space($c)) { $state = self::ST_WHITE; $result .= $c; } // character we don't mind about else { $result .= $c; } break; // $xxx case self::ST_EVAL: if (!self::isVarNameChar($c)) { $result .= $prefix . substr($str, $mark, $i-$mark); $result .= '}'; $state = self::ST_NONE; } break; // single quoted string case self::ST_STR: if ($c === '\\') { $backslashed = true; } elseif ($backslashed) { $backslashed = false; } // end of string, back to none state elseif ($c === '\'') { $result .= substr($str, $mark, $i-$mark+1); $inString = false; $state = self::ST_NONE; } break; // double quoted string case self::ST_ESTR: if ($c === '\\') { $backslashed = true; } elseif ($backslashed) { $backslashed = false; } // end of string, back to none state elseif ($c === '"') { $result .= substr($str, $mark, $i-$mark+1); $inString = false; $state = self::ST_NONE; } // instring interpolation, search } and transform the // interpollation to insert it into the string elseif ($c === '$' && $i+1 < $len && $str[$i+1] === '{') { $result .= substr($str, $mark, $i-$mark) . '{'; $sub = 0; for ($j = $i; $j<$len; $j++) { if ($str[$j] === '{') { $sub++; } elseif ($str[$j] === '}' && (--$sub) == 0) { $part = substr($str, $i+2, $j-$i-2); $result .= self::transform($part, $prefix); $i = $j; $mark = $i; } } } break; // var state case self::ST_VAR: if (self::isVarNameChar($c)) { } // end of var, begin of member (method or var) elseif ($c === '.') { $result .= $prefix . substr($str, $mark, $i-$mark); $result .= '->'; $state = self::ST_MEMBER; $mark = $i+1; } // static call, the var is a class name elseif ($c === ':' && $i+1 < $len && $str[$i+1] === ':') { $result .= substr($str, $mark, $i-$mark+1); $mark = $i+1; $i++; $state = self::ST_STATIC; break; } // function invocation, the var is a function name elseif ($c === '(') { $result .= substr($str, $mark, $i-$mark+1); $state = self::ST_NONE; } // array index, the var is done elseif ($c === '[') { if ($str[$mark]==='_') { // superglobal? $result .= '$' . substr($str, $mark, $i-$mark+1); } else { $result .= $prefix . substr($str, $mark, $i-$mark+1); } $state = self::ST_NONE; } // end of var with non-var-name character, handle keywords // and populate the var name else { $var = substr($str, $mark, $i-$mark); $low = strtolower($var); // boolean and null if ($low === 'true' || $low === 'false' || $low === 'null') { $result .= $var; } // lt, gt, ge, eq, ... elseif (array_key_exists($low, self::$TranslationTable)) { $result .= self::$TranslationTable[$low]; } // instanceof keyword elseif ($low === 'instanceof') { $result .= $var; $instanceof = true; } // previous was instanceof elseif ($instanceof) { // last was instanceof, this var is a class name $result .= $var; $instanceof = false; } // regular variable else { $result .= $prefix . $var; } $i--; $state = self::ST_NONE; } break; // object member case self::ST_MEMBER: if (self::isVarNameChar($c)) { } // eval mode ${foo} elseif ($c === '$' && ($i >= $len-2 || $str[$i+1] !== '{')) { $result .= '{' . $prefix; $mark++; $eval = true; } // x.${foo} x->{foo} elseif ($c === '$') { $mark++; } // end of var member var, begin of new member elseif ($c === '.') { $result .= substr($str, $mark, $i-$mark); if ($eval) { $result .='}'; $eval = false; } $result .= '->'; $mark = $i+1; $state = self::ST_MEMBER; } // begin of static access elseif ($c === ':') { $result .= substr($str, $mark, $i-$mark+1); if ($eval) { $result .='}'; $eval = false; } $state = self::ST_STATIC; break; } // the member is a method or an array elseif ($c === '(' || $c === '[') { $result .= substr($str, $mark, $i-$mark+1); if ($eval) { $result .='}'; $eval = false; } $state = self::ST_NONE; } // regular end of member, it is a var else { $var = substr($str, $mark, $i-$mark); if ($var !== '' && !preg_match('/^[a-z][a-z0-9_\x7f-\xff]*$/i',$var)) { throw new PHPTAL_ParserException("Invalid field name '$var' in expression php:$str"); } $result .= $var; if ($eval) { $result .='}'; $eval = false; } $state = self::ST_NONE; $i--; } break; // wait for separator case self::ST_DEFINE: if (self::isVarNameChar($c)) { } else { $state = self::ST_NONE; $result .= substr($str, $mark, $i-$mark); $i--; } break; // static call, can be const, static var, static method // Klass::$static // Klass::const // Kclass::staticMethod() // case self::ST_STATIC: if (self::isVarNameChar($c)) { } // static var elseif ($c === '$') { } // end of static var which is an object and begin of member elseif ($c === '.') { $result .= substr($str, $mark, $i-$mark); $result .= '->'; $mark = $i+1; $state = self::ST_MEMBER; } // end of static var which is a class name elseif ($c === ':') { $result .= substr($str, $mark, $i-$mark+1); $state = self::ST_STATIC; break; } // static method or array elseif ($c === '(' || $c === '[') { $result .= substr($str, $mark, $i-$mark+1); $state = self::ST_NONE; } // end of static var or const else { $result .= substr($str, $mark, $i-$mark); $state = self::ST_NONE; $i--; } break; // numeric value case self::ST_NUM: if (!self::isDigitCompound($c)) { $var = substr($str, $mark, $i-$mark); if (self::isAlpha($c) || $c === '_') { throw new PHPTAL_ParserException("Syntax error in number '$var$c' in expression php:$str"); } if (!is_numeric($var)) { throw new PHPTAL_ParserException("Syntax error in number '$var' in expression php:$str"); } $result .= $var; $state = self::ST_NONE; $i--; } break; } } $result = trim($result); // CodeWriter doesn't like expressions that look like blocks if ($result[strlen($result)-1] === '}') return '('.$result.')'; return $result; }
[ "public", "static", "function", "transform", "(", "$", "str", ",", "$", "prefix", "=", "'$'", ")", "{", "$", "len", "=", "strlen", "(", "$", "str", ")", ";", "$", "state", "=", "self", "::", "ST_WHITE", ";", "$", "result", "=", "''", ";", "$", ...
transform PHPTAL's php-like syntax into real PHP
[ "transform", "PHPTAL", "s", "php", "-", "like", "syntax", "into", "real", "PHP" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/Transformer.php#L53-L383
phptal/PHPTAL
classes/PHPTAL/Dom/Attr.php
PHPTAL_Dom_Attr.overwriteValueWithVariable
function overwriteValueWithVariable($phpVariable) { $this->replacedState = self::VALUE_REPLACED; $this->phpVariable = $phpVariable; $this->setPHPCode('echo '.$phpVariable); }
php
function overwriteValueWithVariable($phpVariable) { $this->replacedState = self::VALUE_REPLACED; $this->phpVariable = $phpVariable; $this->setPHPCode('echo '.$phpVariable); }
[ "function", "overwriteValueWithVariable", "(", "$", "phpVariable", ")", "{", "$", "this", "->", "replacedState", "=", "self", "::", "VALUE_REPLACED", ";", "$", "this", "->", "phpVariable", "=", "$", "phpVariable", ";", "$", "this", "->", "setPHPCode", "(", "...
generate value of this attribute from variable
[ "generate", "value", "of", "this", "attribute", "from", "variable" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Attr.php#L154-L159
phptal/PHPTAL
classes/PHPTAL/Dom/Attr.php
PHPTAL_Dom_Attr.overwriteFullWithVariable
function overwriteFullWithVariable($phpVariable) { $this->replacedState = self::FULLY_REPLACED; $this->phpVariable = $phpVariable; $this->setPHPCode('echo '.$phpVariable); }
php
function overwriteFullWithVariable($phpVariable) { $this->replacedState = self::FULLY_REPLACED; $this->phpVariable = $phpVariable; $this->setPHPCode('echo '.$phpVariable); }
[ "function", "overwriteFullWithVariable", "(", "$", "phpVariable", ")", "{", "$", "this", "->", "replacedState", "=", "self", "::", "FULLY_REPLACED", ";", "$", "this", "->", "phpVariable", "=", "$", "phpVariable", ";", "$", "this", "->", "setPHPCode", "(", "'...
generate complete syntax of this attribute using variable
[ "generate", "complete", "syntax", "of", "this", "attribute", "using", "variable" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Attr.php#L164-L169
phptal/PHPTAL
classes/PHPTAL/Dom/Attr.php
PHPTAL_Dom_Attr.overwriteValueWithCode
function overwriteValueWithCode($code) { $this->replacedState = self::VALUE_REPLACED; $this->phpVariable = null; $this->setPHPCode($code); }
php
function overwriteValueWithCode($code) { $this->replacedState = self::VALUE_REPLACED; $this->phpVariable = null; $this->setPHPCode($code); }
[ "function", "overwriteValueWithCode", "(", "$", "code", ")", "{", "$", "this", "->", "replacedState", "=", "self", "::", "VALUE_REPLACED", ";", "$", "this", "->", "phpVariable", "=", "null", ";", "$", "this", "->", "setPHPCode", "(", "$", "code", ")", ";...
use any PHP code to generate this attribute's value
[ "use", "any", "PHP", "code", "to", "generate", "this", "attribute", "s", "value" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Attr.php#L174-L179
phptal/PHPTAL
classes/PHPTAL/GetTextTranslator.php
PHPTAL_GetTextTranslator.setLanguage
public function setLanguage(/*...*/) { $langs = func_get_args(); $langCode = $this->trySettingLanguages(LC_ALL, $langs); if ($langCode) return $langCode; if (defined("LC_MESSAGES")) { $langCode = $this->trySettingLanguages(LC_MESSAGES, $langs); if ($langCode) return $langCode; } throw new PHPTAL_ConfigurationException('Language(s) code(s) "'.implode(', ', $langs).'" not supported by your system'); }
php
public function setLanguage(/*...*/) { $langs = func_get_args(); $langCode = $this->trySettingLanguages(LC_ALL, $langs); if ($langCode) return $langCode; if (defined("LC_MESSAGES")) { $langCode = $this->trySettingLanguages(LC_MESSAGES, $langs); if ($langCode) return $langCode; } throw new PHPTAL_ConfigurationException('Language(s) code(s) "'.implode(', ', $langs).'" not supported by your system'); }
[ "public", "function", "setLanguage", "(", "/*...*/", ")", "{", "$", "langs", "=", "func_get_args", "(", ")", ";", "$", "langCode", "=", "$", "this", "->", "trySettingLanguages", "(", "LC_ALL", ",", "$", "langs", ")", ";", "if", "(", "$", "langCode", ")...
It expects locale names as arguments. Choses first one that works. setLanguage("en_US.utf8","en_US","en_GB","en") @return string - chosen language
[ "It", "expects", "locale", "names", "as", "arguments", ".", "Choses", "first", "one", "that", "works", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/GetTextTranslator.php#L73-L86
phptal/PHPTAL
classes/PHPTAL/GetTextTranslator.php
PHPTAL_GetTextTranslator.addDomain
public function addDomain($domain, $path='./locale/') { bindtextdomain($domain, $path); if ($this->_encoding) { bind_textdomain_codeset($domain, $this->_encoding); } $this->useDomain($domain); }
php
public function addDomain($domain, $path='./locale/') { bindtextdomain($domain, $path); if ($this->_encoding) { bind_textdomain_codeset($domain, $this->_encoding); } $this->useDomain($domain); }
[ "public", "function", "addDomain", "(", "$", "domain", ",", "$", "path", "=", "'./locale/'", ")", "{", "bindtextdomain", "(", "$", "domain", ",", "$", "path", ")", ";", "if", "(", "$", "this", "->", "_encoding", ")", "{", "bind_textdomain_codeset", "(", ...
Adds translation domain (usually it's the same as name of .po file [without extension]) Encoding must be set before calling addDomain!
[ "Adds", "translation", "domain", "(", "usually", "it", "s", "the", "same", "as", "name", "of", ".", "po", "file", "[", "without", "extension", "]", ")" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/GetTextTranslator.php#L106-L113
phptal/PHPTAL
classes/PHPTAL/GetTextTranslator.php
PHPTAL_GetTextTranslator.useDomain
public function useDomain($domain) { $old = $this->_currentDomain; $this->_currentDomain = $domain; textdomain($domain); return $old; }
php
public function useDomain($domain) { $old = $this->_currentDomain; $this->_currentDomain = $domain; textdomain($domain); return $old; }
[ "public", "function", "useDomain", "(", "$", "domain", ")", "{", "$", "old", "=", "$", "this", "->", "_currentDomain", ";", "$", "this", "->", "_currentDomain", "=", "$", "domain", ";", "textdomain", "(", "$", "domain", ")", ";", "return", "$", "old", ...
Switches to one of the domains previously set via addDomain() @param string $domain name of translation domain to be used. @return string - old domain
[ "Switches", "to", "one", "of", "the", "domains", "previously", "set", "via", "addDomain", "()" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/GetTextTranslator.php#L122-L128
phptal/PHPTAL
classes/PHPTAL/GetTextTranslator.php
PHPTAL_GetTextTranslator.translate
public function translate($key, $htmlencode=true) { if ($this->_canonicalize) $key = self::_canonicalizeKey($key); $value = gettext($key); if ($htmlencode) { $value = htmlspecialchars($value, ENT_QUOTES, $this->_encoding); } while (preg_match('/\${(.*?)\}/sm', $value, $m)) { list($src, $var) = $m; if (!array_key_exists($var, $this->_vars)) { throw new PHPTAL_VariableNotFoundException('Interpolation error. Translation uses ${'.$var.'}, which is not defined in the template (via i18n:name)'); } $value = str_replace($src, $this->_vars[$var], $value); } return $value; }
php
public function translate($key, $htmlencode=true) { if ($this->_canonicalize) $key = self::_canonicalizeKey($key); $value = gettext($key); if ($htmlencode) { $value = htmlspecialchars($value, ENT_QUOTES, $this->_encoding); } while (preg_match('/\${(.*?)\}/sm', $value, $m)) { list($src, $var) = $m; if (!array_key_exists($var, $this->_vars)) { throw new PHPTAL_VariableNotFoundException('Interpolation error. Translation uses ${'.$var.'}, which is not defined in the template (via i18n:name)'); } $value = str_replace($src, $this->_vars[$var], $value); } return $value; }
[ "public", "function", "translate", "(", "$", "key", ",", "$", "htmlencode", "=", "true", ")", "{", "if", "(", "$", "this", "->", "_canonicalize", ")", "$", "key", "=", "self", "::", "_canonicalizeKey", "(", "$", "key", ")", ";", "$", "value", "=", ...
translate given key. @param bool $htmlencode if true, output will be HTML-escaped.
[ "translate", "given", "key", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/GetTextTranslator.php#L143-L160
phptal/PHPTAL
classes/PHPTAL/GetTextTranslator.php
PHPTAL_GetTextTranslator._canonicalizeKey
private static function _canonicalizeKey($key_) { $result = ""; $key_ = trim($key_); $key_ = str_replace("\n", "", $key_); $key_ = str_replace("\r", "", $key_); for ($i = 0; $i<strlen($key_); $i++) { $c = $key_[$i]; $o = ord($c); if ($o < 5 || $o > 127) { $result .= 'C<'.$o.'>'; } else { $result .= $c; } } return $result; }
php
private static function _canonicalizeKey($key_) { $result = ""; $key_ = trim($key_); $key_ = str_replace("\n", "", $key_); $key_ = str_replace("\r", "", $key_); for ($i = 0; $i<strlen($key_); $i++) { $c = $key_[$i]; $o = ord($c); if ($o < 5 || $o > 127) { $result .= 'C<'.$o.'>'; } else { $result .= $c; } } return $result; }
[ "private", "static", "function", "_canonicalizeKey", "(", "$", "key_", ")", "{", "$", "result", "=", "\"\"", ";", "$", "key_", "=", "trim", "(", "$", "key_", ")", ";", "$", "key_", "=", "str_replace", "(", "\"\\n\"", ",", "\"\"", ",", "$", "key_", ...
For backwards compatibility only.
[ "For", "backwards", "compatibility", "only", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/GetTextTranslator.php#L165-L181
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.setDocType
public function setDocType($doctype,$called_from_macro) { // FIXME: this is temporary workaround for problem of DOCTYPE disappearing in cloned PHPTAL object (because clone keeps _parentContext) if (!$this->_docType) { $this->_docType = $doctype; } if ($this->_parentContext) { $this->_parentContext->setDocType($doctype, $called_from_macro); } else if ($this->_echoDeclarations) { if (!$called_from_macro) { echo $doctype; } else { throw new PHPTAL_ConfigurationException("Executed macro in file with DOCTYPE when using echoExecute(). This is not supported yet. Remove DOCTYPE or use PHPTAL->execute()."); } } else if (!$this->_docType) { $this->_docType = $doctype; } }
php
public function setDocType($doctype,$called_from_macro) { // FIXME: this is temporary workaround for problem of DOCTYPE disappearing in cloned PHPTAL object (because clone keeps _parentContext) if (!$this->_docType) { $this->_docType = $doctype; } if ($this->_parentContext) { $this->_parentContext->setDocType($doctype, $called_from_macro); } else if ($this->_echoDeclarations) { if (!$called_from_macro) { echo $doctype; } else { throw new PHPTAL_ConfigurationException("Executed macro in file with DOCTYPE when using echoExecute(). This is not supported yet. Remove DOCTYPE or use PHPTAL->execute()."); } } else if (!$this->_docType) { $this->_docType = $doctype; } }
[ "public", "function", "setDocType", "(", "$", "doctype", ",", "$", "called_from_macro", ")", "{", "// FIXME: this is temporary workaround for problem of DOCTYPE disappearing in cloned PHPTAL object (because clone keeps _parentContext)", "if", "(", "!", "$", "this", "->", "_docTyp...
Set output document type if not already set. This method ensure PHPTAL uses the first DOCTYPE encountered (main template or any macro template source containing a DOCTYPE. @param bool $called_from_macro will do nothing if _echoDeclarations is also set @return void
[ "Set", "output", "document", "type", "if", "not", "already", "set", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L104-L123
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.setXmlDeclaration
public function setXmlDeclaration($xmldec, $called_from_macro) { // FIXME if (!$this->_xmlDeclaration) { $this->_xmlDeclaration = $xmldec; } if ($this->_parentContext) { $this->_parentContext->setXmlDeclaration($xmldec, $called_from_macro); } else if ($this->_echoDeclarations) { if (!$called_from_macro) { echo $xmldec."\n"; } else { throw new PHPTAL_ConfigurationException("Executed macro in file with XML declaration when using echoExecute(). This is not supported yet. Remove XML declaration or use PHPTAL->execute()."); } } else if (!$this->_xmlDeclaration) { $this->_xmlDeclaration = $xmldec; } }
php
public function setXmlDeclaration($xmldec, $called_from_macro) { // FIXME if (!$this->_xmlDeclaration) { $this->_xmlDeclaration = $xmldec; } if ($this->_parentContext) { $this->_parentContext->setXmlDeclaration($xmldec, $called_from_macro); } else if ($this->_echoDeclarations) { if (!$called_from_macro) { echo $xmldec."\n"; } else { throw new PHPTAL_ConfigurationException("Executed macro in file with XML declaration when using echoExecute(). This is not supported yet. Remove XML declaration or use PHPTAL->execute()."); } } else if (!$this->_xmlDeclaration) { $this->_xmlDeclaration = $xmldec; } }
[ "public", "function", "setXmlDeclaration", "(", "$", "xmldec", ",", "$", "called_from_macro", ")", "{", "// FIXME", "if", "(", "!", "$", "this", "->", "_xmlDeclaration", ")", "{", "$", "this", "->", "_xmlDeclaration", "=", "$", "xmldec", ";", "}", "if", ...
Set output document xml declaration. This method ensure PHPTAL uses the first xml declaration encountered (main template or any macro template source containing an xml declaration) @param bool $called_from_macro will do nothing if _echoDeclarations is also set @return void
[ "Set", "output", "document", "xml", "declaration", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L136-L154
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.hasSlot
public function hasSlot($key) { return isset($this->_slots[$key]) || ($this->_parentContext && $this->_parentContext->hasSlot($key)); }
php
public function hasSlot($key) { return isset($this->_slots[$key]) || ($this->_parentContext && $this->_parentContext->hasSlot($key)); }
[ "public", "function", "hasSlot", "(", "$", "key", ")", "{", "return", "isset", "(", "$", "this", "->", "_slots", "[", "$", "key", "]", ")", "||", "(", "$", "this", "->", "_parentContext", "&&", "$", "this", "->", "_parentContext", "->", "hasSlot", "(...
Returns true if specified slot is filled. @return bool
[ "Returns", "true", "if", "specified", "slot", "is", "filled", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L172-L175
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.getSlot
public function getSlot($key) { if (isset($this->_slots[$key])) { if (is_string($this->_slots[$key])) { return $this->_slots[$key]; } ob_start(); call_user_func($this->_slots[$key][0], $this->_slots[$key][1], $this->_slots[$key][2]); return ob_get_clean(); } else if ($this->_parentContext) { return $this->_parentContext->getSlot($key); } }
php
public function getSlot($key) { if (isset($this->_slots[$key])) { if (is_string($this->_slots[$key])) { return $this->_slots[$key]; } ob_start(); call_user_func($this->_slots[$key][0], $this->_slots[$key][1], $this->_slots[$key][2]); return ob_get_clean(); } else if ($this->_parentContext) { return $this->_parentContext->getSlot($key); } }
[ "public", "function", "getSlot", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_slots", "[", "$", "key", "]", ")", ")", "{", "if", "(", "is_string", "(", "$", "this", "->", "_slots", "[", "$", "key", "]", ")", ")", "...
Returns the content of specified filled slot. Use echoSlot() whenever you just want to output the slot @return string
[ "Returns", "the", "content", "of", "specified", "filled", "slot", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L184-L196
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.echoSlot
public function echoSlot($key) { if (isset($this->_slots[$key])) { if (is_string($this->_slots[$key])) { echo $this->_slots[$key]; } else { call_user_func($this->_slots[$key][0], $this->_slots[$key][1], $this->_slots[$key][2]); } } else if ($this->_parentContext) { return $this->_parentContext->echoSlot($key); } }
php
public function echoSlot($key) { if (isset($this->_slots[$key])) { if (is_string($this->_slots[$key])) { echo $this->_slots[$key]; } else { call_user_func($this->_slots[$key][0], $this->_slots[$key][1], $this->_slots[$key][2]); } } else if ($this->_parentContext) { return $this->_parentContext->echoSlot($key); } }
[ "public", "function", "echoSlot", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_slots", "[", "$", "key", "]", ")", ")", "{", "if", "(", "is_string", "(", "$", "this", "->", "_slots", "[", "$", "key", "]", ")", ")", ...
Immediately echoes content of specified filled slot. Equivalent of echo $this->getSlot(); @return string
[ "Immediately", "echoes", "content", "of", "specified", "filled", "slot", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L205-L216
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.fillSlot
public function fillSlot($key, $content) { $this->_slots[$key] = $content; if ($this->_parentContext) { // Works around bug with tal:define popping context after fillslot $this->_parentContext->_slots[$key] = $content; } }
php
public function fillSlot($key, $content) { $this->_slots[$key] = $content; if ($this->_parentContext) { // Works around bug with tal:define popping context after fillslot $this->_parentContext->_slots[$key] = $content; } }
[ "public", "function", "fillSlot", "(", "$", "key", ",", "$", "content", ")", "{", "$", "this", "->", "_slots", "[", "$", "key", "]", "=", "$", "content", ";", "if", "(", "$", "this", "->", "_parentContext", ")", "{", "// Works around bug with tal:define ...
Fill a macro slot. @return void
[ "Fill", "a", "macro", "slot", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L223-L230
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.pathError
private static function pathError($base, $path, $current, $basename) { if ($current !== $path) { $pathinfo = " (in path '.../$path')"; } else $pathinfo = ''; if (!empty($basename)) { $basename = "'" . $basename . "' "; } if (is_array($base)) { throw new PHPTAL_VariableNotFoundException("Array {$basename}doesn't have key named '$current'$pathinfo"); } if (is_object($base)) { throw new PHPTAL_VariableNotFoundException(ucfirst(get_class($base))." object {$basename}doesn't have method/property named '$current'$pathinfo"); } throw new PHPTAL_VariableNotFoundException(trim("Attempt to read property '$current'$pathinfo from ".gettype($base)." value {$basename}")); }
php
private static function pathError($base, $path, $current, $basename) { if ($current !== $path) { $pathinfo = " (in path '.../$path')"; } else $pathinfo = ''; if (!empty($basename)) { $basename = "'" . $basename . "' "; } if (is_array($base)) { throw new PHPTAL_VariableNotFoundException("Array {$basename}doesn't have key named '$current'$pathinfo"); } if (is_object($base)) { throw new PHPTAL_VariableNotFoundException(ucfirst(get_class($base))." object {$basename}doesn't have method/property named '$current'$pathinfo"); } throw new PHPTAL_VariableNotFoundException(trim("Attempt to read property '$current'$pathinfo from ".gettype($base)." value {$basename}")); }
[ "private", "static", "function", "pathError", "(", "$", "base", ",", "$", "path", ",", "$", "current", ",", "$", "basename", ")", "{", "if", "(", "$", "current", "!==", "$", "path", ")", "{", "$", "pathinfo", "=", "\" (in path '.../$path')\"", ";", "}"...
helper method for PHPTAL_Context::path() @access private
[ "helper", "method", "for", "PHPTAL_Context", "::", "path", "()" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L316-L333
phptal/PHPTAL
classes/PHPTAL/Context.php
PHPTAL_Context.path
public static function path($base, $path, $nothrow=false) { if ($base === null) { if ($nothrow) return null; PHPTAL_Context::pathError($base, $path, $path, $path); } $chunks = explode('/', $path); $current = null; $prev = null; for ($i = 0; $i < count($chunks); $i++) { if ($current != $chunks[$i]) { // if not $i-- before continue; $prev = $current; $current = $chunks[$i]; } // object handling if (is_object($base)) { // look for method. Both method_exists and is_callable are required because of __call() and protected methods if (method_exists($base, $current) && is_callable(array($base, $current))) { $base = $base->$current(); continue; } // look for property if (property_exists($base, $current)) { $base = $base->$current; continue; } if ($base instanceof ArrayAccess && $base->offsetExists($current)) { $base = $base->offsetGet($current); continue; } if (($current === 'length' || $current === 'size') && $base instanceof Countable) { $base = count($base); continue; } // look for isset (priority over __get) if (method_exists($base, '__isset')) { if ($base->__isset($current)) { $base = $base->$current; continue; } } // ask __get and discard if it returns null elseif (method_exists($base, '__get')) { $tmp = $base->$current; if (null !== $tmp) { $base = $tmp; continue; } } // magic method call if (method_exists($base, '__call')) { try { $base = $base->__call($current, array()); continue; } catch(BadMethodCallException $e) {} } if (is_callable($base)) { $base = phptal_unravel_closure($base); $i--; continue; } if ($nothrow) { return null; } PHPTAL_Context::pathError($base, $path, $current, $prev); } // array handling if (is_array($base)) { // key or index if (array_key_exists((string)$current, $base)) { $base = $base[$current]; continue; } // virtual methods provided by phptal if ($current == 'length' || $current == 'size') { $base = count($base); continue; } if ($nothrow) return null; PHPTAL_Context::pathError($base, $path, $current, $prev); } // string handling if (is_string($base)) { // virtual methods provided by phptal if ($current == 'length' || $current == 'size') { $base = strlen($base); continue; } // access char at index if (is_numeric($current)) { $base = $base[$current]; continue; } } // if this point is reached, then the part cannot be resolved if ($nothrow) return null; PHPTAL_Context::pathError($base, $path, $current, $prev); } return $base; }
php
public static function path($base, $path, $nothrow=false) { if ($base === null) { if ($nothrow) return null; PHPTAL_Context::pathError($base, $path, $path, $path); } $chunks = explode('/', $path); $current = null; $prev = null; for ($i = 0; $i < count($chunks); $i++) { if ($current != $chunks[$i]) { // if not $i-- before continue; $prev = $current; $current = $chunks[$i]; } // object handling if (is_object($base)) { // look for method. Both method_exists and is_callable are required because of __call() and protected methods if (method_exists($base, $current) && is_callable(array($base, $current))) { $base = $base->$current(); continue; } // look for property if (property_exists($base, $current)) { $base = $base->$current; continue; } if ($base instanceof ArrayAccess && $base->offsetExists($current)) { $base = $base->offsetGet($current); continue; } if (($current === 'length' || $current === 'size') && $base instanceof Countable) { $base = count($base); continue; } // look for isset (priority over __get) if (method_exists($base, '__isset')) { if ($base->__isset($current)) { $base = $base->$current; continue; } } // ask __get and discard if it returns null elseif (method_exists($base, '__get')) { $tmp = $base->$current; if (null !== $tmp) { $base = $tmp; continue; } } // magic method call if (method_exists($base, '__call')) { try { $base = $base->__call($current, array()); continue; } catch(BadMethodCallException $e) {} } if (is_callable($base)) { $base = phptal_unravel_closure($base); $i--; continue; } if ($nothrow) { return null; } PHPTAL_Context::pathError($base, $path, $current, $prev); } // array handling if (is_array($base)) { // key or index if (array_key_exists((string)$current, $base)) { $base = $base[$current]; continue; } // virtual methods provided by phptal if ($current == 'length' || $current == 'size') { $base = count($base); continue; } if ($nothrow) return null; PHPTAL_Context::pathError($base, $path, $current, $prev); } // string handling if (is_string($base)) { // virtual methods provided by phptal if ($current == 'length' || $current == 'size') { $base = strlen($base); continue; } // access char at index if (is_numeric($current)) { $base = $base[$current]; continue; } } // if this point is reached, then the part cannot be resolved if ($nothrow) return null; PHPTAL_Context::pathError($base, $path, $current, $prev); } return $base; }
[ "public", "static", "function", "path", "(", "$", "base", ",", "$", "path", ",", "$", "nothrow", "=", "false", ")", "{", "if", "(", "$", "base", "===", "null", ")", "{", "if", "(", "$", "nothrow", ")", "return", "null", ";", "PHPTAL_Context", "::",...
Resolve TALES path starting from the first path element. The TALES path : object/method1/10/method2 will call : $ctx->path($ctx->object, 'method1/10/method2') This function is very important for PHPTAL performance. This function will become non-static in the future @param mixed $base first element of the path ($ctx) @param string $path rest of the path @param bool $nothrow is used by phptal_exists(). Prevents this function from throwing an exception when a part of the path cannot be resolved, null is returned instead. @access private @return mixed
[ "Resolve", "TALES", "path", "starting", "from", "the", "first", "path", "element", ".", "The", "TALES", "path", ":", "object", "/", "method1", "/", "10", "/", "method2", "will", "call", ":", "$ctx", "-", ">", "path", "(", "$ctx", "-", ">", "object", ...
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Context.php#L353-L477
phptal/PHPTAL
classes/PHPTAL/Dom/Defs.php
PHPTAL_Dom_Defs.isEmptyTagNS
public function isEmptyTagNS($namespace_uri, $local_name) { return ($namespace_uri === 'http://www.w3.org/1999/xhtml' || $namespace_uri === '') && in_array(strtolower($local_name), self::$XHTML_EMPTY_TAGS); }
php
public function isEmptyTagNS($namespace_uri, $local_name) { return ($namespace_uri === 'http://www.w3.org/1999/xhtml' || $namespace_uri === '') && in_array(strtolower($local_name), self::$XHTML_EMPTY_TAGS); }
[ "public", "function", "isEmptyTagNS", "(", "$", "namespace_uri", ",", "$", "local_name", ")", "{", "return", "(", "$", "namespace_uri", "===", "'http://www.w3.org/1999/xhtml'", "||", "$", "namespace_uri", "===", "''", ")", "&&", "in_array", "(", "strtolower", "(...
true if it's empty in XHTML (e.g. <img/>) it will assume elements with no namespace may be XHTML too. @param string $tagName local name of the tag @return bool
[ "true", "if", "it", "s", "empty", "in", "XHTML", "(", "e", ".", "g", ".", "<img", "/", ">", ")", "it", "will", "assume", "elements", "with", "no", "namespace", "may", "be", "XHTML", "too", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Defs.php#L59-L63
phptal/PHPTAL
classes/PHPTAL/Dom/Defs.php
PHPTAL_Dom_Defs.prefixToNamespaceURI
public function prefixToNamespaceURI($prefix) { return isset($this->prefix_to_uri[$prefix]) ? $this->prefix_to_uri[$prefix] : false; }
php
public function prefixToNamespaceURI($prefix) { return isset($this->prefix_to_uri[$prefix]) ? $this->prefix_to_uri[$prefix] : false; }
[ "public", "function", "prefixToNamespaceURI", "(", "$", "prefix", ")", "{", "return", "isset", "(", "$", "this", "->", "prefix_to_uri", "[", "$", "prefix", "]", ")", "?", "$", "this", "->", "prefix_to_uri", "[", "$", "prefix", "]", ":", "false", ";", "...
gives namespace URI for given registered (built-in) prefix
[ "gives", "namespace", "URI", "for", "given", "registered", "(", "built", "-", "in", ")", "prefix" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Defs.php#L68-L71
phptal/PHPTAL
classes/PHPTAL/Dom/Defs.php
PHPTAL_Dom_Defs.isValidAttributeNS
public function isValidAttributeNS($namespace_uri, $local_name) { if (!$this->isHandledNamespace($namespace_uri)) return false; $attrs = $this->namespaces_by_uri[$namespace_uri]->getAttributes(); return isset($attrs[$local_name]); }
php
public function isValidAttributeNS($namespace_uri, $local_name) { if (!$this->isHandledNamespace($namespace_uri)) return false; $attrs = $this->namespaces_by_uri[$namespace_uri]->getAttributes(); return isset($attrs[$local_name]); }
[ "public", "function", "isValidAttributeNS", "(", "$", "namespace_uri", ",", "$", "local_name", ")", "{", "if", "(", "!", "$", "this", "->", "isHandledNamespace", "(", "$", "namespace_uri", ")", ")", "return", "false", ";", "$", "attrs", "=", "$", "this", ...
Returns true if the attribute is a valid phptal attribute Examples of valid attributes: tal:content, metal:use-slot Examples of invalid attributes: tal:unknown, metal:content @return bool
[ "Returns", "true", "if", "the", "attribute", "is", "a", "valid", "phptal", "attribute" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Defs.php#L120-L126
phptal/PHPTAL
classes/PHPTAL/Dom/Defs.php
PHPTAL_Dom_Defs.getNamespaceAttribute
public function getNamespaceAttribute($namespace_uri, $local_name) { $attrs = $this->namespaces_by_uri[$namespace_uri]->getAttributes(); return $attrs[$local_name]; }
php
public function getNamespaceAttribute($namespace_uri, $local_name) { $attrs = $this->namespaces_by_uri[$namespace_uri]->getAttributes(); return $attrs[$local_name]; }
[ "public", "function", "getNamespaceAttribute", "(", "$", "namespace_uri", ",", "$", "local_name", ")", "{", "$", "attrs", "=", "$", "this", "->", "namespaces_by_uri", "[", "$", "namespace_uri", "]", "->", "getAttributes", "(", ")", ";", "return", "$", "attrs...
return objects that holds information about given TAL attribute
[ "return", "objects", "that", "holds", "information", "about", "given", "TAL", "attribute" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Defs.php#L152-L156
phptal/PHPTAL
classes/PHPTAL/Dom/Defs.php
PHPTAL_Dom_Defs.registerNamespace
public function registerNamespace(PHPTAL_Namespace $ns) { $this->namespaces_by_uri[$ns->getNamespaceURI()] = $ns; $this->prefix_to_uri[$ns->getPrefix()] = $ns->getNamespaceURI(); $prefix = strtolower($ns->getPrefix()); foreach ($ns->getAttributes() as $name => $attribute) { $key = $prefix.':'.strtolower($name); $this->_dictionary[$key] = $attribute; } }
php
public function registerNamespace(PHPTAL_Namespace $ns) { $this->namespaces_by_uri[$ns->getNamespaceURI()] = $ns; $this->prefix_to_uri[$ns->getPrefix()] = $ns->getNamespaceURI(); $prefix = strtolower($ns->getPrefix()); foreach ($ns->getAttributes() as $name => $attribute) { $key = $prefix.':'.strtolower($name); $this->_dictionary[$key] = $attribute; } }
[ "public", "function", "registerNamespace", "(", "PHPTAL_Namespace", "$", "ns", ")", "{", "$", "this", "->", "namespaces_by_uri", "[", "$", "ns", "->", "getNamespaceURI", "(", ")", "]", "=", "$", "ns", ";", "$", "this", "->", "prefix_to_uri", "[", "$", "n...
Register a PHPTAL_Namespace and its attribute into PHPTAL.
[ "Register", "a", "PHPTAL_Namespace", "and", "its", "attribute", "into", "PHPTAL", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/Defs.php#L161-L170
phptal/PHPTAL
classes/PHPTAL/Dom/PHPTALDocumentBuilder.php
PHPTAL_Dom_PHPTALDocumentBuilder.onDocumentStart
public function onDocumentStart() { $this->documentElement = new PHPTAL_Dom_Element('documentElement', 'http://xml.zope.org/namespaces/tal', array(), $this->getXmlnsState()); $this->documentElement->setSource($this->file, $this->line); $this->_current = $this->documentElement; }
php
public function onDocumentStart() { $this->documentElement = new PHPTAL_Dom_Element('documentElement', 'http://xml.zope.org/namespaces/tal', array(), $this->getXmlnsState()); $this->documentElement->setSource($this->file, $this->line); $this->_current = $this->documentElement; }
[ "public", "function", "onDocumentStart", "(", ")", "{", "$", "this", "->", "documentElement", "=", "new", "PHPTAL_Dom_Element", "(", "'documentElement'", ",", "'http://xml.zope.org/namespaces/tal'", ",", "array", "(", ")", ",", "$", "this", "->", "getXmlnsState", ...
~~~~~ XmlParser implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[ "~~~~~", "XmlParser", "implementation", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/PHPTALDocumentBuilder.php#L45-L50
phptal/PHPTAL
classes/PHPTAL/TalesRegistry.php
PHPTAL_TalesRegistry.getCallback
public function getCallback($prefix) { if ($this->isRegistered($prefix) && !$this->_callbacks[$prefix]['is_fallback']) { return $this->_callbacks[$prefix]['callback']; } if ($callback = $this->findUnregisteredCallback($prefix)) { return $callback; } if ($this->isRegistered($prefix)) { return $this->_callbacks[$prefix]['callback']; } return null; }
php
public function getCallback($prefix) { if ($this->isRegistered($prefix) && !$this->_callbacks[$prefix]['is_fallback']) { return $this->_callbacks[$prefix]['callback']; } if ($callback = $this->findUnregisteredCallback($prefix)) { return $callback; } if ($this->isRegistered($prefix)) { return $this->_callbacks[$prefix]['callback']; } return null; }
[ "public", "function", "getCallback", "(", "$", "prefix", ")", "{", "if", "(", "$", "this", "->", "isRegistered", "(", "$", "prefix", ")", "&&", "!", "$", "this", "->", "_callbacks", "[", "$", "prefix", "]", "[", "'is_fallback'", "]", ")", "{", "retur...
get callback for the prefix @return callback or NULL
[ "get", "callback", "for", "the", "prefix" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/TalesRegistry.php#L163-L178
phptal/PHPTAL
classes/PHPTAL/PreFilter/Compress.php
PHPTAL_PreFilter_Compress.normalizeAttributes
protected function normalizeAttributes(PHPTAL_Dom_Element $element) { parent::normalizeAttributes($element); $attrs_by_qname = array(); foreach ($element->getAttributeNodes() as $attrnode) { // safe, as there can't be two attrs with same qname $attrs_by_qname[$attrnode->getQualifiedName()] = $attrnode; } if (count($attrs_by_qname) > 1) { uksort($attrs_by_qname, array($this, 'compareQNames')); $element->setAttributeNodes(array_values($attrs_by_qname)); } }
php
protected function normalizeAttributes(PHPTAL_Dom_Element $element) { parent::normalizeAttributes($element); $attrs_by_qname = array(); foreach ($element->getAttributeNodes() as $attrnode) { // safe, as there can't be two attrs with same qname $attrs_by_qname[$attrnode->getQualifiedName()] = $attrnode; } if (count($attrs_by_qname) > 1) { uksort($attrs_by_qname, array($this, 'compareQNames')); $element->setAttributeNodes(array_values($attrs_by_qname)); } }
[ "protected", "function", "normalizeAttributes", "(", "PHPTAL_Dom_Element", "$", "element", ")", "{", "parent", "::", "normalizeAttributes", "(", "$", "element", ")", ";", "$", "attrs_by_qname", "=", "array", "(", ")", ";", "foreach", "(", "$", "element", "->",...
Consistent sorting of attributes might give slightly better gzip performance
[ "Consistent", "sorting", "of", "attributes", "might", "give", "slightly", "better", "gzip", "performance" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/PreFilter/Compress.php#L202-L216
phptal/PHPTAL
classes/PHPTAL/PreFilter/Compress.php
PHPTAL_PreFilter_Compress.compareQNames
private static function compareQNames($a, $b) { $a_index = array_search($a, self::$attributes_order); $b_index = array_search($b, self::$attributes_order); if ($a_index !== false && $b_index !== false) { return $a_index - $b_index; } if ($a_index === false && $b_index === false) { return strcmp($a, $b); } return ($a_index === false) ? 1 : -1; }
php
private static function compareQNames($a, $b) { $a_index = array_search($a, self::$attributes_order); $b_index = array_search($b, self::$attributes_order); if ($a_index !== false && $b_index !== false) { return $a_index - $b_index; } if ($a_index === false && $b_index === false) { return strcmp($a, $b); } return ($a_index === false) ? 1 : -1; }
[ "private", "static", "function", "compareQNames", "(", "$", "a", ",", "$", "b", ")", "{", "$", "a_index", "=", "array_search", "(", "$", "a", ",", "self", "::", "$", "attributes_order", ")", ";", "$", "b_index", "=", "array_search", "(", "$", "b", ",...
compare names according to $attributes_order array. Elements that are not in array, are considered greater than all elements in array, and are sorted alphabetically.
[ "compare", "names", "according", "to", "$attributes_order", "array", ".", "Elements", "that", "are", "not", "in", "array", "are", "considered", "greater", "than", "all", "elements", "in", "array", "and", "are", "sorted", "alphabetically", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/PreFilter/Compress.php#L230-L241
phptal/PHPTAL
classes/PHPTAL/PreFilter/Compress.php
PHPTAL_PreFilter_Compress.elementSpecificOptimizations
private function elementSpecificOptimizations(PHPTAL_Dom_Element $element) { if ($element->getNamespaceURI() !== 'http://www.w3.org/1999/xhtml' && $element->getNamespaceURI() !== '') { return; } if ($this->getPHPTAL()->getOutputMode() !== PHPTAL::HTML5) { return; } // <meta charset> if ('meta' === $element->getLocalName() && $element->getAttributeNS('','http-equiv') === 'Content-Type') { $element->removeAttributeNS('','http-equiv'); $element->removeAttributeNS('','content'); $element->setAttributeNS('','charset',strtolower($this->getPHPTAL()->getEncoding())); } elseif (('link' === $element->getLocalName() && $element->getAttributeNS('','rel') === 'stylesheet') || ('style' === $element->getLocalName())) { // There's only one type of stylesheets that works. $element->removeAttributeNS('','type'); } elseif ('script' === $element->getLocalName()) { $element->removeAttributeNS('','language'); // Only remove type that matches default. E4X, vbscript, coffeescript, etc. must be preserved $type = $element->getAttributeNS('','type'); $is_std = preg_match('/^(?:text|application)\/(?:ecma|java)script(\s*;\s*charset\s*=\s*[^;]*)?$/', $type); // Remote scripts should have type specified in HTTP headers. if ($is_std || $element->getAttributeNS('','src')) { $element->removeAttributeNS('','type'); } } }
php
private function elementSpecificOptimizations(PHPTAL_Dom_Element $element) { if ($element->getNamespaceURI() !== 'http://www.w3.org/1999/xhtml' && $element->getNamespaceURI() !== '') { return; } if ($this->getPHPTAL()->getOutputMode() !== PHPTAL::HTML5) { return; } // <meta charset> if ('meta' === $element->getLocalName() && $element->getAttributeNS('','http-equiv') === 'Content-Type') { $element->removeAttributeNS('','http-equiv'); $element->removeAttributeNS('','content'); $element->setAttributeNS('','charset',strtolower($this->getPHPTAL()->getEncoding())); } elseif (('link' === $element->getLocalName() && $element->getAttributeNS('','rel') === 'stylesheet') || ('style' === $element->getLocalName())) { // There's only one type of stylesheets that works. $element->removeAttributeNS('','type'); } elseif ('script' === $element->getLocalName()) { $element->removeAttributeNS('','language'); // Only remove type that matches default. E4X, vbscript, coffeescript, etc. must be preserved $type = $element->getAttributeNS('','type'); $is_std = preg_match('/^(?:text|application)\/(?:ecma|java)script(\s*;\s*charset\s*=\s*[^;]*)?$/', $type); // Remote scripts should have type specified in HTTP headers. if ($is_std || $element->getAttributeNS('','src')) { $element->removeAttributeNS('','type'); } } }
[ "private", "function", "elementSpecificOptimizations", "(", "PHPTAL_Dom_Element", "$", "element", ")", "{", "if", "(", "$", "element", "->", "getNamespaceURI", "(", ")", "!==", "'http://www.w3.org/1999/xhtml'", "&&", "$", "element", "->", "getNamespaceURI", "(", ")"...
HTML5 doesn't care about boilerplate
[ "HTML5", "doesn", "t", "care", "about", "boilerplate" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/PreFilter/Compress.php#L246-L281
phptal/PHPTAL
classes/PHPTAL/Php/TalesInternal.php
PHPTAL_Php_TalesInternal.path
static public function path($expression, $nothrow=false) { $expression = trim($expression); if ($expression == 'default') return self::DEFAULT_KEYWORD; if ($expression == 'nothing') return self::NOTHING_KEYWORD; if ($expression == '') return self::NOTHING_KEYWORD; // split OR expressions terminated by a string if (preg_match('/^(.*?)\s*\|\s*?(string:.*)$/sm', $expression, $m)) { list(, $expression, $string) = $m; } // split OR expressions terminated by a 'fast' string elseif (preg_match('/^(.*?)\s*\|\s*\'((?:[^\'\\\\]|\\\\.)*)\'\s*$/sm', $expression, $m)) { list(, $expression, $string) = $m; $string = 'string:'.stripslashes($string); } // split OR expressions $exps = preg_split('/\s*\|\s*/sm', $expression); // if (many expressions) or (expressions or terminating string) found then // generate the array of sub expressions and return it. if (count($exps) > 1 || isset($string)) { $result = array(); foreach ($exps as $i=>$exp) { if(isset($string) || $i < count($exps) - 1) { $result[] = self::compileToPHPExpressions(trim($exp), true); } else { // the last expression can thorw exception. $result[] = self::compileToPHPExpressions(trim($exp), false); } } if (isset($string)) { $result[] = self::compileToPHPExpressions($string, true); } return $result; } // see if there are subexpressions, but skip interpolated parts, i.e. ${a/b}/c is 2 parts if (preg_match('/^((?:[^$\/]+|\$\$|\${[^}]+}|\$))\/(.+)$/s', $expression, $m)) { if (!self::checkExpressionPart($m[1])) { throw new PHPTAL_ParserException("Invalid TALES path: '$expression', expected '{$m[1]}' to be variable name"); } $next = self::string($m[1]); $expression = self::string($m[2]); } else { if (!self::checkExpressionPart($expression)) { throw new PHPTAL_ParserException("Invalid TALES path: '$expression', expected variable name. Complex expressions need php: modifier."); } $next = self::string($expression); $expression = null; } if ($nothrow) { return '$ctx->path($ctx, ' . $next . ($expression === null ? '' : '."/".'.$expression) . ', true)'; } if (preg_match('/^\'[a-z][a-z0-9_]*\'$/i', $next)) $next = substr($next, 1, -1); else $next = '{'.$next.'}'; // if no sub part for this expression, just optimize the generated code // and access the $ctx->var if ($expression === null) { return '$ctx->'.$next; } // otherwise we have to call PHPTAL_Context::path() to resolve the path at runtime // extract the first part of the expression (it will be the PHPTAL_Context::path() // $base and pass the remaining of the path to PHPTAL_Context::path() return '$ctx->path($ctx->'.$next.', '.$expression.')'; }
php
static public function path($expression, $nothrow=false) { $expression = trim($expression); if ($expression == 'default') return self::DEFAULT_KEYWORD; if ($expression == 'nothing') return self::NOTHING_KEYWORD; if ($expression == '') return self::NOTHING_KEYWORD; // split OR expressions terminated by a string if (preg_match('/^(.*?)\s*\|\s*?(string:.*)$/sm', $expression, $m)) { list(, $expression, $string) = $m; } // split OR expressions terminated by a 'fast' string elseif (preg_match('/^(.*?)\s*\|\s*\'((?:[^\'\\\\]|\\\\.)*)\'\s*$/sm', $expression, $m)) { list(, $expression, $string) = $m; $string = 'string:'.stripslashes($string); } // split OR expressions $exps = preg_split('/\s*\|\s*/sm', $expression); // if (many expressions) or (expressions or terminating string) found then // generate the array of sub expressions and return it. if (count($exps) > 1 || isset($string)) { $result = array(); foreach ($exps as $i=>$exp) { if(isset($string) || $i < count($exps) - 1) { $result[] = self::compileToPHPExpressions(trim($exp), true); } else { // the last expression can thorw exception. $result[] = self::compileToPHPExpressions(trim($exp), false); } } if (isset($string)) { $result[] = self::compileToPHPExpressions($string, true); } return $result; } // see if there are subexpressions, but skip interpolated parts, i.e. ${a/b}/c is 2 parts if (preg_match('/^((?:[^$\/]+|\$\$|\${[^}]+}|\$))\/(.+)$/s', $expression, $m)) { if (!self::checkExpressionPart($m[1])) { throw new PHPTAL_ParserException("Invalid TALES path: '$expression', expected '{$m[1]}' to be variable name"); } $next = self::string($m[1]); $expression = self::string($m[2]); } else { if (!self::checkExpressionPart($expression)) { throw new PHPTAL_ParserException("Invalid TALES path: '$expression', expected variable name. Complex expressions need php: modifier."); } $next = self::string($expression); $expression = null; } if ($nothrow) { return '$ctx->path($ctx, ' . $next . ($expression === null ? '' : '."/".'.$expression) . ', true)'; } if (preg_match('/^\'[a-z][a-z0-9_]*\'$/i', $next)) $next = substr($next, 1, -1); else $next = '{'.$next.'}'; // if no sub part for this expression, just optimize the generated code // and access the $ctx->var if ($expression === null) { return '$ctx->'.$next; } // otherwise we have to call PHPTAL_Context::path() to resolve the path at runtime // extract the first part of the expression (it will be the PHPTAL_Context::path() // $base and pass the remaining of the path to PHPTAL_Context::path() return '$ctx->path($ctx->'.$next.', '.$expression.')'; }
[ "static", "public", "function", "path", "(", "$", "expression", ",", "$", "nothrow", "=", "false", ")", "{", "$", "expression", "=", "trim", "(", "$", "expression", ")", ";", "if", "(", "$", "expression", "==", "'default'", ")", "return", "self", "::",...
path: PathExpr ::= Path [ '|' Path ]* Path ::= variable [ '/' URL_Segment ]* variable ::= Name Examples: path: username path: user/name path: object/method/10/method/member path: object/${dynamicmembername}/method path: maybethis | path: maybethat | path: default PHPTAL: 'default' may lead to some 'difficult' attributes implementation For example, the tal:content will have to insert php code like: if (isset($ctx->maybethis)) { echo $ctx->maybethis; } elseif (isset($ctx->maybethat) { echo $ctx->maybethat; } else { // process default tag content } @returns string or array
[ "path", ":" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/TalesInternal.php#L124-L198
phptal/PHPTAL
classes/PHPTAL/Php/TalesInternal.php
PHPTAL_Php_TalesInternal.phptal_internal_php_block
static public function phptal_internal_php_block($src) { $src = rawurldecode($src); // Simple echo can be supported via regular method if (preg_match('/^\s*echo\s+((?:[^;]+|"[^"\\\\]*"|\'[^\'\\\\]*\'|\/\*.*?\*\/)+);*\s*$/s',$src,$m)) { return $m[1]; } // <?php block expects statements, but modifiers must return expressions. // unfortunately this ugliness is the only way to support it currently. // ? > keeps semicolon optional return "eval(".self::string($src.'?>').")"; }
php
static public function phptal_internal_php_block($src) { $src = rawurldecode($src); // Simple echo can be supported via regular method if (preg_match('/^\s*echo\s+((?:[^;]+|"[^"\\\\]*"|\'[^\'\\\\]*\'|\/\*.*?\*\/)+);*\s*$/s',$src,$m)) { return $m[1]; } // <?php block expects statements, but modifiers must return expressions. // unfortunately this ugliness is the only way to support it currently. // ? > keeps semicolon optional return "eval(".self::string($src.'?>').")"; }
[ "static", "public", "function", "phptal_internal_php_block", "(", "$", "src", ")", "{", "$", "src", "=", "rawurldecode", "(", "$", "src", ")", ";", "// Simple echo can be supported via regular method", "if", "(", "preg_match", "(", "'/^\\s*echo\\s+((?:[^;]+|\"[^\"\\\\\\...
phptal-internal-php-block: modifier for emulation of <?php ?> in attributes. Please don't use it in the templates!
[ "phptal", "-", "internal", "-", "php", "-", "block", ":", "modifier", "for", "emulation", "of", "<?php", "?", ">", "in", "attributes", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/TalesInternal.php#L363-L377
phptal/PHPTAL
classes/PHPTAL/Php/TalesInternal.php
PHPTAL_Php_TalesInternal.exists
static public function exists($src, $nothrow) { $src = trim($src); if (ctype_alnum($src)) return 'isset($ctx->'.$src.')'; return '(null !== ' . self::compileToPHPExpression($src, true) . ')'; }
php
static public function exists($src, $nothrow) { $src = trim($src); if (ctype_alnum($src)) return 'isset($ctx->'.$src.')'; return '(null !== ' . self::compileToPHPExpression($src, true) . ')'; }
[ "static", "public", "function", "exists", "(", "$", "src", ",", "$", "nothrow", ")", "{", "$", "src", "=", "trim", "(", "$", "src", ")", ";", "if", "(", "ctype_alnum", "(", "$", "src", ")", ")", "return", "'isset($ctx->'", ".", "$", "src", ".", "...
exists: modifier. Returns the code required to invoke Context::exists() on specified path.
[ "exists", ":", "modifier", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/TalesInternal.php#L384-L389
phptal/PHPTAL
classes/PHPTAL/Php/TalesInternal.php
PHPTAL_Php_TalesInternal.compileToPHPExpression
public static function compileToPHPExpression($expression, $nothrow=false) { $r = self::compileToPHPExpressions($expression, $nothrow); if (!is_array($r)) return $r; // this weird ternary operator construct is to execute noThrow inside the expression return '($ctx->noThrow(true)||1?'.self::convertExpressionsToExpression($r, $nothrow).':"")'; }
php
public static function compileToPHPExpression($expression, $nothrow=false) { $r = self::compileToPHPExpressions($expression, $nothrow); if (!is_array($r)) return $r; // this weird ternary operator construct is to execute noThrow inside the expression return '($ctx->noThrow(true)||1?'.self::convertExpressionsToExpression($r, $nothrow).':"")'; }
[ "public", "static", "function", "compileToPHPExpression", "(", "$", "expression", ",", "$", "nothrow", "=", "false", ")", "{", "$", "r", "=", "self", "::", "compileToPHPExpressions", "(", "$", "expression", ",", "$", "nothrow", ")", ";", "if", "(", "!", ...
translates TALES expression with alternatives into single PHP expression. Identical to compileToPHPExpressions() for singular expressions. @see PHPTAL_Php_TalesInternal::compileToPHPExpressions() @return string
[ "translates", "TALES", "expression", "with", "alternatives", "into", "single", "PHP", "expression", ".", "Identical", "to", "compileToPHPExpressions", "()", "for", "singular", "expressions", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/TalesInternal.php#L425-L432
phptal/PHPTAL
classes/PHPTAL/Php/TalesInternal.php
PHPTAL_Php_TalesInternal.convertExpressionsToExpression
private static function convertExpressionsToExpression(array $array, $nothrow) { if (count($array)==1) return '($ctx->noThrow('.($nothrow?'true':'false').')||1?('. ($array[0]==self::NOTHING_KEYWORD?'null':$array[0]). '):"")'; $expr = array_shift($array); return "(!phptal_isempty(\$_tmp5=$expr) && (\$ctx->noThrow(false)||1)?\$_tmp5:".self::convertExpressionsToExpression($array, $nothrow).')'; }
php
private static function convertExpressionsToExpression(array $array, $nothrow) { if (count($array)==1) return '($ctx->noThrow('.($nothrow?'true':'false').')||1?('. ($array[0]==self::NOTHING_KEYWORD?'null':$array[0]). '):"")'; $expr = array_shift($array); return "(!phptal_isempty(\$_tmp5=$expr) && (\$ctx->noThrow(false)||1)?\$_tmp5:".self::convertExpressionsToExpression($array, $nothrow).')'; }
[ "private", "static", "function", "convertExpressionsToExpression", "(", "array", "$", "array", ",", "$", "nothrow", ")", "{", "if", "(", "count", "(", "$", "array", ")", "==", "1", ")", "return", "'($ctx->noThrow('", ".", "(", "$", "nothrow", "?", "'true'"...
/* helper function for compileToPHPExpression @access private
[ "/", "*", "helper", "function", "for", "compileToPHPExpression" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/TalesInternal.php#L438-L447
phptal/PHPTAL
classes/PHPTAL/Php/TalesInternal.php
PHPTAL_Php_TalesInternal.compileToPHPExpressions
public static function compileToPHPExpressions($expression, $nothrow=false) { $expression = trim($expression); // Look for tales modifier (string:, exists:, Namespaced\Tale:, etc...) if (preg_match('/^([a-z](?:[a-z0-9._\\\\-]*[a-z0-9])?):(.*)$/si', $expression, $m)) { list(, $typePrefix, $expression) = $m; } // may be a 'string' elseif (preg_match('/^\'((?:[^\']|\\\\.)*)\'$/s', $expression, $m)) { $expression = stripslashes($m[1]); $typePrefix = 'string'; } // failback to path: else { $typePrefix = 'path'; } // is a registered TALES expression modifier $callback = PHPTAL_TalesRegistry::getInstance()->getCallback($typePrefix); if ($callback !== NULL) { $result = call_user_func($callback, $expression, $nothrow); self::verifyPHPExpressions($typePrefix, $result); return $result; } $func = 'phptal_tales_'.str_replace('-', '_', $typePrefix); throw new PHPTAL_UnknownModifierException("Unknown phptal modifier '$typePrefix'. Function '$func' does not exist", $typePrefix); }
php
public static function compileToPHPExpressions($expression, $nothrow=false) { $expression = trim($expression); // Look for tales modifier (string:, exists:, Namespaced\Tale:, etc...) if (preg_match('/^([a-z](?:[a-z0-9._\\\\-]*[a-z0-9])?):(.*)$/si', $expression, $m)) { list(, $typePrefix, $expression) = $m; } // may be a 'string' elseif (preg_match('/^\'((?:[^\']|\\\\.)*)\'$/s', $expression, $m)) { $expression = stripslashes($m[1]); $typePrefix = 'string'; } // failback to path: else { $typePrefix = 'path'; } // is a registered TALES expression modifier $callback = PHPTAL_TalesRegistry::getInstance()->getCallback($typePrefix); if ($callback !== NULL) { $result = call_user_func($callback, $expression, $nothrow); self::verifyPHPExpressions($typePrefix, $result); return $result; } $func = 'phptal_tales_'.str_replace('-', '_', $typePrefix); throw new PHPTAL_UnknownModifierException("Unknown phptal modifier '$typePrefix'. Function '$func' does not exist", $typePrefix); }
[ "public", "static", "function", "compileToPHPExpressions", "(", "$", "expression", ",", "$", "nothrow", "=", "false", ")", "{", "$", "expression", "=", "trim", "(", "$", "expression", ")", ";", "// Look for tales modifier (string:, exists:, Namespaced\\Tale:, etc...)", ...
returns PHP code that will evaluate given TALES expression. e.g. "string:foo${bar}" may be transformed to "'foo'.phptal_escape($ctx->bar)" Expressions with alternatives ("foo | bar") will cause it to return array Use PHPTAL_Php_TalesInternal::compileToPHPExpression() if you always want string. @param bool $nothrow if true, invalid expression will return NULL (at run time) rather than throwing exception @return string or array
[ "returns", "PHP", "code", "that", "will", "evaluate", "given", "TALES", "expression", ".", "e", ".", "g", ".", "string", ":", "foo$", "{", "bar", "}", "may", "be", "transformed", "to", "foo", ".", "phptal_escape", "(", "$ctx", "-", ">", "bar", ")" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/TalesInternal.php#L460-L489
phptal/PHPTAL
classes/PHPTAL/RepeatController.php
PHPTAL_RepeatController.valid
public function valid() { $valid = $this->valid || $this->validOnNext; $this->validOnNext = $this->valid; return $valid; }
php
public function valid() { $valid = $this->valid || $this->validOnNext; $this->validOnNext = $this->valid; return $valid; }
[ "public", "function", "valid", "(", ")", "{", "$", "valid", "=", "$", "this", "->", "valid", "||", "$", "this", "->", "validOnNext", ";", "$", "this", "->", "validOnNext", "=", "$", "this", "->", "valid", ";", "return", "$", "valid", ";", "}" ]
Tells if the iteration is over @return bool True if the iteration is not finished yet
[ "Tells", "if", "the", "iteration", "is", "over" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/RepeatController.php#L110-L116
phptal/PHPTAL
classes/PHPTAL/RepeatController.php
PHPTAL_RepeatController.rewind
public function rewind() { $this->index = 0; $this->length = null; $this->end = false; $this->iterator->rewind(); // Prefetch the next element if ($this->iterator->valid()) { $this->validOnNext = true; $this->prefetch(); } else { $this->validOnNext = false; } if ($this->uses_groups) { // Notify the grouping helper of the change $this->groups->reset(); } }
php
public function rewind() { $this->index = 0; $this->length = null; $this->end = false; $this->iterator->rewind(); // Prefetch the next element if ($this->iterator->valid()) { $this->validOnNext = true; $this->prefetch(); } else { $this->validOnNext = false; } if ($this->uses_groups) { // Notify the grouping helper of the change $this->groups->reset(); } }
[ "public", "function", "rewind", "(", ")", "{", "$", "this", "->", "index", "=", "0", ";", "$", "this", "->", "length", "=", "null", ";", "$", "this", "->", "end", "=", "false", ";", "$", "this", "->", "iterator", "->", "rewind", "(", ")", ";", ...
Restarts the iteration process going back to the first element
[ "Restarts", "the", "iteration", "process", "going", "back", "to", "the", "first", "element" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/RepeatController.php#L145-L165
phptal/PHPTAL
classes/PHPTAL/RepeatController.php
PHPTAL_RepeatController.next
public function next() { $this->index++; // Prefetch the next element if ($this->validOnNext) $this->prefetch(); if ($this->uses_groups) { // Notify the grouping helper of the change $this->groups->reset(); } }
php
public function next() { $this->index++; // Prefetch the next element if ($this->validOnNext) $this->prefetch(); if ($this->uses_groups) { // Notify the grouping helper of the change $this->groups->reset(); } }
[ "public", "function", "next", "(", ")", "{", "$", "this", "->", "index", "++", ";", "// Prefetch the next element", "if", "(", "$", "this", "->", "validOnNext", ")", "$", "this", "->", "prefetch", "(", ")", ";", "if", "(", "$", "this", "->", "uses_grou...
Fetches the next element in the iteration and advances the pointer
[ "Fetches", "the", "next", "element", "in", "the", "iteration", "and", "advances", "the", "pointer" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/RepeatController.php#L171-L182
phptal/PHPTAL
classes/PHPTAL/RepeatController.php
PHPTAL_RepeatController.prefetch
protected function prefetch() { $this->valid = true; $this->current = $this->iterator->current(); $this->key = $this->iterator->key(); $this->iterator->next(); if ( !$this->iterator->valid() ) { $this->valid = false; $this->end = true; } }
php
protected function prefetch() { $this->valid = true; $this->current = $this->iterator->current(); $this->key = $this->iterator->key(); $this->iterator->next(); if ( !$this->iterator->valid() ) { $this->valid = false; $this->end = true; } }
[ "protected", "function", "prefetch", "(", ")", "{", "$", "this", "->", "valid", "=", "true", ";", "$", "this", "->", "current", "=", "$", "this", "->", "iterator", "->", "current", "(", ")", ";", "$", "this", "->", "key", "=", "$", "this", "->", ...
Fetches the next element from the source data store and updates the end flag if needed. @access protected
[ "Fetches", "the", "next", "element", "from", "the", "source", "data", "store", "and", "updates", "the", "end", "flag", "if", "needed", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/RepeatController.php#L251-L262
phptal/PHPTAL
classes/PHPTAL/RepeatController.php
PHPTAL_RepeatController.int2letter
protected function int2letter($int) { $lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $size = strlen($lookup); $letters = ''; while ($int > 0) { $int--; $letters = $lookup[$int % $size] . $letters; $int = floor($int / $size); } return $letters; }
php
protected function int2letter($int) { $lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $size = strlen($lookup); $letters = ''; while ($int > 0) { $int--; $letters = $lookup[$int % $size] . $letters; $int = floor($int / $size); } return $letters; }
[ "protected", "function", "int2letter", "(", "$", "int", ")", "{", "$", "lookup", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'", ";", "$", "size", "=", "strlen", "(", "$", "lookup", ")", ";", "$", "letters", "=", "''", ";", "while", "(", "$", "int", ">", "0", "...
Converts an integer number (1 based) to a sequence of letters @param int $int The number to convert @return String The letters equivalent as a, b, c-z ... aa, ab, ac-zz ... @access protected
[ "Converts", "an", "integer", "number", "(", "1", "based", ")", "to", "a", "sequence", "of", "letters" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/RepeatController.php#L272-L284
phptal/PHPTAL
classes/PHPTAL/RepeatController.php
PHPTAL_RepeatController.int2roman
protected function int2roman($int) { $lookup = array( '1000' => 'M', '900' => 'CM', '500' => 'D', '400' => 'CD', '100' => 'C', '90' => 'XC', '50' => 'L', '40' => 'XL', '10' => 'X', '9' => 'IX', '5' => 'V', '4' => 'IV', '1' => 'I', ); $roman = ''; foreach ($lookup as $max => $letters) { while ($int >= $max) { $roman .= $letters; $int -= $max; } } return $roman; }
php
protected function int2roman($int) { $lookup = array( '1000' => 'M', '900' => 'CM', '500' => 'D', '400' => 'CD', '100' => 'C', '90' => 'XC', '50' => 'L', '40' => 'XL', '10' => 'X', '9' => 'IX', '5' => 'V', '4' => 'IV', '1' => 'I', ); $roman = ''; foreach ($lookup as $max => $letters) { while ($int >= $max) { $roman .= $letters; $int -= $max; } } return $roman; }
[ "protected", "function", "int2roman", "(", "$", "int", ")", "{", "$", "lookup", "=", "array", "(", "'1000'", "=>", "'M'", ",", "'900'", "=>", "'CM'", ",", "'500'", "=>", "'D'", ",", "'400'", "=>", "'CD'", ",", "'100'", "=>", "'C'", ",", "'90'", "=>...
Converts an integer number (1 based) to a roman numeral @param int $int The number to convert @return String The roman numeral @access protected
[ "Converts", "an", "integer", "number", "(", "1", "based", ")", "to", "a", "roman", "numeral" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/RepeatController.php#L294-L321
phptal/PHPTAL
classes/PHPTAL/Php/State.php
PHPTAL_Php_State.evaluateExpression
public function evaluateExpression($expression) { if ($this->getTalesMode() === 'php') { return PHPTAL_Php_TalesInternal::php($expression); } return PHPTAL_Php_TalesInternal::compileToPHPExpressions($expression, false); }
php
public function evaluateExpression($expression) { if ($this->getTalesMode() === 'php') { return PHPTAL_Php_TalesInternal::php($expression); } return PHPTAL_Php_TalesInternal::compileToPHPExpressions($expression, false); }
[ "public", "function", "evaluateExpression", "(", "$", "expression", ")", "{", "if", "(", "$", "this", "->", "getTalesMode", "(", ")", "===", "'php'", ")", "{", "return", "PHPTAL_Php_TalesInternal", "::", "php", "(", "$", "expression", ")", ";", "}", "retur...
compile TALES expression according to current talesMode @return string with PHP code or array with expressions for TalesChainExecutor
[ "compile", "TALES", "expression", "according", "to", "current", "talesMode" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/State.php#L120-L126
phptal/PHPTAL
classes/PHPTAL/Php/State.php
PHPTAL_Php_State.compileTalesToPHPExpression
private function compileTalesToPHPExpression($expression) { if ($this->getTalesMode() === 'php') { return PHPTAL_Php_TalesInternal::php($expression); } return PHPTAL_Php_TalesInternal::compileToPHPExpression($expression, false); }
php
private function compileTalesToPHPExpression($expression) { if ($this->getTalesMode() === 'php') { return PHPTAL_Php_TalesInternal::php($expression); } return PHPTAL_Php_TalesInternal::compileToPHPExpression($expression, false); }
[ "private", "function", "compileTalesToPHPExpression", "(", "$", "expression", ")", "{", "if", "(", "$", "this", "->", "getTalesMode", "(", ")", "===", "'php'", ")", "{", "return", "PHPTAL_Php_TalesInternal", "::", "php", "(", "$", "expression", ")", ";", "}"...
compile TALES expression according to current talesMode @return string with PHP code
[ "compile", "TALES", "expression", "according", "to", "current", "talesMode" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/State.php#L132-L138
phptal/PHPTAL
classes/PHPTAL/Php/State.php
PHPTAL_Php_State.htmlchars
public function htmlchars($php) { // PHP strings can be escaped at compile time if (preg_match('/^\'((?:[^\'{]+|\\\\.)*)\'$/s', $php, $m)) { return "'".htmlspecialchars(str_replace('\\\'', "'", $m[1]), ENT_QUOTES, $this->encoding)."'"; } return 'phptal_escape('.$php.', \''.$this->encoding.'\')'; }
php
public function htmlchars($php) { // PHP strings can be escaped at compile time if (preg_match('/^\'((?:[^\'{]+|\\\\.)*)\'$/s', $php, $m)) { return "'".htmlspecialchars(str_replace('\\\'', "'", $m[1]), ENT_QUOTES, $this->encoding)."'"; } return 'phptal_escape('.$php.', \''.$this->encoding.'\')'; }
[ "public", "function", "htmlchars", "(", "$", "php", ")", "{", "// PHP strings can be escaped at compile time", "if", "(", "preg_match", "(", "'/^\\'((?:[^\\'{]+|\\\\\\\\.)*)\\'$/s'", ",", "$", "php", ",", "$", "m", ")", ")", "{", "return", "\"'\"", ".", "htmlspeci...
expects PHP code and returns PHP code that will generate escaped string Optimizes case when PHP string is given. @return php code
[ "expects", "PHP", "code", "and", "returns", "PHP", "code", "that", "will", "generate", "escaped", "string", "Optimizes", "case", "when", "PHP", "string", "is", "given", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/State.php#L230-L237
phptal/PHPTAL
classes/PHPTAL/Dom/SaxXmlParser.php
PHPTAL_Dom_SaxXmlParser.convertBytesToEntities
private static function convertBytesToEntities(array $m) { $m = $m[1]; $out = ""; for($i=0; $i < strlen($m); $i++) { $out .= '&#X'.strtoupper(dechex(ord($m[$i]))).';'; } return $out; }
php
private static function convertBytesToEntities(array $m) { $m = $m[1]; $out = ""; for($i=0; $i < strlen($m); $i++) { $out .= '&#X'.strtoupper(dechex(ord($m[$i]))).';'; } return $out; }
[ "private", "static", "function", "convertBytesToEntities", "(", "array", "$", "m", ")", "{", "$", "m", "=", "$", "m", "[", "1", "]", ";", "$", "out", "=", "\"\"", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "m...
preg callback Changes all bytes to hexadecimal XML entities @param array $m first array element is used for input @return string
[ "preg", "callback", "Changes", "all", "bytes", "to", "hexadecimal", "XML", "entities" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/SaxXmlParser.php#L425-L434
phptal/PHPTAL
classes/PHPTAL/Dom/SaxXmlParser.php
PHPTAL_Dom_SaxXmlParser.sanitizeEscapedText
private function sanitizeEscapedText($str) { $str = str_replace('&apos;', '&#39;', $str); // PHP's html_entity_decode doesn't seem to support that! /* <?php ?> blocks can't reliably work in attributes (due to escaping impossible in XML) so they have to be converted into special TALES expression */ $types = version_compare(PHP_VERSION, '5.4.0') < 0 ? (ini_get('short_open_tag') ? 'php|=|' : 'php') : 'php|='; $str = preg_replace_callback("/<\?($types)(.*?)\?>/", array('self', 'convertPHPBlockToTALES'), $str); // corrects all non-entities and neutralizes potentially problematic CDATA end marker $str = strtr(preg_replace('/&(?!(?:#x?[a-f0-9]+|[a-z][a-z0-9]*);)/i', '&amp;', $str), array('<'=>'&lt;', ']]>'=>']]&gt;')); return $str; }
php
private function sanitizeEscapedText($str) { $str = str_replace('&apos;', '&#39;', $str); // PHP's html_entity_decode doesn't seem to support that! /* <?php ?> blocks can't reliably work in attributes (due to escaping impossible in XML) so they have to be converted into special TALES expression */ $types = version_compare(PHP_VERSION, '5.4.0') < 0 ? (ini_get('short_open_tag') ? 'php|=|' : 'php') : 'php|='; $str = preg_replace_callback("/<\?($types)(.*?)\?>/", array('self', 'convertPHPBlockToTALES'), $str); // corrects all non-entities and neutralizes potentially problematic CDATA end marker $str = strtr(preg_replace('/&(?!(?:#x?[a-f0-9]+|[a-z][a-z0-9]*);)/i', '&amp;', $str), array('<'=>'&lt;', ']]>'=>']]&gt;')); return $str; }
[ "private", "function", "sanitizeEscapedText", "(", "$", "str", ")", "{", "$", "str", "=", "str_replace", "(", "'&apos;'", ",", "'&#39;'", ",", "$", "str", ")", ";", "// PHP's html_entity_decode doesn't seem to support that!", "/* <?php ?> blocks can't reliably work in att...
This is where this parser violates XML and refuses to be an annoying bastard.
[ "This", "is", "where", "this", "parser", "violates", "XML", "and", "refuses", "to", "be", "an", "annoying", "bastard", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Dom/SaxXmlParser.php#L439-L453
phptal/PHPTAL
classes/PHPTAL/RepeatControllerGroups.php
PHPTAL_RepeatControllerGroups.last
public function last($data) { if ( !is_array($data) && !is_object($data) && !is_null($data) ) { if ( !isset($this->cache['L']) ) { $hash = md5($data); if (empty($this->dict['L'])) { $this->dict['L'] = $hash; $res = false; } elseif ($this->dict['L'] !== $hash) { $this->dict['L'] = $hash; $res = true; } else { $res = false; } $this->cache['L'] = $res; } return $this->cache['L']; } $this->data = $data; $this->branch = 'L'; $this->vars = array(); return $this; }
php
public function last($data) { if ( !is_array($data) && !is_object($data) && !is_null($data) ) { if ( !isset($this->cache['L']) ) { $hash = md5($data); if (empty($this->dict['L'])) { $this->dict['L'] = $hash; $res = false; } elseif ($this->dict['L'] !== $hash) { $this->dict['L'] = $hash; $res = true; } else { $res = false; } $this->cache['L'] = $res; } return $this->cache['L']; } $this->data = $data; $this->branch = 'L'; $this->vars = array(); return $this; }
[ "public", "function", "last", "(", "$", "data", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", "&&", "!", "is_object", "(", "$", "data", ")", "&&", "!", "is_null", "(", "$", "data", ")", ")", "{", "if", "(", "!", "isset", "(", "...
Checks if the data passed is the last one in a group @param mixed $data The data to evaluate @return Mixed True if the last item in the group, false if not and this same object if the path is not finished
[ "Checks", "if", "the", "data", "passed", "is", "the", "last", "one", "in", "a", "group" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/RepeatControllerGroups.php#L90-L118
phptal/PHPTAL
classes/PHPTAL/Php/Attribute/METAL/UseMacro.php
PHPTAL_Php_Attribute_METAL_UseMacro.generateFillSlots
private function generateFillSlots(PHPTAL_Php_CodeWriter $codewriter, PHPTAL_Dom_Node $phpelement) { if (false == ($phpelement instanceof PHPTAL_Dom_Element)) { return; } // if the tag contains one of the allowed attribute, we generate it foreach (self::$ALLOWED_ATTRIBUTES as $qname => $uri) { if ($phpelement->hasAttributeNS($uri, $qname)) { $phpelement->generateCode($codewriter); return; } } foreach ($phpelement->childNodes as $child) { $this->generateFillSlots($codewriter, $child); } }
php
private function generateFillSlots(PHPTAL_Php_CodeWriter $codewriter, PHPTAL_Dom_Node $phpelement) { if (false == ($phpelement instanceof PHPTAL_Dom_Element)) { return; } // if the tag contains one of the allowed attribute, we generate it foreach (self::$ALLOWED_ATTRIBUTES as $qname => $uri) { if ($phpelement->hasAttributeNS($uri, $qname)) { $phpelement->generateCode($codewriter); return; } } foreach ($phpelement->childNodes as $child) { $this->generateFillSlots($codewriter, $child); } }
[ "private", "function", "generateFillSlots", "(", "PHPTAL_Php_CodeWriter", "$", "codewriter", ",", "PHPTAL_Dom_Node", "$", "phpelement", ")", "{", "if", "(", "false", "==", "(", "$", "phpelement", "instanceof", "PHPTAL_Dom_Element", ")", ")", "{", "return", ";", ...
recursively generates code for slots
[ "recursively", "generates", "code", "for", "slots" ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/Attribute/METAL/UseMacro.php#L117-L134
phptal/PHPTAL
classes/PHPTAL/Php/Attribute/TAL/Define.php
PHPTAL_Php_Attribute_TAL_Define.parseExpression
public function parseExpression($exp) { $defineScope = false; // (local | global) $defineVar = false; // var to define // extract defineScope from expression $exp = trim($exp); if (preg_match('/^(local|global)\s+(.*?)$/ism', $exp, $m)) { list(, $defineScope, $exp) = $m; $exp = trim($exp); } // extract varname and expression from remaining of expression list($defineVar, $exp) = $this->parseSetExpression($exp); if ($exp !== null) $exp = trim($exp); return array($defineScope, $defineVar, $exp); }
php
public function parseExpression($exp) { $defineScope = false; // (local | global) $defineVar = false; // var to define // extract defineScope from expression $exp = trim($exp); if (preg_match('/^(local|global)\s+(.*?)$/ism', $exp, $m)) { list(, $defineScope, $exp) = $m; $exp = trim($exp); } // extract varname and expression from remaining of expression list($defineVar, $exp) = $this->parseSetExpression($exp); if ($exp !== null) $exp = trim($exp); return array($defineScope, $defineVar, $exp); }
[ "public", "function", "parseExpression", "(", "$", "exp", ")", "{", "$", "defineScope", "=", "false", ";", "// (local | global)", "$", "defineVar", "=", "false", ";", "// var to define", "// extract defineScope from expression", "$", "exp", "=", "trim", "(", "$", ...
Parse the define expression, already splitted in sub parts by ';'.
[ "Parse", "the", "define", "expression", "already", "splitted", "in", "sub", "parts", "by", ";", "." ]
train
https://github.com/phptal/PHPTAL/blob/40e0cdbebfa1c5bfca7b722037ea41fee7362946/classes/PHPTAL/Php/Attribute/TAL/Define.php#L154-L170
FriendsOfCake/search
src/Model/Filter/Finder.php
Finder.process
public function process() { $args = $this->getArgs(); $map = $this->getConfig('map'); foreach ($map as $to => $from) { $args[$to] = isset($args[$from]) ? $args[$from] : null; } $options = $this->getConfig('options'); $args += $options; $this->getQuery()->find($this->finder(), $args); return true; }
php
public function process() { $args = $this->getArgs(); $map = $this->getConfig('map'); foreach ($map as $to => $from) { $args[$to] = isset($args[$from]) ? $args[$from] : null; } $options = $this->getConfig('options'); $args += $options; $this->getQuery()->find($this->finder(), $args); return true; }
[ "public", "function", "process", "(", ")", "{", "$", "args", "=", "$", "this", "->", "getArgs", "(", ")", ";", "$", "map", "=", "$", "this", "->", "getConfig", "(", "'map'", ")", ";", "foreach", "(", "$", "map", "as", "$", "to", "=>", "$", "fro...
Add a condition based on a custom finder. @return bool
[ "Add", "a", "condition", "based", "on", "a", "custom", "finder", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Finder.php#L31-L45
FriendsOfCake/search
src/Model/Filter/Compare.php
Compare.process
public function process() { $conditions = []; if (!in_array($this->getConfig('operator'), $this->_operators, true)) { throw new InvalidArgumentException(sprintf( 'The operator %s is invalid!', $this->getConfig('operator') )); } $value = $this->value(); if (!is_scalar($value)) { return false; } foreach ($this->fields() as $field) { $left = $field . ' ' . $this->getConfig('operator'); $conditions[] = [$left => $value]; } $this->getQuery()->andWhere([$this->getConfig('mode') => $conditions]); return true; }
php
public function process() { $conditions = []; if (!in_array($this->getConfig('operator'), $this->_operators, true)) { throw new InvalidArgumentException(sprintf( 'The operator %s is invalid!', $this->getConfig('operator') )); } $value = $this->value(); if (!is_scalar($value)) { return false; } foreach ($this->fields() as $field) { $left = $field . ' ' . $this->getConfig('operator'); $conditions[] = [$left => $value]; } $this->getQuery()->andWhere([$this->getConfig('mode') => $conditions]); return true; }
[ "public", "function", "process", "(", ")", "{", "$", "conditions", "=", "[", "]", ";", "if", "(", "!", "in_array", "(", "$", "this", "->", "getConfig", "(", "'operator'", ")", ",", "$", "this", "->", "_operators", ",", "true", ")", ")", "{", "throw...
Process a comparison-based condition (e.g. $field <= $value). @return bool @throws \InvalidArgumentException
[ "Process", "a", "comparison", "-", "based", "condition", "(", "e", ".", "g", ".", "$field", "<", "=", "$value", ")", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Compare.php#L34-L57
FriendsOfCake/search
src/Model/SearchTrait.php
SearchTrait.findSearch
public function findSearch(QueryInterface $query, array $options) { if (!isset($options['search'])) { throw new Exception( 'Custom finder "search" expects search arguments ' . 'to be nested under key "search" in find() options.' ); } $filters = $this->_getFilters(Hash::get($options, 'collection', Manager::DEFAULT_COLLECTION)); $params = $this->_flattenParams((array)$options['search'], $filters); $params = $this->_extractParams($params, $filters); return $this->_processFilters($filters, $params, $query); }
php
public function findSearch(QueryInterface $query, array $options) { if (!isset($options['search'])) { throw new Exception( 'Custom finder "search" expects search arguments ' . 'to be nested under key "search" in find() options.' ); } $filters = $this->_getFilters(Hash::get($options, 'collection', Manager::DEFAULT_COLLECTION)); $params = $this->_flattenParams((array)$options['search'], $filters); $params = $this->_extractParams($params, $filters); return $this->_processFilters($filters, $params, $query); }
[ "public", "function", "findSearch", "(", "QueryInterface", "$", "query", ",", "array", "$", "options", ")", "{", "if", "(", "!", "isset", "(", "$", "options", "[", "'search'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'Custom finder \"search\"...
Callback fired from the controller. @param \Cake\Datasource\QueryInterface $query Query. @param array $options The options for the find. - `search`: Array of search arguments. - `collection`: Filter collection name. @return \Cake\Datasource\QueryInterface The Query object used in pagination. @throws \Exception When missing search arguments.
[ "Callback", "fired", "from", "the", "controller", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/SearchTrait.php#L51-L66
FriendsOfCake/search
src/Model/SearchTrait.php
SearchTrait.searchManager
public function searchManager() { if ($this->_manager === null) { $this->_manager = new Manager( $this->_repository(), $this->_collectionClass ); } return $this->_manager; }
php
public function searchManager() { if ($this->_manager === null) { $this->_manager = new Manager( $this->_repository(), $this->_collectionClass ); } return $this->_manager; }
[ "public", "function", "searchManager", "(", ")", "{", "if", "(", "$", "this", "->", "_manager", "===", "null", ")", "{", "$", "this", "->", "_manager", "=", "new", "Manager", "(", "$", "this", "->", "_repository", "(", ")", ",", "$", "this", "->", ...
Returns the search filter manager. @return \Search\Manager
[ "Returns", "the", "search", "filter", "manager", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/SearchTrait.php#L94-L104
FriendsOfCake/search
src/Model/SearchTrait.php
SearchTrait._extractParams
protected function _extractParams($params, FilterCollectionInterface $filters) { $emptyValues = $this->_emptyValues(); $nonEmptyParams = Hash::filter($params, function ($val) use ($emptyValues) { return !in_array($val, $emptyValues, true); }); return array_intersect_key($nonEmptyParams, iterator_to_array($filters)); }
php
protected function _extractParams($params, FilterCollectionInterface $filters) { $emptyValues = $this->_emptyValues(); $nonEmptyParams = Hash::filter($params, function ($val) use ($emptyValues) { return !in_array($val, $emptyValues, true); }); return array_intersect_key($nonEmptyParams, iterator_to_array($filters)); }
[ "protected", "function", "_extractParams", "(", "$", "params", ",", "FilterCollectionInterface", "$", "filters", ")", "{", "$", "emptyValues", "=", "$", "this", "->", "_emptyValues", "(", ")", ";", "$", "nonEmptyParams", "=", "Hash", "::", "filter", "(", "$"...
Extracts all parameters for which a filter with a matching field name exists. @param array $params The parameters array to extract from. @param \Search\Model\Filter\FilterCollectionInterface $filters Filter collection. @return array The extracted parameters.
[ "Extracts", "all", "parameters", "for", "which", "a", "filter", "with", "a", "matching", "field", "name", "exists", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/SearchTrait.php#L114-L123
FriendsOfCake/search
src/Model/SearchTrait.php
SearchTrait._flattenParams
protected function _flattenParams(array $params, FilterCollectionInterface $filters) { $flattened = []; foreach ($params as $key => $value) { if (!is_array($value) || (!empty($filters[$key]) && $filters[$key]->getConfig('flatten') === false) ) { $flattened[$key] = $value; continue; } foreach ($value as $childKey => $childValue) { if (!is_numeric($childKey)) { $flattened[$key . '.' . $childKey] = $childValue; } else { $flattened[$key][$childKey] = $childValue; } } } return $flattened; }
php
protected function _flattenParams(array $params, FilterCollectionInterface $filters) { $flattened = []; foreach ($params as $key => $value) { if (!is_array($value) || (!empty($filters[$key]) && $filters[$key]->getConfig('flatten') === false) ) { $flattened[$key] = $value; continue; } foreach ($value as $childKey => $childValue) { if (!is_numeric($childKey)) { $flattened[$key . '.' . $childKey] = $childValue; } else { $flattened[$key][$childKey] = $childValue; } } } return $flattened; }
[ "protected", "function", "_flattenParams", "(", "array", "$", "params", ",", "FilterCollectionInterface", "$", "filters", ")", "{", "$", "flattened", "=", "[", "]", ";", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$", "value", ")", "{", "if",...
Flattens a parameters array, so that possible aliased parameter keys that are provided in a nested fashion, are being grouped using flat keys. ### Example: The following parameters array: ``` [ 'Alias' => [ 'field' => 'value' 'otherField' => [ 'value', 'otherValue' ] ], 'field' => 'value' ] ``` would return as ``` [ 'Alias.field' => 'value', 'Alias.otherField' => [ 'value', 'otherValue' ], 'field' => 'value' ] ``` @param array $params The parameters array to flatten. @param \Search\Model\Filter\FilterCollectionInterface $filters Filter collection instance. @return array The flattened parameters array.
[ "Flattens", "a", "parameters", "array", "so", "that", "possible", "aliased", "parameter", "keys", "that", "are", "provided", "in", "a", "nested", "fashion", "are", "being", "grouped", "using", "flat", "keys", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/SearchTrait.php#L164-L185
FriendsOfCake/search
src/Model/SearchTrait.php
SearchTrait._processFilters
protected function _processFilters(FilterCollectionInterface $filters, $params, $query) { $this->_searchParams = $params; $this->_isSearch = false; foreach ($filters as $filter) { $filter->setArgs($params); $filter->setQuery($query); if ($filter->skip()) { continue; } $result = $filter->process(); if ($result !== false) { $this->_isSearch = true; } } return $query; }
php
protected function _processFilters(FilterCollectionInterface $filters, $params, $query) { $this->_searchParams = $params; $this->_isSearch = false; foreach ($filters as $filter) { $filter->setArgs($params); $filter->setQuery($query); if ($filter->skip()) { continue; } $result = $filter->process(); if ($result !== false) { $this->_isSearch = true; } } return $query; }
[ "protected", "function", "_processFilters", "(", "FilterCollectionInterface", "$", "filters", ",", "$", "params", ",", "$", "query", ")", "{", "$", "this", "->", "_searchParams", "=", "$", "params", ";", "$", "this", "->", "_isSearch", "=", "false", ";", "...
Processes the given filters. @param \Search\Model\Filter\FilterCollectionInterface $filters The filters to process. @param array $params The parameters to pass to the filters. @param \Cake\Datasource\QueryInterface $query The query to pass to the filters. @return \Cake\Datasource\QueryInterface The query processed by the filters.
[ "Processes", "the", "given", "filters", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/SearchTrait.php#L206-L224
FriendsOfCake/search
src/Manager.php
Manager.getFilters
public function getFilters($collection = self::DEFAULT_COLLECTION) { if (!isset($this->_collections[$collection])) { $this->_collections[$collection] = $this->_loadCollection($collection); } return $this->_collections[$collection]; }
php
public function getFilters($collection = self::DEFAULT_COLLECTION) { if (!isset($this->_collections[$collection])) { $this->_collections[$collection] = $this->_loadCollection($collection); } return $this->_collections[$collection]; }
[ "public", "function", "getFilters", "(", "$", "collection", "=", "self", "::", "DEFAULT_COLLECTION", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_collections", "[", "$", "collection", "]", ")", ")", "{", "$", "this", "->", "_collections",...
Gets all filters in a given collection. @param string $collection Name of the filter collection. @return \Search\Model\Filter\FilterCollectionInterface Filter collection instance. @throws \InvalidArgumentException If requested collection is not set.
[ "Gets", "all", "filters", "in", "a", "given", "collection", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Manager.php#L84-L91
FriendsOfCake/search
src/Manager.php
Manager._loadCollection
protected function _loadCollection($name) { if ($name === self::DEFAULT_COLLECTION) { $class = $this->_collectionClass; } else { $class = Inflector::camelize(str_replace('-', '_', $name)); } $className = App::className($class, 'Model/Filter', 'Collection'); if (!$className) { throw new InvalidArgumentException(sprintf( 'The collection class "%sCollection" does not exist', $class )); } $instance = new $className($this); if (!$instance instanceof FilterCollectionInterface) { throw new InvalidArgumentException(sprintf( 'The collection must be instance of FilterCollectionInterface. ' . 'Got instance of "%s" instead', get_class($instance) )); } return $instance; }
php
protected function _loadCollection($name) { if ($name === self::DEFAULT_COLLECTION) { $class = $this->_collectionClass; } else { $class = Inflector::camelize(str_replace('-', '_', $name)); } $className = App::className($class, 'Model/Filter', 'Collection'); if (!$className) { throw new InvalidArgumentException(sprintf( 'The collection class "%sCollection" does not exist', $class )); } $instance = new $className($this); if (!$instance instanceof FilterCollectionInterface) { throw new InvalidArgumentException(sprintf( 'The collection must be instance of FilterCollectionInterface. ' . 'Got instance of "%s" instead', get_class($instance) )); } return $instance; }
[ "protected", "function", "_loadCollection", "(", "$", "name", ")", "{", "if", "(", "$", "name", "===", "self", "::", "DEFAULT_COLLECTION", ")", "{", "$", "class", "=", "$", "this", "->", "_collectionClass", ";", "}", "else", "{", "$", "class", "=", "In...
Loads a filter collection. @param string $name Collection name or FQCN. @return \Search\Model\Filter\FilterCollectionInterface @throws \InvalidArgumentException When no filter was found.
[ "Loads", "a", "filter", "collection", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Manager.php#L100-L126
FriendsOfCake/search
src/Manager.php
Manager._collection
protected function _collection() { if (!isset($this->_collections[$this->_collection])) { $this->_collections[$this->_collection] = new $this->_collectionClass($this); } return $this->_collections[$this->_collection]; }
php
protected function _collection() { if (!isset($this->_collections[$this->_collection])) { $this->_collections[$this->_collection] = new $this->_collectionClass($this); } return $this->_collections[$this->_collection]; }
[ "protected", "function", "_collection", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_collections", "[", "$", "this", "->", "_collection", "]", ")", ")", "{", "$", "this", "->", "_collections", "[", "$", "this", "->", "_collection",...
Get instance for current collection. @return \Search\Model\Filter\FilterCollectionInterface
[ "Get", "instance", "for", "current", "collection", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Manager.php#L146-L153
FriendsOfCake/search
src/Manager.php
Manager.add
public function add($name, $filter, array $options = []) { $this->_collection()->add($name, $filter, $options); return $this; }
php
public function add($name, $filter, array $options = []) { $this->_collection()->add($name, $filter, $options); return $this; }
[ "public", "function", "add", "(", "$", "name", ",", "$", "filter", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "_collection", "(", ")", "->", "add", "(", "$", "name", ",", "$", "filter", ",", "$", "options", ")", "...
Adds a new filter to the active collection. @param string $name Field name. @param string $filter Filter name. @param array $options Filter options. @return $this
[ "Adds", "a", "new", "filter", "to", "the", "active", "collection", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Manager.php#L173-L178
FriendsOfCake/search
src/Model/Filter/Like.php
Like.process
public function process() { $this->_setEscaper(); $comparison = $this->getConfig('comparison'); $valueMode = $this->getConfig('valueMode'); $value = $this->value(); $isMultiValue = is_array($value); $conditions = []; foreach ($this->fields() as $field) { $left = $field . ' ' . $comparison; if ($isMultiValue) { $valueConditions = []; foreach ($value as $val) { $right = $this->_wildcards($val); if ($right !== false) { $valueConditions[] = [$left => $right]; } } if (!empty($valueConditions)) { $conditions[] = [$valueMode => $valueConditions]; } } else { $right = $this->_wildcards($value); if ($right !== false) { $conditions[] = [$left => $right]; } } } if (!empty($conditions)) { $colTypes = $this->getConfig('colType'); if ($colTypes) { $colTypes = $this->_aliasColTypes($colTypes); } $this->getQuery()->andWhere([$this->getConfig('fieldMode') => $conditions], $colTypes); return true; } return false; }
php
public function process() { $this->_setEscaper(); $comparison = $this->getConfig('comparison'); $valueMode = $this->getConfig('valueMode'); $value = $this->value(); $isMultiValue = is_array($value); $conditions = []; foreach ($this->fields() as $field) { $left = $field . ' ' . $comparison; if ($isMultiValue) { $valueConditions = []; foreach ($value as $val) { $right = $this->_wildcards($val); if ($right !== false) { $valueConditions[] = [$left => $right]; } } if (!empty($valueConditions)) { $conditions[] = [$valueMode => $valueConditions]; } } else { $right = $this->_wildcards($value); if ($right !== false) { $conditions[] = [$left => $right]; } } } if (!empty($conditions)) { $colTypes = $this->getConfig('colType'); if ($colTypes) { $colTypes = $this->_aliasColTypes($colTypes); } $this->getQuery()->andWhere([$this->getConfig('fieldMode') => $conditions], $colTypes); return true; } return false; }
[ "public", "function", "process", "(", ")", "{", "$", "this", "->", "_setEscaper", "(", ")", ";", "$", "comparison", "=", "$", "this", "->", "getConfig", "(", "'comparison'", ")", ";", "$", "valueMode", "=", "$", "this", "->", "getConfig", "(", "'valueM...
Process a LIKE condition ($x LIKE $y). @return bool
[ "Process", "a", "LIKE", "condition", "(", "$x", "LIKE", "$y", ")", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Like.php#L41-L83
FriendsOfCake/search
src/Model/Filter/Like.php
Like._aliasColTypes
protected function _aliasColTypes($colTypes) { $repository = $this->manager()->getRepository(); if (!method_exists($repository, 'aliasField')) { return $colTypes; } $return = []; foreach ($colTypes as $field => $colType) { $return[$repository->aliasField($field)] = $colType; } return $return; }
php
protected function _aliasColTypes($colTypes) { $repository = $this->manager()->getRepository(); if (!method_exists($repository, 'aliasField')) { return $colTypes; } $return = []; foreach ($colTypes as $field => $colType) { $return[$repository->aliasField($field)] = $colType; } return $return; }
[ "protected", "function", "_aliasColTypes", "(", "$", "colTypes", ")", "{", "$", "repository", "=", "$", "this", "->", "manager", "(", ")", "->", "getRepository", "(", ")", ";", "if", "(", "!", "method_exists", "(", "$", "repository", ",", "'aliasField'", ...
Alias the column type fields to match the field aliases of the conditions. @param array $colTypes Column types to be aliased. @return array Aliased column types.
[ "Alias", "the", "column", "type", "fields", "to", "match", "the", "field", "aliases", "of", "the", "conditions", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Like.php#L91-L104
FriendsOfCake/search
src/Model/Filter/Like.php
Like._wildcards
protected function _wildcards($value) { if (!is_string($value)) { return false; } $value = $this->_formatWildcards($value); if ($this->getConfig('before')) { $value = $this->_formatWildcards($this->getConfig('wildcardAny')) . $value; } if ($this->getConfig('after')) { $value = $value . $this->_formatWildcards($this->getConfig('wildcardAny')); } return $value; }
php
protected function _wildcards($value) { if (!is_string($value)) { return false; } $value = $this->_formatWildcards($value); if ($this->getConfig('before')) { $value = $this->_formatWildcards($this->getConfig('wildcardAny')) . $value; } if ($this->getConfig('after')) { $value = $value . $this->_formatWildcards($this->getConfig('wildcardAny')); } return $value; }
[ "protected", "function", "_wildcards", "(", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "$", "value", "=", "$", "this", "->", "_formatWildcards", "(", "$", "value", ")", ";", "...
Wrap wild cards around the value. @param string $value Value. @return string|false Either the wildcard decorated input value, or `false` when encountering a non-string value.
[ "Wrap", "wild", "cards", "around", "the", "value", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Like.php#L113-L129
FriendsOfCake/search
src/Model/Filter/Like.php
Like._setEscaper
protected function _setEscaper() { if ($this->getConfig('escaper') === null) { $query = $this->getQuery(); if (!$query instanceof Query) { throw new RuntimeException('$query must be instance of Cake\ORM\Query to be able to check driver name.'); } $driver = get_class($query->getConnection()->getDriver()); $driverName = 'Sqlserver'; if (substr_compare($driver, $driverName, -strlen($driverName)) === 0) { $this->setConfig('escaper', 'Search.Sqlserver'); } else { $this->setConfig('escaper', 'Search.Default'); } } $class = $this->getConfig('escaper'); $className = App::className($class, 'Model/Filter/Escaper', 'Escaper'); if (!$className) { throw new InvalidArgumentException(sprintf( 'Escape driver "%s" in like filter was not found.', $class )); } $this->_escaper = new $className($this->getConfig()); }
php
protected function _setEscaper() { if ($this->getConfig('escaper') === null) { $query = $this->getQuery(); if (!$query instanceof Query) { throw new RuntimeException('$query must be instance of Cake\ORM\Query to be able to check driver name.'); } $driver = get_class($query->getConnection()->getDriver()); $driverName = 'Sqlserver'; if (substr_compare($driver, $driverName, -strlen($driverName)) === 0) { $this->setConfig('escaper', 'Search.Sqlserver'); } else { $this->setConfig('escaper', 'Search.Default'); } } $class = $this->getConfig('escaper'); $className = App::className($class, 'Model/Filter/Escaper', 'Escaper'); if (!$className) { throw new InvalidArgumentException(sprintf( 'Escape driver "%s" in like filter was not found.', $class )); } $this->_escaper = new $className($this->getConfig()); }
[ "protected", "function", "_setEscaper", "(", ")", "{", "if", "(", "$", "this", "->", "getConfig", "(", "'escaper'", ")", "===", "null", ")", "{", "$", "query", "=", "$", "this", "->", "getQuery", "(", ")", ";", "if", "(", "!", "$", "query", "instan...
set configuration for escape driver name @return void @throws \InvalidArgumentException
[ "set", "configuration", "for", "escape", "driver", "name" ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Like.php#L151-L177
FriendsOfCake/search
src/Model/Filter/Base.php
Base.field
public function field() { $field = $this->getConfig('field'); if (!$this->getConfig('aliasField')) { return $field; } $repository = $this->manager()->getRepository(); if (!method_exists($repository, 'aliasField')) { return $field; } if (is_string($field)) { return $repository->aliasField($field); } $return = []; foreach ($field as $fld) { $return[] = $repository->aliasField($fld); } return $return; }
php
public function field() { $field = $this->getConfig('field'); if (!$this->getConfig('aliasField')) { return $field; } $repository = $this->manager()->getRepository(); if (!method_exists($repository, 'aliasField')) { return $field; } if (is_string($field)) { return $repository->aliasField($field); } $return = []; foreach ($field as $fld) { $return[] = $repository->aliasField($fld); } return $return; }
[ "public", "function", "field", "(", ")", "{", "$", "field", "=", "$", "this", "->", "getConfig", "(", "'field'", ")", ";", "if", "(", "!", "$", "this", "->", "getConfig", "(", "'aliasField'", ")", ")", "{", "return", "$", "field", ";", "}", "$", ...
Get the database field name. @deprecated Use fields() instead. @return string|array
[ "Get", "the", "database", "field", "name", "." ]
train
https://github.com/FriendsOfCake/search/blob/b57d024a2d83215d402dae79b2bcad0142e712fd/src/Model/Filter/Base.php#L108-L130