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
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Eresus/EresusCMS
src/core/Feed/Writer.php
Eresus_Feed_Writer.generateFeed
public function generateFeed() { // TODO Вынести возврат заголовков в отдельный метод //header("Content-type: text/xml"); $feed = $this->generateHead() . $this->generateChannels() . $this->generateItems() . $this->generateTale(); return $feed; }
php
public function generateFeed() { // TODO Вынести возврат заголовков в отдельный метод //header("Content-type: text/xml"); $feed = $this->generateHead() . $this->generateChannels() . $this->generateItems() . $this->generateTale(); return $feed; }
[ "public", "function", "generateFeed", "(", ")", "{", "// TODO Вынести возврат заголовков в отдельный метод", "//header(\"Content-type: text/xml\");", "$", "feed", "=", "$", "this", "->", "generateHead", "(", ")", ".", "$", "this", "->", "generateChannels", "(", ")", ".", "$", "this", "->", "generateItems", "(", ")", ".", "$", "this", "->", "generateTale", "(", ")", ";", "return", "$", "feed", ";", "}" ]
Возвращает разметку RSS/ATOM @return string RSS/ATOM
[ "Возвращает", "разметку", "RSS", "/", "ATOM" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Feed/Writer.php#L133-L145
Eresus/EresusCMS
src/core/Feed/Writer.php
Eresus_Feed_Writer.generateHead
private function generateHead() { $out = '<?xml version="1.0" encoding="utf-8"?>' . "\n"; if ($this->version == self::RSS2) { $out .= '<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" >' . PHP_EOL; } elseif ($this->version == self::RSS1) { $out .= '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" >' . PHP_EOL; } elseif ($this->version == self::ATOM) { $out .= '<feed xmlns="http://www.w3.org/2005/Atom">' . PHP_EOL; } return $out; }
php
private function generateHead() { $out = '<?xml version="1.0" encoding="utf-8"?>' . "\n"; if ($this->version == self::RSS2) { $out .= '<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" >' . PHP_EOL; } elseif ($this->version == self::RSS1) { $out .= '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" >' . PHP_EOL; } elseif ($this->version == self::ATOM) { $out .= '<feed xmlns="http://www.w3.org/2005/Atom">' . PHP_EOL; } return $out; }
[ "private", "function", "generateHead", "(", ")", "{", "$", "out", "=", "'<?xml version=\"1.0\" encoding=\"utf-8\"?>'", ".", "\"\\n\"", ";", "if", "(", "$", "this", "->", "version", "==", "self", "::", "RSS2", ")", "{", "$", "out", ".=", "'<rss version=\"2.0\"\n\t\t\t\t\txmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n\t\t\t\t\txmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n\t\t\t\t >'", ".", "PHP_EOL", ";", "}", "elseif", "(", "$", "this", "->", "version", "==", "self", "::", "RSS1", ")", "{", "$", "out", ".=", "'<rdf:RDF\n\t\t\t\t\t xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\t\t\t\t\t xmlns=\"http://purl.org/rss/1.0/\"\n\t\t\t\t\t xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n\t\t\t\t\t>'", ".", "PHP_EOL", ";", "}", "elseif", "(", "$", "this", "->", "version", "==", "self", "::", "ATOM", ")", "{", "$", "out", ".=", "'<feed xmlns=\"http://www.w3.org/2005/Atom\">'", ".", "PHP_EOL", ";", "}", "return", "$", "out", ";", "}" ]
Prints the xml and rss namespace @return string
[ "Prints", "the", "xml", "and", "rss", "namespace" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Feed/Writer.php#L254-L278
Eresus/EresusCMS
src/core/Feed/Writer.php
Eresus_Feed_Writer.makeNode
private function makeNode($tagName, $tagContent, $attributes = null) { $nodeText = ''; $attrText = ''; if (is_array($attributes)) { foreach ($attributes as $key => $value) { $attrText .= " $key=\"$value\" "; } } if (is_array($tagContent) && $this->version == self::RSS1) { $attrText = ' rdf:parseType="Resource"'; } $attrText .= (in_array($tagName, $this->CDATAEncoding) && $this->version == self::ATOM)? ' type="html" ' : ''; $nodeText .= (in_array($tagName, $this->CDATAEncoding))? "<{$tagName}{$attrText}><![CDATA[" : "<{$tagName}{$attrText}>"; if (is_array($tagContent)) { foreach ($tagContent as $key => $value) { $nodeText .= $this->makeNode($key, $value); } } else { $nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? $this->sanitizeCDATA($tagContent) : htmlspecialchars($tagContent); } $nodeText .= (in_array($tagName, $this->CDATAEncoding))? "]]></$tagName>" : "</$tagName>"; return $nodeText . PHP_EOL; }
php
private function makeNode($tagName, $tagContent, $attributes = null) { $nodeText = ''; $attrText = ''; if (is_array($attributes)) { foreach ($attributes as $key => $value) { $attrText .= " $key=\"$value\" "; } } if (is_array($tagContent) && $this->version == self::RSS1) { $attrText = ' rdf:parseType="Resource"'; } $attrText .= (in_array($tagName, $this->CDATAEncoding) && $this->version == self::ATOM)? ' type="html" ' : ''; $nodeText .= (in_array($tagName, $this->CDATAEncoding))? "<{$tagName}{$attrText}><![CDATA[" : "<{$tagName}{$attrText}>"; if (is_array($tagContent)) { foreach ($tagContent as $key => $value) { $nodeText .= $this->makeNode($key, $value); } } else { $nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? $this->sanitizeCDATA($tagContent) : htmlspecialchars($tagContent); } $nodeText .= (in_array($tagName, $this->CDATAEncoding))? "]]></$tagName>" : "</$tagName>"; return $nodeText . PHP_EOL; }
[ "private", "function", "makeNode", "(", "$", "tagName", ",", "$", "tagContent", ",", "$", "attributes", "=", "null", ")", "{", "$", "nodeText", "=", "''", ";", "$", "attrText", "=", "''", ";", "if", "(", "is_array", "(", "$", "attributes", ")", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "attrText", ".=", "\" $key=\\\"$value\\\" \"", ";", "}", "}", "if", "(", "is_array", "(", "$", "tagContent", ")", "&&", "$", "this", "->", "version", "==", "self", "::", "RSS1", ")", "{", "$", "attrText", "=", "' rdf:parseType=\"Resource\"'", ";", "}", "$", "attrText", ".=", "(", "in_array", "(", "$", "tagName", ",", "$", "this", "->", "CDATAEncoding", ")", "&&", "$", "this", "->", "version", "==", "self", "::", "ATOM", ")", "?", "' type=\"html\" '", ":", "''", ";", "$", "nodeText", ".=", "(", "in_array", "(", "$", "tagName", ",", "$", "this", "->", "CDATAEncoding", ")", ")", "?", "\"<{$tagName}{$attrText}><![CDATA[\"", ":", "\"<{$tagName}{$attrText}>\"", ";", "if", "(", "is_array", "(", "$", "tagContent", ")", ")", "{", "foreach", "(", "$", "tagContent", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "nodeText", ".=", "$", "this", "->", "makeNode", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "else", "{", "$", "nodeText", ".=", "(", "in_array", "(", "$", "tagName", ",", "$", "this", "->", "CDATAEncoding", ")", ")", "?", "$", "this", "->", "sanitizeCDATA", "(", "$", "tagContent", ")", ":", "htmlspecialchars", "(", "$", "tagContent", ")", ";", "}", "$", "nodeText", ".=", "(", "in_array", "(", "$", "tagName", ",", "$", "this", "->", "CDATAEncoding", ")", ")", "?", "\"]]></$tagName>\"", ":", "\"</$tagName>\"", ";", "return", "$", "nodeText", ".", "PHP_EOL", ";", "}" ]
Creates a single node as xml format @param string $tagName name of the tag @param mixed $tagContent tag value as string or array of nested tags in 'tagName' => 'tagValue' format @param array $attributes Attributes (if any) in 'attrName' => 'attrValue' format @return string formatted xml tag
[ "Creates", "a", "single", "node", "as", "xml", "format" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Feed/Writer.php#L316-L357
Eresus/EresusCMS
src/core/Feed/Writer.php
Eresus_Feed_Writer.generateChannels
private function generateChannels() { $out = ''; //Start channel tag switch ($this->version) { case self::RSS2: $out .= '<channel>' . PHP_EOL; break; case self::RSS1: $out .= (isset($this->data['ChannelAbout']))? "<channel rdf:about=\"{$this->data['ChannelAbout']}\">" : "<channel rdf:about=\"{$this->channels['link']}\">"; break; } //Print Items of channel foreach ($this->channels as $key => $value) { if ($this->version == self::ATOM && $key == 'link') { // ATOM prints link element as href attribute $out .= $this->makeNode($key,'',array('href'=>$value, 'rel'=>'self', 'type'=>'application/atom+xml')); //Add the id for ATOM $out .= $this->makeNode('id',$this->uuid($value,'urn:uuid:')); } else { $out .= $this->makeNode($key, $value); } } //RSS 1.0 have special tag <rdf:Seq> with channel if ($this->version == self::RSS1) { $out .= "<items>" . PHP_EOL . "<rdf:Seq>" . PHP_EOL; foreach ($this->items as $item) { $thisItems = $item->getElements(); $out .= "<rdf:li resource=\"{$thisItems['link']['content']}\"/>" . PHP_EOL; } $out .= "</rdf:Seq>" . PHP_EOL . "</items>" . PHP_EOL . "</channel>" . PHP_EOL; } return $out; }
php
private function generateChannels() { $out = ''; //Start channel tag switch ($this->version) { case self::RSS2: $out .= '<channel>' . PHP_EOL; break; case self::RSS1: $out .= (isset($this->data['ChannelAbout']))? "<channel rdf:about=\"{$this->data['ChannelAbout']}\">" : "<channel rdf:about=\"{$this->channels['link']}\">"; break; } //Print Items of channel foreach ($this->channels as $key => $value) { if ($this->version == self::ATOM && $key == 'link') { // ATOM prints link element as href attribute $out .= $this->makeNode($key,'',array('href'=>$value, 'rel'=>'self', 'type'=>'application/atom+xml')); //Add the id for ATOM $out .= $this->makeNode('id',$this->uuid($value,'urn:uuid:')); } else { $out .= $this->makeNode($key, $value); } } //RSS 1.0 have special tag <rdf:Seq> with channel if ($this->version == self::RSS1) { $out .= "<items>" . PHP_EOL . "<rdf:Seq>" . PHP_EOL; foreach ($this->items as $item) { $thisItems = $item->getElements(); $out .= "<rdf:li resource=\"{$thisItems['link']['content']}\"/>" . PHP_EOL; } $out .= "</rdf:Seq>" . PHP_EOL . "</items>" . PHP_EOL . "</channel>" . PHP_EOL; } return $out; }
[ "private", "function", "generateChannels", "(", ")", "{", "$", "out", "=", "''", ";", "//Start channel tag", "switch", "(", "$", "this", "->", "version", ")", "{", "case", "self", "::", "RSS2", ":", "$", "out", ".=", "'<channel>'", ".", "PHP_EOL", ";", "break", ";", "case", "self", "::", "RSS1", ":", "$", "out", ".=", "(", "isset", "(", "$", "this", "->", "data", "[", "'ChannelAbout'", "]", ")", ")", "?", "\"<channel rdf:about=\\\"{$this->data['ChannelAbout']}\\\">\"", ":", "\"<channel rdf:about=\\\"{$this->channels['link']}\\\">\"", ";", "break", ";", "}", "//Print Items of channel", "foreach", "(", "$", "this", "->", "channels", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "this", "->", "version", "==", "self", "::", "ATOM", "&&", "$", "key", "==", "'link'", ")", "{", "// ATOM prints link element as href attribute", "$", "out", ".=", "$", "this", "->", "makeNode", "(", "$", "key", ",", "''", ",", "array", "(", "'href'", "=>", "$", "value", ",", "'rel'", "=>", "'self'", ",", "'type'", "=>", "'application/atom+xml'", ")", ")", ";", "//Add the id for ATOM", "$", "out", ".=", "$", "this", "->", "makeNode", "(", "'id'", ",", "$", "this", "->", "uuid", "(", "$", "value", ",", "'urn:uuid:'", ")", ")", ";", "}", "else", "{", "$", "out", ".=", "$", "this", "->", "makeNode", "(", "$", "key", ",", "$", "value", ")", ";", "}", "}", "//RSS 1.0 have special tag <rdf:Seq> with channel", "if", "(", "$", "this", "->", "version", "==", "self", "::", "RSS1", ")", "{", "$", "out", ".=", "\"<items>\"", ".", "PHP_EOL", ".", "\"<rdf:Seq>\"", ".", "PHP_EOL", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "$", "thisItems", "=", "$", "item", "->", "getElements", "(", ")", ";", "$", "out", ".=", "\"<rdf:li resource=\\\"{$thisItems['link']['content']}\\\"/>\"", ".", "PHP_EOL", ";", "}", "$", "out", ".=", "\"</rdf:Seq>\"", ".", "PHP_EOL", ".", "\"</items>\"", ".", "PHP_EOL", ".", "\"</channel>\"", ".", "PHP_EOL", ";", "}", "return", "$", "out", ";", "}" ]
Print channels @return string
[ "Print", "channels" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Feed/Writer.php#L365-L411
Eresus/EresusCMS
src/core/Feed/Writer.php
Eresus_Feed_Writer.generateItems
private function generateItems() { $out = ''; foreach ($this->items as $item) { $thisItems = $item->getElements(); //the argument is printed as rdf:about attribute of item in rss 1.0 $out .= $this->startItem($thisItems['link']['content']); foreach ($thisItems as $feedItem ) { $out .= $this->makeNode($feedItem['name'], $feedItem['content'], $feedItem['attributes']); } $out .= $this->endItem(); } return $out; }
php
private function generateItems() { $out = ''; foreach ($this->items as $item) { $thisItems = $item->getElements(); //the argument is printed as rdf:about attribute of item in rss 1.0 $out .= $this->startItem($thisItems['link']['content']); foreach ($thisItems as $feedItem ) { $out .= $this->makeNode($feedItem['name'], $feedItem['content'], $feedItem['attributes']); } $out .= $this->endItem(); } return $out; }
[ "private", "function", "generateItems", "(", ")", "{", "$", "out", "=", "''", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "$", "thisItems", "=", "$", "item", "->", "getElements", "(", ")", ";", "//the argument is printed as rdf:about attribute of item in rss 1.0", "$", "out", ".=", "$", "this", "->", "startItem", "(", "$", "thisItems", "[", "'link'", "]", "[", "'content'", "]", ")", ";", "foreach", "(", "$", "thisItems", "as", "$", "feedItem", ")", "{", "$", "out", ".=", "$", "this", "->", "makeNode", "(", "$", "feedItem", "[", "'name'", "]", ",", "$", "feedItem", "[", "'content'", "]", ",", "$", "feedItem", "[", "'attributes'", "]", ")", ";", "}", "$", "out", ".=", "$", "this", "->", "endItem", "(", ")", ";", "}", "return", "$", "out", ";", "}" ]
Prints formatted feed items @return string
[ "Prints", "formatted", "feed", "items" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Feed/Writer.php#L419-L436
Eresus/EresusCMS
src/core/Feed/Writer.php
Eresus_Feed_Writer.startItem
private function startItem($about = false) { $out = ''; if ($this->version == self::RSS2) { $out .= '<item>' . PHP_EOL; } elseif ($this->version == self::RSS1) { if ($about) { $out .= "<item rdf:about=\"$about\">" . PHP_EOL; } else { throw new LogicException('link element is not set .\n' . 'It\'s required for RSS 1.0 to be used as about attribute of item'); } } elseif ($this->version == self::ATOM) { $out .= "<entry>" . PHP_EOL; } return $out; }
php
private function startItem($about = false) { $out = ''; if ($this->version == self::RSS2) { $out .= '<item>' . PHP_EOL; } elseif ($this->version == self::RSS1) { if ($about) { $out .= "<item rdf:about=\"$about\">" . PHP_EOL; } else { throw new LogicException('link element is not set .\n' . 'It\'s required for RSS 1.0 to be used as about attribute of item'); } } elseif ($this->version == self::ATOM) { $out .= "<entry>" . PHP_EOL; } return $out; }
[ "private", "function", "startItem", "(", "$", "about", "=", "false", ")", "{", "$", "out", "=", "''", ";", "if", "(", "$", "this", "->", "version", "==", "self", "::", "RSS2", ")", "{", "$", "out", ".=", "'<item>'", ".", "PHP_EOL", ";", "}", "elseif", "(", "$", "this", "->", "version", "==", "self", "::", "RSS1", ")", "{", "if", "(", "$", "about", ")", "{", "$", "out", ".=", "\"<item rdf:about=\\\"$about\\\">\"", ".", "PHP_EOL", ";", "}", "else", "{", "throw", "new", "LogicException", "(", "'link element is not set .\\n'", ".", "'It\\'s required for RSS 1.0 to be used as about attribute of item'", ")", ";", "}", "}", "elseif", "(", "$", "this", "->", "version", "==", "self", "::", "ATOM", ")", "{", "$", "out", ".=", "\"<entry>\"", ".", "PHP_EOL", ";", "}", "return", "$", "out", ";", "}" ]
Make the starting tag of channels @param bool|string $about The value of about tag which is used for only RSS 1.0 @throws LogicException @return string
[ "Make", "the", "starting", "tag", "of", "channels" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Feed/Writer.php#L446-L470
texthtml/oauth2-provider
src/OAuth2AuthenticationListener.php
OAuth2AuthenticationListener.handle
public function handle(GetResponseEvent $event) { $request = BridgeRequest::createFromRequest($event->getRequest()); $response = new BridgeResponse; if (!$this->oauth2Server->verifyResourceRequest($request, $response)) { return; } try { $token = $this->oauth2Server->getAccessTokenData($request); $token = $this->authenticationManager->authenticate( new OAuth2Token( $token['client_id'], $token['user_id'], $token['access_token'], $this->providerKey, [], explode(" ", $token['scope']) ) ); $this->tokenStorage->setToken($token); } catch (AuthenticationException $failed) { $this->handleAuthenticationError($event, $request, $failed); } }
php
public function handle(GetResponseEvent $event) { $request = BridgeRequest::createFromRequest($event->getRequest()); $response = new BridgeResponse; if (!$this->oauth2Server->verifyResourceRequest($request, $response)) { return; } try { $token = $this->oauth2Server->getAccessTokenData($request); $token = $this->authenticationManager->authenticate( new OAuth2Token( $token['client_id'], $token['user_id'], $token['access_token'], $this->providerKey, [], explode(" ", $token['scope']) ) ); $this->tokenStorage->setToken($token); } catch (AuthenticationException $failed) { $this->handleAuthenticationError($event, $request, $failed); } }
[ "public", "function", "handle", "(", "GetResponseEvent", "$", "event", ")", "{", "$", "request", "=", "BridgeRequest", "::", "createFromRequest", "(", "$", "event", "->", "getRequest", "(", ")", ")", ";", "$", "response", "=", "new", "BridgeResponse", ";", "if", "(", "!", "$", "this", "->", "oauth2Server", "->", "verifyResourceRequest", "(", "$", "request", ",", "$", "response", ")", ")", "{", "return", ";", "}", "try", "{", "$", "token", "=", "$", "this", "->", "oauth2Server", "->", "getAccessTokenData", "(", "$", "request", ")", ";", "$", "token", "=", "$", "this", "->", "authenticationManager", "->", "authenticate", "(", "new", "OAuth2Token", "(", "$", "token", "[", "'client_id'", "]", ",", "$", "token", "[", "'user_id'", "]", ",", "$", "token", "[", "'access_token'", "]", ",", "$", "this", "->", "providerKey", ",", "[", "]", ",", "explode", "(", "\" \"", ",", "$", "token", "[", "'scope'", "]", ")", ")", ")", ";", "$", "this", "->", "tokenStorage", "->", "setToken", "(", "$", "token", ")", ";", "}", "catch", "(", "AuthenticationException", "$", "failed", ")", "{", "$", "this", "->", "handleAuthenticationError", "(", "$", "event", ",", "$", "request", ",", "$", "failed", ")", ";", "}", "}" ]
Handles basic authentication. @param GetResponseEvent $event A GetResponseEvent instance
[ "Handles", "basic", "authentication", "." ]
train
https://github.com/texthtml/oauth2-provider/blob/a216205b8466ae16e0b8e17249ce89b90db1f5d4/src/OAuth2AuthenticationListener.php#L52-L77
inhere/php-librarys
src/Utils/DataCategory.php
DataCategory.getDataArray
public function getDataArray(array $need = []) { $arrData = $this->getData(); if ($need) { $arrList = []; foreach ($arrData as $item) { $needArr = array(); foreach ($need as $val) { if (isset($item[$val])) { $needArr[$val] = $item[$val]; } else { trigger_error('参数错误!' . $this->modelClass . '不存在字段:' . $val, E_USER_ERROR); } } $arrList[] = $needArr; } return $arrList; } return $arrData; }
php
public function getDataArray(array $need = []) { $arrData = $this->getData(); if ($need) { $arrList = []; foreach ($arrData as $item) { $needArr = array(); foreach ($need as $val) { if (isset($item[$val])) { $needArr[$val] = $item[$val]; } else { trigger_error('参数错误!' . $this->modelClass . '不存在字段:' . $val, E_USER_ERROR); } } $arrList[] = $needArr; } return $arrList; } return $arrData; }
[ "public", "function", "getDataArray", "(", "array", "$", "need", "=", "[", "]", ")", "{", "$", "arrData", "=", "$", "this", "->", "getData", "(", ")", ";", "if", "(", "$", "need", ")", "{", "$", "arrList", "=", "[", "]", ";", "foreach", "(", "$", "arrData", "as", "$", "item", ")", "{", "$", "needArr", "=", "array", "(", ")", ";", "foreach", "(", "$", "need", "as", "$", "val", ")", "{", "if", "(", "isset", "(", "$", "item", "[", "$", "val", "]", ")", ")", "{", "$", "needArr", "[", "$", "val", "]", "=", "$", "item", "[", "$", "val", "]", ";", "}", "else", "{", "trigger_error", "(", "'参数错误!' . $this->", "o", "e", "lCla", "ss", " . '不存在字段:", " ", " $val, E_USER_ERROR)", "", "", "", "", "", "", "", "}", "}", "$", "arrList", "[", "]", "=", "$", "needArr", ";", "}", "return", "$", "arrList", ";", "}", "return", "$", "arrData", ";", "}" ]
getDataArray 初始数据转换成的数组 @param array $need | 'all' [需要获取哪些字段值] 1. 'all' 全部字段 2. array('chName','enName') --> 获取数组仅含有 chName enName 字段 @return array
[ "getDataArray", "初始数据转换成的数组" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Utils/DataCategory.php#L80-L105
inhere/php-librarys
src/Utils/DataCategory.php
DataCategory.getCategoryArr
public function getCategoryArr($rootId = '0', array $need = [], $setKey = 'id') { $allDataArr = $this->getDataArray(); if ($rootId === '0' || $rootId === '') { return $allDataArr; } $arr_result = $needArr = array(); $id = $this->pkColumn; $parentId = $this->pidColumn; # 递归获取子级 $allNeedArr = $this->arrTree($allDataArr, $rootId); foreach ($allNeedArr as $value) { if (isset($value[$this->childKeyName])) { /** @var array $items */ $items = $value[$this->childKeyName]; foreach ($items as $key => $item) { foreach ($need as $val) { if (isset($item[$val])) { $needArr[$val] = $item[$val]; } else { throw new \RuntimeException('parameter error!' . $this->modelClass . 'There is no field in the table: ' . $val); } } if ($setKey === '') { $arr_result[] = $needArr; } else { $arr_result[$item[$setKey]] = $needArr; } } } } return $arr_result; }
php
public function getCategoryArr($rootId = '0', array $need = [], $setKey = 'id') { $allDataArr = $this->getDataArray(); if ($rootId === '0' || $rootId === '') { return $allDataArr; } $arr_result = $needArr = array(); $id = $this->pkColumn; $parentId = $this->pidColumn; # 递归获取子级 $allNeedArr = $this->arrTree($allDataArr, $rootId); foreach ($allNeedArr as $value) { if (isset($value[$this->childKeyName])) { /** @var array $items */ $items = $value[$this->childKeyName]; foreach ($items as $key => $item) { foreach ($need as $val) { if (isset($item[$val])) { $needArr[$val] = $item[$val]; } else { throw new \RuntimeException('parameter error!' . $this->modelClass . 'There is no field in the table: ' . $val); } } if ($setKey === '') { $arr_result[] = $needArr; } else { $arr_result[$item[$setKey]] = $needArr; } } } } return $arr_result; }
[ "public", "function", "getCategoryArr", "(", "$", "rootId", "=", "'0'", ",", "array", "$", "need", "=", "[", "]", ",", "$", "setKey", "=", "'id'", ")", "{", "$", "allDataArr", "=", "$", "this", "->", "getDataArray", "(", ")", ";", "if", "(", "$", "rootId", "===", "'0'", "||", "$", "rootId", "===", "''", ")", "{", "return", "$", "allDataArr", ";", "}", "$", "arr_result", "=", "$", "needArr", "=", "array", "(", ")", ";", "$", "id", "=", "$", "this", "->", "pkColumn", ";", "$", "parentId", "=", "$", "this", "->", "pidColumn", ";", "# 递归获取子级", "$", "allNeedArr", "=", "$", "this", "->", "arrTree", "(", "$", "allDataArr", ",", "$", "rootId", ")", ";", "foreach", "(", "$", "allNeedArr", "as", "$", "value", ")", "{", "if", "(", "isset", "(", "$", "value", "[", "$", "this", "->", "childKeyName", "]", ")", ")", "{", "/** @var array $items */", "$", "items", "=", "$", "value", "[", "$", "this", "->", "childKeyName", "]", ";", "foreach", "(", "$", "items", "as", "$", "key", "=>", "$", "item", ")", "{", "foreach", "(", "$", "need", "as", "$", "val", ")", "{", "if", "(", "isset", "(", "$", "item", "[", "$", "val", "]", ")", ")", "{", "$", "needArr", "[", "$", "val", "]", "=", "$", "item", "[", "$", "val", "]", ";", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "'parameter error!'", ".", "$", "this", "->", "modelClass", ".", "'There is no field in the table: '", ".", "$", "val", ")", ";", "}", "}", "if", "(", "$", "setKey", "===", "''", ")", "{", "$", "arr_result", "[", "]", "=", "$", "needArr", ";", "}", "else", "{", "$", "arr_result", "[", "$", "item", "[", "$", "setKey", "]", "]", "=", "$", "needArr", ";", "}", "}", "}", "}", "return", "$", "arr_result", ";", "}" ]
[getCategoryArr 指定层级父id(parentId),获取其下面的子级初始数据数组] @param string $rootId [ 当等于0时,等同于 调用 getDataArray() ] @param array $need @see getDataArray() @param string $setKey @return array @throws \RuntimeException
[ "[", "getCategoryArr", "指定层级父id", "(", "parentId", ")", ",获取其下面的子级初始数据数组", "]" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Utils/DataCategory.php#L115-L154
inhere/php-librarys
src/Utils/DataCategory.php
DataCategory.getCategoryTree
public function getCategoryTree($rootId = 0, array $need = [], $setKey = 'id') { if (!$rootId) { $rootId = 0; } if ($need) { $need = array_merge([$this->pkColumn, $this->pidColumn], $need); } $arrList = $this->getDataArray($need); return $this->arrTree($arrList, $rootId, $setKey); }
php
public function getCategoryTree($rootId = 0, array $need = [], $setKey = 'id') { if (!$rootId) { $rootId = 0; } if ($need) { $need = array_merge([$this->pkColumn, $this->pidColumn], $need); } $arrList = $this->getDataArray($need); return $this->arrTree($arrList, $rootId, $setKey); }
[ "public", "function", "getCategoryTree", "(", "$", "rootId", "=", "0", ",", "array", "$", "need", "=", "[", "]", ",", "$", "setKey", "=", "'id'", ")", "{", "if", "(", "!", "$", "rootId", ")", "{", "$", "rootId", "=", "0", ";", "}", "if", "(", "$", "need", ")", "{", "$", "need", "=", "array_merge", "(", "[", "$", "this", "->", "pkColumn", ",", "$", "this", "->", "pidColumn", "]", ",", "$", "need", ")", ";", "}", "$", "arrList", "=", "$", "this", "->", "getDataArray", "(", "$", "need", ")", ";", "return", "$", "this", "->", "arrTree", "(", "$", "arrList", ",", "$", "rootId", ",", "$", "setKey", ")", ";", "}" ]
getCategory 递归获取树形图 @param string|int $rootId [开始层父级id 默认 0,顶级] @param array|string $need 需要获取哪些字段值,id pid默认含有 1. [] 全部字段 2. array('chName','enName') --> 获取含有 id pid chName enName 字段 @param string $setKey 需要什么作为 树形数组的 键名,默认:主键id值为键,留空为自增的数字. e.g. id | enName @return array
[ "getCategory", "递归获取树形图" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Utils/DataCategory.php#L165-L178
inhere/php-librarys
src/Utils/DataCategory.php
DataCategory.arrTree
public function arrTree(array $tree, $rootId = 0, $setKey = 'id') { $result = []; $id = $this->pkColumn; $parentId = $this->pidColumn; $childKey = $this->childKeyName; foreach ($tree as $leaf) { if ($leaf[$parentId] === $rootId) { foreach ($tree as $subLeaf) { if ($subLeaf[$parentId] === $leaf[$id]) { $leaf[$childKey] = $this->arrTree($tree, $leaf[$id], $setKey); break; } } if ($setKey) { $result[$leaf[$setKey]] = $leaf; } else { $result[] = $leaf; } } } return $result; }
php
public function arrTree(array $tree, $rootId = 0, $setKey = 'id') { $result = []; $id = $this->pkColumn; $parentId = $this->pidColumn; $childKey = $this->childKeyName; foreach ($tree as $leaf) { if ($leaf[$parentId] === $rootId) { foreach ($tree as $subLeaf) { if ($subLeaf[$parentId] === $leaf[$id]) { $leaf[$childKey] = $this->arrTree($tree, $leaf[$id], $setKey); break; } } if ($setKey) { $result[$leaf[$setKey]] = $leaf; } else { $result[] = $leaf; } } } return $result; }
[ "public", "function", "arrTree", "(", "array", "$", "tree", ",", "$", "rootId", "=", "0", ",", "$", "setKey", "=", "'id'", ")", "{", "$", "result", "=", "[", "]", ";", "$", "id", "=", "$", "this", "->", "pkColumn", ";", "$", "parentId", "=", "$", "this", "->", "pidColumn", ";", "$", "childKey", "=", "$", "this", "->", "childKeyName", ";", "foreach", "(", "$", "tree", "as", "$", "leaf", ")", "{", "if", "(", "$", "leaf", "[", "$", "parentId", "]", "===", "$", "rootId", ")", "{", "foreach", "(", "$", "tree", "as", "$", "subLeaf", ")", "{", "if", "(", "$", "subLeaf", "[", "$", "parentId", "]", "===", "$", "leaf", "[", "$", "id", "]", ")", "{", "$", "leaf", "[", "$", "childKey", "]", "=", "$", "this", "->", "arrTree", "(", "$", "tree", ",", "$", "leaf", "[", "$", "id", "]", ",", "$", "setKey", ")", ";", "break", ";", "}", "}", "if", "(", "$", "setKey", ")", "{", "$", "result", "[", "$", "leaf", "[", "$", "setKey", "]", "]", "=", "$", "leaf", ";", "}", "else", "{", "$", "result", "[", "]", "=", "$", "leaf", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
arrTree 树形数组递归 @param array $tree 需要处理的原始数组 @param integer $rootId 开始层父级id 默认 0,顶级 @param string $setKey 需要什么作为 树形数组的 键名,默认:主键id值为键,留空为自增的数字. e.g. id | enName @return array
[ "arrTree", "树形数组递归" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Utils/DataCategory.php#L187-L212
Eresus/EresusCMS
src/core/framework/core/3rdparty/dwoo/Dwoo/Block/Plugin.php
Dwoo_Block_Plugin.preProcessing
public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) { return Dwoo_Compiler::PHP_OPEN.$prepend.'$this->addStack("'.$type.'", array('.Dwoo_Compiler::implode_r($compiler->getCompiledParams($params)).'));'.$append.Dwoo_Compiler::PHP_CLOSE; }
php
public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type) { return Dwoo_Compiler::PHP_OPEN.$prepend.'$this->addStack("'.$type.'", array('.Dwoo_Compiler::implode_r($compiler->getCompiledParams($params)).'));'.$append.Dwoo_Compiler::PHP_CLOSE; }
[ "public", "static", "function", "preProcessing", "(", "Dwoo_Compiler", "$", "compiler", ",", "array", "$", "params", ",", "$", "prepend", ",", "$", "append", ",", "$", "type", ")", "{", "return", "Dwoo_Compiler", "::", "PHP_OPEN", ".", "$", "prepend", ".", "'$this->addStack(\"'", ".", "$", "type", ".", "'\", array('", ".", "Dwoo_Compiler", "::", "implode_r", "(", "$", "compiler", "->", "getCompiledParams", "(", "$", "params", ")", ")", ".", "'));'", ".", "$", "append", ".", "Dwoo_Compiler", "::", "PHP_CLOSE", ";", "}" ]
called at compile time to define what the block should output in the compiled template code, happens when the block is declared basically this will replace the {block arg arg arg} tag in the template @param Dwoo_Compiler $compiler the compiler instance that calls this function @param array $params an array containing original and compiled parameters @param string $prepend that is just meant to allow a child class to call parent::postProcessing($compiler, $params, "foo();") to add a command before the default commands are executed @param string $append that is just meant to allow a child class to call parent::postProcessing($compiler, $params, null, "foo();") to add a command after the default commands are executed @param string $type the type is the plugin class name used
[ "called", "at", "compile", "time", "to", "define", "what", "the", "block", "should", "output", "in", "the", "compiled", "template", "code", "happens", "when", "the", "block", "is", "declared" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/dwoo/Dwoo/Block/Plugin.php#L78-L81
ekuiter/feature-php
FeaturePhp/Exporter/DownloadZipExporter.php
DownloadZipExporter.download
private function download($productLineName) { $productLineName = str_replace("\"", "", $productLineName); if (headers_sent()) throw new DownloadZipExporterException("could download zip archive"); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=\"$productLineName.zip\""); set_time_limit(0); $file = @fopen($this->target, "rb"); while(!feof($file)) { print(@fread($file, 1024*8)); ob_flush(); flush(); } }
php
private function download($productLineName) { $productLineName = str_replace("\"", "", $productLineName); if (headers_sent()) throw new DownloadZipExporterException("could download zip archive"); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=\"$productLineName.zip\""); set_time_limit(0); $file = @fopen($this->target, "rb"); while(!feof($file)) { print(@fread($file, 1024*8)); ob_flush(); flush(); } }
[ "private", "function", "download", "(", "$", "productLineName", ")", "{", "$", "productLineName", "=", "str_replace", "(", "\"\\\"\"", ",", "\"\"", ",", "$", "productLineName", ")", ";", "if", "(", "headers_sent", "(", ")", ")", "throw", "new", "DownloadZipExporterException", "(", "\"could download zip archive\"", ")", ";", "header", "(", "\"Content-Type: application/zip\"", ")", ";", "header", "(", "\"Content-Disposition: attachment; filename=\\\"$productLineName.zip\\\"\"", ")", ";", "set_time_limit", "(", "0", ")", ";", "$", "file", "=", "@", "fopen", "(", "$", "this", "->", "target", ",", "\"rb\"", ")", ";", "while", "(", "!", "feof", "(", "$", "file", ")", ")", "{", "print", "(", "@", "fread", "(", "$", "file", ",", "1024", "*", "8", ")", ")", ";", "ob_flush", "(", ")", ";", "flush", "(", ")", ";", "}", "}" ]
Downloads the temporary ZIP archive. This only works when no headers and no output have been sent yet, otherwise users receive corrupted ZIP files. @param string $productLineName the name of the product line, used as the ZIP archive file name
[ "Downloads", "the", "temporary", "ZIP", "archive", ".", "This", "only", "works", "when", "no", "headers", "and", "no", "output", "have", "been", "sent", "yet", "otherwise", "users", "receive", "corrupted", "ZIP", "files", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Exporter/DownloadZipExporter.php#L55-L68
ekuiter/feature-php
FeaturePhp/Exporter/DownloadZipExporter.php
DownloadZipExporter.export
public function export($product) { try { parent::export($product); $this->download($product->getProductLine()->getName()); } catch (\Exception $e) {} try { $this->remove(); } catch (\Exception $e) {} }
php
public function export($product) { try { parent::export($product); $this->download($product->getProductLine()->getName()); } catch (\Exception $e) {} try { $this->remove(); } catch (\Exception $e) {} }
[ "public", "function", "export", "(", "$", "product", ")", "{", "try", "{", "parent", "::", "export", "(", "$", "product", ")", ";", "$", "this", "->", "download", "(", "$", "product", "->", "getProductLine", "(", ")", "->", "getName", "(", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "try", "{", "$", "this", "->", "remove", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "}" ]
Exports a product as a ZIP archive and offers it for downloading. This only works when no headers and no output have been sent yet. Note that any occurring errors are ignored so that the downloaded archive will not be corrupted. There is currently no way to obtain error information in this case because feature-php does not have an external log file. @param \FeaturePhp\ProductLine\Product $product
[ "Exports", "a", "product", "as", "a", "ZIP", "archive", "and", "offers", "it", "for", "downloading", ".", "This", "only", "works", "when", "no", "headers", "and", "no", "output", "have", "been", "sent", "yet", ".", "Note", "that", "any", "occurring", "errors", "are", "ignored", "so", "that", "the", "downloaded", "archive", "will", "not", "be", "corrupted", ".", "There", "is", "currently", "no", "way", "to", "obtain", "error", "information", "in", "this", "case", "because", "feature", "-", "php", "does", "not", "have", "an", "external", "log", "file", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Exporter/DownloadZipExporter.php#L78-L87
php-lug/lug
src/Bundle/AdminBundle/DependencyInjection/LugAdminExtension.php
LugAdminExtension.prepend
public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); if (isset($bundles['LugGridBundle'])) { $resources = [ 'body', 'column_action', 'column_sorting', 'column_sortings', 'filters', 'global_action', ]; $templates = []; foreach ($resources as $resource) { $templates[$resource] = '@LugAdmin/Grid/'.$resource.'.html.twig'; } $container->prependExtensionConfig('lug_grid', ['templates' => $templates]); } }
php
public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); if (isset($bundles['LugGridBundle'])) { $resources = [ 'body', 'column_action', 'column_sorting', 'column_sortings', 'filters', 'global_action', ]; $templates = []; foreach ($resources as $resource) { $templates[$resource] = '@LugAdmin/Grid/'.$resource.'.html.twig'; } $container->prependExtensionConfig('lug_grid', ['templates' => $templates]); } }
[ "public", "function", "prepend", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "bundles", "=", "$", "container", "->", "getParameter", "(", "'kernel.bundles'", ")", ";", "if", "(", "isset", "(", "$", "bundles", "[", "'LugGridBundle'", "]", ")", ")", "{", "$", "resources", "=", "[", "'body'", ",", "'column_action'", ",", "'column_sorting'", ",", "'column_sortings'", ",", "'filters'", ",", "'global_action'", ",", "]", ";", "$", "templates", "=", "[", "]", ";", "foreach", "(", "$", "resources", "as", "$", "resource", ")", "{", "$", "templates", "[", "$", "resource", "]", "=", "'@LugAdmin/Grid/'", ".", "$", "resource", ".", "'.html.twig'", ";", "}", "$", "container", "->", "prependExtensionConfig", "(", "'lug_grid'", ",", "[", "'templates'", "=>", "$", "templates", "]", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/AdminBundle/DependencyInjection/LugAdminExtension.php#L40-L62
VincentChalnot/SidusDataGridBundle
DependencyInjection/SidusDataGridExtension.php
SidusDataGridExtension.load
public function load(array $configs, ContainerBuilder $container) { parent::load($configs, $container); $configuration = $this->createConfigurationParser(); $this->globalConfiguration = $this->processConfiguration($configuration, $configs); $dataGridRegistry = $container->getDefinition(DataGridRegistry::class); foreach ((array) $this->globalConfiguration['configurations'] as $code => $dataGridConfiguration) { $dataGridConfiguration = $this->finalizeConfiguration($code, $dataGridConfiguration); $dataGridRegistry->addMethodCall('addRawDataGridConfiguration', [$code, $dataGridConfiguration]); } }
php
public function load(array $configs, ContainerBuilder $container) { parent::load($configs, $container); $configuration = $this->createConfigurationParser(); $this->globalConfiguration = $this->processConfiguration($configuration, $configs); $dataGridRegistry = $container->getDefinition(DataGridRegistry::class); foreach ((array) $this->globalConfiguration['configurations'] as $code => $dataGridConfiguration) { $dataGridConfiguration = $this->finalizeConfiguration($code, $dataGridConfiguration); $dataGridRegistry->addMethodCall('addRawDataGridConfiguration', [$code, $dataGridConfiguration]); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "parent", "::", "load", "(", "$", "configs", ",", "$", "container", ")", ";", "$", "configuration", "=", "$", "this", "->", "createConfigurationParser", "(", ")", ";", "$", "this", "->", "globalConfiguration", "=", "$", "this", "->", "processConfiguration", "(", "$", "configuration", ",", "$", "configs", ")", ";", "$", "dataGridRegistry", "=", "$", "container", "->", "getDefinition", "(", "DataGridRegistry", "::", "class", ")", ";", "foreach", "(", "(", "array", ")", "$", "this", "->", "globalConfiguration", "[", "'configurations'", "]", "as", "$", "code", "=>", "$", "dataGridConfiguration", ")", "{", "$", "dataGridConfiguration", "=", "$", "this", "->", "finalizeConfiguration", "(", "$", "code", ",", "$", "dataGridConfiguration", ")", ";", "$", "dataGridRegistry", "->", "addMethodCall", "(", "'addRawDataGridConfiguration'", ",", "[", "$", "code", ",", "$", "dataGridConfiguration", "]", ")", ";", "}", "}" ]
{@inheritdoc} @throws \Exception
[ "{", "@inheritdoc", "}" ]
train
https://github.com/VincentChalnot/SidusDataGridBundle/blob/aa929113e2208ed335f514d2891affaf7fddf3f6/DependencyInjection/SidusDataGridExtension.php#L38-L50
VincentChalnot/SidusDataGridBundle
DependencyInjection/SidusDataGridExtension.php
SidusDataGridExtension.finalizeConfiguration
protected function finalizeConfiguration( string $code, array $dataGridConfiguration ): array { // Handle possible parent configuration @todo find a better way to do this if (isset($dataGridConfiguration['parent'])) { $parent = $dataGridConfiguration['parent']; if (empty($this->globalConfiguration['configurations'][$parent])) { throw new UnexpectedValueException("Unknown configuration {$parent}"); } $parentConfig = $this->globalConfiguration['configurations'][$parent]; $dataGridConfiguration = array_merge($parentConfig, $dataGridConfiguration); } unset($dataGridConfiguration['parent']); // Set default values from global configuration if (empty($dataGridConfiguration['form_theme'])) { $dataGridConfiguration['form_theme'] = $this->globalConfiguration['default_form_theme']; } if (empty($dataGridConfiguration['template'])) { $dataGridConfiguration['template'] = $this->globalConfiguration['default_datagrid_template']; } if (empty($dataGridConfiguration['column_value_renderer'])) { $dataGridConfiguration['column_value_renderer'] = $this->globalConfiguration['default_column_value_renderer']; } if (empty($dataGridConfiguration['column_label_renderer'])) { $dataGridConfiguration['column_label_renderer'] = $this->globalConfiguration['default_column_label_renderer']; } if (isset($dataGridConfiguration['query_handler'])) { // Allow either a service or a direct configuration for filters if (\is_array($dataGridConfiguration['query_handler'])) { $dataGridConfiguration['query_handler'] = $this->finalizeFilterConfiguration( $code, $dataGridConfiguration['query_handler'] ); } elseif (0 === strpos($dataGridConfiguration['query_handler'], '@')) { $dataGridConfiguration['query_handler'] = new Reference( ltrim($dataGridConfiguration['query_handler'], '@') ); } else { throw new UnexpectedValueException( 'query_handler option must be either a service or a valid filter configuration' ); } } return $dataGridConfiguration; }
php
protected function finalizeConfiguration( string $code, array $dataGridConfiguration ): array { // Handle possible parent configuration @todo find a better way to do this if (isset($dataGridConfiguration['parent'])) { $parent = $dataGridConfiguration['parent']; if (empty($this->globalConfiguration['configurations'][$parent])) { throw new UnexpectedValueException("Unknown configuration {$parent}"); } $parentConfig = $this->globalConfiguration['configurations'][$parent]; $dataGridConfiguration = array_merge($parentConfig, $dataGridConfiguration); } unset($dataGridConfiguration['parent']); // Set default values from global configuration if (empty($dataGridConfiguration['form_theme'])) { $dataGridConfiguration['form_theme'] = $this->globalConfiguration['default_form_theme']; } if (empty($dataGridConfiguration['template'])) { $dataGridConfiguration['template'] = $this->globalConfiguration['default_datagrid_template']; } if (empty($dataGridConfiguration['column_value_renderer'])) { $dataGridConfiguration['column_value_renderer'] = $this->globalConfiguration['default_column_value_renderer']; } if (empty($dataGridConfiguration['column_label_renderer'])) { $dataGridConfiguration['column_label_renderer'] = $this->globalConfiguration['default_column_label_renderer']; } if (isset($dataGridConfiguration['query_handler'])) { // Allow either a service or a direct configuration for filters if (\is_array($dataGridConfiguration['query_handler'])) { $dataGridConfiguration['query_handler'] = $this->finalizeFilterConfiguration( $code, $dataGridConfiguration['query_handler'] ); } elseif (0 === strpos($dataGridConfiguration['query_handler'], '@')) { $dataGridConfiguration['query_handler'] = new Reference( ltrim($dataGridConfiguration['query_handler'], '@') ); } else { throw new UnexpectedValueException( 'query_handler option must be either a service or a valid filter configuration' ); } } return $dataGridConfiguration; }
[ "protected", "function", "finalizeConfiguration", "(", "string", "$", "code", ",", "array", "$", "dataGridConfiguration", ")", ":", "array", "{", "// Handle possible parent configuration @todo find a better way to do this", "if", "(", "isset", "(", "$", "dataGridConfiguration", "[", "'parent'", "]", ")", ")", "{", "$", "parent", "=", "$", "dataGridConfiguration", "[", "'parent'", "]", ";", "if", "(", "empty", "(", "$", "this", "->", "globalConfiguration", "[", "'configurations'", "]", "[", "$", "parent", "]", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "\"Unknown configuration {$parent}\"", ")", ";", "}", "$", "parentConfig", "=", "$", "this", "->", "globalConfiguration", "[", "'configurations'", "]", "[", "$", "parent", "]", ";", "$", "dataGridConfiguration", "=", "array_merge", "(", "$", "parentConfig", ",", "$", "dataGridConfiguration", ")", ";", "}", "unset", "(", "$", "dataGridConfiguration", "[", "'parent'", "]", ")", ";", "// Set default values from global configuration", "if", "(", "empty", "(", "$", "dataGridConfiguration", "[", "'form_theme'", "]", ")", ")", "{", "$", "dataGridConfiguration", "[", "'form_theme'", "]", "=", "$", "this", "->", "globalConfiguration", "[", "'default_form_theme'", "]", ";", "}", "if", "(", "empty", "(", "$", "dataGridConfiguration", "[", "'template'", "]", ")", ")", "{", "$", "dataGridConfiguration", "[", "'template'", "]", "=", "$", "this", "->", "globalConfiguration", "[", "'default_datagrid_template'", "]", ";", "}", "if", "(", "empty", "(", "$", "dataGridConfiguration", "[", "'column_value_renderer'", "]", ")", ")", "{", "$", "dataGridConfiguration", "[", "'column_value_renderer'", "]", "=", "$", "this", "->", "globalConfiguration", "[", "'default_column_value_renderer'", "]", ";", "}", "if", "(", "empty", "(", "$", "dataGridConfiguration", "[", "'column_label_renderer'", "]", ")", ")", "{", "$", "dataGridConfiguration", "[", "'column_label_renderer'", "]", "=", "$", "this", "->", "globalConfiguration", "[", "'default_column_label_renderer'", "]", ";", "}", "if", "(", "isset", "(", "$", "dataGridConfiguration", "[", "'query_handler'", "]", ")", ")", "{", "// Allow either a service or a direct configuration for filters", "if", "(", "\\", "is_array", "(", "$", "dataGridConfiguration", "[", "'query_handler'", "]", ")", ")", "{", "$", "dataGridConfiguration", "[", "'query_handler'", "]", "=", "$", "this", "->", "finalizeFilterConfiguration", "(", "$", "code", ",", "$", "dataGridConfiguration", "[", "'query_handler'", "]", ")", ";", "}", "elseif", "(", "0", "===", "strpos", "(", "$", "dataGridConfiguration", "[", "'query_handler'", "]", ",", "'@'", ")", ")", "{", "$", "dataGridConfiguration", "[", "'query_handler'", "]", "=", "new", "Reference", "(", "ltrim", "(", "$", "dataGridConfiguration", "[", "'query_handler'", "]", ",", "'@'", ")", ")", ";", "}", "else", "{", "throw", "new", "UnexpectedValueException", "(", "'query_handler option must be either a service or a valid filter configuration'", ")", ";", "}", "}", "return", "$", "dataGridConfiguration", ";", "}" ]
Handle configuration parsing logic not handled by the semantic configuration definition @param string $code @param array $dataGridConfiguration @throws \Exception @return array
[ "Handle", "configuration", "parsing", "logic", "not", "handled", "by", "the", "semantic", "configuration", "definition" ]
train
https://github.com/VincentChalnot/SidusDataGridBundle/blob/aa929113e2208ed335f514d2891affaf7fddf3f6/DependencyInjection/SidusDataGridExtension.php#L62-L110
VincentChalnot/SidusDataGridBundle
DependencyInjection/SidusDataGridExtension.php
SidusDataGridExtension.finalizeFilterConfiguration
protected function finalizeFilterConfiguration(string $code, array $queryHandlerConfig): array { // Parse configuration using Configuration parser from FilterBundle $configuration = $this->createFilterConfigurationParser(); $parsedFilterConfig = $this->processConfiguration( $configuration, [ [ 'configurations' => [ $code => $queryHandlerConfig, ], ], ] ); return $parsedFilterConfig['configurations'][$code]; }
php
protected function finalizeFilterConfiguration(string $code, array $queryHandlerConfig): array { // Parse configuration using Configuration parser from FilterBundle $configuration = $this->createFilterConfigurationParser(); $parsedFilterConfig = $this->processConfiguration( $configuration, [ [ 'configurations' => [ $code => $queryHandlerConfig, ], ], ] ); return $parsedFilterConfig['configurations'][$code]; }
[ "protected", "function", "finalizeFilterConfiguration", "(", "string", "$", "code", ",", "array", "$", "queryHandlerConfig", ")", ":", "array", "{", "// Parse configuration using Configuration parser from FilterBundle", "$", "configuration", "=", "$", "this", "->", "createFilterConfigurationParser", "(", ")", ";", "$", "parsedFilterConfig", "=", "$", "this", "->", "processConfiguration", "(", "$", "configuration", ",", "[", "[", "'configurations'", "=>", "[", "$", "code", "=>", "$", "queryHandlerConfig", ",", "]", ",", "]", ",", "]", ")", ";", "return", "$", "parsedFilterConfig", "[", "'configurations'", "]", "[", "$", "code", "]", ";", "}" ]
@param string $code @param array $queryHandlerConfig @return array
[ "@param", "string", "$code", "@param", "array", "$queryHandlerConfig" ]
train
https://github.com/VincentChalnot/SidusDataGridBundle/blob/aa929113e2208ed335f514d2891affaf7fddf3f6/DependencyInjection/SidusDataGridExtension.php#L118-L134
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/rfc2231_implementation.php
ezcMailRfc2231Implementation.parseHeader
public static function parseHeader( $header ) { $result = array(); // argument if ( preg_match( '/^\s*([^;]*);?/i', $header, $matches ) ) { $result[0] = $matches[1]; } // We must go through all parameters and store this data because // parameters can be unordered. We will store them in this buffer // array( paramName => array( array( value => string, encoding ) ) ) $parameterBuffer = array(); // parameters if ( preg_match_all( '/\s*(\S*?)="?([^;"]*);?/i', $header, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $parameter ) { // if normal parameter, simply add it if ( !preg_match( '/([^\*]+)\*(\d+)?(\*)?/', $parameter[1], $metaData ) ) { $result[1][$parameter[1]] = array( 'value' => $parameter[2] ); } else // coded and/or folded { // metaData [1] holds the param name // metaData [2] holds the count or is not set in case of charset only // metaData [3] holds '*' if there is charset in addition to folding if ( isset( $metaData[2] ) ) // we have folding { $parameterBuffer[$metaData[1]][$metaData[2]]['value'] = $parameter[2]; $parameterBuffer[$metaData[1]][$metaData[2]]['encoding'] = isset( $metaData[3] ) ? true : false;; } else { $parameterBuffer[$metaData[1]][0]['value'] = $parameter[2]; $parameterBuffer[$metaData[1]][0]['encoding'] = true; } } } // whohooo... we have all the parameters nicely sorted. // Now we must go through them all and convert them into the end result foreach ( $parameterBuffer as $paramName => $parts ) { // fetch language and encoding if we have it // syntax: '[charset]'[language]'encoded_string $language = null; $charset = null; if ( $parts[0]['encoding'] == true ) { preg_match( "/(\S*)'(\S*)'(.*)/", $parts[0]['value'], $matches ); $charset = $matches[1]; $language = $matches[2]; $parts[0]['value'] = urldecode( $matches[3] ); // rewrite value: todo: decoding $result[1][$paramName] = array( 'value' => $parts[0]['value'] ); } $result[1][$paramName] = array( 'value' => $parts[0]['value'] ); if ( strlen( $charset ) > 0 ) { $result[1][$paramName]['charset'] = $charset; } if ( strlen( $language ) > 0 ) { $result[1][$paramName]['language'] = $language; } if ( count( $parts > 1 ) ) { for ( $i = 1; $i < count( $parts ); $i++ ) { $result[1][$paramName]['value'] .= $parts[$i]['encoding'] ? urldecode( $parts[$i]['value'] ) : $parts[$i]['value']; } } } } return $result; }
php
public static function parseHeader( $header ) { $result = array(); // argument if ( preg_match( '/^\s*([^;]*);?/i', $header, $matches ) ) { $result[0] = $matches[1]; } // We must go through all parameters and store this data because // parameters can be unordered. We will store them in this buffer // array( paramName => array( array( value => string, encoding ) ) ) $parameterBuffer = array(); // parameters if ( preg_match_all( '/\s*(\S*?)="?([^;"]*);?/i', $header, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $parameter ) { // if normal parameter, simply add it if ( !preg_match( '/([^\*]+)\*(\d+)?(\*)?/', $parameter[1], $metaData ) ) { $result[1][$parameter[1]] = array( 'value' => $parameter[2] ); } else // coded and/or folded { // metaData [1] holds the param name // metaData [2] holds the count or is not set in case of charset only // metaData [3] holds '*' if there is charset in addition to folding if ( isset( $metaData[2] ) ) // we have folding { $parameterBuffer[$metaData[1]][$metaData[2]]['value'] = $parameter[2]; $parameterBuffer[$metaData[1]][$metaData[2]]['encoding'] = isset( $metaData[3] ) ? true : false;; } else { $parameterBuffer[$metaData[1]][0]['value'] = $parameter[2]; $parameterBuffer[$metaData[1]][0]['encoding'] = true; } } } // whohooo... we have all the parameters nicely sorted. // Now we must go through them all and convert them into the end result foreach ( $parameterBuffer as $paramName => $parts ) { // fetch language and encoding if we have it // syntax: '[charset]'[language]'encoded_string $language = null; $charset = null; if ( $parts[0]['encoding'] == true ) { preg_match( "/(\S*)'(\S*)'(.*)/", $parts[0]['value'], $matches ); $charset = $matches[1]; $language = $matches[2]; $parts[0]['value'] = urldecode( $matches[3] ); // rewrite value: todo: decoding $result[1][$paramName] = array( 'value' => $parts[0]['value'] ); } $result[1][$paramName] = array( 'value' => $parts[0]['value'] ); if ( strlen( $charset ) > 0 ) { $result[1][$paramName]['charset'] = $charset; } if ( strlen( $language ) > 0 ) { $result[1][$paramName]['language'] = $language; } if ( count( $parts > 1 ) ) { for ( $i = 1; $i < count( $parts ); $i++ ) { $result[1][$paramName]['value'] .= $parts[$i]['encoding'] ? urldecode( $parts[$i]['value'] ) : $parts[$i]['value']; } } } } return $result; }
[ "public", "static", "function", "parseHeader", "(", "$", "header", ")", "{", "$", "result", "=", "array", "(", ")", ";", "// argument", "if", "(", "preg_match", "(", "'/^\\s*([^;]*);?/i'", ",", "$", "header", ",", "$", "matches", ")", ")", "{", "$", "result", "[", "0", "]", "=", "$", "matches", "[", "1", "]", ";", "}", "// We must go through all parameters and store this data because", "// parameters can be unordered. We will store them in this buffer", "// array( paramName => array( array( value => string, encoding ) ) )", "$", "parameterBuffer", "=", "array", "(", ")", ";", "// parameters", "if", "(", "preg_match_all", "(", "'/\\s*(\\S*?)=\"?([^;\"]*);?/i'", ",", "$", "header", ",", "$", "matches", ",", "PREG_SET_ORDER", ")", ")", "{", "foreach", "(", "$", "matches", "as", "$", "parameter", ")", "{", "// if normal parameter, simply add it", "if", "(", "!", "preg_match", "(", "'/([^\\*]+)\\*(\\d+)?(\\*)?/'", ",", "$", "parameter", "[", "1", "]", ",", "$", "metaData", ")", ")", "{", "$", "result", "[", "1", "]", "[", "$", "parameter", "[", "1", "]", "]", "=", "array", "(", "'value'", "=>", "$", "parameter", "[", "2", "]", ")", ";", "}", "else", "// coded and/or folded", "{", "// metaData [1] holds the param name", "// metaData [2] holds the count or is not set in case of charset only", "// metaData [3] holds '*' if there is charset in addition to folding", "if", "(", "isset", "(", "$", "metaData", "[", "2", "]", ")", ")", "// we have folding", "{", "$", "parameterBuffer", "[", "$", "metaData", "[", "1", "]", "]", "[", "$", "metaData", "[", "2", "]", "]", "[", "'value'", "]", "=", "$", "parameter", "[", "2", "]", ";", "$", "parameterBuffer", "[", "$", "metaData", "[", "1", "]", "]", "[", "$", "metaData", "[", "2", "]", "]", "[", "'encoding'", "]", "=", "isset", "(", "$", "metaData", "[", "3", "]", ")", "?", "true", ":", "false", ";", ";", "}", "else", "{", "$", "parameterBuffer", "[", "$", "metaData", "[", "1", "]", "]", "[", "0", "]", "[", "'value'", "]", "=", "$", "parameter", "[", "2", "]", ";", "$", "parameterBuffer", "[", "$", "metaData", "[", "1", "]", "]", "[", "0", "]", "[", "'encoding'", "]", "=", "true", ";", "}", "}", "}", "// whohooo... we have all the parameters nicely sorted.", "// Now we must go through them all and convert them into the end result", "foreach", "(", "$", "parameterBuffer", "as", "$", "paramName", "=>", "$", "parts", ")", "{", "// fetch language and encoding if we have it", "// syntax: '[charset]'[language]'encoded_string", "$", "language", "=", "null", ";", "$", "charset", "=", "null", ";", "if", "(", "$", "parts", "[", "0", "]", "[", "'encoding'", "]", "==", "true", ")", "{", "preg_match", "(", "\"/(\\S*)'(\\S*)'(.*)/\"", ",", "$", "parts", "[", "0", "]", "[", "'value'", "]", ",", "$", "matches", ")", ";", "$", "charset", "=", "$", "matches", "[", "1", "]", ";", "$", "language", "=", "$", "matches", "[", "2", "]", ";", "$", "parts", "[", "0", "]", "[", "'value'", "]", "=", "urldecode", "(", "$", "matches", "[", "3", "]", ")", ";", "// rewrite value: todo: decoding", "$", "result", "[", "1", "]", "[", "$", "paramName", "]", "=", "array", "(", "'value'", "=>", "$", "parts", "[", "0", "]", "[", "'value'", "]", ")", ";", "}", "$", "result", "[", "1", "]", "[", "$", "paramName", "]", "=", "array", "(", "'value'", "=>", "$", "parts", "[", "0", "]", "[", "'value'", "]", ")", ";", "if", "(", "strlen", "(", "$", "charset", ")", ">", "0", ")", "{", "$", "result", "[", "1", "]", "[", "$", "paramName", "]", "[", "'charset'", "]", "=", "$", "charset", ";", "}", "if", "(", "strlen", "(", "$", "language", ")", ">", "0", ")", "{", "$", "result", "[", "1", "]", "[", "$", "paramName", "]", "[", "'language'", "]", "=", "$", "language", ";", "}", "if", "(", "count", "(", "$", "parts", ">", "1", ")", ")", "{", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "count", "(", "$", "parts", ")", ";", "$", "i", "++", ")", "{", "$", "result", "[", "1", "]", "[", "$", "paramName", "]", "[", "'value'", "]", ".=", "$", "parts", "[", "$", "i", "]", "[", "'encoding'", "]", "?", "urldecode", "(", "$", "parts", "[", "$", "i", "]", "[", "'value'", "]", ")", ":", "$", "parts", "[", "$", "i", "]", "[", "'value'", "]", ";", "}", "}", "}", "}", "return", "$", "result", ";", "}" ]
Returns the parsed header $header according to RFC 2231. This method returns the parsed header as a structured array and is intended for internal usage. Use parseContentDisposition and parseContentType to retrieve the correct header structs directly. @param string $header @return array( 'argument', array( 'paramName' => array( value => string, charset => string, language => string ) ) );
[ "Returns", "the", "parsed", "header", "$header", "according", "to", "RFC", "2231", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/rfc2231_implementation.php#L34-L115
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/rfc2231_implementation.php
ezcMailRfc2231Implementation.parseContentDisposition
public static function parseContentDisposition( $header, ezcMailContentDispositionHeader $cd = null ) { if ( $cd === null ) { $cd = new ezcMailContentDispositionHeader(); } $parsedHeader = self::parseHeader( $header ); $cd->disposition = $parsedHeader[0]; if ( isset( $parsedHeader[1] ) ) { foreach ( $parsedHeader[1] as $paramName => $data ) { switch ( $paramName ) { case 'filename': $cd->fileName = $data['value']; $cd->displayFileName = trim( $data['value'], '"' ); if ( isset( $data['charset'] ) ) { $cd->fileNameCharSet = $data['charset']; $cd->displayFileName = ezcMailCharsetConverter::convertToUTF8Iconv( $cd->displayFileName, $cd->fileNameCharSet ); } // Work around for bogus email clients that think // it's allowed to use mime-encoding for filenames. // It isn't, see RFC 2184, and issue #13038. else if ( preg_match( '@^=\?[^?]+\?[QqBb]\?@', $cd->displayFileName ) ) { $cd->displayFileName = ezcMailTools::mimeDecode( $cd->displayFileName ); } if ( isset( $data['language'] ) ) { $cd->fileNameLanguage = $data['language']; } break; case 'creation-date': $cd->creationDate = $data['value']; break; case 'modification-date': $cd->modificationDate = $data['value']; break; case 'read-date': $cd->readDate = $data['value']; break; case 'size': $cd->size = $data['value']; break; default: $cd->additionalParameters[$paramName] = $data['value']; if ( isset( $data['charset'] ) ) { $cd->additionalParametersMetaData[$paramName]['charSet'] = $data['charset']; } if ( isset( $data['language'] ) ) { $cd->additionalParametersMetaData[$paramName]['language'] = $data['language']; } break; } } } return $cd; }
php
public static function parseContentDisposition( $header, ezcMailContentDispositionHeader $cd = null ) { if ( $cd === null ) { $cd = new ezcMailContentDispositionHeader(); } $parsedHeader = self::parseHeader( $header ); $cd->disposition = $parsedHeader[0]; if ( isset( $parsedHeader[1] ) ) { foreach ( $parsedHeader[1] as $paramName => $data ) { switch ( $paramName ) { case 'filename': $cd->fileName = $data['value']; $cd->displayFileName = trim( $data['value'], '"' ); if ( isset( $data['charset'] ) ) { $cd->fileNameCharSet = $data['charset']; $cd->displayFileName = ezcMailCharsetConverter::convertToUTF8Iconv( $cd->displayFileName, $cd->fileNameCharSet ); } // Work around for bogus email clients that think // it's allowed to use mime-encoding for filenames. // It isn't, see RFC 2184, and issue #13038. else if ( preg_match( '@^=\?[^?]+\?[QqBb]\?@', $cd->displayFileName ) ) { $cd->displayFileName = ezcMailTools::mimeDecode( $cd->displayFileName ); } if ( isset( $data['language'] ) ) { $cd->fileNameLanguage = $data['language']; } break; case 'creation-date': $cd->creationDate = $data['value']; break; case 'modification-date': $cd->modificationDate = $data['value']; break; case 'read-date': $cd->readDate = $data['value']; break; case 'size': $cd->size = $data['value']; break; default: $cd->additionalParameters[$paramName] = $data['value']; if ( isset( $data['charset'] ) ) { $cd->additionalParametersMetaData[$paramName]['charSet'] = $data['charset']; } if ( isset( $data['language'] ) ) { $cd->additionalParametersMetaData[$paramName]['language'] = $data['language']; } break; } } } return $cd; }
[ "public", "static", "function", "parseContentDisposition", "(", "$", "header", ",", "ezcMailContentDispositionHeader", "$", "cd", "=", "null", ")", "{", "if", "(", "$", "cd", "===", "null", ")", "{", "$", "cd", "=", "new", "ezcMailContentDispositionHeader", "(", ")", ";", "}", "$", "parsedHeader", "=", "self", "::", "parseHeader", "(", "$", "header", ")", ";", "$", "cd", "->", "disposition", "=", "$", "parsedHeader", "[", "0", "]", ";", "if", "(", "isset", "(", "$", "parsedHeader", "[", "1", "]", ")", ")", "{", "foreach", "(", "$", "parsedHeader", "[", "1", "]", "as", "$", "paramName", "=>", "$", "data", ")", "{", "switch", "(", "$", "paramName", ")", "{", "case", "'filename'", ":", "$", "cd", "->", "fileName", "=", "$", "data", "[", "'value'", "]", ";", "$", "cd", "->", "displayFileName", "=", "trim", "(", "$", "data", "[", "'value'", "]", ",", "'\"'", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "'charset'", "]", ")", ")", "{", "$", "cd", "->", "fileNameCharSet", "=", "$", "data", "[", "'charset'", "]", ";", "$", "cd", "->", "displayFileName", "=", "ezcMailCharsetConverter", "::", "convertToUTF8Iconv", "(", "$", "cd", "->", "displayFileName", ",", "$", "cd", "->", "fileNameCharSet", ")", ";", "}", "// Work around for bogus email clients that think", "// it's allowed to use mime-encoding for filenames.", "// It isn't, see RFC 2184, and issue #13038.", "else", "if", "(", "preg_match", "(", "'@^=\\?[^?]+\\?[QqBb]\\?@'", ",", "$", "cd", "->", "displayFileName", ")", ")", "{", "$", "cd", "->", "displayFileName", "=", "ezcMailTools", "::", "mimeDecode", "(", "$", "cd", "->", "displayFileName", ")", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'language'", "]", ")", ")", "{", "$", "cd", "->", "fileNameLanguage", "=", "$", "data", "[", "'language'", "]", ";", "}", "break", ";", "case", "'creation-date'", ":", "$", "cd", "->", "creationDate", "=", "$", "data", "[", "'value'", "]", ";", "break", ";", "case", "'modification-date'", ":", "$", "cd", "->", "modificationDate", "=", "$", "data", "[", "'value'", "]", ";", "break", ";", "case", "'read-date'", ":", "$", "cd", "->", "readDate", "=", "$", "data", "[", "'value'", "]", ";", "break", ";", "case", "'size'", ":", "$", "cd", "->", "size", "=", "$", "data", "[", "'value'", "]", ";", "break", ";", "default", ":", "$", "cd", "->", "additionalParameters", "[", "$", "paramName", "]", "=", "$", "data", "[", "'value'", "]", ";", "if", "(", "isset", "(", "$", "data", "[", "'charset'", "]", ")", ")", "{", "$", "cd", "->", "additionalParametersMetaData", "[", "$", "paramName", "]", "[", "'charSet'", "]", "=", "$", "data", "[", "'charset'", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'language'", "]", ")", ")", "{", "$", "cd", "->", "additionalParametersMetaData", "[", "$", "paramName", "]", "[", "'language'", "]", "=", "$", "data", "[", "'language'", "]", ";", "}", "break", ";", "}", "}", "}", "return", "$", "cd", ";", "}" ]
Returns the a ezcMailContentDispositionHeader for the parsed $header. If $cd is provided this object will be used to fill in the blanks. This function will not clear out any old values in the object. @param string $header @param ezcMailContentDispositionHeader $cd @return ezcMailContentDispositionHeader
[ "Returns", "the", "a", "ezcMailContentDispositionHeader", "for", "the", "parsed", "$header", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/rfc2231_implementation.php#L127-L190
SachaMorard/phalcon-model-annotations
Library/Phalcon/Annotations/ModelListener.php
ModelListener.afterInitialize
public function afterInitialize(Event $event, ModelsManager $manager, $model) { //Reflector /** @var \Phalcon\Annotations\Reflection $reflector */ $reflector = $this->annotations->get($model); /** * Read the annotations in the class' docblock */ $annotations = $reflector->getClassAnnotations(); if ($annotations) { /** * Traverse the annotations */ foreach ($annotations as $annotation) { switch ($annotation->getName()) { /** * Initializes the model's source */ case 'Source': $arguments = $annotation->getArguments(); $model->setConnectionService($arguments[0]); $manager->setModelSource($model, $arguments[1]); break; /** * Initializes Has-Many relations */ case 'HasMany': $arguments = $annotation->getArguments(); if (!isset($arguments[3])) { $arguments[3] = null; } $manager->addHasMany($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3]); break; /** * Initializes Has-Many-To-Many relations */ case 'HasManyToMany': $arguments = $annotation->getArguments(); if (!isset($arguments[6])) { $arguments[6] = null; } $manager->addHasManyToMany($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]); break; /** * Initializes Has-One relations */ case 'HasOne': $arguments = $annotation->getArguments(); if (!isset($arguments[3])) { $arguments[3] = null; } $manager->addHasOne($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3]); break; /** * Initializes Has-Many relations */ case 'BelongsTo': $arguments = $annotation->getArguments(); if (!isset($arguments[3])) { $arguments[3] = null; } $manager->addBelongsTo($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3]); break; } } } }
php
public function afterInitialize(Event $event, ModelsManager $manager, $model) { //Reflector /** @var \Phalcon\Annotations\Reflection $reflector */ $reflector = $this->annotations->get($model); /** * Read the annotations in the class' docblock */ $annotations = $reflector->getClassAnnotations(); if ($annotations) { /** * Traverse the annotations */ foreach ($annotations as $annotation) { switch ($annotation->getName()) { /** * Initializes the model's source */ case 'Source': $arguments = $annotation->getArguments(); $model->setConnectionService($arguments[0]); $manager->setModelSource($model, $arguments[1]); break; /** * Initializes Has-Many relations */ case 'HasMany': $arguments = $annotation->getArguments(); if (!isset($arguments[3])) { $arguments[3] = null; } $manager->addHasMany($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3]); break; /** * Initializes Has-Many-To-Many relations */ case 'HasManyToMany': $arguments = $annotation->getArguments(); if (!isset($arguments[6])) { $arguments[6] = null; } $manager->addHasManyToMany($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]); break; /** * Initializes Has-One relations */ case 'HasOne': $arguments = $annotation->getArguments(); if (!isset($arguments[3])) { $arguments[3] = null; } $manager->addHasOne($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3]); break; /** * Initializes Has-Many relations */ case 'BelongsTo': $arguments = $annotation->getArguments(); if (!isset($arguments[3])) { $arguments[3] = null; } $manager->addBelongsTo($model, $arguments[0], $arguments[1], $arguments[2], $arguments[3]); break; } } } }
[ "public", "function", "afterInitialize", "(", "Event", "$", "event", ",", "ModelsManager", "$", "manager", ",", "$", "model", ")", "{", "//Reflector", "/** @var \\Phalcon\\Annotations\\Reflection $reflector */", "$", "reflector", "=", "$", "this", "->", "annotations", "->", "get", "(", "$", "model", ")", ";", "/**\n * Read the annotations in the class' docblock\n */", "$", "annotations", "=", "$", "reflector", "->", "getClassAnnotations", "(", ")", ";", "if", "(", "$", "annotations", ")", "{", "/**\n * Traverse the annotations\n */", "foreach", "(", "$", "annotations", "as", "$", "annotation", ")", "{", "switch", "(", "$", "annotation", "->", "getName", "(", ")", ")", "{", "/**\n * Initializes the model's source\n */", "case", "'Source'", ":", "$", "arguments", "=", "$", "annotation", "->", "getArguments", "(", ")", ";", "$", "model", "->", "setConnectionService", "(", "$", "arguments", "[", "0", "]", ")", ";", "$", "manager", "->", "setModelSource", "(", "$", "model", ",", "$", "arguments", "[", "1", "]", ")", ";", "break", ";", "/**\n * Initializes Has-Many relations\n */", "case", "'HasMany'", ":", "$", "arguments", "=", "$", "annotation", "->", "getArguments", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "arguments", "[", "3", "]", ")", ")", "{", "$", "arguments", "[", "3", "]", "=", "null", ";", "}", "$", "manager", "->", "addHasMany", "(", "$", "model", ",", "$", "arguments", "[", "0", "]", ",", "$", "arguments", "[", "1", "]", ",", "$", "arguments", "[", "2", "]", ",", "$", "arguments", "[", "3", "]", ")", ";", "break", ";", "/**\n * Initializes Has-Many-To-Many relations\n */", "case", "'HasManyToMany'", ":", "$", "arguments", "=", "$", "annotation", "->", "getArguments", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "arguments", "[", "6", "]", ")", ")", "{", "$", "arguments", "[", "6", "]", "=", "null", ";", "}", "$", "manager", "->", "addHasManyToMany", "(", "$", "model", ",", "$", "arguments", "[", "0", "]", ",", "$", "arguments", "[", "1", "]", ",", "$", "arguments", "[", "2", "]", ",", "$", "arguments", "[", "3", "]", ",", "$", "arguments", "[", "4", "]", ",", "$", "arguments", "[", "5", "]", ",", "$", "arguments", "[", "6", "]", ")", ";", "break", ";", "/**\n * Initializes Has-One relations\n */", "case", "'HasOne'", ":", "$", "arguments", "=", "$", "annotation", "->", "getArguments", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "arguments", "[", "3", "]", ")", ")", "{", "$", "arguments", "[", "3", "]", "=", "null", ";", "}", "$", "manager", "->", "addHasOne", "(", "$", "model", ",", "$", "arguments", "[", "0", "]", ",", "$", "arguments", "[", "1", "]", ",", "$", "arguments", "[", "2", "]", ",", "$", "arguments", "[", "3", "]", ")", ";", "break", ";", "/**\n * Initializes Has-Many relations\n */", "case", "'BelongsTo'", ":", "$", "arguments", "=", "$", "annotation", "->", "getArguments", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "arguments", "[", "3", "]", ")", ")", "{", "$", "arguments", "[", "3", "]", "=", "null", ";", "}", "$", "manager", "->", "addBelongsTo", "(", "$", "model", ",", "$", "arguments", "[", "0", "]", ",", "$", "arguments", "[", "1", "]", ",", "$", "arguments", "[", "2", "]", ",", "$", "arguments", "[", "3", "]", ")", ";", "break", ";", "}", "}", "}", "}" ]
This is called after initialize the model @param Event $event @param ModelsManager $manager @param $model
[ "This", "is", "called", "after", "initialize", "the", "model" ]
train
https://github.com/SachaMorard/phalcon-model-annotations/blob/64cb04903f101c1fd85e8067c0dcdfc6ca133fb5/Library/Phalcon/Annotations/ModelListener.php#L25-L91
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsTo.php
BelongsTo.getEagerModelKeys
protected function getEagerModelKeys(array $models) { // First we need to gather all of the keys from the parent models so we know what // to query for via the eager loading query. We will add them to an array then // execute a "where in" statement to gather up all of those related records. $keys = collect($models)->map(function ($model) { return $model->{$this->foreignKey}; })->filter()->all(); // If there are no keys that were not null we will just return an array with either // null or 0 in (depending on if incrementing keys are in use) so the query wont // fail plus returns zero results, which should be what the developer expects. if (count($keys) === 0) { return [$this->relationHasIncrementingId() ? 0 : null]; } return array_values(array_unique($keys)); }
php
protected function getEagerModelKeys(array $models) { // First we need to gather all of the keys from the parent models so we know what // to query for via the eager loading query. We will add them to an array then // execute a "where in" statement to gather up all of those related records. $keys = collect($models)->map(function ($model) { return $model->{$this->foreignKey}; })->filter()->all(); // If there are no keys that were not null we will just return an array with either // null or 0 in (depending on if incrementing keys are in use) so the query wont // fail plus returns zero results, which should be what the developer expects. if (count($keys) === 0) { return [$this->relationHasIncrementingId() ? 0 : null]; } return array_values(array_unique($keys)); }
[ "protected", "function", "getEagerModelKeys", "(", "array", "$", "models", ")", "{", "// First we need to gather all of the keys from the parent models so we know what", "// to query for via the eager loading query. We will add them to an array then", "// execute a \"where in\" statement to gather up all of those related records.", "$", "keys", "=", "collect", "(", "$", "models", ")", "->", "map", "(", "function", "(", "$", "model", ")", "{", "return", "$", "model", "->", "{", "$", "this", "->", "foreignKey", "}", ";", "}", ")", "->", "filter", "(", ")", "->", "all", "(", ")", ";", "// If there are no keys that were not null we will just return an array with either", "// null or 0 in (depending on if incrementing keys are in use) so the query wont", "// fail plus returns zero results, which should be what the developer expects.", "if", "(", "count", "(", "$", "keys", ")", "===", "0", ")", "{", "return", "[", "$", "this", "->", "relationHasIncrementingId", "(", ")", "?", "0", ":", "null", "]", ";", "}", "return", "array_values", "(", "array_unique", "(", "$", "keys", ")", ")", ";", "}" ]
Gather the keys from an array of related models. @param array $models @return array
[ "Gather", "the", "keys", "from", "an", "array", "of", "related", "models", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsTo.php#L120-L137
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsTo.php
BelongsTo.associate
public function associate($model) { $ownerKey = $model instanceof Model ? $model->getAttribute($this->ownerKey) : $model; $this->child->setAttribute($this->foreignKey, $ownerKey); if ($model instanceof Model) { $this->child->setRelation($this->relation, $model); } return $this->child; }
php
public function associate($model) { $ownerKey = $model instanceof Model ? $model->getAttribute($this->ownerKey) : $model; $this->child->setAttribute($this->foreignKey, $ownerKey); if ($model instanceof Model) { $this->child->setRelation($this->relation, $model); } return $this->child; }
[ "public", "function", "associate", "(", "$", "model", ")", "{", "$", "ownerKey", "=", "$", "model", "instanceof", "Model", "?", "$", "model", "->", "getAttribute", "(", "$", "this", "->", "ownerKey", ")", ":", "$", "model", ";", "$", "this", "->", "child", "->", "setAttribute", "(", "$", "this", "->", "foreignKey", ",", "$", "ownerKey", ")", ";", "if", "(", "$", "model", "instanceof", "Model", ")", "{", "$", "this", "->", "child", "->", "setRelation", "(", "$", "this", "->", "relation", ",", "$", "model", ")", ";", "}", "return", "$", "this", "->", "child", ";", "}" ]
Associate the model instance to the given parent. @param int|\Mellivora\Database\Eloquent\Model $model @return \Mellivora\Database\Eloquent\Model
[ "Associate", "the", "model", "instance", "to", "the", "given", "parent", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsTo.php#L211-L222
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsTo.php
BelongsTo.getRelationExistenceQuery
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from === $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); } return $query->select($columns)->whereColumn( $this->getQualifiedForeignKey(), '=', $query->getModel()->getTable() . '.' . $this->ownerKey ); }
php
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from === $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns); } return $query->select($columns)->whereColumn( $this->getQualifiedForeignKey(), '=', $query->getModel()->getTable() . '.' . $this->ownerKey ); }
[ "public", "function", "getRelationExistenceQuery", "(", "Builder", "$", "query", ",", "Builder", "$", "parentQuery", ",", "$", "columns", "=", "[", "'*'", "]", ")", "{", "if", "(", "$", "parentQuery", "->", "getQuery", "(", ")", "->", "from", "===", "$", "query", "->", "getQuery", "(", ")", "->", "from", ")", "{", "return", "$", "this", "->", "getRelationExistenceQueryForSelfRelation", "(", "$", "query", ",", "$", "parentQuery", ",", "$", "columns", ")", ";", "}", "return", "$", "query", "->", "select", "(", "$", "columns", ")", "->", "whereColumn", "(", "$", "this", "->", "getQualifiedForeignKey", "(", ")", ",", "'='", ",", "$", "query", "->", "getModel", "(", ")", "->", "getTable", "(", ")", ".", "'.'", ".", "$", "this", "->", "ownerKey", ")", ";", "}" ]
Add the constraints for a relationship query. @param \Mellivora\Database\Eloquent\Builder $query @param \Mellivora\Database\Eloquent\Builder $parentQuery @param array|mixed $columns @return \Mellivora\Database\Eloquent\Builder
[ "Add", "the", "constraints", "for", "a", "relationship", "query", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsTo.php#L245-L256
krakphp/job
src/Queue/Doctrine/DoctrineQueue.php
DoctrineQueue.enqueue
public function enqueue(Job\WrappedJob $job) { $this->repo->addJob($job, $this->name); }
php
public function enqueue(Job\WrappedJob $job) { $this->repo->addJob($job, $this->name); }
[ "public", "function", "enqueue", "(", "Job", "\\", "WrappedJob", "$", "job", ")", "{", "$", "this", "->", "repo", "->", "addJob", "(", "$", "job", ",", "$", "this", "->", "name", ")", ";", "}" ]
push a job onto the queue
[ "push", "a", "job", "onto", "the", "queue" ]
train
https://github.com/krakphp/job/blob/0c16020c1baa13d91f819ecba8334861ba7c4d6c/src/Queue/Doctrine/DoctrineQueue.php#L19-L21
krakphp/job
src/Queue/Doctrine/DoctrineQueue.php
DoctrineQueue.dequeue
public function dequeue() { if (!count($this->cached_jobs)) { $this->cached_jobs = $this->repo->getAvailableJobs($this->name); } if (!count($this->cached_jobs)) { return; } $job_row = array_shift($this->cached_jobs); $job = Job\WrappedJob::fromString($job_row['job'])->withAddedPayload([ '_doctrine' => ['id' => $job_row['id']] ])->withQueueProvider('doctrine'); $this->repo->processJob($job); return $job; }
php
public function dequeue() { if (!count($this->cached_jobs)) { $this->cached_jobs = $this->repo->getAvailableJobs($this->name); } if (!count($this->cached_jobs)) { return; } $job_row = array_shift($this->cached_jobs); $job = Job\WrappedJob::fromString($job_row['job'])->withAddedPayload([ '_doctrine' => ['id' => $job_row['id']] ])->withQueueProvider('doctrine'); $this->repo->processJob($job); return $job; }
[ "public", "function", "dequeue", "(", ")", "{", "if", "(", "!", "count", "(", "$", "this", "->", "cached_jobs", ")", ")", "{", "$", "this", "->", "cached_jobs", "=", "$", "this", "->", "repo", "->", "getAvailableJobs", "(", "$", "this", "->", "name", ")", ";", "}", "if", "(", "!", "count", "(", "$", "this", "->", "cached_jobs", ")", ")", "{", "return", ";", "}", "$", "job_row", "=", "array_shift", "(", "$", "this", "->", "cached_jobs", ")", ";", "$", "job", "=", "Job", "\\", "WrappedJob", "::", "fromString", "(", "$", "job_row", "[", "'job'", "]", ")", "->", "withAddedPayload", "(", "[", "'_doctrine'", "=>", "[", "'id'", "=>", "$", "job_row", "[", "'id'", "]", "]", "]", ")", "->", "withQueueProvider", "(", "'doctrine'", ")", ";", "$", "this", "->", "repo", "->", "processJob", "(", "$", "job", ")", ";", "return", "$", "job", ";", "}" ]
take a job off of the queue
[ "take", "a", "job", "off", "of", "the", "queue" ]
train
https://github.com/krakphp/job/blob/0c16020c1baa13d91f819ecba8334861ba7c4d6c/src/Queue/Doctrine/DoctrineQueue.php#L24-L38
shabbyrobe/amiss
src/Filter.php
Filter.getChildren
public function getChildren($objects, $path) { $array = array(); if (!is_array($path)) { $path = explode('/', $path); } if (!is_array($objects)) { $objects = array($objects); } $ret = $objects; foreach ($path as $child) { $array = []; $meta = null; $properties = null; if ($ret && is_object(current($ret))) { $meta = $this->mapper->getMeta(get_class(current($ret)), !'strict'); if ($meta) { $properties = $meta->getProperties(); } } foreach ($ret as $o) { $field = isset($properties[$child]) ? $properties[$child] : null; if (!$field || !isset($field['getter'])) { $value = $o->{$child}; } else { $g = [$o, $field['getter']]; $value = $g(); } if (is_array($value) || $value instanceof \Traversable) { $array = array_merge($array, $value); } elseif ($value !== null) { $array[] = $value; } } $ret = $array; } return $ret; }
php
public function getChildren($objects, $path) { $array = array(); if (!is_array($path)) { $path = explode('/', $path); } if (!is_array($objects)) { $objects = array($objects); } $ret = $objects; foreach ($path as $child) { $array = []; $meta = null; $properties = null; if ($ret && is_object(current($ret))) { $meta = $this->mapper->getMeta(get_class(current($ret)), !'strict'); if ($meta) { $properties = $meta->getProperties(); } } foreach ($ret as $o) { $field = isset($properties[$child]) ? $properties[$child] : null; if (!$field || !isset($field['getter'])) { $value = $o->{$child}; } else { $g = [$o, $field['getter']]; $value = $g(); } if (is_array($value) || $value instanceof \Traversable) { $array = array_merge($array, $value); } elseif ($value !== null) { $array[] = $value; } } $ret = $array; } return $ret; }
[ "public", "function", "getChildren", "(", "$", "objects", ",", "$", "path", ")", "{", "$", "array", "=", "array", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "path", ")", ")", "{", "$", "path", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "objects", ")", ")", "{", "$", "objects", "=", "array", "(", "$", "objects", ")", ";", "}", "$", "ret", "=", "$", "objects", ";", "foreach", "(", "$", "path", "as", "$", "child", ")", "{", "$", "array", "=", "[", "]", ";", "$", "meta", "=", "null", ";", "$", "properties", "=", "null", ";", "if", "(", "$", "ret", "&&", "is_object", "(", "current", "(", "$", "ret", ")", ")", ")", "{", "$", "meta", "=", "$", "this", "->", "mapper", "->", "getMeta", "(", "get_class", "(", "current", "(", "$", "ret", ")", ")", ",", "!", "'strict'", ")", ";", "if", "(", "$", "meta", ")", "{", "$", "properties", "=", "$", "meta", "->", "getProperties", "(", ")", ";", "}", "}", "foreach", "(", "$", "ret", "as", "$", "o", ")", "{", "$", "field", "=", "isset", "(", "$", "properties", "[", "$", "child", "]", ")", "?", "$", "properties", "[", "$", "child", "]", ":", "null", ";", "if", "(", "!", "$", "field", "||", "!", "isset", "(", "$", "field", "[", "'getter'", "]", ")", ")", "{", "$", "value", "=", "$", "o", "->", "{", "$", "child", "}", ";", "}", "else", "{", "$", "g", "=", "[", "$", "o", ",", "$", "field", "[", "'getter'", "]", "]", ";", "$", "value", "=", "$", "g", "(", ")", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", "||", "$", "value", "instanceof", "\\", "Traversable", ")", "{", "$", "array", "=", "array_merge", "(", "$", "array", ",", "$", "value", ")", ";", "}", "elseif", "(", "$", "value", "!==", "null", ")", "{", "$", "array", "[", "]", "=", "$", "value", ";", "}", "}", "$", "ret", "=", "$", "array", ";", "}", "return", "$", "ret", ";", "}" ]
Retrieve all object child values through a property path. Path can be an array: ['prop', 'childProp', 'veryChildProp'] Or a '/' delimited string: prop/childProp/veryChildProp @param object[] $objects @param string|array $path @return array
[ "Retrieve", "all", "object", "child", "values", "through", "a", "property", "path", "." ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Filter.php#L23-L68
shabbyrobe/amiss
src/Filter.php
Filter.indexBy
public function indexBy($list, $property, $meta=null, $allowDupes=null, $ignoreNulls=null) { $allowDupes = $allowDupes !== null ? $allowDupes : false; $ignoreNulls = $ignoreNulls !== null ? $ignoreNulls : true; if (!$list) { return []; } if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { if (!($first = current($list))) { throw new \UnexpectedValueException(); } $meta = $this->mapper->getMeta(get_class($first)); } $index = array(); $props = $meta ? $meta->getProperties() : []; foreach ($list as $object) { $propDef = !isset($props[$property]) ? null : $props[$property]; $value = !$propDef || !isset($propDef['getter']) ? $object->{$property} : call_user_func(array($object, $propDef['getter'])); if ($value === null && $ignoreNulls) { continue; } if (!$allowDupes && isset($index[$value])) { throw new \UnexpectedValueException("Duplicate value for property $property"); } $index[$value] = $object; } return $index; }
php
public function indexBy($list, $property, $meta=null, $allowDupes=null, $ignoreNulls=null) { $allowDupes = $allowDupes !== null ? $allowDupes : false; $ignoreNulls = $ignoreNulls !== null ? $ignoreNulls : true; if (!$list) { return []; } if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { if (!($first = current($list))) { throw new \UnexpectedValueException(); } $meta = $this->mapper->getMeta(get_class($first)); } $index = array(); $props = $meta ? $meta->getProperties() : []; foreach ($list as $object) { $propDef = !isset($props[$property]) ? null : $props[$property]; $value = !$propDef || !isset($propDef['getter']) ? $object->{$property} : call_user_func(array($object, $propDef['getter'])); if ($value === null && $ignoreNulls) { continue; } if (!$allowDupes && isset($index[$value])) { throw new \UnexpectedValueException("Duplicate value for property $property"); } $index[$value] = $object; } return $index; }
[ "public", "function", "indexBy", "(", "$", "list", ",", "$", "property", ",", "$", "meta", "=", "null", ",", "$", "allowDupes", "=", "null", ",", "$", "ignoreNulls", "=", "null", ")", "{", "$", "allowDupes", "=", "$", "allowDupes", "!==", "null", "?", "$", "allowDupes", ":", "false", ";", "$", "ignoreNulls", "=", "$", "ignoreNulls", "!==", "null", "?", "$", "ignoreNulls", ":", "true", ";", "if", "(", "!", "$", "list", ")", "{", "return", "[", "]", ";", "}", "if", "(", "$", "meta", ")", "{", "$", "meta", "=", "!", "$", "meta", "instanceof", "Meta", "?", "$", "this", "->", "mapper", "->", "getMeta", "(", "$", "meta", ")", ":", "$", "meta", ";", "}", "else", "{", "if", "(", "!", "(", "$", "first", "=", "current", "(", "$", "list", ")", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", ")", ";", "}", "$", "meta", "=", "$", "this", "->", "mapper", "->", "getMeta", "(", "get_class", "(", "$", "first", ")", ")", ";", "}", "$", "index", "=", "array", "(", ")", ";", "$", "props", "=", "$", "meta", "?", "$", "meta", "->", "getProperties", "(", ")", ":", "[", "]", ";", "foreach", "(", "$", "list", "as", "$", "object", ")", "{", "$", "propDef", "=", "!", "isset", "(", "$", "props", "[", "$", "property", "]", ")", "?", "null", ":", "$", "props", "[", "$", "property", "]", ";", "$", "value", "=", "!", "$", "propDef", "||", "!", "isset", "(", "$", "propDef", "[", "'getter'", "]", ")", "?", "$", "object", "->", "{", "$", "property", "}", ":", "call_user_func", "(", "array", "(", "$", "object", ",", "$", "propDef", "[", "'getter'", "]", ")", ")", ";", "if", "(", "$", "value", "===", "null", "&&", "$", "ignoreNulls", ")", "{", "continue", ";", "}", "if", "(", "!", "$", "allowDupes", "&&", "isset", "(", "$", "index", "[", "$", "value", "]", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "\"Duplicate value for property $property\"", ")", ";", "}", "$", "index", "[", "$", "value", "]", "=", "$", "object", ";", "}", "return", "$", "index", ";", "}" ]
Iterate over an array of objects and returns an array of objects indexed by a property @return array
[ "Iterate", "over", "an", "array", "of", "objects", "and", "returns", "an", "array", "of", "objects", "indexed", "by", "a", "property" ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Filter.php#L76-L113
shabbyrobe/amiss
src/Filter.php
Filter.groupBy
public function groupBy($list, $property, $meta=null) { if (!$list) { return []; } if (!$meta) { if (!($first = current($list))) { throw new \UnexpectedValueException(); } $meta = $this->mapper->getMeta(get_class($first)); } $groups = []; $props = $meta->getProperties(); foreach ($list as $object) { $propDef = !isset($props[$property]) ? null : $props[$property]; $value = !$propDef || !isset($propDef['getter']) ? $object->{$property} : call_user_func(array($object, $propDef['getter'])); $groups[$value][] = $object; } return $groups; }
php
public function groupBy($list, $property, $meta=null) { if (!$list) { return []; } if (!$meta) { if (!($first = current($list))) { throw new \UnexpectedValueException(); } $meta = $this->mapper->getMeta(get_class($first)); } $groups = []; $props = $meta->getProperties(); foreach ($list as $object) { $propDef = !isset($props[$property]) ? null : $props[$property]; $value = !$propDef || !isset($propDef['getter']) ? $object->{$property} : call_user_func(array($object, $propDef['getter'])); $groups[$value][] = $object; } return $groups; }
[ "public", "function", "groupBy", "(", "$", "list", ",", "$", "property", ",", "$", "meta", "=", "null", ")", "{", "if", "(", "!", "$", "list", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "$", "meta", ")", "{", "if", "(", "!", "(", "$", "first", "=", "current", "(", "$", "list", ")", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", ")", ";", "}", "$", "meta", "=", "$", "this", "->", "mapper", "->", "getMeta", "(", "get_class", "(", "$", "first", ")", ")", ";", "}", "$", "groups", "=", "[", "]", ";", "$", "props", "=", "$", "meta", "->", "getProperties", "(", ")", ";", "foreach", "(", "$", "list", "as", "$", "object", ")", "{", "$", "propDef", "=", "!", "isset", "(", "$", "props", "[", "$", "property", "]", ")", "?", "null", ":", "$", "props", "[", "$", "property", "]", ";", "$", "value", "=", "!", "$", "propDef", "||", "!", "isset", "(", "$", "propDef", "[", "'getter'", "]", ")", "?", "$", "object", "->", "{", "$", "property", "}", ":", "call_user_func", "(", "array", "(", "$", "object", ",", "$", "propDef", "[", "'getter'", "]", ")", ")", ";", "$", "groups", "[", "$", "value", "]", "[", "]", "=", "$", "object", ";", "}", "return", "$", "groups", ";", "}" ]
Iterate over an array of objects and group them by the value of a property @return array[group] = class[]
[ "Iterate", "over", "an", "array", "of", "objects", "and", "group", "them", "by", "the", "value", "of", "a", "property" ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Filter.php#L120-L144
mridang/magazine
lib/magento/Archive/Helper/File/Bz.php
Mage_Archive_Helper_File_Bz._open
protected function _open($mode) { $this->_fileHandler = @bzopen($this->_filePath, $mode); if (false === $this->_fileHandler) { throw new Mage_Exception('Failed to open file ' . $this->_filePath); } }
php
protected function _open($mode) { $this->_fileHandler = @bzopen($this->_filePath, $mode); if (false === $this->_fileHandler) { throw new Mage_Exception('Failed to open file ' . $this->_filePath); } }
[ "protected", "function", "_open", "(", "$", "mode", ")", "{", "$", "this", "->", "_fileHandler", "=", "@", "bzopen", "(", "$", "this", "->", "_filePath", ",", "$", "mode", ")", ";", "if", "(", "false", "===", "$", "this", "->", "_fileHandler", ")", "{", "throw", "new", "Mage_Exception", "(", "'Failed to open file '", ".", "$", "this", "->", "_filePath", ")", ";", "}", "}" ]
Open bz archive file @throws Mage_Exception @param string $mode
[ "Open", "bz", "archive", "file" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File/Bz.php#L42-L49
mridang/magazine
lib/magento/Archive/Helper/File/Bz.php
Mage_Archive_Helper_File_Bz._read
protected function _read($length) { $data = bzread($this->_fileHandler, $length); if (false === $data) { throw new Mage_Exception('Failed to read data from ' . $this->_filePath); } return $data; }
php
protected function _read($length) { $data = bzread($this->_fileHandler, $length); if (false === $data) { throw new Mage_Exception('Failed to read data from ' . $this->_filePath); } return $data; }
[ "protected", "function", "_read", "(", "$", "length", ")", "{", "$", "data", "=", "bzread", "(", "$", "this", "->", "_fileHandler", ",", "$", "length", ")", ";", "if", "(", "false", "===", "$", "data", ")", "{", "throw", "new", "Mage_Exception", "(", "'Failed to read data from '", ".", "$", "this", "->", "_filePath", ")", ";", "}", "return", "$", "data", ";", "}" ]
Read data from bz archive @throws Mage_Exception @param int $length @return string
[ "Read", "data", "from", "bz", "archive" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File/Bz.php#L73-L82
oroinc/OroLayoutComponent
OptionValueBag.php
OptionValueBag.buildValue
public function buildValue() { $actions = [ 'add' => [], 'replace' => [], 'remove' => [], ]; foreach ($this->actions as $action) { switch ($action->getName()) { case 'add': $actions['add'][] = [$action->getArgument(0)]; break; case 'replace': $actions['replace'][] = [$action->getArgument(0), $action->getArgument(1)]; break; case 'remove': $actions['remove'][] = [$action->getArgument(0)]; break; } } $builder = $this->getBuilder(); foreach ($actions as $action => $calls) { foreach ($calls as $arguments) { call_user_func_array([$builder, $action], $arguments); } } return $builder->get(); }
php
public function buildValue() { $actions = [ 'add' => [], 'replace' => [], 'remove' => [], ]; foreach ($this->actions as $action) { switch ($action->getName()) { case 'add': $actions['add'][] = [$action->getArgument(0)]; break; case 'replace': $actions['replace'][] = [$action->getArgument(0), $action->getArgument(1)]; break; case 'remove': $actions['remove'][] = [$action->getArgument(0)]; break; } } $builder = $this->getBuilder(); foreach ($actions as $action => $calls) { foreach ($calls as $arguments) { call_user_func_array([$builder, $action], $arguments); } } return $builder->get(); }
[ "public", "function", "buildValue", "(", ")", "{", "$", "actions", "=", "[", "'add'", "=>", "[", "]", ",", "'replace'", "=>", "[", "]", ",", "'remove'", "=>", "[", "]", ",", "]", ";", "foreach", "(", "$", "this", "->", "actions", "as", "$", "action", ")", "{", "switch", "(", "$", "action", "->", "getName", "(", ")", ")", "{", "case", "'add'", ":", "$", "actions", "[", "'add'", "]", "[", "]", "=", "[", "$", "action", "->", "getArgument", "(", "0", ")", "]", ";", "break", ";", "case", "'replace'", ":", "$", "actions", "[", "'replace'", "]", "[", "]", "=", "[", "$", "action", "->", "getArgument", "(", "0", ")", ",", "$", "action", "->", "getArgument", "(", "1", ")", "]", ";", "break", ";", "case", "'remove'", ":", "$", "actions", "[", "'remove'", "]", "[", "]", "=", "[", "$", "action", "->", "getArgument", "(", "0", ")", "]", ";", "break", ";", "}", "}", "$", "builder", "=", "$", "this", "->", "getBuilder", "(", ")", ";", "foreach", "(", "$", "actions", "as", "$", "action", "=>", "$", "calls", ")", "{", "foreach", "(", "$", "calls", "as", "$", "arguments", ")", "{", "call_user_func_array", "(", "[", "$", "builder", ",", "$", "action", "]", ",", "$", "arguments", ")", ";", "}", "}", "return", "$", "builder", "->", "get", "(", ")", ";", "}" ]
Builds a block option value using the given builder @return mixed The built value
[ "Builds", "a", "block", "option", "value", "using", "the", "given", "builder" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/OptionValueBag.php#L59-L90
oroinc/OroLayoutComponent
OptionValueBag.php
OptionValueBag.getBuilder
protected function getBuilder() { $isArray = false; // guess builder type based on arguments if ($this->actions) { /** @var Action $action */ $action = reset($this->actions); $arguments = $action->getArguments(); if ($arguments) { $argument = reset($arguments); if (is_array($argument)) { $isArray = true; } } } if ($isArray) { return new ArrayOptionValueBuilder(); } return new StringOptionValueBuilder(); }
php
protected function getBuilder() { $isArray = false; // guess builder type based on arguments if ($this->actions) { /** @var Action $action */ $action = reset($this->actions); $arguments = $action->getArguments(); if ($arguments) { $argument = reset($arguments); if (is_array($argument)) { $isArray = true; } } } if ($isArray) { return new ArrayOptionValueBuilder(); } return new StringOptionValueBuilder(); }
[ "protected", "function", "getBuilder", "(", ")", "{", "$", "isArray", "=", "false", ";", "// guess builder type based on arguments", "if", "(", "$", "this", "->", "actions", ")", "{", "/** @var Action $action */", "$", "action", "=", "reset", "(", "$", "this", "->", "actions", ")", ";", "$", "arguments", "=", "$", "action", "->", "getArguments", "(", ")", ";", "if", "(", "$", "arguments", ")", "{", "$", "argument", "=", "reset", "(", "$", "arguments", ")", ";", "if", "(", "is_array", "(", "$", "argument", ")", ")", "{", "$", "isArray", "=", "true", ";", "}", "}", "}", "if", "(", "$", "isArray", ")", "{", "return", "new", "ArrayOptionValueBuilder", "(", ")", ";", "}", "return", "new", "StringOptionValueBuilder", "(", ")", ";", "}" ]
Returns options builder based on values in value bag @return OptionValueBuilderInterface
[ "Returns", "options", "builder", "based", "on", "values", "in", "value", "bag" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/OptionValueBag.php#L97-L119
InfiniteSoftware/ISEcommpayPayum
EcommpayGatewayFactory.php
EcommpayGatewayFactory.populateConfig
protected function populateConfig(ArrayObject $config) { $config->defaults([ 'payum.factory_name' => 'ecommpay', 'payum.factory_title' => 'ecommpay', 'payum.action.capture' => new CaptureAction(), 'payum.action.authorize' => new AuthorizeAction(), 'payum.action.refund' => new RefundAction(), 'payum.action.cancel' => new CancelAction(), 'payum.action.notify' => new NotifyAction(), 'payum.action.status' => new StatusAction(), 'payum.action.convert_payment' => new ConvertPaymentAction(), ]); if (false == $config['payum.api']) { $config['payum.default_options'] = array( 'sandbox' => true, ); $config->defaults($config['payum.default_options']); $config['payum.required_options'] = []; $config['payum.api'] = function (ArrayObject $config) { $config->validateNotEmpty($config['payum.required_options']); return [ 'secretKey' => $config['secretKey'], 'projectId' => $config['projectId'], 'endpoint' => 'https://paymentpage.ecommpay.com/payment?' ]; }; } }
php
protected function populateConfig(ArrayObject $config) { $config->defaults([ 'payum.factory_name' => 'ecommpay', 'payum.factory_title' => 'ecommpay', 'payum.action.capture' => new CaptureAction(), 'payum.action.authorize' => new AuthorizeAction(), 'payum.action.refund' => new RefundAction(), 'payum.action.cancel' => new CancelAction(), 'payum.action.notify' => new NotifyAction(), 'payum.action.status' => new StatusAction(), 'payum.action.convert_payment' => new ConvertPaymentAction(), ]); if (false == $config['payum.api']) { $config['payum.default_options'] = array( 'sandbox' => true, ); $config->defaults($config['payum.default_options']); $config['payum.required_options'] = []; $config['payum.api'] = function (ArrayObject $config) { $config->validateNotEmpty($config['payum.required_options']); return [ 'secretKey' => $config['secretKey'], 'projectId' => $config['projectId'], 'endpoint' => 'https://paymentpage.ecommpay.com/payment?' ]; }; } }
[ "protected", "function", "populateConfig", "(", "ArrayObject", "$", "config", ")", "{", "$", "config", "->", "defaults", "(", "[", "'payum.factory_name'", "=>", "'ecommpay'", ",", "'payum.factory_title'", "=>", "'ecommpay'", ",", "'payum.action.capture'", "=>", "new", "CaptureAction", "(", ")", ",", "'payum.action.authorize'", "=>", "new", "AuthorizeAction", "(", ")", ",", "'payum.action.refund'", "=>", "new", "RefundAction", "(", ")", ",", "'payum.action.cancel'", "=>", "new", "CancelAction", "(", ")", ",", "'payum.action.notify'", "=>", "new", "NotifyAction", "(", ")", ",", "'payum.action.status'", "=>", "new", "StatusAction", "(", ")", ",", "'payum.action.convert_payment'", "=>", "new", "ConvertPaymentAction", "(", ")", ",", "]", ")", ";", "if", "(", "false", "==", "$", "config", "[", "'payum.api'", "]", ")", "{", "$", "config", "[", "'payum.default_options'", "]", "=", "array", "(", "'sandbox'", "=>", "true", ",", ")", ";", "$", "config", "->", "defaults", "(", "$", "config", "[", "'payum.default_options'", "]", ")", ";", "$", "config", "[", "'payum.required_options'", "]", "=", "[", "]", ";", "$", "config", "[", "'payum.api'", "]", "=", "function", "(", "ArrayObject", "$", "config", ")", "{", "$", "config", "->", "validateNotEmpty", "(", "$", "config", "[", "'payum.required_options'", "]", ")", ";", "return", "[", "'secretKey'", "=>", "$", "config", "[", "'secretKey'", "]", ",", "'projectId'", "=>", "$", "config", "[", "'projectId'", "]", ",", "'endpoint'", "=>", "'https://paymentpage.ecommpay.com/payment?'", "]", ";", "}", ";", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/InfiniteSoftware/ISEcommpayPayum/blob/44a073e3d885d9007aa54d6ff13aea93a9e52e7c/EcommpayGatewayFactory.php#L20-L51
Eresus/EresusCMS
src/core/classes/backward/TListContentPlugin.php
TListContentPlugin.clientRenderContent
public function clientRenderContent() { $result = ''; if (!isset($this->settings['itemsPerPage'])) { $this->settings['itemsPerPage'] = 0; } /** @var TClientUI $page */ $page = Eresus_Kernel::app()->getPage(); if ($page->topic) { $result = $this->clientRenderItem(); } else { $db = Eresus_CMS::getLegacyKernel()->db; $this->table['fields'] = $db->fields($this->table['name']); $itemsCount = $db->count($this->table['name'], "(`section`='" . $page->id . "')". (in_array('active', $this->table['fields'])?"AND(`active`='1')":'')); if ($itemsCount) { $this->pagesCount = $this->settings['itemsPerPage'] ? ((integer) ($itemsCount / $this->settings['itemsPerPage']) + (($itemsCount % $this->settings['itemsPerPage']) > 0)):1; } if (!$page->subpage) { $page->subpage = $this->table['sortDesc'] ? $this->pagesCount : 1; } if ($itemsCount && ($page->subpage > $this->pagesCount)) { throw new Eresus_CMS_Exception_NotFound; } else { $result .= $this->clientRenderList(); } } return $result; }
php
public function clientRenderContent() { $result = ''; if (!isset($this->settings['itemsPerPage'])) { $this->settings['itemsPerPage'] = 0; } /** @var TClientUI $page */ $page = Eresus_Kernel::app()->getPage(); if ($page->topic) { $result = $this->clientRenderItem(); } else { $db = Eresus_CMS::getLegacyKernel()->db; $this->table['fields'] = $db->fields($this->table['name']); $itemsCount = $db->count($this->table['name'], "(`section`='" . $page->id . "')". (in_array('active', $this->table['fields'])?"AND(`active`='1')":'')); if ($itemsCount) { $this->pagesCount = $this->settings['itemsPerPage'] ? ((integer) ($itemsCount / $this->settings['itemsPerPage']) + (($itemsCount % $this->settings['itemsPerPage']) > 0)):1; } if (!$page->subpage) { $page->subpage = $this->table['sortDesc'] ? $this->pagesCount : 1; } if ($itemsCount && ($page->subpage > $this->pagesCount)) { throw new Eresus_CMS_Exception_NotFound; } else { $result .= $this->clientRenderList(); } } return $result; }
[ "public", "function", "clientRenderContent", "(", ")", "{", "$", "result", "=", "''", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "settings", "[", "'itemsPerPage'", "]", ")", ")", "{", "$", "this", "->", "settings", "[", "'itemsPerPage'", "]", "=", "0", ";", "}", "/** @var TClientUI $page */", "$", "page", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", ";", "if", "(", "$", "page", "->", "topic", ")", "{", "$", "result", "=", "$", "this", "->", "clientRenderItem", "(", ")", ";", "}", "else", "{", "$", "db", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", ";", "$", "this", "->", "table", "[", "'fields'", "]", "=", "$", "db", "->", "fields", "(", "$", "this", "->", "table", "[", "'name'", "]", ")", ";", "$", "itemsCount", "=", "$", "db", "->", "count", "(", "$", "this", "->", "table", "[", "'name'", "]", ",", "\"(`section`='\"", ".", "$", "page", "->", "id", ".", "\"')\"", ".", "(", "in_array", "(", "'active'", ",", "$", "this", "->", "table", "[", "'fields'", "]", ")", "?", "\"AND(`active`='1')\"", ":", "''", ")", ")", ";", "if", "(", "$", "itemsCount", ")", "{", "$", "this", "->", "pagesCount", "=", "$", "this", "->", "settings", "[", "'itemsPerPage'", "]", "?", "(", "(", "integer", ")", "(", "$", "itemsCount", "/", "$", "this", "->", "settings", "[", "'itemsPerPage'", "]", ")", "+", "(", "(", "$", "itemsCount", "%", "$", "this", "->", "settings", "[", "'itemsPerPage'", "]", ")", ">", "0", ")", ")", ":", "1", ";", "}", "if", "(", "!", "$", "page", "->", "subpage", ")", "{", "$", "page", "->", "subpage", "=", "$", "this", "->", "table", "[", "'sortDesc'", "]", "?", "$", "this", "->", "pagesCount", ":", "1", ";", "}", "if", "(", "$", "itemsCount", "&&", "(", "$", "page", "->", "subpage", ">", "$", "this", "->", "pagesCount", ")", ")", "{", "throw", "new", "Eresus_CMS_Exception_NotFound", ";", "}", "else", "{", "$", "result", ".=", "$", "this", "->", "clientRenderList", "(", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Отрисовка клиентской части @throws Eresus_CMS_Exception_NotFound @return string|Eresus_HTTP_Response
[ "Отрисовка", "клиентской", "части" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes/backward/TListContentPlugin.php#L266-L305
Eresus/EresusCMS
src/core/classes/backward/TListContentPlugin.php
TListContentPlugin.clientRenderPages
protected function clientRenderPages() { /** @var TClientUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->pages($this->pagesCount, $this->settings['itemsPerPage'], $this->table['sortDesc']); return $result; }
php
protected function clientRenderPages() { /** @var TClientUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->pages($this->pagesCount, $this->settings['itemsPerPage'], $this->table['sortDesc']); return $result; }
[ "protected", "function", "clientRenderPages", "(", ")", "{", "/** @var TClientUI $page */", "$", "page", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", ";", "$", "result", "=", "$", "page", "->", "pages", "(", "$", "this", "->", "pagesCount", ",", "$", "this", "->", "settings", "[", "'itemsPerPage'", "]", ",", "$", "this", "->", "table", "[", "'sortDesc'", "]", ")", ";", "return", "$", "result", ";", "}" ]
Возвращает разметку переключателя страниц @return string
[ "Возвращает", "разметку", "переключателя", "страниц" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes/backward/TListContentPlugin.php#L377-L384
phpnfe/tools
src/Certificado/Dom.php
Dom.getNodeValue
public function getNodeValue($nodeName, $itemNum = 0, $extraTextBefore = '', $extraTextAfter = '') { $node = $this->getElementsByTagName($nodeName)->item($itemNum); if (isset($node)) { $texto = html_entity_decode(trim($node->nodeValue), ENT_QUOTES, 'UTF-8'); return $extraTextBefore . $texto . $extraTextAfter; } return ''; }
php
public function getNodeValue($nodeName, $itemNum = 0, $extraTextBefore = '', $extraTextAfter = '') { $node = $this->getElementsByTagName($nodeName)->item($itemNum); if (isset($node)) { $texto = html_entity_decode(trim($node->nodeValue), ENT_QUOTES, 'UTF-8'); return $extraTextBefore . $texto . $extraTextAfter; } return ''; }
[ "public", "function", "getNodeValue", "(", "$", "nodeName", ",", "$", "itemNum", "=", "0", ",", "$", "extraTextBefore", "=", "''", ",", "$", "extraTextAfter", "=", "''", ")", "{", "$", "node", "=", "$", "this", "->", "getElementsByTagName", "(", "$", "nodeName", ")", "->", "item", "(", "$", "itemNum", ")", ";", "if", "(", "isset", "(", "$", "node", ")", ")", "{", "$", "texto", "=", "html_entity_decode", "(", "trim", "(", "$", "node", "->", "nodeValue", ")", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "return", "$", "extraTextBefore", ".", "$", "texto", ".", "$", "extraTextAfter", ";", "}", "return", "''", ";", "}" ]
getNodeValue. Extrai o valor do node DOM. @param string $nodeName identificador da TAG do xml @param int $itemNum numero do item a ser retornado @param string $extraTextBefore prefixo do retorno @param string $extraTextAfter sufixo do retorno @return string
[ "getNodeValue", ".", "Extrai", "o", "valor", "do", "node", "DOM", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Dom.php#L53-L63
phpnfe/tools
src/Certificado/Dom.php
Dom.getValue
public function getValue($node, $name) { if (empty($node)) { return ''; } $texto = ! empty($node->getElementsByTagName($name)->item(0)->nodeValue) ? $node->getElementsByTagName($name)->item(0)->nodeValue : ''; return html_entity_decode($texto, ENT_QUOTES, 'UTF-8'); }
php
public function getValue($node, $name) { if (empty($node)) { return ''; } $texto = ! empty($node->getElementsByTagName($name)->item(0)->nodeValue) ? $node->getElementsByTagName($name)->item(0)->nodeValue : ''; return html_entity_decode($texto, ENT_QUOTES, 'UTF-8'); }
[ "public", "function", "getValue", "(", "$", "node", ",", "$", "name", ")", "{", "if", "(", "empty", "(", "$", "node", ")", ")", "{", "return", "''", ";", "}", "$", "texto", "=", "!", "empty", "(", "$", "node", "->", "getElementsByTagName", "(", "$", "name", ")", "->", "item", "(", "0", ")", "->", "nodeValue", ")", "?", "$", "node", "->", "getElementsByTagName", "(", "$", "name", ")", "->", "item", "(", "0", ")", "->", "nodeValue", ":", "''", ";", "return", "html_entity_decode", "(", "$", "texto", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "}" ]
getValue. @param DOMElement $node @param string $name @return string
[ "getValue", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Dom.php#L71-L80
phpnfe/tools
src/Certificado/Dom.php
Dom.getNode
public function getNode($nodeName, $itemNum = 0) { $node = $this->getElementsByTagName($nodeName)->item($itemNum); if (isset($node)) { return $node; } return ''; }
php
public function getNode($nodeName, $itemNum = 0) { $node = $this->getElementsByTagName($nodeName)->item($itemNum); if (isset($node)) { return $node; } return ''; }
[ "public", "function", "getNode", "(", "$", "nodeName", ",", "$", "itemNum", "=", "0", ")", "{", "$", "node", "=", "$", "this", "->", "getElementsByTagName", "(", "$", "nodeName", ")", "->", "item", "(", "$", "itemNum", ")", ";", "if", "(", "isset", "(", "$", "node", ")", ")", "{", "return", "$", "node", ";", "}", "return", "''", ";", "}" ]
getNode Retorna o node solicitado. @param string $nodeName @param int $itemNum @return DOMElement se existir ou string vazia se não
[ "getNode", "Retorna", "o", "node", "solicitado", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Dom.php#L89-L97
phpnfe/tools
src/Certificado/Dom.php
Dom.addChild
public function addChild(&$parent, $name, $content = '', $obrigatorio = false, $descricao = '', $force = false) { if ($obrigatorio && $content === '' && ! $force) { $this->erros[] = [ 'tag' => $name, 'desc' => $descricao, 'erro' => 'Preenchimento Obrigatório!', ]; } if ($obrigatorio || $content !== '') { $content = trim($content); $content = htmlspecialchars($content, ENT_QUOTES); $temp = $this->createElement($name, $content); $parent->appendChild($temp); } }
php
public function addChild(&$parent, $name, $content = '', $obrigatorio = false, $descricao = '', $force = false) { if ($obrigatorio && $content === '' && ! $force) { $this->erros[] = [ 'tag' => $name, 'desc' => $descricao, 'erro' => 'Preenchimento Obrigatório!', ]; } if ($obrigatorio || $content !== '') { $content = trim($content); $content = htmlspecialchars($content, ENT_QUOTES); $temp = $this->createElement($name, $content); $parent->appendChild($temp); } }
[ "public", "function", "addChild", "(", "&", "$", "parent", ",", "$", "name", ",", "$", "content", "=", "''", ",", "$", "obrigatorio", "=", "false", ",", "$", "descricao", "=", "''", ",", "$", "force", "=", "false", ")", "{", "if", "(", "$", "obrigatorio", "&&", "$", "content", "===", "''", "&&", "!", "$", "force", ")", "{", "$", "this", "->", "erros", "[", "]", "=", "[", "'tag'", "=>", "$", "name", ",", "'desc'", "=>", "$", "descricao", ",", "'erro'", "=>", "'Preenchimento Obrigatório!',", "", "]", ";", "}", "if", "(", "$", "obrigatorio", "||", "$", "content", "!==", "''", ")", "{", "$", "content", "=", "trim", "(", "$", "content", ")", ";", "$", "content", "=", "htmlspecialchars", "(", "$", "content", ",", "ENT_QUOTES", ")", ";", "$", "temp", "=", "$", "this", "->", "createElement", "(", "$", "name", ",", "$", "content", ")", ";", "$", "parent", "->", "appendChild", "(", "$", "temp", ")", ";", "}", "}" ]
addChild Adiciona um elemento ao node xml passado como referencia Serão inclusos erros na array $erros[] sempre que a tag for obrigatória e nenhum parâmetro for passado na variável $content e $force for false. @param \DOMElement $parent @param string $name @param string $content @param bool $obrigatorio @param string $descricao @param bool $force força a criação do elemento mesmo sem dados e não considera como erro @return void
[ "addChild", "Adiciona", "um", "elemento", "ao", "node", "xml", "passado", "como", "referencia", "Serão", "inclusos", "erros", "na", "array", "$erros", "[]", "sempre", "que", "a", "tag", "for", "obrigatória", "e", "nenhum", "parâmetro", "for", "passado", "na", "variável", "$content", "e", "$force", "for", "false", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Dom.php#L112-L127
phpnfe/tools
src/Certificado/Dom.php
Dom.getChave
public function getChave($nodeName = 'infNFe') { $node = $this->getElementsByTagName($nodeName)->item(0); if (! empty($node)) { $chaveId = $node->getAttribute('Id'); $chave = preg_replace('/[^0-9]/', '', $chaveId); return $chave; } return ''; }
php
public function getChave($nodeName = 'infNFe') { $node = $this->getElementsByTagName($nodeName)->item(0); if (! empty($node)) { $chaveId = $node->getAttribute('Id'); $chave = preg_replace('/[^0-9]/', '', $chaveId); return $chave; } return ''; }
[ "public", "function", "getChave", "(", "$", "nodeName", "=", "'infNFe'", ")", "{", "$", "node", "=", "$", "this", "->", "getElementsByTagName", "(", "$", "nodeName", ")", "->", "item", "(", "0", ")", ";", "if", "(", "!", "empty", "(", "$", "node", ")", ")", "{", "$", "chaveId", "=", "$", "node", "->", "getAttribute", "(", "'Id'", ")", ";", "$", "chave", "=", "preg_replace", "(", "'/[^0-9]/'", ",", "''", ",", "$", "chaveId", ")", ";", "return", "$", "chave", ";", "}", "return", "''", ";", "}" ]
getChave. @param string $nodeName @return string
[ "getChave", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Dom.php#L134-L145
phpnfe/tools
src/Certificado/Dom.php
Dom.appChild
public function appChild(&$parent, $child, $msg = '') { if (empty($parent)) { throw new Exception($msg); } if (! empty($child)) { $parent->appendChild($child); } }
php
public function appChild(&$parent, $child, $msg = '') { if (empty($parent)) { throw new Exception($msg); } if (! empty($child)) { $parent->appendChild($child); } }
[ "public", "function", "appChild", "(", "&", "$", "parent", ",", "$", "child", ",", "$", "msg", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "parent", ")", ")", "{", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "child", ")", ")", "{", "$", "parent", "->", "appendChild", "(", "$", "child", ")", ";", "}", "}" ]
appChild Acrescenta DOMElement a pai DOMElement Caso o pai esteja vazio retorna uma exception com a mensagem O parametro "child" pode ser vazio. @param \DOMNode $parent @param \DOMNode $child @param string $msg @return void @throws Exception
[ "appChild", "Acrescenta", "DOMElement", "a", "pai", "DOMElement", "Caso", "o", "pai", "esteja", "vazio", "retorna", "uma", "exception", "com", "a", "mensagem", "O", "parametro", "child", "pode", "ser", "vazio", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Dom.php#L158-L166
phpnfe/tools
src/Certificado/Dom.php
Dom.addArrayChild
public function addArrayChild(&$parent, $arr) { $num = 0; if (! empty($arr) && ! empty($parent)) { foreach ($arr as $node) { $this->appChild($parent, $node, ''); $num++; } } return $num; }
php
public function addArrayChild(&$parent, $arr) { $num = 0; if (! empty($arr) && ! empty($parent)) { foreach ($arr as $node) { $this->appChild($parent, $node, ''); $num++; } } return $num; }
[ "public", "function", "addArrayChild", "(", "&", "$", "parent", ",", "$", "arr", ")", "{", "$", "num", "=", "0", ";", "if", "(", "!", "empty", "(", "$", "arr", ")", "&&", "!", "empty", "(", "$", "parent", ")", ")", "{", "foreach", "(", "$", "arr", "as", "$", "node", ")", "{", "$", "this", "->", "appChild", "(", "$", "parent", ",", "$", "node", ",", "''", ")", ";", "$", "num", "++", ";", "}", "}", "return", "$", "num", ";", "}" ]
addArrayChild Adiciona a um DOMNode parent, outros elementos passados em um array de DOMElements. @param DOMElement $parent @param array $arr @return int
[ "addArrayChild", "Adiciona", "a", "um", "DOMNode", "parent", "outros", "elementos", "passados", "em", "um", "array", "de", "DOMElements", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Dom.php#L175-L186
zicht/z
src/Zicht/Tool/Configuration/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $zConfig = $treeBuilder->root('z'); $toArray = function ($s) { return array($s); }; $zConfig ->children() ->scalarNode('SHELL')->end() ->scalarNode('TIMEOUT')->end() ->arrayNode('globals') ->defaultValue(array()) ->prototype('variable')->end() ->end() ->arrayNode('tasks') ->prototype('array') ->beforeNormalization() ->ifTrue( function ($in) { return is_string($in) // allow for 'lists' (skipping the 'do' key) || (is_array($in) && range(0, count($in) - 1) === array_keys($in)); } ) ->then( function ($v) { return array('do' => $v); } ) ->end() ->children() ->scalarNode('name')->end() ->scalarNode('help')->defaultValue(null)->end() ->arrayNode('flags') ->prototype('boolean')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->arrayNode('opts') ->prototype('scalar')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->arrayNode('args') ->prototype('scalar')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->arrayNode('set') ->prototype('scalar')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->scalarNode('unless')->defaultValue(null)->end() ->scalarNode('if')->defaultValue(null)->end() ->scalarNode('assert')->defaultValue(null)->end() ->arrayNode('pre') ->beforeNormalization() ->ifString()->then($toArray) ->end() ->prototype('scalar')->end() ->defaultValue(array()) ->end() ->arrayNode('post') ->beforeNormalization() ->ifString()->then($toArray) ->end() ->prototype('scalar')->end() ->defaultValue(array()) ->end() ->arrayNode('do') ->beforeNormalization() ->ifString()->then($toArray) ->end() ->performNoDeepMerging() ->prototype('scalar')->end() ->defaultValue(array()) ->end() ->scalarNode('yield')->defaultValue(null)->end() ->end() ->end() ->useAttributeAsKey('name') ->end() ->end() ->end(); foreach ($this->plugins as $plugin) { $plugin->appendConfiguration($zConfig); } return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $zConfig = $treeBuilder->root('z'); $toArray = function ($s) { return array($s); }; $zConfig ->children() ->scalarNode('SHELL')->end() ->scalarNode('TIMEOUT')->end() ->arrayNode('globals') ->defaultValue(array()) ->prototype('variable')->end() ->end() ->arrayNode('tasks') ->prototype('array') ->beforeNormalization() ->ifTrue( function ($in) { return is_string($in) // allow for 'lists' (skipping the 'do' key) || (is_array($in) && range(0, count($in) - 1) === array_keys($in)); } ) ->then( function ($v) { return array('do' => $v); } ) ->end() ->children() ->scalarNode('name')->end() ->scalarNode('help')->defaultValue(null)->end() ->arrayNode('flags') ->prototype('boolean')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->arrayNode('opts') ->prototype('scalar')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->arrayNode('args') ->prototype('scalar')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->arrayNode('set') ->prototype('scalar')->end() ->useAttributeAsKey('name') ->defaultValue(array()) ->end() ->scalarNode('unless')->defaultValue(null)->end() ->scalarNode('if')->defaultValue(null)->end() ->scalarNode('assert')->defaultValue(null)->end() ->arrayNode('pre') ->beforeNormalization() ->ifString()->then($toArray) ->end() ->prototype('scalar')->end() ->defaultValue(array()) ->end() ->arrayNode('post') ->beforeNormalization() ->ifString()->then($toArray) ->end() ->prototype('scalar')->end() ->defaultValue(array()) ->end() ->arrayNode('do') ->beforeNormalization() ->ifString()->then($toArray) ->end() ->performNoDeepMerging() ->prototype('scalar')->end() ->defaultValue(array()) ->end() ->scalarNode('yield')->defaultValue(null)->end() ->end() ->end() ->useAttributeAsKey('name') ->end() ->end() ->end(); foreach ($this->plugins as $plugin) { $plugin->appendConfiguration($zConfig); } return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "zConfig", "=", "$", "treeBuilder", "->", "root", "(", "'z'", ")", ";", "$", "toArray", "=", "function", "(", "$", "s", ")", "{", "return", "array", "(", "$", "s", ")", ";", "}", ";", "$", "zConfig", "->", "children", "(", ")", "->", "scalarNode", "(", "'SHELL'", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'TIMEOUT'", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'globals'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "prototype", "(", "'variable'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'tasks'", ")", "->", "prototype", "(", "'array'", ")", "->", "beforeNormalization", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "in", ")", "{", "return", "is_string", "(", "$", "in", ")", "// allow for 'lists' (skipping the 'do' key)", "||", "(", "is_array", "(", "$", "in", ")", "&&", "range", "(", "0", ",", "count", "(", "$", "in", ")", "-", "1", ")", "===", "array_keys", "(", "$", "in", ")", ")", ";", "}", ")", "->", "then", "(", "function", "(", "$", "v", ")", "{", "return", "array", "(", "'do'", "=>", "$", "v", ")", ";", "}", ")", "->", "end", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'name'", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'help'", ")", "->", "defaultValue", "(", "null", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'flags'", ")", "->", "prototype", "(", "'boolean'", ")", "->", "end", "(", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'opts'", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'args'", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'set'", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'unless'", ")", "->", "defaultValue", "(", "null", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'if'", ")", "->", "defaultValue", "(", "null", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'assert'", ")", "->", "defaultValue", "(", "null", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'pre'", ")", "->", "beforeNormalization", "(", ")", "->", "ifString", "(", ")", "->", "then", "(", "$", "toArray", ")", "->", "end", "(", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'post'", ")", "->", "beforeNormalization", "(", ")", "->", "ifString", "(", ")", "->", "then", "(", "$", "toArray", ")", "->", "end", "(", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'do'", ")", "->", "beforeNormalization", "(", ")", "->", "ifString", "(", ")", "->", "then", "(", "$", "toArray", ")", "->", "end", "(", ")", "->", "performNoDeepMerging", "(", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'yield'", ")", "->", "defaultValue", "(", "null", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "foreach", "(", "$", "this", "->", "plugins", "as", "$", "plugin", ")", "{", "$", "plugin", "->", "appendConfiguration", "(", "$", "zConfig", ")", ";", "}", "return", "$", "treeBuilder", ";", "}" ]
Generates the configuration tree builder. @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
[ "Generates", "the", "configuration", "tree", "builder", "." ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Configuration/Configuration.php#L38-L134
bzarzuela/modelfilter
src/ModelFilter.php
ModelFilter.setKey
public function setKey($key) { $this->key = $key; // Initialize if we're the first instance. if (! session()->has('bzarzuela.filters')) { session(['bzarzuela.filters' => [$key => []]]); } return $this; }
php
public function setKey($key) { $this->key = $key; // Initialize if we're the first instance. if (! session()->has('bzarzuela.filters')) { session(['bzarzuela.filters' => [$key => []]]); } return $this; }
[ "public", "function", "setKey", "(", "$", "key", ")", "{", "$", "this", "->", "key", "=", "$", "key", ";", "// Initialize if we're the first instance.", "if", "(", "!", "session", "(", ")", "->", "has", "(", "'bzarzuela.filters'", ")", ")", "{", "session", "(", "[", "'bzarzuela.filters'", "=>", "[", "$", "key", "=>", "[", "]", "]", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets a unique key to hold the filter form data in the session. @param string $key Key name. Usually the model's table name
[ "Sets", "a", "unique", "key", "to", "hold", "the", "filter", "form", "data", "in", "the", "session", "." ]
train
https://github.com/bzarzuela/modelfilter/blob/2ca04409934245b8bf5a0a9684da2f45b234dfa7/src/ModelFilter.php#L31-L41
bzarzuela/modelfilter
src/ModelFilter.php
ModelFilter.getFormData
public function getFormData($field = null) { $filters = session('bzarzuela.filters'); if (isset($filters[$this->key]['form_data'])) { if (! is_null($field)) { if (! isset($filters[$this->key]['form_data'][$field])) { return null; } return $filters[$this->key]['form_data'][$field]; } return $filters[$this->key]['form_data']; } if (! is_null($field)) { return null; } return []; }
php
public function getFormData($field = null) { $filters = session('bzarzuela.filters'); if (isset($filters[$this->key]['form_data'])) { if (! is_null($field)) { if (! isset($filters[$this->key]['form_data'][$field])) { return null; } return $filters[$this->key]['form_data'][$field]; } return $filters[$this->key]['form_data']; } if (! is_null($field)) { return null; } return []; }
[ "public", "function", "getFormData", "(", "$", "field", "=", "null", ")", "{", "$", "filters", "=", "session", "(", "'bzarzuela.filters'", ")", ";", "if", "(", "isset", "(", "$", "filters", "[", "$", "this", "->", "key", "]", "[", "'form_data'", "]", ")", ")", "{", "if", "(", "!", "is_null", "(", "$", "field", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "filters", "[", "$", "this", "->", "key", "]", "[", "'form_data'", "]", "[", "$", "field", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "filters", "[", "$", "this", "->", "key", "]", "[", "'form_data'", "]", "[", "$", "field", "]", ";", "}", "return", "$", "filters", "[", "$", "this", "->", "key", "]", "[", "'form_data'", "]", ";", "}", "if", "(", "!", "is_null", "(", "$", "field", ")", ")", "{", "return", "null", ";", "}", "return", "[", "]", ";", "}" ]
Gets either the whole form data or just a field inside. @param null $field @return array|null
[ "Gets", "either", "the", "whole", "form", "data", "or", "just", "a", "field", "inside", "." ]
train
https://github.com/bzarzuela/modelfilter/blob/2ca04409934245b8bf5a0a9684da2f45b234dfa7/src/ModelFilter.php#L87-L110
bzarzuela/modelfilter
src/ModelFilter.php
ModelFilter.filter
public function filter($query) { foreach ($this->getRules() as $name => $rule) { if ($this->getFormData($name) == '') { continue; } $type = $rule[0]; switch ($type) { case 'primary': $query->where($name, '=', $this->getFormData($name)); // Exit out of the loop, we don't need to process other conditions break 2; case 'in': $query->whereIn($rule[1], $this->getFormData($name)); break; case 'from': $query->where($rule[1], '>=', date('Y-m-d 00:00:00', strtotime($this->getFormData($name)))); break; case 'to': $query->where($rule[1], '<=', date('Y-m-d 23:59:59', strtotime($this->getFormData($name)))); break; case 'like': $field = $name; if (isset($rule[1])) { $field = $rule[1]; } $query->where($field, 'like', $this->getFormData($name) . '%'); break; case 'scope': if ($this->getFormData($name)) { $scope = $name; $query->$scope(); } break; default: $field = $name; if (isset($rule[1])) { $field = $rule[1]; } $query->where($field, '=', $this->getFormData($name)); break; } } return $query; }
php
public function filter($query) { foreach ($this->getRules() as $name => $rule) { if ($this->getFormData($name) == '') { continue; } $type = $rule[0]; switch ($type) { case 'primary': $query->where($name, '=', $this->getFormData($name)); // Exit out of the loop, we don't need to process other conditions break 2; case 'in': $query->whereIn($rule[1], $this->getFormData($name)); break; case 'from': $query->where($rule[1], '>=', date('Y-m-d 00:00:00', strtotime($this->getFormData($name)))); break; case 'to': $query->where($rule[1], '<=', date('Y-m-d 23:59:59', strtotime($this->getFormData($name)))); break; case 'like': $field = $name; if (isset($rule[1])) { $field = $rule[1]; } $query->where($field, 'like', $this->getFormData($name) . '%'); break; case 'scope': if ($this->getFormData($name)) { $scope = $name; $query->$scope(); } break; default: $field = $name; if (isset($rule[1])) { $field = $rule[1]; } $query->where($field, '=', $this->getFormData($name)); break; } } return $query; }
[ "public", "function", "filter", "(", "$", "query", ")", "{", "foreach", "(", "$", "this", "->", "getRules", "(", ")", "as", "$", "name", "=>", "$", "rule", ")", "{", "if", "(", "$", "this", "->", "getFormData", "(", "$", "name", ")", "==", "''", ")", "{", "continue", ";", "}", "$", "type", "=", "$", "rule", "[", "0", "]", ";", "switch", "(", "$", "type", ")", "{", "case", "'primary'", ":", "$", "query", "->", "where", "(", "$", "name", ",", "'='", ",", "$", "this", "->", "getFormData", "(", "$", "name", ")", ")", ";", "// Exit out of the loop, we don't need to process other conditions", "break", "2", ";", "case", "'in'", ":", "$", "query", "->", "whereIn", "(", "$", "rule", "[", "1", "]", ",", "$", "this", "->", "getFormData", "(", "$", "name", ")", ")", ";", "break", ";", "case", "'from'", ":", "$", "query", "->", "where", "(", "$", "rule", "[", "1", "]", ",", "'>='", ",", "date", "(", "'Y-m-d 00:00:00'", ",", "strtotime", "(", "$", "this", "->", "getFormData", "(", "$", "name", ")", ")", ")", ")", ";", "break", ";", "case", "'to'", ":", "$", "query", "->", "where", "(", "$", "rule", "[", "1", "]", ",", "'<='", ",", "date", "(", "'Y-m-d 23:59:59'", ",", "strtotime", "(", "$", "this", "->", "getFormData", "(", "$", "name", ")", ")", ")", ")", ";", "break", ";", "case", "'like'", ":", "$", "field", "=", "$", "name", ";", "if", "(", "isset", "(", "$", "rule", "[", "1", "]", ")", ")", "{", "$", "field", "=", "$", "rule", "[", "1", "]", ";", "}", "$", "query", "->", "where", "(", "$", "field", ",", "'like'", ",", "$", "this", "->", "getFormData", "(", "$", "name", ")", ".", "'%'", ")", ";", "break", ";", "case", "'scope'", ":", "if", "(", "$", "this", "->", "getFormData", "(", "$", "name", ")", ")", "{", "$", "scope", "=", "$", "name", ";", "$", "query", "->", "$", "scope", "(", ")", ";", "}", "break", ";", "default", ":", "$", "field", "=", "$", "name", ";", "if", "(", "isset", "(", "$", "rule", "[", "1", "]", ")", ")", "{", "$", "field", "=", "$", "rule", "[", "1", "]", ";", "}", "$", "query", "->", "where", "(", "$", "field", ",", "'='", ",", "$", "this", "->", "getFormData", "(", "$", "name", ")", ")", ";", "break", ";", "}", "}", "return", "$", "query", ";", "}" ]
Applies the form data according to the different rules that were initially configured. For example: $tickets = $this->filter(Ticket::query())->paginate(30); @param $query @return mixed
[ "Applies", "the", "form", "data", "according", "to", "the", "different", "rules", "that", "were", "initially", "configured", ".", "For", "example", ":", "$tickets", "=", "$this", "-", ">", "filter", "(", "Ticket", "::", "query", "()", ")", "-", ">", "paginate", "(", "30", ")", ";" ]
train
https://github.com/bzarzuela/modelfilter/blob/2ca04409934245b8bf5a0a9684da2f45b234dfa7/src/ModelFilter.php#L120-L174
caffeinated/beverage
src/Path.php
Path.join
public static function join() { $arguments = func_get_args(); if (func_get_args() === 1 and is_array($arguments[ 0 ])) { $arguments = $arguments[ 0 ]; } foreach ($arguments as $key => $argument) { $arguments[ $key ] = Str::removeRight($arguments[ $key ], '/'); if ($key > 0) { $arguments[ $key ] = Str::removeLeft($arguments[ $key ], '/'); } } return implode(DIRECTORY_SEPARATOR, $arguments); }
php
public static function join() { $arguments = func_get_args(); if (func_get_args() === 1 and is_array($arguments[ 0 ])) { $arguments = $arguments[ 0 ]; } foreach ($arguments as $key => $argument) { $arguments[ $key ] = Str::removeRight($arguments[ $key ], '/'); if ($key > 0) { $arguments[ $key ] = Str::removeLeft($arguments[ $key ], '/'); } } return implode(DIRECTORY_SEPARATOR, $arguments); }
[ "public", "static", "function", "join", "(", ")", "{", "$", "arguments", "=", "func_get_args", "(", ")", ";", "if", "(", "func_get_args", "(", ")", "===", "1", "and", "is_array", "(", "$", "arguments", "[", "0", "]", ")", ")", "{", "$", "arguments", "=", "$", "arguments", "[", "0", "]", ";", "}", "foreach", "(", "$", "arguments", "as", "$", "key", "=>", "$", "argument", ")", "{", "$", "arguments", "[", "$", "key", "]", "=", "Str", "::", "removeRight", "(", "$", "arguments", "[", "$", "key", "]", ",", "'/'", ")", ";", "if", "(", "$", "key", ">", "0", ")", "{", "$", "arguments", "[", "$", "key", "]", "=", "Str", "::", "removeLeft", "(", "$", "arguments", "[", "$", "key", "]", ",", "'/'", ")", ";", "}", "}", "return", "implode", "(", "DIRECTORY_SEPARATOR", ",", "$", "arguments", ")", ";", "}" ]
Joins a split file system path. @param array|string $path @return string
[ "Joins", "a", "split", "file", "system", "path", "." ]
train
https://github.com/caffeinated/beverage/blob/c7d612a1d3bc1baddc97fec60ab17224550efaf3/src/Path.php#L27-L44
alexandresalome/journal-extension
src/Behat/JournalExtension/Formatter/JournalFormatter.php
JournalFormatter.printSummary
protected function printSummary(LoggerDataCollector $logger) { $results = $logger->getScenariosStatuses(); $result = $results['failed'] > 0 ? 'failed' : 'passed'; parent::printSummary($logger); $this->writeln('<div class="summary ' . $result . '">'); $this->writeln(<<<'HTML' <div class="switchers screenshot-switchers"> <a href="#" onclick="$('.screenshot,.outline-example-result-screenshots-holder').addClass('jq-toggle-opened'); $('#behat_show_all').click(); return false;" id="behat_show_screenshots">[+] screenshots</a> <a href="#" onclick="$('.screenshot,.outline-example-result-screenshots-holder').removeClass('jq-toggle-opened'); $('#behat_hide_all').click(); return false;" id="behat_hide_screenshots">[-] screenshots</a> </div> HTML ); $this->writeln('</div>'); }
php
protected function printSummary(LoggerDataCollector $logger) { $results = $logger->getScenariosStatuses(); $result = $results['failed'] > 0 ? 'failed' : 'passed'; parent::printSummary($logger); $this->writeln('<div class="summary ' . $result . '">'); $this->writeln(<<<'HTML' <div class="switchers screenshot-switchers"> <a href="#" onclick="$('.screenshot,.outline-example-result-screenshots-holder').addClass('jq-toggle-opened'); $('#behat_show_all').click(); return false;" id="behat_show_screenshots">[+] screenshots</a> <a href="#" onclick="$('.screenshot,.outline-example-result-screenshots-holder').removeClass('jq-toggle-opened'); $('#behat_hide_all').click(); return false;" id="behat_hide_screenshots">[-] screenshots</a> </div> HTML ); $this->writeln('</div>'); }
[ "protected", "function", "printSummary", "(", "LoggerDataCollector", "$", "logger", ")", "{", "$", "results", "=", "$", "logger", "->", "getScenariosStatuses", "(", ")", ";", "$", "result", "=", "$", "results", "[", "'failed'", "]", ">", "0", "?", "'failed'", ":", "'passed'", ";", "parent", "::", "printSummary", "(", "$", "logger", ")", ";", "$", "this", "->", "writeln", "(", "'<div class=\"summary '", ".", "$", "result", ".", "'\">'", ")", ";", "$", "this", "->", "writeln", "(", "<<<'HTML'\n<div class=\"switchers screenshot-switchers\">\n <a href=\"#\" onclick=\"$('.screenshot,.outline-example-result-screenshots-holder').addClass('jq-toggle-opened'); $('#behat_show_all').click(); return false;\" id=\"behat_show_screenshots\">[+] screenshots</a>\n <a href=\"#\" onclick=\"$('.screenshot,.outline-example-result-screenshots-holder').removeClass('jq-toggle-opened'); $('#behat_hide_all').click(); return false;\" id=\"behat_hide_screenshots\">[-] screenshots</a>\n</div>\nHTML", ")", ";", "$", "this", "->", "writeln", "(", "'</div>'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/alexandresalome/journal-extension/blob/de87304abb52abfa6905f1b83d2e35cc7bc52c0d/src/Behat/JournalExtension/Formatter/JournalFormatter.php#L42-L59
alexandresalome/journal-extension
src/Behat/JournalExtension/Formatter/JournalFormatter.php
JournalFormatter.afterStep
public function afterStep(StepEvent $event) { $color = $this->getResultColorCode($event->getResult()); $capture = $this->captureAll || $color == 'failed'; if ($capture) { try { $screenshot = $this->driver->getScreenshot(); if ($screenshot) { $date = new \DateTime('now'); $fileName = $this->screenShotPrefix . $date->format('Y-m-d H.i.s') . '.png'; $file = $this->screenShotDirectory . DIRECTORY_SEPARATOR . $fileName; file_put_contents($file, $screenshot); $this->screenShotMarkup .= '<div class="screenshot">'; $this->screenShotMarkup .= sprintf('<a href="#" class="screenshot-toggler">Toggle screenshot for ' . $event->getStep()->getText() . '</a>'); $this->screenShotMarkup .= sprintf('<img src="%s" />', $fileName); $this->screenShotMarkup .= '</div>'; } } catch (\Exception $e) { $this->screenShotMarkup .= '<div class="screenshot">'; $this->screenShotMarkup .= sprintf('<em>Error while taking screenshot for ' . $event->getStep()->getText() . ' : %s</em>', htmlspecialchars($e->getMessage())); $this->screenShotMarkup .= '</div>'; } } if ($this->inBackground && $this->isBackgroundPrinted) { return; } if (!$this->inBackground && $this->inOutlineExample) { $this->delayedStepEvents[] = $event; return; } $this->printStep( $event->getStep(), $event->getResult(), $event->getDefinition(), $event->getSnippet(), $event->getException() ); $this->writeln($this->screenShotMarkup); $this->screenShotMarkup = ''; }
php
public function afterStep(StepEvent $event) { $color = $this->getResultColorCode($event->getResult()); $capture = $this->captureAll || $color == 'failed'; if ($capture) { try { $screenshot = $this->driver->getScreenshot(); if ($screenshot) { $date = new \DateTime('now'); $fileName = $this->screenShotPrefix . $date->format('Y-m-d H.i.s') . '.png'; $file = $this->screenShotDirectory . DIRECTORY_SEPARATOR . $fileName; file_put_contents($file, $screenshot); $this->screenShotMarkup .= '<div class="screenshot">'; $this->screenShotMarkup .= sprintf('<a href="#" class="screenshot-toggler">Toggle screenshot for ' . $event->getStep()->getText() . '</a>'); $this->screenShotMarkup .= sprintf('<img src="%s" />', $fileName); $this->screenShotMarkup .= '</div>'; } } catch (\Exception $e) { $this->screenShotMarkup .= '<div class="screenshot">'; $this->screenShotMarkup .= sprintf('<em>Error while taking screenshot for ' . $event->getStep()->getText() . ' : %s</em>', htmlspecialchars($e->getMessage())); $this->screenShotMarkup .= '</div>'; } } if ($this->inBackground && $this->isBackgroundPrinted) { return; } if (!$this->inBackground && $this->inOutlineExample) { $this->delayedStepEvents[] = $event; return; } $this->printStep( $event->getStep(), $event->getResult(), $event->getDefinition(), $event->getSnippet(), $event->getException() ); $this->writeln($this->screenShotMarkup); $this->screenShotMarkup = ''; }
[ "public", "function", "afterStep", "(", "StepEvent", "$", "event", ")", "{", "$", "color", "=", "$", "this", "->", "getResultColorCode", "(", "$", "event", "->", "getResult", "(", ")", ")", ";", "$", "capture", "=", "$", "this", "->", "captureAll", "||", "$", "color", "==", "'failed'", ";", "if", "(", "$", "capture", ")", "{", "try", "{", "$", "screenshot", "=", "$", "this", "->", "driver", "->", "getScreenshot", "(", ")", ";", "if", "(", "$", "screenshot", ")", "{", "$", "date", "=", "new", "\\", "DateTime", "(", "'now'", ")", ";", "$", "fileName", "=", "$", "this", "->", "screenShotPrefix", ".", "$", "date", "->", "format", "(", "'Y-m-d H.i.s'", ")", ".", "'.png'", ";", "$", "file", "=", "$", "this", "->", "screenShotDirectory", ".", "DIRECTORY_SEPARATOR", ".", "$", "fileName", ";", "file_put_contents", "(", "$", "file", ",", "$", "screenshot", ")", ";", "$", "this", "->", "screenShotMarkup", ".=", "'<div class=\"screenshot\">'", ";", "$", "this", "->", "screenShotMarkup", ".=", "sprintf", "(", "'<a href=\"#\" class=\"screenshot-toggler\">Toggle screenshot for '", ".", "$", "event", "->", "getStep", "(", ")", "->", "getText", "(", ")", ".", "'</a>'", ")", ";", "$", "this", "->", "screenShotMarkup", ".=", "sprintf", "(", "'<img src=\"%s\" />'", ",", "$", "fileName", ")", ";", "$", "this", "->", "screenShotMarkup", ".=", "'</div>'", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "screenShotMarkup", ".=", "'<div class=\"screenshot\">'", ";", "$", "this", "->", "screenShotMarkup", ".=", "sprintf", "(", "'<em>Error while taking screenshot for '", ".", "$", "event", "->", "getStep", "(", ")", "->", "getText", "(", ")", ".", "' : %s</em>'", ",", "htmlspecialchars", "(", "$", "e", "->", "getMessage", "(", ")", ")", ")", ";", "$", "this", "->", "screenShotMarkup", ".=", "'</div>'", ";", "}", "}", "if", "(", "$", "this", "->", "inBackground", "&&", "$", "this", "->", "isBackgroundPrinted", ")", "{", "return", ";", "}", "if", "(", "!", "$", "this", "->", "inBackground", "&&", "$", "this", "->", "inOutlineExample", ")", "{", "$", "this", "->", "delayedStepEvents", "[", "]", "=", "$", "event", ";", "return", ";", "}", "$", "this", "->", "printStep", "(", "$", "event", "->", "getStep", "(", ")", ",", "$", "event", "->", "getResult", "(", ")", ",", "$", "event", "->", "getDefinition", "(", ")", ",", "$", "event", "->", "getSnippet", "(", ")", ",", "$", "event", "->", "getException", "(", ")", ")", ";", "$", "this", "->", "writeln", "(", "$", "this", "->", "screenShotMarkup", ")", ";", "$", "this", "->", "screenShotMarkup", "=", "''", ";", "}" ]
Listens to "step.after" event. @param StepEvent $event @uses printStep()
[ "Listens", "to", "step", ".", "after", "event", "." ]
train
https://github.com/alexandresalome/journal-extension/blob/de87304abb52abfa6905f1b83d2e35cc7bc52c0d/src/Behat/JournalExtension/Formatter/JournalFormatter.php#L68-L110
alexandresalome/journal-extension
src/Behat/JournalExtension/Formatter/JournalFormatter.php
JournalFormatter.printOutlineExampleResult
protected function printOutlineExampleResult(TableNode $examples, $iteration, $result, $isSkipped) { if (!$this->getParameter('expand')) { $color = $this->getResultColorCode($result); $this->printColorizedTableRow($examples->getRow($iteration + 1), $color); $this->printOutlineExampleResultExceptions($examples, $this->delayedStepEvents); $this->writeln('<tr class="' . $color . '">'); $this->writeln('<td>' . ($iteration + 1) . '</td>'); $this->writeln('<td colspan="' . count($examples->getRow($iteration)) . '">'); $this->writeln('<div><a href="#" class="open-screenshots"> [+] Screenshot links </a>&nbsp;<a href="#" class="close-screenshots"> [-] Screenshot links </a></div>'); $this->writeln('<div class="outline-example-result-screenshots-holder jq-toggle">'); $this->writeln($this->screenShotMarkup); $this->writeln('</div>'); $this->writeln('</td>'); $this->writeln('</tr>'); $this->screenShotMarkup = ''; } else { $this->write('<h4>' . $examples->getKeyword() . ': '); foreach ($examples->getRow($iteration + 1) as $value) { $this->write('<span>' . $value . '</span>'); } $this->writeln('</h4>'); foreach ($this->delayedStepEvents as $event) { $this->writeln('<ol>'); $this->printStep( $event->getStep(), $event->getResult(), $event->getDefinition(), $event->getSnippet(), $event->getException() ); $this->writeln('</ol>'); } } }
php
protected function printOutlineExampleResult(TableNode $examples, $iteration, $result, $isSkipped) { if (!$this->getParameter('expand')) { $color = $this->getResultColorCode($result); $this->printColorizedTableRow($examples->getRow($iteration + 1), $color); $this->printOutlineExampleResultExceptions($examples, $this->delayedStepEvents); $this->writeln('<tr class="' . $color . '">'); $this->writeln('<td>' . ($iteration + 1) . '</td>'); $this->writeln('<td colspan="' . count($examples->getRow($iteration)) . '">'); $this->writeln('<div><a href="#" class="open-screenshots"> [+] Screenshot links </a>&nbsp;<a href="#" class="close-screenshots"> [-] Screenshot links </a></div>'); $this->writeln('<div class="outline-example-result-screenshots-holder jq-toggle">'); $this->writeln($this->screenShotMarkup); $this->writeln('</div>'); $this->writeln('</td>'); $this->writeln('</tr>'); $this->screenShotMarkup = ''; } else { $this->write('<h4>' . $examples->getKeyword() . ': '); foreach ($examples->getRow($iteration + 1) as $value) { $this->write('<span>' . $value . '</span>'); } $this->writeln('</h4>'); foreach ($this->delayedStepEvents as $event) { $this->writeln('<ol>'); $this->printStep( $event->getStep(), $event->getResult(), $event->getDefinition(), $event->getSnippet(), $event->getException() ); $this->writeln('</ol>'); } } }
[ "protected", "function", "printOutlineExampleResult", "(", "TableNode", "$", "examples", ",", "$", "iteration", ",", "$", "result", ",", "$", "isSkipped", ")", "{", "if", "(", "!", "$", "this", "->", "getParameter", "(", "'expand'", ")", ")", "{", "$", "color", "=", "$", "this", "->", "getResultColorCode", "(", "$", "result", ")", ";", "$", "this", "->", "printColorizedTableRow", "(", "$", "examples", "->", "getRow", "(", "$", "iteration", "+", "1", ")", ",", "$", "color", ")", ";", "$", "this", "->", "printOutlineExampleResultExceptions", "(", "$", "examples", ",", "$", "this", "->", "delayedStepEvents", ")", ";", "$", "this", "->", "writeln", "(", "'<tr class=\"'", ".", "$", "color", ".", "'\">'", ")", ";", "$", "this", "->", "writeln", "(", "'<td>'", ".", "(", "$", "iteration", "+", "1", ")", ".", "'</td>'", ")", ";", "$", "this", "->", "writeln", "(", "'<td colspan=\"'", ".", "count", "(", "$", "examples", "->", "getRow", "(", "$", "iteration", ")", ")", ".", "'\">'", ")", ";", "$", "this", "->", "writeln", "(", "'<div><a href=\"#\" class=\"open-screenshots\"> [+] Screenshot links </a>&nbsp;<a href=\"#\" class=\"close-screenshots\"> [-] Screenshot links </a></div>'", ")", ";", "$", "this", "->", "writeln", "(", "'<div class=\"outline-example-result-screenshots-holder jq-toggle\">'", ")", ";", "$", "this", "->", "writeln", "(", "$", "this", "->", "screenShotMarkup", ")", ";", "$", "this", "->", "writeln", "(", "'</div>'", ")", ";", "$", "this", "->", "writeln", "(", "'</td>'", ")", ";", "$", "this", "->", "writeln", "(", "'</tr>'", ")", ";", "$", "this", "->", "screenShotMarkup", "=", "''", ";", "}", "else", "{", "$", "this", "->", "write", "(", "'<h4>'", ".", "$", "examples", "->", "getKeyword", "(", ")", ".", "': '", ")", ";", "foreach", "(", "$", "examples", "->", "getRow", "(", "$", "iteration", "+", "1", ")", "as", "$", "value", ")", "{", "$", "this", "->", "write", "(", "'<span>'", ".", "$", "value", ".", "'</span>'", ")", ";", "}", "$", "this", "->", "writeln", "(", "'</h4>'", ")", ";", "foreach", "(", "$", "this", "->", "delayedStepEvents", "as", "$", "event", ")", "{", "$", "this", "->", "writeln", "(", "'<ol>'", ")", ";", "$", "this", "->", "printStep", "(", "$", "event", "->", "getStep", "(", ")", ",", "$", "event", "->", "getResult", "(", ")", ",", "$", "event", "->", "getDefinition", "(", ")", ",", "$", "event", "->", "getSnippet", "(", ")", ",", "$", "event", "->", "getException", "(", ")", ")", ";", "$", "this", "->", "writeln", "(", "'</ol>'", ")", ";", "}", "}", "}" ]
{@inheritdoc} @param TableNode $examples @param int $iteration @param int $result @param bool $isSkipped
[ "{" ]
train
https://github.com/alexandresalome/journal-extension/blob/de87304abb52abfa6905f1b83d2e35cc7bc52c0d/src/Behat/JournalExtension/Formatter/JournalFormatter.php#L120-L155
maestroprog/saw-php
src/Service/Executor.php
Executor.exec
public function exec($cmd): ProcessStatus { $cmd = sprintf('%s %s', $this->phpBinaryPath, $cmd . ' &'); if (PHP_OS === 'WINNT') { $cmd = str_replace('/', '\\', $cmd); $cmd = str_replace('\\', '\\\\', $cmd); } if (PHP_SAPI !== 'cli') { // define('STDIN', fopen('php://stdin', 'r')); define('STDOUT', fopen('php://stdout', 'w')); define('STDERR', fopen('php://stderr', 'w')); } $pipes = [['pipe', 'r'], STDOUT, STDERR]; $pipesOpened = []; Log::log($cmd); $resource = proc_open($cmd, $pipes, $pipesOpened, null, null, ['bypass_shell' => true]); if (false === $resource) { throw new \RuntimeException('Cannot be run ' . $cmd); } return new ProcessStatus($resource, $pipesOpened); }
php
public function exec($cmd): ProcessStatus { $cmd = sprintf('%s %s', $this->phpBinaryPath, $cmd . ' &'); if (PHP_OS === 'WINNT') { $cmd = str_replace('/', '\\', $cmd); $cmd = str_replace('\\', '\\\\', $cmd); } if (PHP_SAPI !== 'cli') { // define('STDIN', fopen('php://stdin', 'r')); define('STDOUT', fopen('php://stdout', 'w')); define('STDERR', fopen('php://stderr', 'w')); } $pipes = [['pipe', 'r'], STDOUT, STDERR]; $pipesOpened = []; Log::log($cmd); $resource = proc_open($cmd, $pipes, $pipesOpened, null, null, ['bypass_shell' => true]); if (false === $resource) { throw new \RuntimeException('Cannot be run ' . $cmd); } return new ProcessStatus($resource, $pipesOpened); }
[ "public", "function", "exec", "(", "$", "cmd", ")", ":", "ProcessStatus", "{", "$", "cmd", "=", "sprintf", "(", "'%s %s'", ",", "$", "this", "->", "phpBinaryPath", ",", "$", "cmd", ".", "' &'", ")", ";", "if", "(", "PHP_OS", "===", "'WINNT'", ")", "{", "$", "cmd", "=", "str_replace", "(", "'/'", ",", "'\\\\'", ",", "$", "cmd", ")", ";", "$", "cmd", "=", "str_replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ",", "$", "cmd", ")", ";", "}", "if", "(", "PHP_SAPI", "!==", "'cli'", ")", "{", "// define('STDIN', fopen('php://stdin', 'r'));", "define", "(", "'STDOUT'", ",", "fopen", "(", "'php://stdout'", ",", "'w'", ")", ")", ";", "define", "(", "'STDERR'", ",", "fopen", "(", "'php://stderr'", ",", "'w'", ")", ")", ";", "}", "$", "pipes", "=", "[", "[", "'pipe'", ",", "'r'", "]", ",", "STDOUT", ",", "STDERR", "]", ";", "$", "pipesOpened", "=", "[", "]", ";", "Log", "::", "log", "(", "$", "cmd", ")", ";", "$", "resource", "=", "proc_open", "(", "$", "cmd", ",", "$", "pipes", ",", "$", "pipesOpened", ",", "null", ",", "null", ",", "[", "'bypass_shell'", "=>", "true", "]", ")", ";", "if", "(", "false", "===", "$", "resource", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot be run '", ".", "$", "cmd", ")", ";", "}", "return", "new", "ProcessStatus", "(", "$", "resource", ",", "$", "pipesOpened", ")", ";", "}" ]
Выполняет команду, и возвращает ID запущенного процесса. @param $cmd @return ProcessStatus
[ "Выполняет", "команду", "и", "возвращает", "ID", "запущенного", "процесса", "." ]
train
https://github.com/maestroprog/saw-php/blob/159215a4d7a951cca2a9c2eed3e1aa4f5b624cfb/src/Service/Executor.php#L28-L48
old-town/workflow-designer-server
src/Api/V1/Rest/WorkflowDescriptor/WorkflowDescriptorEntityResource.php
WorkflowDescriptorEntityResource.fetch
public function fetch($id) { $routeMath = $this->getEvent()->getRouteMatch(); $workflowManager = $routeMath->getParam('workflowManager', null); if (null === $workflowManager || '' === trim($workflowManager)) { return new ApiProblemResponse( new ApiProblem(400, 'Invalid workflow manager name') ); } if (null === $id || '' === trim($id)) { return new ApiProblemResponse( new ApiProblem(400, 'Invalid workflow name') ); } try { $serviceLocator = $this->getServiceLocator(); /** @var WorkflowZF2ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(WorkflowZF2ModuleOptions::class); /** @var WorkflowInterface $workflow */ $workflowServiceName = sprintf($moduleOptions->getWorkflowManagerServiceNamePattern(), $workflowManager); $workflow = $this->getServiceLocator()->get($workflowServiceName); $workflowDescriptor = $workflow->getWorkflowDescriptor($id); } catch (\Exception $e) { return new ApiProblemResponse( new ApiProblem(400, $e->getMessage()) ); } return $workflowDescriptor; }
php
public function fetch($id) { $routeMath = $this->getEvent()->getRouteMatch(); $workflowManager = $routeMath->getParam('workflowManager', null); if (null === $workflowManager || '' === trim($workflowManager)) { return new ApiProblemResponse( new ApiProblem(400, 'Invalid workflow manager name') ); } if (null === $id || '' === trim($id)) { return new ApiProblemResponse( new ApiProblem(400, 'Invalid workflow name') ); } try { $serviceLocator = $this->getServiceLocator(); /** @var WorkflowZF2ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(WorkflowZF2ModuleOptions::class); /** @var WorkflowInterface $workflow */ $workflowServiceName = sprintf($moduleOptions->getWorkflowManagerServiceNamePattern(), $workflowManager); $workflow = $this->getServiceLocator()->get($workflowServiceName); $workflowDescriptor = $workflow->getWorkflowDescriptor($id); } catch (\Exception $e) { return new ApiProblemResponse( new ApiProblem(400, $e->getMessage()) ); } return $workflowDescriptor; }
[ "public", "function", "fetch", "(", "$", "id", ")", "{", "$", "routeMath", "=", "$", "this", "->", "getEvent", "(", ")", "->", "getRouteMatch", "(", ")", ";", "$", "workflowManager", "=", "$", "routeMath", "->", "getParam", "(", "'workflowManager'", ",", "null", ")", ";", "if", "(", "null", "===", "$", "workflowManager", "||", "''", "===", "trim", "(", "$", "workflowManager", ")", ")", "{", "return", "new", "ApiProblemResponse", "(", "new", "ApiProblem", "(", "400", ",", "'Invalid workflow manager name'", ")", ")", ";", "}", "if", "(", "null", "===", "$", "id", "||", "''", "===", "trim", "(", "$", "id", ")", ")", "{", "return", "new", "ApiProblemResponse", "(", "new", "ApiProblem", "(", "400", ",", "'Invalid workflow name'", ")", ")", ";", "}", "try", "{", "$", "serviceLocator", "=", "$", "this", "->", "getServiceLocator", "(", ")", ";", "/** @var WorkflowZF2ModuleOptions $moduleOptions */", "$", "moduleOptions", "=", "$", "serviceLocator", "->", "get", "(", "WorkflowZF2ModuleOptions", "::", "class", ")", ";", "/** @var WorkflowInterface $workflow */", "$", "workflowServiceName", "=", "sprintf", "(", "$", "moduleOptions", "->", "getWorkflowManagerServiceNamePattern", "(", ")", ",", "$", "workflowManager", ")", ";", "$", "workflow", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "$", "workflowServiceName", ")", ";", "$", "workflowDescriptor", "=", "$", "workflow", "->", "getWorkflowDescriptor", "(", "$", "id", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "new", "ApiProblemResponse", "(", "new", "ApiProblem", "(", "400", ",", "$", "e", "->", "getMessage", "(", ")", ")", ")", ";", "}", "return", "$", "workflowDescriptor", ";", "}" ]
@param mixed $id @return \OldTown\Workflow\Loader\WorkflowDescriptor @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
[ "@param", "mixed", "$id" ]
train
https://github.com/old-town/workflow-designer-server/blob/6389c5a515861cc8e0b769f1ca7be12c6b78c611/src/Api/V1/Rest/WorkflowDescriptor/WorkflowDescriptorEntityResource.php#L33-L71
JimmDiGrizli/phalcon-config-loader
src/ConfigLoader.php
ConfigLoader.create
public function create($path, $import = true) { $extension = $this->extractExtension($path); $path = str_replace(self::ENVIRONMENT, $this->environment, $path); if ($extension === null) { throw new ExtensionNotFoundException("Extension not found ($path)"); } if (isset($this->adapters[$extension])) { return $this->build($path, $extension, $import); } throw new AdapterNotFoundException("Adapter can be found for $path"); }
php
public function create($path, $import = true) { $extension = $this->extractExtension($path); $path = str_replace(self::ENVIRONMENT, $this->environment, $path); if ($extension === null) { throw new ExtensionNotFoundException("Extension not found ($path)"); } if (isset($this->adapters[$extension])) { return $this->build($path, $extension, $import); } throw new AdapterNotFoundException("Adapter can be found for $path"); }
[ "public", "function", "create", "(", "$", "path", ",", "$", "import", "=", "true", ")", "{", "$", "extension", "=", "$", "this", "->", "extractExtension", "(", "$", "path", ")", ";", "$", "path", "=", "str_replace", "(", "self", "::", "ENVIRONMENT", ",", "$", "this", "->", "environment", ",", "$", "path", ")", ";", "if", "(", "$", "extension", "===", "null", ")", "{", "throw", "new", "ExtensionNotFoundException", "(", "\"Extension not found ($path)\"", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "adapters", "[", "$", "extension", "]", ")", ")", "{", "return", "$", "this", "->", "build", "(", "$", "path", ",", "$", "extension", ",", "$", "import", ")", ";", "}", "throw", "new", "AdapterNotFoundException", "(", "\"Adapter can be found for $path\"", ")", ";", "}" ]
Create config @param string $path Path to the config file @param bool $import Import encountered config files @return BaseConfig @throws ExtensionNotFoundException @throws AdapterNotFoundException
[ "Create", "config" ]
train
https://github.com/JimmDiGrizli/phalcon-config-loader/blob/9a68dc02057f16aa2431681675ca0bb876a7d571/src/ConfigLoader.php#L67-L82
JimmDiGrizli/phalcon-config-loader
src/ConfigLoader.php
ConfigLoader.importResource
protected function importResource(BaseConfig $baseConfig) { foreach ($baseConfig as $key => $value) { if ($value instanceof BaseConfig) { $this->importResource($value); } elseif (is_string($value)) { if ($key === self::RESOURCES_KEY) { $resources = $this->clear( $baseConfig, $this->create($value) ); $baseConfig->merge($resources); $baseConfig->offsetUnset($key); } elseif (substr_count($value, self::RESOURCES_VALUE)) { $baseConfig[$key] = $this->create( substr($value, strlen(self::RESOURCES_VALUE)) ); } elseif ($key === self::MODULE_KEY) { $resources = $this->clear( $baseConfig, $this->moduleConfigCreate($value) ); $baseConfig->merge($resources); $baseConfig->offsetUnset($key); } elseif (substr_count($value, self::MODULE_VALUE)) { $baseConfig[$key] = $this->moduleConfigCreate( substr( $value, strlen(self::MODULE_VALUE) ) ); } if (substr_count($value, self::ENVIRONMENT)) { $baseConfig[$key] = str_replace( self::ENVIRONMENT, $this->environment, $value ); } } } }
php
protected function importResource(BaseConfig $baseConfig) { foreach ($baseConfig as $key => $value) { if ($value instanceof BaseConfig) { $this->importResource($value); } elseif (is_string($value)) { if ($key === self::RESOURCES_KEY) { $resources = $this->clear( $baseConfig, $this->create($value) ); $baseConfig->merge($resources); $baseConfig->offsetUnset($key); } elseif (substr_count($value, self::RESOURCES_VALUE)) { $baseConfig[$key] = $this->create( substr($value, strlen(self::RESOURCES_VALUE)) ); } elseif ($key === self::MODULE_KEY) { $resources = $this->clear( $baseConfig, $this->moduleConfigCreate($value) ); $baseConfig->merge($resources); $baseConfig->offsetUnset($key); } elseif (substr_count($value, self::MODULE_VALUE)) { $baseConfig[$key] = $this->moduleConfigCreate( substr( $value, strlen(self::MODULE_VALUE) ) ); } if (substr_count($value, self::ENVIRONMENT)) { $baseConfig[$key] = str_replace( self::ENVIRONMENT, $this->environment, $value ); } } } }
[ "protected", "function", "importResource", "(", "BaseConfig", "$", "baseConfig", ")", "{", "foreach", "(", "$", "baseConfig", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "BaseConfig", ")", "{", "$", "this", "->", "importResource", "(", "$", "value", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "value", ")", ")", "{", "if", "(", "$", "key", "===", "self", "::", "RESOURCES_KEY", ")", "{", "$", "resources", "=", "$", "this", "->", "clear", "(", "$", "baseConfig", ",", "$", "this", "->", "create", "(", "$", "value", ")", ")", ";", "$", "baseConfig", "->", "merge", "(", "$", "resources", ")", ";", "$", "baseConfig", "->", "offsetUnset", "(", "$", "key", ")", ";", "}", "elseif", "(", "substr_count", "(", "$", "value", ",", "self", "::", "RESOURCES_VALUE", ")", ")", "{", "$", "baseConfig", "[", "$", "key", "]", "=", "$", "this", "->", "create", "(", "substr", "(", "$", "value", ",", "strlen", "(", "self", "::", "RESOURCES_VALUE", ")", ")", ")", ";", "}", "elseif", "(", "$", "key", "===", "self", "::", "MODULE_KEY", ")", "{", "$", "resources", "=", "$", "this", "->", "clear", "(", "$", "baseConfig", ",", "$", "this", "->", "moduleConfigCreate", "(", "$", "value", ")", ")", ";", "$", "baseConfig", "->", "merge", "(", "$", "resources", ")", ";", "$", "baseConfig", "->", "offsetUnset", "(", "$", "key", ")", ";", "}", "elseif", "(", "substr_count", "(", "$", "value", ",", "self", "::", "MODULE_VALUE", ")", ")", "{", "$", "baseConfig", "[", "$", "key", "]", "=", "$", "this", "->", "moduleConfigCreate", "(", "substr", "(", "$", "value", ",", "strlen", "(", "self", "::", "MODULE_VALUE", ")", ")", ")", ";", "}", "if", "(", "substr_count", "(", "$", "value", ",", "self", "::", "ENVIRONMENT", ")", ")", "{", "$", "baseConfig", "[", "$", "key", "]", "=", "str_replace", "(", "self", "::", "ENVIRONMENT", ",", "$", "this", "->", "environment", ",", "$", "value", ")", ";", "}", "}", "}", "}" ]
Import encountered files in the configuration @param Config $baseConfig @throws AdapterNotFoundException @throws ConstantDirNotFoundException @throws ExtensionNotFoundException
[ "Import", "encountered", "files", "in", "the", "configuration" ]
train
https://github.com/JimmDiGrizli/phalcon-config-loader/blob/9a68dc02057f16aa2431681675ca0bb876a7d571/src/ConfigLoader.php#L156-L204
JimmDiGrizli/phalcon-config-loader
src/ConfigLoader.php
ConfigLoader.clear
public function clear(Config $means, Config $target) { foreach ($target as $key => $value) { if ($value instanceof BaseConfig && isset($means[$key])) { $this->clear($means[$key], $value); } else { if (isset($means[$key])) { $target->offsetUnset($key); } } } return new BaseConfig($target->toArray()); }
php
public function clear(Config $means, Config $target) { foreach ($target as $key => $value) { if ($value instanceof BaseConfig && isset($means[$key])) { $this->clear($means[$key], $value); } else { if (isset($means[$key])) { $target->offsetUnset($key); } } } return new BaseConfig($target->toArray()); }
[ "public", "function", "clear", "(", "Config", "$", "means", ",", "Config", "$", "target", ")", "{", "foreach", "(", "$", "target", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "BaseConfig", "&&", "isset", "(", "$", "means", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "clear", "(", "$", "means", "[", "$", "key", "]", ",", "$", "value", ")", ";", "}", "else", "{", "if", "(", "isset", "(", "$", "means", "[", "$", "key", "]", ")", ")", "{", "$", "target", "->", "offsetUnset", "(", "$", "key", ")", ";", "}", "}", "}", "return", "new", "BaseConfig", "(", "$", "target", "->", "toArray", "(", ")", ")", ";", "}" ]
Delete variables that are already defined in the main configuration file @param Config $means Main configuration file @param Config $target Imported configuration file @return Config
[ "Delete", "variables", "that", "are", "already", "defined", "in", "the", "main", "configuration", "file" ]
train
https://github.com/JimmDiGrizli/phalcon-config-loader/blob/9a68dc02057f16aa2431681675ca0bb876a7d571/src/ConfigLoader.php#L213-L226
JimmDiGrizli/phalcon-config-loader
src/ConfigLoader.php
ConfigLoader.moduleConfigCreate
protected function moduleConfigCreate($path) { $value = explode('::', $path); $ref = new ReflectionClass($value[0]); if ($ref->hasConstant('DIR') === false) { throw new ConstantDirNotFoundException( 'Not found constant DIR in class ' . $value[0] ); } return $this->create($value[0]::DIR . $ref->getConstant($value[1])); }
php
protected function moduleConfigCreate($path) { $value = explode('::', $path); $ref = new ReflectionClass($value[0]); if ($ref->hasConstant('DIR') === false) { throw new ConstantDirNotFoundException( 'Not found constant DIR in class ' . $value[0] ); } return $this->create($value[0]::DIR . $ref->getConstant($value[1])); }
[ "protected", "function", "moduleConfigCreate", "(", "$", "path", ")", "{", "$", "value", "=", "explode", "(", "'::'", ",", "$", "path", ")", ";", "$", "ref", "=", "new", "ReflectionClass", "(", "$", "value", "[", "0", "]", ")", ";", "if", "(", "$", "ref", "->", "hasConstant", "(", "'DIR'", ")", "===", "false", ")", "{", "throw", "new", "ConstantDirNotFoundException", "(", "'Not found constant DIR in class '", ".", "$", "value", "[", "0", "]", ")", ";", "}", "return", "$", "this", "->", "create", "(", "$", "value", "[", "0", "]", "::", "DIR", ".", "$", "ref", "->", "getConstant", "(", "$", "value", "[", "1", "]", ")", ")", ";", "}" ]
Create a configuration of the module for further imports @param $path @return Config @throws AdapterNotFoundException @throws ConstantDirNotFoundException @throws ExtensionNotFoundException
[ "Create", "a", "configuration", "of", "the", "module", "for", "further", "imports" ]
train
https://github.com/JimmDiGrizli/phalcon-config-loader/blob/9a68dc02057f16aa2431681675ca0bb876a7d571/src/ConfigLoader.php#L237-L250
JimmDiGrizli/phalcon-config-loader
src/ConfigLoader.php
ConfigLoader.add
public function add($name, $class) { $ref = new ReflectionClass($class); if ($ref->isSubclassOf('Phalcon\Config') === false) { throw new NotFoundTrueParentClassException( $class . ' is\'t subclass of Phalcon/Config' ); } $this->adapters[$name] = $class; }
php
public function add($name, $class) { $ref = new ReflectionClass($class); if ($ref->isSubclassOf('Phalcon\Config') === false) { throw new NotFoundTrueParentClassException( $class . ' is\'t subclass of Phalcon/Config' ); } $this->adapters[$name] = $class; }
[ "public", "function", "add", "(", "$", "name", ",", "$", "class", ")", "{", "$", "ref", "=", "new", "ReflectionClass", "(", "$", "class", ")", ";", "if", "(", "$", "ref", "->", "isSubclassOf", "(", "'Phalcon\\Config'", ")", "===", "false", ")", "{", "throw", "new", "NotFoundTrueParentClassException", "(", "$", "class", ".", "' is\\'t subclass of Phalcon/Config'", ")", ";", "}", "$", "this", "->", "adapters", "[", "$", "name", "]", "=", "$", "class", ";", "}" ]
Adds adapter $class with extension $name @param string $name @param string $class @throws NotFoundTrueParentClassException
[ "Adds", "adapter", "$class", "with", "extension", "$name" ]
train
https://github.com/JimmDiGrizli/phalcon-config-loader/blob/9a68dc02057f16aa2431681675ca0bb876a7d571/src/ConfigLoader.php#L259-L268
webdevvie/pheanstalk-task-queue-bundle
Service/PheanstalkConnection.php
PheanstalkConnection.put
public function put( $data, $priority = \Pheanstalk_PheanstalkInterface::DEFAULT_PRIORITY, $delay = \Pheanstalk_PheanstalkInterface::DEFAULT_DELAY, $timeToRun = \Pheanstalk_PheanstalkInterface::DEFAULT_TTR ) { $this->pheanstalk->put($data, $priority, $delay, $timeToRun); return $this; }
php
public function put( $data, $priority = \Pheanstalk_PheanstalkInterface::DEFAULT_PRIORITY, $delay = \Pheanstalk_PheanstalkInterface::DEFAULT_DELAY, $timeToRun = \Pheanstalk_PheanstalkInterface::DEFAULT_TTR ) { $this->pheanstalk->put($data, $priority, $delay, $timeToRun); return $this; }
[ "public", "function", "put", "(", "$", "data", ",", "$", "priority", "=", "\\", "Pheanstalk_PheanstalkInterface", "::", "DEFAULT_PRIORITY", ",", "$", "delay", "=", "\\", "Pheanstalk_PheanstalkInterface", "::", "DEFAULT_DELAY", ",", "$", "timeToRun", "=", "\\", "Pheanstalk_PheanstalkInterface", "::", "DEFAULT_TTR", ")", "{", "$", "this", "->", "pheanstalk", "->", "put", "(", "$", "data", ",", "$", "priority", ",", "$", "delay", ",", "$", "timeToRun", ")", ";", "return", "$", "this", ";", "}" ]
Puts a task string into the current @param $data @param int $priority @param int $delay @param int $timeToRun @return $this
[ "Puts", "a", "task", "string", "into", "the", "current" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Service/PheanstalkConnection.php#L40-L48
expectation-php/expect
src/matcher/strategy/StringInclusionStrategy.php
StringInclusionStrategy.match
public function match(array $expectValues) { $matchResults = []; $unmatchResults = []; foreach ($expectValues as $expectValue) { $position = strpos($this->actualValue, $expectValue); if ($position !== false) { $matchResults[] = $expectValue; } else { $unmatchResults[] = $expectValue; } } return new InclusionResult($expectValues, $matchResults, $unmatchResults); }
php
public function match(array $expectValues) { $matchResults = []; $unmatchResults = []; foreach ($expectValues as $expectValue) { $position = strpos($this->actualValue, $expectValue); if ($position !== false) { $matchResults[] = $expectValue; } else { $unmatchResults[] = $expectValue; } } return new InclusionResult($expectValues, $matchResults, $unmatchResults); }
[ "public", "function", "match", "(", "array", "$", "expectValues", ")", "{", "$", "matchResults", "=", "[", "]", ";", "$", "unmatchResults", "=", "[", "]", ";", "foreach", "(", "$", "expectValues", "as", "$", "expectValue", ")", "{", "$", "position", "=", "strpos", "(", "$", "this", "->", "actualValue", ",", "$", "expectValue", ")", ";", "if", "(", "$", "position", "!==", "false", ")", "{", "$", "matchResults", "[", "]", "=", "$", "expectValue", ";", "}", "else", "{", "$", "unmatchResults", "[", "]", "=", "$", "expectValue", ";", "}", "}", "return", "new", "InclusionResult", "(", "$", "expectValues", ",", "$", "matchResults", ",", "$", "unmatchResults", ")", ";", "}" ]
<code> <?php $strategy = new StringInclusionStrategy('foo'); $result = $strategy->match([ 'foo', 'bar' ]);. var_dump($result->isMatched()) // true var_dump($result->getMatchResults()); // ['foo'] var_dump($result->getUnmatchResults()); // ['bar'] ?> </code> @param array expectValues
[ "<code", ">", "<?php", "$strategy", "=", "new", "StringInclusionStrategy", "(", "foo", ")", ";", "$result", "=", "$strategy", "-", ">", "match", "(", "[", "foo", "bar", "]", ")", ";", "." ]
train
https://github.com/expectation-php/expect/blob/1a32c5af37f3dc8dabe4e8eedeeb21aea16ce139/src/matcher/strategy/StringInclusionStrategy.php#L42-L57
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.getTab
public function getTab(): string { return '<span title="Doctrine 2">' . '<svg viewBox="0 0 2048 2048"><path fill="#aaa" d="M1024 896q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280' . '-93.5-103-128v-170q119 84 325 127t443 43zm0 768q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128' . 'v-170q119 84 325 127t443 43zm0-384q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128v-170q119 84 ' . '325 127t443 43zm0-1152q208 0 385 34.5t280 93.5 103 128v128q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128v-128q0-69 103' . '-128t280-93.5 385-34.5z"></path></svg>' . '<span class="tracy-label">' . count($this->queries) . ' queries' . ($this->totalTime ? ' / ' . sprintf('%0.1f', $this->totalTime * 1000) . ' ms' : '') . '</span>' . '</span>'; }
php
public function getTab(): string { return '<span title="Doctrine 2">' . '<svg viewBox="0 0 2048 2048"><path fill="#aaa" d="M1024 896q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280' . '-93.5-103-128v-170q119 84 325 127t443 43zm0 768q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128' . 'v-170q119 84 325 127t443 43zm0-384q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128v-170q119 84 ' . '325 127t443 43zm0-1152q208 0 385 34.5t280 93.5 103 128v128q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128v-128q0-69 103' . '-128t280-93.5 385-34.5z"></path></svg>' . '<span class="tracy-label">' . count($this->queries) . ' queries' . ($this->totalTime ? ' / ' . sprintf('%0.1f', $this->totalTime * 1000) . ' ms' : '') . '</span>' . '</span>'; }
[ "public", "function", "getTab", "(", ")", ":", "string", "{", "return", "'<span title=\"Doctrine 2\">'", ".", "'<svg viewBox=\"0 0 2048 2048\"><path fill=\"#aaa\" d=\"M1024 896q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280'", ".", "'-93.5-103-128v-170q119 84 325 127t443 43zm0 768q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128'", ".", "'v-170q119 84 325 127t443 43zm0-384q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128v-170q119 84 '", ".", "'325 127t443 43zm0-1152q208 0 385 34.5t280 93.5 103 128v128q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128v-128q0-69 103'", ".", "'-128t280-93.5 385-34.5z\"></path></svg>'", ".", "'<span class=\"tracy-label\">'", ".", "count", "(", "$", "this", "->", "queries", ")", ".", "' queries'", ".", "(", "$", "this", "->", "totalTime", "?", "' / '", ".", "sprintf", "(", "'%0.1f'", ",", "$", "this", "->", "totalTime", "*", "1000", ")", ".", "' ms'", ":", "''", ")", ".", "'</span>'", ".", "'</span>'", ";", "}" ]
Renders tab for Tracy Debug Bar. @return string
[ "Renders", "tab", "for", "Tracy", "Debug", "Bar", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L73-L85
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.getPanel
public function getPanel(): string { if (empty($this->queries)) { return ''; } $params = $this->connection->getParams(); $host = ($params['driver'] === 'pdo_sqlite' && isset($params['path'])) ? 'path: ' . basename($params['path']) : sprintf('host: %s%s/%s', $this->connection->getHost(), (($p = $this->connection->getPort()) ? ':' . $p : ''), $this->connection->getDatabase()); return '<style> #nette-debug td.nette-Doctrine2Panel-sql { background: white !important} #nette-debug .nette-Doctrine2Panel-source { color: #BBB !important } #nette-debug nette-Doctrine2Panel tr table { margin: 8px 0; max-height: 150px; overflow:auto } #tracy-debug td.nette-Doctrine2Panel-sql { background: white !important} #tracy-debug .nette-Doctrine2Panel-source { color: #BBB !important } #tracy-debug nette-Doctrine2Panel tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style>' . sprintf('<h1>Queries: %s%s, %s</h1>', count($this->queries), ($this->totalTime ? ', time: ' . sprintf('%0.3f', $this->totalTime * 1000) . ' ms' : ''), $host) . '<div class="nette-inner tracy-inner nette-Doctrine2Panel">' . implode('<br>', array_filter([$this->renderPanelCacheStatistics(), $this->renderPanelQueries()])) . '</div>'; }
php
public function getPanel(): string { if (empty($this->queries)) { return ''; } $params = $this->connection->getParams(); $host = ($params['driver'] === 'pdo_sqlite' && isset($params['path'])) ? 'path: ' . basename($params['path']) : sprintf('host: %s%s/%s', $this->connection->getHost(), (($p = $this->connection->getPort()) ? ':' . $p : ''), $this->connection->getDatabase()); return '<style> #nette-debug td.nette-Doctrine2Panel-sql { background: white !important} #nette-debug .nette-Doctrine2Panel-source { color: #BBB !important } #nette-debug nette-Doctrine2Panel tr table { margin: 8px 0; max-height: 150px; overflow:auto } #tracy-debug td.nette-Doctrine2Panel-sql { background: white !important} #tracy-debug .nette-Doctrine2Panel-source { color: #BBB !important } #tracy-debug nette-Doctrine2Panel tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style>' . sprintf('<h1>Queries: %s%s, %s</h1>', count($this->queries), ($this->totalTime ? ', time: ' . sprintf('%0.3f', $this->totalTime * 1000) . ' ms' : ''), $host) . '<div class="nette-inner tracy-inner nette-Doctrine2Panel">' . implode('<br>', array_filter([$this->renderPanelCacheStatistics(), $this->renderPanelQueries()])) . '</div>'; }
[ "public", "function", "getPanel", "(", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "this", "->", "queries", ")", ")", "{", "return", "''", ";", "}", "$", "params", "=", "$", "this", "->", "connection", "->", "getParams", "(", ")", ";", "$", "host", "=", "(", "$", "params", "[", "'driver'", "]", "===", "'pdo_sqlite'", "&&", "isset", "(", "$", "params", "[", "'path'", "]", ")", ")", "?", "'path: '", ".", "basename", "(", "$", "params", "[", "'path'", "]", ")", ":", "sprintf", "(", "'host: %s%s/%s'", ",", "$", "this", "->", "connection", "->", "getHost", "(", ")", ",", "(", "(", "$", "p", "=", "$", "this", "->", "connection", "->", "getPort", "(", ")", ")", "?", "':'", ".", "$", "p", ":", "''", ")", ",", "$", "this", "->", "connection", "->", "getDatabase", "(", ")", ")", ";", "return", "'<style>\n\t\t\t\t#nette-debug td.nette-Doctrine2Panel-sql { background: white !important}\n\t\t\t\t#nette-debug .nette-Doctrine2Panel-source { color: #BBB !important }\n\t\t\t\t#nette-debug nette-Doctrine2Panel tr table { margin: 8px 0; max-height: 150px; overflow:auto }\n\t\t\t\t#tracy-debug td.nette-Doctrine2Panel-sql { background: white !important}\n\t\t\t\t#tracy-debug .nette-Doctrine2Panel-source { color: #BBB !important }\n\t\t\t\t#tracy-debug nette-Doctrine2Panel tr table { margin: 8px 0; max-height: 150px; overflow:auto }\n\t\t\t</style>'", ".", "sprintf", "(", "'<h1>Queries: %s%s, %s</h1>'", ",", "count", "(", "$", "this", "->", "queries", ")", ",", "(", "$", "this", "->", "totalTime", "?", "', time: '", ".", "sprintf", "(", "'%0.3f'", ",", "$", "this", "->", "totalTime", "*", "1000", ")", ".", "' ms'", ":", "''", ")", ",", "$", "host", ")", ".", "'<div class=\"nette-inner tracy-inner nette-Doctrine2Panel\">'", ".", "implode", "(", "'<br>'", ",", "array_filter", "(", "[", "$", "this", "->", "renderPanelCacheStatistics", "(", ")", ",", "$", "this", "->", "renderPanelQueries", "(", ")", "]", ")", ")", ".", "'</div>'", ";", "}" ]
Renders panel for Tracy Debug Bar. @return string
[ "Renders", "panel", "for", "Tracy", "Debug", "Bar", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L93-L119
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.renderPanelCacheStatistics
private function renderPanelCacheStatistics(): string { if (empty($this->entityManager)) { return ''; } $config = $this->entityManager->getConfiguration(); if (!$config->isSecondLevelCacheEnabled()) { return ''; } $loggerChain = $config->getSecondLevelCacheConfiguration()->getCacheLogger(); if (!$loggerChain instanceof Doctrine\ORM\Cache\Logging\CacheLoggerChain) { return ''; } if (!$statistics = $loggerChain->getLogger('statistics')) { return ''; } return Dumper::toHtml($statistics, [Dumper::DEPTH => 5]); }
php
private function renderPanelCacheStatistics(): string { if (empty($this->entityManager)) { return ''; } $config = $this->entityManager->getConfiguration(); if (!$config->isSecondLevelCacheEnabled()) { return ''; } $loggerChain = $config->getSecondLevelCacheConfiguration()->getCacheLogger(); if (!$loggerChain instanceof Doctrine\ORM\Cache\Logging\CacheLoggerChain) { return ''; } if (!$statistics = $loggerChain->getLogger('statistics')) { return ''; } return Dumper::toHtml($statistics, [Dumper::DEPTH => 5]); }
[ "private", "function", "renderPanelCacheStatistics", "(", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "this", "->", "entityManager", ")", ")", "{", "return", "''", ";", "}", "$", "config", "=", "$", "this", "->", "entityManager", "->", "getConfiguration", "(", ")", ";", "if", "(", "!", "$", "config", "->", "isSecondLevelCacheEnabled", "(", ")", ")", "{", "return", "''", ";", "}", "$", "loggerChain", "=", "$", "config", "->", "getSecondLevelCacheConfiguration", "(", ")", "->", "getCacheLogger", "(", ")", ";", "if", "(", "!", "$", "loggerChain", "instanceof", "Doctrine", "\\", "ORM", "\\", "Cache", "\\", "Logging", "\\", "CacheLoggerChain", ")", "{", "return", "''", ";", "}", "if", "(", "!", "$", "statistics", "=", "$", "loggerChain", "->", "getLogger", "(", "'statistics'", ")", ")", "{", "return", "''", ";", "}", "return", "Dumper", "::", "toHtml", "(", "$", "statistics", ",", "[", "Dumper", "::", "DEPTH", "=>", "5", "]", ")", ";", "}" ]
Renders cache statistics. @return string
[ "Renders", "cache", "statistics", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L127-L149
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.renderPanelQueries
private function renderPanelQueries(): string { if (empty($this->queries)) { return ''; } $s = ''; foreach ($this->queries as $query) { [$sql, $params, $time, $types, $source] = $query; $q = SqlDumper::dump($sql, $params); $q .= $source ? Helpers::editorLink($source[0], $source[1]) : ''; $s .= '<tr><td>' . sprintf('%0.3f', $time * 1000) . '</td><td class="nette-Doctrine2Panel-sql">' . $q . '</td></tr>'; } return '<table><tr><th>ms</th><th>SQL Statement</th></tr>' . $s . '</table>'; }
php
private function renderPanelQueries(): string { if (empty($this->queries)) { return ''; } $s = ''; foreach ($this->queries as $query) { [$sql, $params, $time, $types, $source] = $query; $q = SqlDumper::dump($sql, $params); $q .= $source ? Helpers::editorLink($source[0], $source[1]) : ''; $s .= '<tr><td>' . sprintf('%0.3f', $time * 1000) . '</td><td class="nette-Doctrine2Panel-sql">' . $q . '</td></tr>'; } return '<table><tr><th>ms</th><th>SQL Statement</th></tr>' . $s . '</table>'; }
[ "private", "function", "renderPanelQueries", "(", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "this", "->", "queries", ")", ")", "{", "return", "''", ";", "}", "$", "s", "=", "''", ";", "foreach", "(", "$", "this", "->", "queries", "as", "$", "query", ")", "{", "[", "$", "sql", ",", "$", "params", ",", "$", "time", ",", "$", "types", ",", "$", "source", "]", "=", "$", "query", ";", "$", "q", "=", "SqlDumper", "::", "dump", "(", "$", "sql", ",", "$", "params", ")", ";", "$", "q", ".=", "$", "source", "?", "Helpers", "::", "editorLink", "(", "$", "source", "[", "0", "]", ",", "$", "source", "[", "1", "]", ")", ":", "''", ";", "$", "s", ".=", "'<tr><td>'", ".", "sprintf", "(", "'%0.3f'", ",", "$", "time", "*", "1000", ")", ".", "'</td><td class=\"nette-Doctrine2Panel-sql\">'", ".", "$", "q", ".", "'</td></tr>'", ";", "}", "return", "'<table><tr><th>ms</th><th>SQL Statement</th></tr>'", ".", "$", "s", ".", "'</table>'", ";", "}" ]
Renders SQL queries. @return string
[ "Renders", "SQL", "queries", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L157-L172
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.startQuery
public function startQuery($sql, array $params = NULL, array $types = NULL) { Debugger::timer('doctrine'); $source = NULL; foreach (debug_backtrace() as $row) { if (isset($row['file']) && $this->filterTracePaths(realpath($row['file']))) { if (isset($row['class']) && stripos($row['class'], '\\' . Proxy::MARKER) !== FALSE) { if (!in_array(Proxy::class, class_implements($row['class']))) { continue; } elseif (isset($row['function']) && $row['function'] === '__load') { continue; } } elseif (stripos($row['file'], DIRECTORY_SEPARATOR . Proxy::MARKER) !== FALSE) { continue; } $source = [$row['file'], (int) $row['line']]; break; } } $this->queries[] = [$sql, (array) $params, NULL, (array) $types, $source]; }
php
public function startQuery($sql, array $params = NULL, array $types = NULL) { Debugger::timer('doctrine'); $source = NULL; foreach (debug_backtrace() as $row) { if (isset($row['file']) && $this->filterTracePaths(realpath($row['file']))) { if (isset($row['class']) && stripos($row['class'], '\\' . Proxy::MARKER) !== FALSE) { if (!in_array(Proxy::class, class_implements($row['class']))) { continue; } elseif (isset($row['function']) && $row['function'] === '__load') { continue; } } elseif (stripos($row['file'], DIRECTORY_SEPARATOR . Proxy::MARKER) !== FALSE) { continue; } $source = [$row['file'], (int) $row['line']]; break; } } $this->queries[] = [$sql, (array) $params, NULL, (array) $types, $source]; }
[ "public", "function", "startQuery", "(", "$", "sql", ",", "array", "$", "params", "=", "NULL", ",", "array", "$", "types", "=", "NULL", ")", "{", "Debugger", "::", "timer", "(", "'doctrine'", ")", ";", "$", "source", "=", "NULL", ";", "foreach", "(", "debug_backtrace", "(", ")", "as", "$", "row", ")", "{", "if", "(", "isset", "(", "$", "row", "[", "'file'", "]", ")", "&&", "$", "this", "->", "filterTracePaths", "(", "realpath", "(", "$", "row", "[", "'file'", "]", ")", ")", ")", "{", "if", "(", "isset", "(", "$", "row", "[", "'class'", "]", ")", "&&", "stripos", "(", "$", "row", "[", "'class'", "]", ",", "'\\\\'", ".", "Proxy", "::", "MARKER", ")", "!==", "FALSE", ")", "{", "if", "(", "!", "in_array", "(", "Proxy", "::", "class", ",", "class_implements", "(", "$", "row", "[", "'class'", "]", ")", ")", ")", "{", "continue", ";", "}", "elseif", "(", "isset", "(", "$", "row", "[", "'function'", "]", ")", "&&", "$", "row", "[", "'function'", "]", "===", "'__load'", ")", "{", "continue", ";", "}", "}", "elseif", "(", "stripos", "(", "$", "row", "[", "'file'", "]", ",", "DIRECTORY_SEPARATOR", ".", "Proxy", "::", "MARKER", ")", "!==", "FALSE", ")", "{", "continue", ";", "}", "$", "source", "=", "[", "$", "row", "[", "'file'", "]", ",", "(", "int", ")", "$", "row", "[", "'line'", "]", "]", ";", "break", ";", "}", "}", "$", "this", "->", "queries", "[", "]", "=", "[", "$", "sql", ",", "(", "array", ")", "$", "params", ",", "NULL", ",", "(", "array", ")", "$", "types", ",", "$", "source", "]", ";", "}" ]
Logs a SQL statement somewhere. @param string $sql the SQL to be executed @param mixed[]|NULL $params the SQL parameters @param string[]|NULL $types the SQL parameter types @return void
[ "Logs", "a", "SQL", "statement", "somewhere", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L187-L209
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.stopQuery
public function stopQuery() { $keys = array_keys($this->queries); $key = end($keys); $this->queries[$key][2] = $time = Debugger::timer('doctrine'); $this->totalTime += $time; return $this->queries[$key] + array_fill_keys(range(0, 4), NULL); }
php
public function stopQuery() { $keys = array_keys($this->queries); $key = end($keys); $this->queries[$key][2] = $time = Debugger::timer('doctrine'); $this->totalTime += $time; return $this->queries[$key] + array_fill_keys(range(0, 4), NULL); }
[ "public", "function", "stopQuery", "(", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "this", "->", "queries", ")", ";", "$", "key", "=", "end", "(", "$", "keys", ")", ";", "$", "this", "->", "queries", "[", "$", "key", "]", "[", "2", "]", "=", "$", "time", "=", "Debugger", "::", "timer", "(", "'doctrine'", ")", ";", "$", "this", "->", "totalTime", "+=", "$", "time", ";", "return", "$", "this", "->", "queries", "[", "$", "key", "]", "+", "array_fill_keys", "(", "range", "(", "0", ",", "4", ")", ",", "NULL", ")", ";", "}" ]
Marks the last started query as stopped. This can be used for timing of queries. @return array
[ "Marks", "the", "last", "started", "query", "as", "stopped", ".", "This", "can", "be", "used", "for", "timing", "of", "queries", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L217-L225
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.setEntityManager
public function setEntityManager(EntityManager $entityManager) { $this->entityManager = $entityManager; $this->connection = $entityManager->getConnection(); $bar = Debugger::getBar(); $bar->addPanel($this); $config = $this->connection->getConfiguration(); $logger = $config->getSQLLogger(); if ($logger instanceof Doctrine\DBAL\Logging\LoggerChain) { $logger->addLogger($this); } else { $config->setSQLLogger($this); } }
php
public function setEntityManager(EntityManager $entityManager) { $this->entityManager = $entityManager; $this->connection = $entityManager->getConnection(); $bar = Debugger::getBar(); $bar->addPanel($this); $config = $this->connection->getConfiguration(); $logger = $config->getSQLLogger(); if ($logger instanceof Doctrine\DBAL\Logging\LoggerChain) { $logger->addLogger($this); } else { $config->setSQLLogger($this); } }
[ "public", "function", "setEntityManager", "(", "EntityManager", "$", "entityManager", ")", "{", "$", "this", "->", "entityManager", "=", "$", "entityManager", ";", "$", "this", "->", "connection", "=", "$", "entityManager", "->", "getConnection", "(", ")", ";", "$", "bar", "=", "Debugger", "::", "getBar", "(", ")", ";", "$", "bar", "->", "addPanel", "(", "$", "this", ")", ";", "$", "config", "=", "$", "this", "->", "connection", "->", "getConfiguration", "(", ")", ";", "$", "logger", "=", "$", "config", "->", "getSQLLogger", "(", ")", ";", "if", "(", "$", "logger", "instanceof", "Doctrine", "\\", "DBAL", "\\", "Logging", "\\", "LoggerChain", ")", "{", "$", "logger", "->", "addLogger", "(", "$", "this", ")", ";", "}", "else", "{", "$", "config", "->", "setSQLLogger", "(", "$", "this", ")", ";", "}", "}" ]
Sets entity manager. @param EntityManager $entityManager The Doctrine Entity Manager
[ "Sets", "entity", "manager", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L236-L251
andromeda-framework/doctrine
src/Doctrine/Tracy/Panel.php
Panel.filterTracePaths
private function filterTracePaths($file) { $file = str_replace(DIRECTORY_SEPARATOR, '/', $file); $return = is_file($file); foreach ($this->skipPaths as $path) { if (!$return) { break; } $return = $return && strpos($file, '/' . trim($path, '/') . '/') === FALSE; } return $return; }
php
private function filterTracePaths($file) { $file = str_replace(DIRECTORY_SEPARATOR, '/', $file); $return = is_file($file); foreach ($this->skipPaths as $path) { if (!$return) { break; } $return = $return && strpos($file, '/' . trim($path, '/') . '/') === FALSE; } return $return; }
[ "private", "function", "filterTracePaths", "(", "$", "file", ")", "{", "$", "file", "=", "str_replace", "(", "DIRECTORY_SEPARATOR", ",", "'/'", ",", "$", "file", ")", ";", "$", "return", "=", "is_file", "(", "$", "file", ")", ";", "foreach", "(", "$", "this", "->", "skipPaths", "as", "$", "path", ")", "{", "if", "(", "!", "$", "return", ")", "{", "break", ";", "}", "$", "return", "=", "$", "return", "&&", "strpos", "(", "$", "file", ",", "'/'", ".", "trim", "(", "$", "path", ",", "'/'", ")", ".", "'/'", ")", "===", "FALSE", ";", "}", "return", "$", "return", ";", "}" ]
@param string $file @return bool
[ "@param", "string", "$file" ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Tracy/Panel.php#L259-L270
GrupaZero/api
src/Gzero/Api/Controller/Admin/OptionController.php
OptionController.index
public function index() { $this->authorize('read', Option::class); return $this->respondWithSuccess($this->optionRepo->getCategories(), new OptionCategoryTransformer); }
php
public function index() { $this->authorize('read', Option::class); return $this->respondWithSuccess($this->optionRepo->getCategories(), new OptionCategoryTransformer); }
[ "public", "function", "index", "(", ")", "{", "$", "this", "->", "authorize", "(", "'read'", ",", "Option", "::", "class", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "this", "->", "optionRepo", "->", "getCategories", "(", ")", ",", "new", "OptionCategoryTransformer", ")", ";", "}" ]
Display a listing of the resource. @return \Illuminate\Http\JsonResponse
[ "Display", "a", "listing", "of", "the", "resource", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/OptionController.php#L54-L58
GrupaZero/api
src/Gzero/Api/Controller/Admin/OptionController.php
OptionController.show
public function show($key) { $this->authorize('read', Option::class); try { $option = $this->optionRepo->getOptions($key); return $this->respondWithSuccess($option, new OptionTransformer); } catch (RepositoryValidationException $e) { return $this->respondWithError($e->getMessage()); } }
php
public function show($key) { $this->authorize('read', Option::class); try { $option = $this->optionRepo->getOptions($key); return $this->respondWithSuccess($option, new OptionTransformer); } catch (RepositoryValidationException $e) { return $this->respondWithError($e->getMessage()); } }
[ "public", "function", "show", "(", "$", "key", ")", "{", "$", "this", "->", "authorize", "(", "'read'", ",", "Option", "::", "class", ")", ";", "try", "{", "$", "option", "=", "$", "this", "->", "optionRepo", "->", "getOptions", "(", "$", "key", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "option", ",", "new", "OptionTransformer", ")", ";", "}", "catch", "(", "RepositoryValidationException", "$", "e", ")", "{", "return", "$", "this", "->", "respondWithError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Display all options from selected category. @param string $key option category key @return \Illuminate\Http\JsonResponse
[ "Display", "all", "options", "from", "selected", "category", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/OptionController.php#L67-L76
GrupaZero/api
src/Gzero/Api/Controller/Admin/OptionController.php
OptionController.update
public function update($categoryKey) { $input = $this->validator->validate('update'); $this->authorize('update', [Option::class, $categoryKey]); try { $this->optionRepo->updateOrCreateOption($categoryKey, $input['key'], $input['value']); return $this->respondWithSuccess($this->optionRepo->getOptions($categoryKey), new OptionTransformer); } catch (RepositoryValidationException $e) { return $this->respondWithError($e->getMessage()); } }
php
public function update($categoryKey) { $input = $this->validator->validate('update'); $this->authorize('update', [Option::class, $categoryKey]); try { $this->optionRepo->updateOrCreateOption($categoryKey, $input['key'], $input['value']); return $this->respondWithSuccess($this->optionRepo->getOptions($categoryKey), new OptionTransformer); } catch (RepositoryValidationException $e) { return $this->respondWithError($e->getMessage()); } }
[ "public", "function", "update", "(", "$", "categoryKey", ")", "{", "$", "input", "=", "$", "this", "->", "validator", "->", "validate", "(", "'update'", ")", ";", "$", "this", "->", "authorize", "(", "'update'", ",", "[", "Option", "::", "class", ",", "$", "categoryKey", "]", ")", ";", "try", "{", "$", "this", "->", "optionRepo", "->", "updateOrCreateOption", "(", "$", "categoryKey", ",", "$", "input", "[", "'key'", "]", ",", "$", "input", "[", "'value'", "]", ")", ";", "return", "$", "this", "->", "respondWithSuccess", "(", "$", "this", "->", "optionRepo", "->", "getOptions", "(", "$", "categoryKey", ")", ",", "new", "OptionTransformer", ")", ";", "}", "catch", "(", "RepositoryValidationException", "$", "e", ")", "{", "return", "$", "this", "->", "respondWithError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Updates the specified resource in the database. @param string $categoryKey option category key @return \Illuminate\Http\JsonResponse @throws \Gzero\Validator\ValidationException
[ "Updates", "the", "specified", "resource", "in", "the", "database", "." ]
train
https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Controller/Admin/OptionController.php#L87-L97
php-lug/lug
src/Bundle/GridBundle/Form/Type/Batch/GridBatchValueType.php
GridBatchValueType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $idPropertyPath = function (Options $options) { $propertyPath = $options['grid']->getDefinition()->getResource()->getIdPropertyPath(); return function ($choice) use ($propertyPath) { return $this->propertyAccessor->getValue($choice, $propertyPath); }; }; $labelPropertyPath = function (Options $options) { $propertyPath = $options['grid']->getDefinition()->getResource()->getLabelPropertyPath(); return function ($choice) use ($propertyPath) { return $this->propertyAccessor->getValue($choice, $propertyPath); }; }; $resolver ->setDefaults([ 'multiple' => true, 'translation_domain' => false, 'choices' => [], 'choices_as_values' => true, 'choice_name' => $idPropertyPath, 'choice_value' => $idPropertyPath, 'choice_label' => $labelPropertyPath, 'class' => function (Options $options) { return $options['grid']->getDefinition()->getResource()->getModel(); }, 'expanded' => function (Options $options) { return !$this->parameterResolver->resolveApi(); }, 'constraints' => function (Options $options) { $resource = $options['grid']->getDefinition()->getResource(); return [new Count([ 'min' => 1, 'minMessage' => 'lug.'.$resource->getName().'.batch.empty', ])]; }, ]) ->setRequired('grid') ->setAllowedTypes('grid', GridViewInterface::class); }
php
public function configureOptions(OptionsResolver $resolver) { $idPropertyPath = function (Options $options) { $propertyPath = $options['grid']->getDefinition()->getResource()->getIdPropertyPath(); return function ($choice) use ($propertyPath) { return $this->propertyAccessor->getValue($choice, $propertyPath); }; }; $labelPropertyPath = function (Options $options) { $propertyPath = $options['grid']->getDefinition()->getResource()->getLabelPropertyPath(); return function ($choice) use ($propertyPath) { return $this->propertyAccessor->getValue($choice, $propertyPath); }; }; $resolver ->setDefaults([ 'multiple' => true, 'translation_domain' => false, 'choices' => [], 'choices_as_values' => true, 'choice_name' => $idPropertyPath, 'choice_value' => $idPropertyPath, 'choice_label' => $labelPropertyPath, 'class' => function (Options $options) { return $options['grid']->getDefinition()->getResource()->getModel(); }, 'expanded' => function (Options $options) { return !$this->parameterResolver->resolveApi(); }, 'constraints' => function (Options $options) { $resource = $options['grid']->getDefinition()->getResource(); return [new Count([ 'min' => 1, 'minMessage' => 'lug.'.$resource->getName().'.batch.empty', ])]; }, ]) ->setRequired('grid') ->setAllowedTypes('grid', GridViewInterface::class); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "$", "idPropertyPath", "=", "function", "(", "Options", "$", "options", ")", "{", "$", "propertyPath", "=", "$", "options", "[", "'grid'", "]", "->", "getDefinition", "(", ")", "->", "getResource", "(", ")", "->", "getIdPropertyPath", "(", ")", ";", "return", "function", "(", "$", "choice", ")", "use", "(", "$", "propertyPath", ")", "{", "return", "$", "this", "->", "propertyAccessor", "->", "getValue", "(", "$", "choice", ",", "$", "propertyPath", ")", ";", "}", ";", "}", ";", "$", "labelPropertyPath", "=", "function", "(", "Options", "$", "options", ")", "{", "$", "propertyPath", "=", "$", "options", "[", "'grid'", "]", "->", "getDefinition", "(", ")", "->", "getResource", "(", ")", "->", "getLabelPropertyPath", "(", ")", ";", "return", "function", "(", "$", "choice", ")", "use", "(", "$", "propertyPath", ")", "{", "return", "$", "this", "->", "propertyAccessor", "->", "getValue", "(", "$", "choice", ",", "$", "propertyPath", ")", ";", "}", ";", "}", ";", "$", "resolver", "->", "setDefaults", "(", "[", "'multiple'", "=>", "true", ",", "'translation_domain'", "=>", "false", ",", "'choices'", "=>", "[", "]", ",", "'choices_as_values'", "=>", "true", ",", "'choice_name'", "=>", "$", "idPropertyPath", ",", "'choice_value'", "=>", "$", "idPropertyPath", ",", "'choice_label'", "=>", "$", "labelPropertyPath", ",", "'class'", "=>", "function", "(", "Options", "$", "options", ")", "{", "return", "$", "options", "[", "'grid'", "]", "->", "getDefinition", "(", ")", "->", "getResource", "(", ")", "->", "getModel", "(", ")", ";", "}", ",", "'expanded'", "=>", "function", "(", "Options", "$", "options", ")", "{", "return", "!", "$", "this", "->", "parameterResolver", "->", "resolveApi", "(", ")", ";", "}", ",", "'constraints'", "=>", "function", "(", "Options", "$", "options", ")", "{", "$", "resource", "=", "$", "options", "[", "'grid'", "]", "->", "getDefinition", "(", ")", "->", "getResource", "(", ")", ";", "return", "[", "new", "Count", "(", "[", "'min'", "=>", "1", ",", "'minMessage'", "=>", "'lug.'", ".", "$", "resource", "->", "getName", "(", ")", ".", "'.batch.empty'", ",", "]", ")", "]", ";", "}", ",", "]", ")", "->", "setRequired", "(", "'grid'", ")", "->", "setAllowedTypes", "(", "'grid'", ",", "GridViewInterface", "::", "class", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Form/Type/Batch/GridBatchValueType.php#L53-L97
DevGroup-ru/yii2-users-module
src/widgets/SocialNetworksWidget.php
SocialNetworksWidget.renderMainContent
protected function renderMainContent() { echo Html::beginTag('div', ['class' => 'social-login']); foreach ($this->getClients() as $externalService) { $socialServiceId = SocialService::classNameToId(get_class($externalService)); $i18n = SocialService::i18nNameById($socialServiceId); $this->clientLink( $externalService, '<i class="demo-icon icon-basic-'.$externalService->getName().'"></i>', [ 'class' => "social-login__social-network social-login__social-network--" . $externalService->getName(), 'title' => $i18n, ] ); } echo Html::endTag('ul'); }
php
protected function renderMainContent() { echo Html::beginTag('div', ['class' => 'social-login']); foreach ($this->getClients() as $externalService) { $socialServiceId = SocialService::classNameToId(get_class($externalService)); $i18n = SocialService::i18nNameById($socialServiceId); $this->clientLink( $externalService, '<i class="demo-icon icon-basic-'.$externalService->getName().'"></i>', [ 'class' => "social-login__social-network social-login__social-network--" . $externalService->getName(), 'title' => $i18n, ] ); } echo Html::endTag('ul'); }
[ "protected", "function", "renderMainContent", "(", ")", "{", "echo", "Html", "::", "beginTag", "(", "'div'", ",", "[", "'class'", "=>", "'social-login'", "]", ")", ";", "foreach", "(", "$", "this", "->", "getClients", "(", ")", "as", "$", "externalService", ")", "{", "$", "socialServiceId", "=", "SocialService", "::", "classNameToId", "(", "get_class", "(", "$", "externalService", ")", ")", ";", "$", "i18n", "=", "SocialService", "::", "i18nNameById", "(", "$", "socialServiceId", ")", ";", "$", "this", "->", "clientLink", "(", "$", "externalService", ",", "'<i class=\"demo-icon icon-basic-'", ".", "$", "externalService", "->", "getName", "(", ")", ".", "'\"></i>'", ",", "[", "'class'", "=>", "\"social-login__social-network social-login__social-network--\"", ".", "$", "externalService", "->", "getName", "(", ")", ",", "'title'", "=>", "$", "i18n", ",", "]", ")", ";", "}", "echo", "Html", "::", "endTag", "(", "'ul'", ")", ";", "}" ]
Renders the main content, which includes all external services links.
[ "Renders", "the", "main", "content", "which", "includes", "all", "external", "services", "links", "." ]
train
https://github.com/DevGroup-ru/yii2-users-module/blob/ff0103dc55c3462627ccc704c33e70c96053f750/src/widgets/SocialNetworksWidget.php#L16-L33
phPoirot/psr7
HttpMessage.php
HttpMessage.withProtocolVersion
function withProtocolVersion($version) { $version = (string) $version; if ($version === $this->getProtocolVersion()) return $this; $new = clone $this; $new->version = $version; return $new; }
php
function withProtocolVersion($version) { $version = (string) $version; if ($version === $this->getProtocolVersion()) return $this; $new = clone $this; $new->version = $version; return $new; }
[ "function", "withProtocolVersion", "(", "$", "version", ")", "{", "$", "version", "=", "(", "string", ")", "$", "version", ";", "if", "(", "$", "version", "===", "$", "this", "->", "getProtocolVersion", "(", ")", ")", "return", "$", "this", ";", "$", "new", "=", "clone", "$", "this", ";", "$", "new", "->", "version", "=", "$", "version", ";", "return", "$", "new", ";", "}" ]
Return an instance with the specified HTTP protocol version. The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0"). This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new protocol version. @param string $version HTTP protocol version @return HttpMessage @throws \Exception
[ "Return", "an", "instance", "with", "the", "specified", "HTTP", "protocol", "version", "." ]
train
https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpMessage.php#L47-L57
phPoirot/psr7
HttpMessage.php
HttpMessage.getHeader
function getHeader($name) { if (! $this->hasHeader($name)) return array(); $header = $this->_c_headerNormalized[strtolower($name)]; $value = $this->headers[$header]; $value = is_array($value) ? $value : array($value); return $value; }
php
function getHeader($name) { if (! $this->hasHeader($name)) return array(); $header = $this->_c_headerNormalized[strtolower($name)]; $value = $this->headers[$header]; $value = is_array($value) ? $value : array($value); return $value; }
[ "function", "getHeader", "(", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "hasHeader", "(", "$", "name", ")", ")", "return", "array", "(", ")", ";", "$", "header", "=", "$", "this", "->", "_c_headerNormalized", "[", "strtolower", "(", "$", "name", ")", "]", ";", "$", "value", "=", "$", "this", "->", "headers", "[", "$", "header", "]", ";", "$", "value", "=", "is_array", "(", "$", "value", ")", "?", "$", "value", ":", "array", "(", "$", "value", ")", ";", "return", "$", "value", ";", "}" ]
Retrieves a message header value by the given case-insensitive name. This method returns an array of all the header values of the given case-insensitive header name. If the header does not appear in the message, this method MUST return an empty array. @param string $name Case-insensitive header field name. @return string[] An array of string values as provided for the given header. If the header does not appear in the message, this method MUST return an empty array.
[ "Retrieves", "a", "message", "header", "value", "by", "the", "given", "case", "-", "insensitive", "name", "." ]
train
https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpMessage.php#L116-L125
phPoirot/psr7
HttpMessage.php
HttpMessage.withHeader
function withHeader($name, $value) { if (is_string($value)) $value = array($value); if (! is_array($value) ) throw new \InvalidArgumentException( 'Invalid header value; must be a string or array of strings' ); if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $name)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header name', $name )); foreach ($value as $v) { if (!self::isValid($v)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header value', $value )); } $normalized = strtolower($name); // also replace oldest one if has $new = clone $this; $new->_c_headerNormalized[$normalized] = $name; $new->headers[$name] = $value; return $new; }
php
function withHeader($name, $value) { if (is_string($value)) $value = array($value); if (! is_array($value) ) throw new \InvalidArgumentException( 'Invalid header value; must be a string or array of strings' ); if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $name)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header name', $name )); foreach ($value as $v) { if (!self::isValid($v)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header value', $value )); } $normalized = strtolower($name); // also replace oldest one if has $new = clone $this; $new->_c_headerNormalized[$normalized] = $name; $new->headers[$name] = $value; return $new; }
[ "function", "withHeader", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "$", "value", "=", "array", "(", "$", "value", ")", ";", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid header value; must be a string or array of strings'", ")", ";", "if", "(", "!", "preg_match", "(", "'/^[a-zA-Z0-9\\'`#$%&*+.^_|~!-]+$/'", ",", "$", "name", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'\"%s\" is not valid header name'", ",", "$", "name", ")", ")", ";", "foreach", "(", "$", "value", "as", "$", "v", ")", "{", "if", "(", "!", "self", "::", "isValid", "(", "$", "v", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'\"%s\" is not valid header value'", ",", "$", "value", ")", ")", ";", "}", "$", "normalized", "=", "strtolower", "(", "$", "name", ")", ";", "// also replace oldest one if has", "$", "new", "=", "clone", "$", "this", ";", "$", "new", "->", "_c_headerNormalized", "[", "$", "normalized", "]", "=", "$", "name", ";", "$", "new", "->", "headers", "[", "$", "name", "]", "=", "$", "value", ";", "return", "$", "new", ";", "}" ]
Return an instance with the provided value replacing the specified header. While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders(). This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value. @param string $name Case-insensitive header field name. @param string|string[] $value Header value(s). @return self @throws \InvalidArgumentException for invalid header names or values.
[ "Return", "an", "instance", "with", "the", "provided", "value", "replacing", "the", "specified", "header", "." ]
train
https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpMessage.php#L170-L200
phPoirot/psr7
HttpMessage.php
HttpMessage.withAddedHeader
function withAddedHeader($name, $value) { if (is_string($value)) $value = array($value); if (! is_array($value) ) throw new \InvalidArgumentException( 'Invalid header value; must be a string or array of strings' ); if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $name)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header name', $name )); if (!self::isValid($value)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header value', $value )); if (! $this->hasHeader($name)) return $this->withHeader($name, $value); $normalized = strtolower($name); $header = $this->_c_headerNormalized[$normalized]; $new = clone $this; $new->headers[$header] = array_merge($this->headers[$header], $value); return $new; }
php
function withAddedHeader($name, $value) { if (is_string($value)) $value = array($value); if (! is_array($value) ) throw new \InvalidArgumentException( 'Invalid header value; must be a string or array of strings' ); if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $name)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header name', $name )); if (!self::isValid($value)) throw new \InvalidArgumentException(sprintf( '"%s" is not valid header value', $value )); if (! $this->hasHeader($name)) return $this->withHeader($name, $value); $normalized = strtolower($name); $header = $this->_c_headerNormalized[$normalized]; $new = clone $this; $new->headers[$header] = array_merge($this->headers[$header], $value); return $new; }
[ "function", "withAddedHeader", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "$", "value", "=", "array", "(", "$", "value", ")", ";", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid header value; must be a string or array of strings'", ")", ";", "if", "(", "!", "preg_match", "(", "'/^[a-zA-Z0-9\\'`#$%&*+.^_|~!-]+$/'", ",", "$", "name", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'\"%s\" is not valid header name'", ",", "$", "name", ")", ")", ";", "if", "(", "!", "self", "::", "isValid", "(", "$", "value", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'\"%s\" is not valid header value'", ",", "$", "value", ")", ")", ";", "if", "(", "!", "$", "this", "->", "hasHeader", "(", "$", "name", ")", ")", "return", "$", "this", "->", "withHeader", "(", "$", "name", ",", "$", "value", ")", ";", "$", "normalized", "=", "strtolower", "(", "$", "name", ")", ";", "$", "header", "=", "$", "this", "->", "_c_headerNormalized", "[", "$", "normalized", "]", ";", "$", "new", "=", "clone", "$", "this", ";", "$", "new", "->", "headers", "[", "$", "header", "]", "=", "array_merge", "(", "$", "this", "->", "headers", "[", "$", "header", "]", ",", "$", "value", ")", ";", "return", "$", "new", ";", "}" ]
Return an instance with the specified header appended with the given value. Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added. This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new header and/or value. @param string $name Case-insensitive header field name to add. @param string|string[] $value Header value(s). @return self @throws \InvalidArgumentException for invalid header names or values.
[ "Return", "an", "instance", "with", "the", "specified", "header", "appended", "with", "the", "given", "value", "." ]
train
https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpMessage.php#L218-L250
phPoirot/psr7
HttpMessage.php
HttpMessage.isValid
static function isValid($value) { if (!\Poirot\Std\isStringify($value)) throw new \InvalidArgumentException(sprintf( 'Header value must be string; given: (%s).' , \Poirot\Std\flatten($value) )); $value = (string) $value; // Look for: // \n not preceded by \r, OR // \r not followed by \n, OR // \r\n not followed by space or horizontal tab; these are all CRLF attacks if (preg_match("#(?:(?:(?<!\r)\n)|(?:\r(?!\n))|(?:\r\n(?![ \t])))#", $value)) { return false; } // Non-visible, non-whitespace characters // 9 === horizontal tab // 10 === line feed // 13 === carriage return // 32-126, 128-254 === visible // 127 === DEL (disallowed) // 255 === null byte (disallowed) if (preg_match('/[^\x09\x0a\x0d\x20-\x7E\x80-\xFE]/', $value)) { return false; } return true; }
php
static function isValid($value) { if (!\Poirot\Std\isStringify($value)) throw new \InvalidArgumentException(sprintf( 'Header value must be string; given: (%s).' , \Poirot\Std\flatten($value) )); $value = (string) $value; // Look for: // \n not preceded by \r, OR // \r not followed by \n, OR // \r\n not followed by space or horizontal tab; these are all CRLF attacks if (preg_match("#(?:(?:(?<!\r)\n)|(?:\r(?!\n))|(?:\r\n(?![ \t])))#", $value)) { return false; } // Non-visible, non-whitespace characters // 9 === horizontal tab // 10 === line feed // 13 === carriage return // 32-126, 128-254 === visible // 127 === DEL (disallowed) // 255 === null byte (disallowed) if (preg_match('/[^\x09\x0a\x0d\x20-\x7E\x80-\xFE]/', $value)) { return false; } return true; }
[ "static", "function", "isValid", "(", "$", "value", ")", "{", "if", "(", "!", "\\", "Poirot", "\\", "Std", "\\", "isStringify", "(", "$", "value", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Header value must be string; given: (%s).'", ",", "\\", "Poirot", "\\", "Std", "\\", "flatten", "(", "$", "value", ")", ")", ")", ";", "$", "value", "=", "(", "string", ")", "$", "value", ";", "// Look for:", "// \\n not preceded by \\r, OR", "// \\r not followed by \\n, OR", "// \\r\\n not followed by space or horizontal tab; these are all CRLF attacks", "if", "(", "preg_match", "(", "\"#(?:(?:(?<!\\r)\\n)|(?:\\r(?!\\n))|(?:\\r\\n(?![ \\t])))#\"", ",", "$", "value", ")", ")", "{", "return", "false", ";", "}", "// Non-visible, non-whitespace characters", "// 9 === horizontal tab", "// 10 === line feed", "// 13 === carriage return", "// 32-126, 128-254 === visible", "// 127 === DEL (disallowed)", "// 255 === null byte (disallowed)", "if", "(", "preg_match", "(", "'/[^\\x09\\x0a\\x0d\\x20-\\x7E\\x80-\\xFE]/'", ",", "$", "value", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validate a header value. Per RFC 7230, only VISIBLE ASCII characters, spaces, and horizontal tabs are allowed in values; header continuations MUST consist of a single CRLF sequence followed by a space or horizontal tab. @see http://en.wikipedia.org/wiki/HTTP_response_splitting @param string $value @return bool
[ "Validate", "a", "header", "value", "." ]
train
https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpMessage.php#L320-L350
phPoirot/psr7
HttpMessage.php
HttpMessage._filterHeaders
protected function _filterHeaders(array $originalHeaders) { $headerNames = $headers = array(); foreach ($originalHeaders as $header => $value) { if (! is_string($header)) { throw new \InvalidArgumentException(sprintf( 'Invalid header name; expected non-empty string, received %s', gettype($header) )); } if (! is_array($value) && ! is_string($value) && ! is_numeric($value)) { throw new \InvalidArgumentException(sprintf( 'Invalid header value type; expected number, string, or array; received %s', (is_object($value) ? get_class($value) : gettype($value)) )); } if (is_array($value)) { array_walk($value, function ($item) { if (! is_string($item) && ! is_numeric($item)) { throw new \InvalidArgumentException(sprintf( 'Invalid header value type; expected number, string, or array; received %s', (is_object($item) ? get_class($item) : gettype($item)) )); } }); } if (! is_array($value)) { $value = array($value); } $headerNames[strtolower($header)] = $header; $headers[$header] = $value; } return array($headerNames, $headers); }
php
protected function _filterHeaders(array $originalHeaders) { $headerNames = $headers = array(); foreach ($originalHeaders as $header => $value) { if (! is_string($header)) { throw new \InvalidArgumentException(sprintf( 'Invalid header name; expected non-empty string, received %s', gettype($header) )); } if (! is_array($value) && ! is_string($value) && ! is_numeric($value)) { throw new \InvalidArgumentException(sprintf( 'Invalid header value type; expected number, string, or array; received %s', (is_object($value) ? get_class($value) : gettype($value)) )); } if (is_array($value)) { array_walk($value, function ($item) { if (! is_string($item) && ! is_numeric($item)) { throw new \InvalidArgumentException(sprintf( 'Invalid header value type; expected number, string, or array; received %s', (is_object($item) ? get_class($item) : gettype($item)) )); } }); } if (! is_array($value)) { $value = array($value); } $headerNames[strtolower($header)] = $header; $headers[$header] = $value; } return array($headerNames, $headers); }
[ "protected", "function", "_filterHeaders", "(", "array", "$", "originalHeaders", ")", "{", "$", "headerNames", "=", "$", "headers", "=", "array", "(", ")", ";", "foreach", "(", "$", "originalHeaders", "as", "$", "header", "=>", "$", "value", ")", "{", "if", "(", "!", "is_string", "(", "$", "header", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid header name; expected non-empty string, received %s'", ",", "gettype", "(", "$", "header", ")", ")", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "value", ")", "&&", "!", "is_string", "(", "$", "value", ")", "&&", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid header value type; expected number, string, or array; received %s'", ",", "(", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "gettype", "(", "$", "value", ")", ")", ")", ")", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "array_walk", "(", "$", "value", ",", "function", "(", "$", "item", ")", "{", "if", "(", "!", "is_string", "(", "$", "item", ")", "&&", "!", "is_numeric", "(", "$", "item", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid header value type; expected number, string, or array; received %s'", ",", "(", "is_object", "(", "$", "item", ")", "?", "get_class", "(", "$", "item", ")", ":", "gettype", "(", "$", "item", ")", ")", ")", ")", ";", "}", "}", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "array", "(", "$", "value", ")", ";", "}", "$", "headerNames", "[", "strtolower", "(", "$", "header", ")", "]", "=", "$", "header", ";", "$", "headers", "[", "$", "header", "]", "=", "$", "value", ";", "}", "return", "array", "(", "$", "headerNames", ",", "$", "headers", ")", ";", "}" ]
Filter a set of headers to ensure they are in the correct internal format. Used by message constructors to allow setting all initial headers at once. @param array $originalHeaders Headers to filter. @return array Filtered headers and names.
[ "Filter", "a", "set", "of", "headers", "to", "ensure", "they", "are", "in", "the", "correct", "internal", "format", "." ]
train
https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpMessage.php#L360-L398
xiewulong/yii2-fileupload
oss/libs/guzzle/http/Guzzle/Http/Url.php
Url.setPath
public function setPath($path) { if (is_array($path)) { $this->path = '/' . implode('/', $path); } else { $this->path = (string) $path; } return $this; }
php
public function setPath($path) { if (is_array($path)) { $this->path = '/' . implode('/', $path); } else { $this->path = (string) $path; } return $this; }
[ "public", "function", "setPath", "(", "$", "path", ")", "{", "if", "(", "is_array", "(", "$", "path", ")", ")", "{", "$", "this", "->", "path", "=", "'/'", ".", "implode", "(", "'/'", ",", "$", "path", ")", ";", "}", "else", "{", "$", "this", "->", "path", "=", "(", "string", ")", "$", "path", ";", "}", "return", "$", "this", ";", "}" ]
Set the path part of the URL @param array|string $path Path string or array of path segments @return Url
[ "Set", "the", "path", "part", "of", "the", "URL" ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/guzzle/http/Guzzle/Http/Url.php#L269-L278
xiewulong/yii2-fileupload
oss/libs/guzzle/http/Guzzle/Http/Url.php
Url.normalizePath
public function normalizePath() { if (!$this->path || $this->path == '/' || $this->path == '*') { return $this; } // Replace // and /./ with / $this->path = str_replace(array('/./', '//'), '/', $this->path); // Remove dot segments if (strpos($this->path, '..') !== false) { // Remove trailing relative paths if possible $segments = $this->getPathSegments(); $last = end($segments); $trailingSlash = false; if ($last === '') { array_pop($segments); $trailingSlash = true; } while ($last == '..' || $last == '.') { if ($last == '..') { array_pop($segments); $last = array_pop($segments); } if ($last == '.' || $last == '') { $last = array_pop($segments); } } $this->path = implode('/', $segments); if ($trailingSlash) { $this->path .= '/'; } } return $this; }
php
public function normalizePath() { if (!$this->path || $this->path == '/' || $this->path == '*') { return $this; } // Replace // and /./ with / $this->path = str_replace(array('/./', '//'), '/', $this->path); // Remove dot segments if (strpos($this->path, '..') !== false) { // Remove trailing relative paths if possible $segments = $this->getPathSegments(); $last = end($segments); $trailingSlash = false; if ($last === '') { array_pop($segments); $trailingSlash = true; } while ($last == '..' || $last == '.') { if ($last == '..') { array_pop($segments); $last = array_pop($segments); } if ($last == '.' || $last == '') { $last = array_pop($segments); } } $this->path = implode('/', $segments); if ($trailingSlash) { $this->path .= '/'; } } return $this; }
[ "public", "function", "normalizePath", "(", ")", "{", "if", "(", "!", "$", "this", "->", "path", "||", "$", "this", "->", "path", "==", "'/'", "||", "$", "this", "->", "path", "==", "'*'", ")", "{", "return", "$", "this", ";", "}", "// Replace // and /./ with /", "$", "this", "->", "path", "=", "str_replace", "(", "array", "(", "'/./'", ",", "'//'", ")", ",", "'/'", ",", "$", "this", "->", "path", ")", ";", "// Remove dot segments", "if", "(", "strpos", "(", "$", "this", "->", "path", ",", "'..'", ")", "!==", "false", ")", "{", "// Remove trailing relative paths if possible", "$", "segments", "=", "$", "this", "->", "getPathSegments", "(", ")", ";", "$", "last", "=", "end", "(", "$", "segments", ")", ";", "$", "trailingSlash", "=", "false", ";", "if", "(", "$", "last", "===", "''", ")", "{", "array_pop", "(", "$", "segments", ")", ";", "$", "trailingSlash", "=", "true", ";", "}", "while", "(", "$", "last", "==", "'..'", "||", "$", "last", "==", "'.'", ")", "{", "if", "(", "$", "last", "==", "'..'", ")", "{", "array_pop", "(", "$", "segments", ")", ";", "$", "last", "=", "array_pop", "(", "$", "segments", ")", ";", "}", "if", "(", "$", "last", "==", "'.'", "||", "$", "last", "==", "''", ")", "{", "$", "last", "=", "array_pop", "(", "$", "segments", ")", ";", "}", "}", "$", "this", "->", "path", "=", "implode", "(", "'/'", ",", "$", "segments", ")", ";", "if", "(", "$", "trailingSlash", ")", "{", "$", "this", "->", "path", ".=", "'/'", ";", "}", "}", "return", "$", "this", ";", "}" ]
Normalize the URL so that double slashes and relative paths are removed @return Url
[ "Normalize", "the", "URL", "so", "that", "double", "slashes", "and", "relative", "paths", "are", "removed" ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/guzzle/http/Guzzle/Http/Url.php#L285-L323
xiewulong/yii2-fileupload
oss/libs/guzzle/http/Guzzle/Http/Url.php
Url.addPath
public function addPath($relativePath) { if (!$relativePath || $relativePath == '/') { return $this; } // Add a leading slash if needed if ($relativePath[0] != '/') { $relativePath = '/' . $relativePath; } return $this->setPath(str_replace('//', '/', $this->getPath() . $relativePath)); }
php
public function addPath($relativePath) { if (!$relativePath || $relativePath == '/') { return $this; } // Add a leading slash if needed if ($relativePath[0] != '/') { $relativePath = '/' . $relativePath; } return $this->setPath(str_replace('//', '/', $this->getPath() . $relativePath)); }
[ "public", "function", "addPath", "(", "$", "relativePath", ")", "{", "if", "(", "!", "$", "relativePath", "||", "$", "relativePath", "==", "'/'", ")", "{", "return", "$", "this", ";", "}", "// Add a leading slash if needed", "if", "(", "$", "relativePath", "[", "0", "]", "!=", "'/'", ")", "{", "$", "relativePath", "=", "'/'", ".", "$", "relativePath", ";", "}", "return", "$", "this", "->", "setPath", "(", "str_replace", "(", "'//'", ",", "'/'", ",", "$", "this", "->", "getPath", "(", ")", ".", "$", "relativePath", ")", ")", ";", "}" ]
Add a relative path to the currently set path @param string $relativePath Relative path to add @return Url
[ "Add", "a", "relative", "path", "to", "the", "currently", "set", "path" ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/guzzle/http/Guzzle/Http/Url.php#L332-L344
philiplb/Valdi
src/Valdi/Validator/AbstractParametrizedValidator.php
AbstractParametrizedValidator.validateParameterCount
protected function validateParameterCount($name, $parameterAmount, array $parameters) { if (count($parameters) !== $parameterAmount) { throw new ValidationException('"'.$name.'" expects '.$parameterAmount.' parameter.'); } }
php
protected function validateParameterCount($name, $parameterAmount, array $parameters) { if (count($parameters) !== $parameterAmount) { throw new ValidationException('"'.$name.'" expects '.$parameterAmount.' parameter.'); } }
[ "protected", "function", "validateParameterCount", "(", "$", "name", ",", "$", "parameterAmount", ",", "array", "$", "parameters", ")", "{", "if", "(", "count", "(", "$", "parameters", ")", "!==", "$", "parameterAmount", ")", "{", "throw", "new", "ValidationException", "(", "'\"'", ".", "$", "name", ".", "'\" expects '", ".", "$", "parameterAmount", ".", "' parameter.'", ")", ";", "}", "}" ]
Throws an exception if the parameters don't fulfill the expected parameter count. @param string $name the name of the validator @param integer $parameterAmount the amount of expected parameters @param string[] $parameters the parameters @throws ValidationException thrown if the amount of parameters isn't the expected one
[ "Throws", "an", "exception", "if", "the", "parameters", "don", "t", "fulfill", "the", "expected", "parameter", "count", "." ]
train
https://github.com/philiplb/Valdi/blob/9927ec34a2cb00cec705e952d3c2374e2dc3c972/src/Valdi/Validator/AbstractParametrizedValidator.php#L35-L39
interactivesolutions/honeycomb-core
src/errors/HCLog.php
HCLog.emergency
public function emergency(string $id, string $message, int $status = 400) { Log::error($id . ' : ' . $message); return response ()->json (['success' => false, 'id' => $id, 'message' => $message], $status); }
php
public function emergency(string $id, string $message, int $status = 400) { Log::error($id . ' : ' . $message); return response ()->json (['success' => false, 'id' => $id, 'message' => $message], $status); }
[ "public", "function", "emergency", "(", "string", "$", "id", ",", "string", "$", "message", ",", "int", "$", "status", "=", "400", ")", "{", "Log", "::", "error", "(", "$", "id", ".", "' : '", ".", "$", "message", ")", ";", "return", "response", "(", ")", "->", "json", "(", "[", "'success'", "=>", "false", ",", "'id'", "=>", "$", "id", ",", "'message'", "=>", "$", "message", "]", ",", "$", "status", ")", ";", "}" ]
Create emergency response @param string $id @param string $message @param int $status @return \Illuminate\Http\JsonResponse
[ "Create", "emergency", "response" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/errors/HCLog.php#L17-L22
interactivesolutions/honeycomb-core
src/errors/HCLog.php
HCLog.notice
public function notice(string $id, string $message, int $status = 400) { Log::info($id . ' : ' . $message); return response ()->json (['success' => false, 'id' => $id, 'message' => $message], $status); }
php
public function notice(string $id, string $message, int $status = 400) { Log::info($id . ' : ' . $message); return response ()->json (['success' => false, 'id' => $id, 'message' => $message], $status); }
[ "public", "function", "notice", "(", "string", "$", "id", ",", "string", "$", "message", ",", "int", "$", "status", "=", "400", ")", "{", "Log", "::", "info", "(", "$", "id", ".", "' : '", ".", "$", "message", ")", ";", "return", "response", "(", ")", "->", "json", "(", "[", "'success'", "=>", "false", ",", "'id'", "=>", "$", "id", ",", "'message'", "=>", "$", "message", "]", ",", "$", "status", ")", ";", "}" ]
Create notice response @param string $id @param string $message @param int $status @return \Illuminate\Http\JsonResponse
[ "Create", "notice", "response" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/errors/HCLog.php#L92-L97
interactivesolutions/honeycomb-core
src/errors/HCLog.php
HCLog.success
public function success(string $id, string $message, int $status = 200) { Log::info($id . ' : ' . $message); return response ()->json (['success' => true, 'id' => $id, 'message' => $message], $status); }
php
public function success(string $id, string $message, int $status = 200) { Log::info($id . ' : ' . $message); return response ()->json (['success' => true, 'id' => $id, 'message' => $message], $status); }
[ "public", "function", "success", "(", "string", "$", "id", ",", "string", "$", "message", ",", "int", "$", "status", "=", "200", ")", "{", "Log", "::", "info", "(", "$", "id", ".", "' : '", ".", "$", "message", ")", ";", "return", "response", "(", ")", "->", "json", "(", "[", "'success'", "=>", "true", ",", "'id'", "=>", "$", "id", ",", "'message'", "=>", "$", "message", "]", ",", "$", "status", ")", ";", "}" ]
Create success response @param string $id @param string $message @param int $status @return \Illuminate\Http\JsonResponse
[ "Create", "success", "response" ]
train
https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/errors/HCLog.php#L135-L140
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex.Structures_Bibtex
function Structures_Bibtex($options = array()) { $this->_delimiters = array('"' => '"', '{' => '}'); $this->data = array(); $this->content = ''; //$this->_stripDelimiter = $stripDel; //$this->_validate = $val; $this->warnings = array(); $this->_options = array( 'stripDelimiter' => true, 'validate' => true, 'unwrap' => false, 'wordWrapWidth' => false, 'wordWrapBreak' => "\n", 'wordWrapCut' => 0, 'removeCurlyBraces' => false, 'extractAuthors' => true, ); foreach ($options as $option => $value) { $this->setOption($option, $value); } $this->rtfstring = 'AUTHORS, "{\b TITLE}", {\i JOURNAL}, YEAR'; $this->htmlstring = 'AUTHORS, "<strong>TITLE</strong>", <em>JOURNAL</em>, YEAR<br />'; $this->allowedEntryTypes = array( 'article', 'book', 'booklet', 'confernce', 'inbook', 'incollection', 'inproceedings', 'manual', 'mastersthesis', 'misc', 'phdthesis', 'proceedings', 'techreport', 'unpublished' ); $this->authorstring = 'VON LAST, JR, FIRST'; }
php
function Structures_Bibtex($options = array()) { $this->_delimiters = array('"' => '"', '{' => '}'); $this->data = array(); $this->content = ''; //$this->_stripDelimiter = $stripDel; //$this->_validate = $val; $this->warnings = array(); $this->_options = array( 'stripDelimiter' => true, 'validate' => true, 'unwrap' => false, 'wordWrapWidth' => false, 'wordWrapBreak' => "\n", 'wordWrapCut' => 0, 'removeCurlyBraces' => false, 'extractAuthors' => true, ); foreach ($options as $option => $value) { $this->setOption($option, $value); } $this->rtfstring = 'AUTHORS, "{\b TITLE}", {\i JOURNAL}, YEAR'; $this->htmlstring = 'AUTHORS, "<strong>TITLE</strong>", <em>JOURNAL</em>, YEAR<br />'; $this->allowedEntryTypes = array( 'article', 'book', 'booklet', 'confernce', 'inbook', 'incollection', 'inproceedings', 'manual', 'mastersthesis', 'misc', 'phdthesis', 'proceedings', 'techreport', 'unpublished' ); $this->authorstring = 'VON LAST, JR, FIRST'; }
[ "function", "Structures_Bibtex", "(", "$", "options", "=", "array", "(", ")", ")", "{", "$", "this", "->", "_delimiters", "=", "array", "(", "'\"'", "=>", "'\"'", ",", "'{'", "=>", "'}'", ")", ";", "$", "this", "->", "data", "=", "array", "(", ")", ";", "$", "this", "->", "content", "=", "''", ";", "//$this->_stripDelimiter = $stripDel;", "//$this->_validate = $val;", "$", "this", "->", "warnings", "=", "array", "(", ")", ";", "$", "this", "->", "_options", "=", "array", "(", "'stripDelimiter'", "=>", "true", ",", "'validate'", "=>", "true", ",", "'unwrap'", "=>", "false", ",", "'wordWrapWidth'", "=>", "false", ",", "'wordWrapBreak'", "=>", "\"\\n\"", ",", "'wordWrapCut'", "=>", "0", ",", "'removeCurlyBraces'", "=>", "false", ",", "'extractAuthors'", "=>", "true", ",", ")", ";", "foreach", "(", "$", "options", "as", "$", "option", "=>", "$", "value", ")", "{", "$", "this", "->", "setOption", "(", "$", "option", ",", "$", "value", ")", ";", "}", "$", "this", "->", "rtfstring", "=", "'AUTHORS, \"{\\b TITLE}\", {\\i JOURNAL}, YEAR'", ";", "$", "this", "->", "htmlstring", "=", "'AUTHORS, \"<strong>TITLE</strong>\", <em>JOURNAL</em>, YEAR<br />'", ";", "$", "this", "->", "allowedEntryTypes", "=", "array", "(", "'article'", ",", "'book'", ",", "'booklet'", ",", "'confernce'", ",", "'inbook'", ",", "'incollection'", ",", "'inproceedings'", ",", "'manual'", ",", "'mastersthesis'", ",", "'misc'", ",", "'phdthesis'", ",", "'proceedings'", ",", "'techreport'", ",", "'unpublished'", ")", ";", "$", "this", "->", "authorstring", "=", "'VON LAST, JR, FIRST'", ";", "}" ]
Constructor @access public @return void
[ "Constructor" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L145-L186
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex.setOption
function setOption($option, $value) { $ret = true; if (array_key_exists($option, $this->_options)) { $this->_options[$option] = $value; } else { throw new InvalidArgumentException('Unknown option ' . $option); } }
php
function setOption($option, $value) { $ret = true; if (array_key_exists($option, $this->_options)) { $this->_options[$option] = $value; } else { throw new InvalidArgumentException('Unknown option ' . $option); } }
[ "function", "setOption", "(", "$", "option", ",", "$", "value", ")", "{", "$", "ret", "=", "true", ";", "if", "(", "array_key_exists", "(", "$", "option", ",", "$", "this", "->", "_options", ")", ")", "{", "$", "this", "->", "_options", "[", "$", "option", "]", "=", "$", "value", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'Unknown option '", ".", "$", "option", ")", ";", "}", "}" ]
Sets run-time configuration options @access public @param string $option option name @param mixed $value value for the option @return mixed true on success @throws InvalidArgumentException
[ "Sets", "run", "-", "time", "configuration", "options" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L197-L205
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex.loadFile
function loadFile($filename) { if (file_exists($filename)) { if (($this->content = @file_get_contents($filename)) === false) { throw new BibtexException('Could not open file ' . $filename); } else { $this->_pos = 0; $this->_oldpos = 0; return true; } } else { throw new BibtexException('Could not find file ' . $filename); } }
php
function loadFile($filename) { if (file_exists($filename)) { if (($this->content = @file_get_contents($filename)) === false) { throw new BibtexException('Could not open file ' . $filename); } else { $this->_pos = 0; $this->_oldpos = 0; return true; } } else { throw new BibtexException('Could not find file ' . $filename); } }
[ "function", "loadFile", "(", "$", "filename", ")", "{", "if", "(", "file_exists", "(", "$", "filename", ")", ")", "{", "if", "(", "(", "$", "this", "->", "content", "=", "@", "file_get_contents", "(", "$", "filename", ")", ")", "===", "false", ")", "{", "throw", "new", "BibtexException", "(", "'Could not open file '", ".", "$", "filename", ")", ";", "}", "else", "{", "$", "this", "->", "_pos", "=", "0", ";", "$", "this", "->", "_oldpos", "=", "0", ";", "return", "true", ";", "}", "}", "else", "{", "throw", "new", "BibtexException", "(", "'Could not find file '", ".", "$", "filename", ")", ";", "}", "}" ]
Reads a give BibTex File @access public @param string $filename Name of the file @return mixed true on success @throws BibtexException
[ "Reads", "a", "give", "BibTex", "File" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L215-L228
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex.parse
function parse() { //The amount of opening braces is compared to the amount of closing braces //Braces inside comments are ignored $this->warnings = array(); $this->data = array(); $valid = true; $open = 0; $entry = false; $char = ''; $lastchar = ''; $buffer = ''; for ($i = 0; $i < strlen($this->content); $i++) { $char = substr($this->content, $i, 1); if ((0 != $open) && ('@' == $char)) { if (!$this->_checkAt($buffer)) { $this->_generateWarning('WARNING_MISSING_END_BRACE', '', $buffer); //To correct the data we need to insert a closing brace $char = '}'; $i--; } } if ((0 == $open) && ('@' == $char)) { //The beginning of an entry $entry = true; } elseif ($entry && ('{' == $char) && ('\\' != $lastchar)) { //Inside an entry and non quoted brace is opening $open++; } elseif ($entry && ('}' == $char) && ('\\' != $lastchar)) { //Inside an entry and non quoted brace is closing $open--; if ($open < 0) { //More are closed than opened $valid = false; } if (0 == $open) { //End of entry $entry = false; $entrydata = $this->_parseEntry($buffer); if (!$entrydata) { /** * This is not yet used. * We are here if the Entry is either not correct or not supported. * But this should already generate a warning. * Therefore it should not be necessary to do anything here */ } else { $this->data[] = $entrydata; } $buffer = ''; } } if ($entry) { //Inside entry $buffer .= $char; } $lastchar = $char; } //If open is one it may be possible that the last ending brace is missing if (1 == $open) { $entrydata = $this->_parseEntry($buffer); if (!$entrydata) { $valid = false; } else { $this->data[] = $entrydata; $buffer = ''; $open = 0; } } //At this point the open should be zero if (0 != $open) { $valid = false; } //Are there Multiple entries with the same cite? if ($this->_options['validate']) { $cites = array(); foreach ($this->data as $entry) { $cites[] = $entry['cite']; } $unique = array_unique($cites); if (sizeof($cites) != sizeof($unique)) { //Some values have not been unique! $notuniques = array(); for ($i = 0; $i < sizeof($cites); $i++) { if (empty($unique[$i])) { $notuniques[] = $cites[$i]; } } $this->_generateWarning('WARNING_MULTIPLE_ENTRIES', implode(',', $notuniques)); } } if ($valid) { $this->content = ''; return true; } else { throw new BibtexException('Unbalanced parenthesis'); } }
php
function parse() { //The amount of opening braces is compared to the amount of closing braces //Braces inside comments are ignored $this->warnings = array(); $this->data = array(); $valid = true; $open = 0; $entry = false; $char = ''; $lastchar = ''; $buffer = ''; for ($i = 0; $i < strlen($this->content); $i++) { $char = substr($this->content, $i, 1); if ((0 != $open) && ('@' == $char)) { if (!$this->_checkAt($buffer)) { $this->_generateWarning('WARNING_MISSING_END_BRACE', '', $buffer); //To correct the data we need to insert a closing brace $char = '}'; $i--; } } if ((0 == $open) && ('@' == $char)) { //The beginning of an entry $entry = true; } elseif ($entry && ('{' == $char) && ('\\' != $lastchar)) { //Inside an entry and non quoted brace is opening $open++; } elseif ($entry && ('}' == $char) && ('\\' != $lastchar)) { //Inside an entry and non quoted brace is closing $open--; if ($open < 0) { //More are closed than opened $valid = false; } if (0 == $open) { //End of entry $entry = false; $entrydata = $this->_parseEntry($buffer); if (!$entrydata) { /** * This is not yet used. * We are here if the Entry is either not correct or not supported. * But this should already generate a warning. * Therefore it should not be necessary to do anything here */ } else { $this->data[] = $entrydata; } $buffer = ''; } } if ($entry) { //Inside entry $buffer .= $char; } $lastchar = $char; } //If open is one it may be possible that the last ending brace is missing if (1 == $open) { $entrydata = $this->_parseEntry($buffer); if (!$entrydata) { $valid = false; } else { $this->data[] = $entrydata; $buffer = ''; $open = 0; } } //At this point the open should be zero if (0 != $open) { $valid = false; } //Are there Multiple entries with the same cite? if ($this->_options['validate']) { $cites = array(); foreach ($this->data as $entry) { $cites[] = $entry['cite']; } $unique = array_unique($cites); if (sizeof($cites) != sizeof($unique)) { //Some values have not been unique! $notuniques = array(); for ($i = 0; $i < sizeof($cites); $i++) { if (empty($unique[$i])) { $notuniques[] = $cites[$i]; } } $this->_generateWarning('WARNING_MULTIPLE_ENTRIES', implode(',', $notuniques)); } } if ($valid) { $this->content = ''; return true; } else { throw new BibtexException('Unbalanced parenthesis'); } }
[ "function", "parse", "(", ")", "{", "//The amount of opening braces is compared to the amount of closing braces", "//Braces inside comments are ignored", "$", "this", "->", "warnings", "=", "array", "(", ")", ";", "$", "this", "->", "data", "=", "array", "(", ")", ";", "$", "valid", "=", "true", ";", "$", "open", "=", "0", ";", "$", "entry", "=", "false", ";", "$", "char", "=", "''", ";", "$", "lastchar", "=", "''", ";", "$", "buffer", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "this", "->", "content", ")", ";", "$", "i", "++", ")", "{", "$", "char", "=", "substr", "(", "$", "this", "->", "content", ",", "$", "i", ",", "1", ")", ";", "if", "(", "(", "0", "!=", "$", "open", ")", "&&", "(", "'@'", "==", "$", "char", ")", ")", "{", "if", "(", "!", "$", "this", "->", "_checkAt", "(", "$", "buffer", ")", ")", "{", "$", "this", "->", "_generateWarning", "(", "'WARNING_MISSING_END_BRACE'", ",", "''", ",", "$", "buffer", ")", ";", "//To correct the data we need to insert a closing brace", "$", "char", "=", "'}'", ";", "$", "i", "--", ";", "}", "}", "if", "(", "(", "0", "==", "$", "open", ")", "&&", "(", "'@'", "==", "$", "char", ")", ")", "{", "//The beginning of an entry", "$", "entry", "=", "true", ";", "}", "elseif", "(", "$", "entry", "&&", "(", "'{'", "==", "$", "char", ")", "&&", "(", "'\\\\'", "!=", "$", "lastchar", ")", ")", "{", "//Inside an entry and non quoted brace is opening", "$", "open", "++", ";", "}", "elseif", "(", "$", "entry", "&&", "(", "'}'", "==", "$", "char", ")", "&&", "(", "'\\\\'", "!=", "$", "lastchar", ")", ")", "{", "//Inside an entry and non quoted brace is closing", "$", "open", "--", ";", "if", "(", "$", "open", "<", "0", ")", "{", "//More are closed than opened", "$", "valid", "=", "false", ";", "}", "if", "(", "0", "==", "$", "open", ")", "{", "//End of entry", "$", "entry", "=", "false", ";", "$", "entrydata", "=", "$", "this", "->", "_parseEntry", "(", "$", "buffer", ")", ";", "if", "(", "!", "$", "entrydata", ")", "{", "/**\n * This is not yet used.\n * We are here if the Entry is either not correct or not supported.\n * But this should already generate a warning.\n * Therefore it should not be necessary to do anything here\n */", "}", "else", "{", "$", "this", "->", "data", "[", "]", "=", "$", "entrydata", ";", "}", "$", "buffer", "=", "''", ";", "}", "}", "if", "(", "$", "entry", ")", "{", "//Inside entry", "$", "buffer", ".=", "$", "char", ";", "}", "$", "lastchar", "=", "$", "char", ";", "}", "//If open is one it may be possible that the last ending brace is missing", "if", "(", "1", "==", "$", "open", ")", "{", "$", "entrydata", "=", "$", "this", "->", "_parseEntry", "(", "$", "buffer", ")", ";", "if", "(", "!", "$", "entrydata", ")", "{", "$", "valid", "=", "false", ";", "}", "else", "{", "$", "this", "->", "data", "[", "]", "=", "$", "entrydata", ";", "$", "buffer", "=", "''", ";", "$", "open", "=", "0", ";", "}", "}", "//At this point the open should be zero", "if", "(", "0", "!=", "$", "open", ")", "{", "$", "valid", "=", "false", ";", "}", "//Are there Multiple entries with the same cite?", "if", "(", "$", "this", "->", "_options", "[", "'validate'", "]", ")", "{", "$", "cites", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "data", "as", "$", "entry", ")", "{", "$", "cites", "[", "]", "=", "$", "entry", "[", "'cite'", "]", ";", "}", "$", "unique", "=", "array_unique", "(", "$", "cites", ")", ";", "if", "(", "sizeof", "(", "$", "cites", ")", "!=", "sizeof", "(", "$", "unique", ")", ")", "{", "//Some values have not been unique!", "$", "notuniques", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "sizeof", "(", "$", "cites", ")", ";", "$", "i", "++", ")", "{", "if", "(", "empty", "(", "$", "unique", "[", "$", "i", "]", ")", ")", "{", "$", "notuniques", "[", "]", "=", "$", "cites", "[", "$", "i", "]", ";", "}", "}", "$", "this", "->", "_generateWarning", "(", "'WARNING_MULTIPLE_ENTRIES'", ",", "implode", "(", "','", ",", "$", "notuniques", ")", ")", ";", "}", "}", "if", "(", "$", "valid", ")", "{", "$", "this", "->", "content", "=", "''", ";", "return", "true", ";", "}", "else", "{", "throw", "new", "BibtexException", "(", "'Unbalanced parenthesis'", ")", ";", "}", "}" ]
Parses what is stored in content and clears the content if the parsing is successfull. @access public @return boolean true on success @throws BibtexException
[ "Parses", "what", "is", "stored", "in", "content", "and", "clears", "the", "content", "if", "the", "parsing", "is", "successfull", "." ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L237-L327
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._parseEntry
function _parseEntry($entry) { $entrycopy = ''; if ($this->_options['validate']) { $entrycopy = $entry; //We need a copy for printing the warnings } $ret = array(); if ('@string' == strtolower(substr($entry, 0, 7))) { //String are not yet supported! if ($this->_options['validate']) { $this->_generateWarning('STRING_ENTRY_NOT_YET_SUPPORTED', '', $entry . '}'); } } elseif ('@preamble' == strtolower(substr($entry, 0, 9))) { //Preamble not yet supported! if ($this->_options['validate']) { $this->_generateWarning('PREAMBLE_ENTRY_NOT_YET_SUPPORTED', '', $entry . '}'); } } else { //Parsing all fields while (strrpos($entry, '=') !== false) { $position = strrpos($entry, '='); //Checking that the equal sign is not quoted or is not inside a equation (For example in an abstract) $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } if ($proceed) { $proceed = $this->_checkEqualSign($entry, $position); } while (!$proceed) { $substring = substr($entry, 0, $position); $position = strrpos($substring, '='); $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } if ($proceed) { $proceed = $this->_checkEqualSign($entry, $position); } } $value = trim(substr($entry, $position + 1)); $entry = substr($entry, 0, $position); if (',' == substr($value, strlen($value) - 1, 1)) { $value = substr($value, 0, -1); } if ($this->_options['validate']) { $this->_validateValue($value, $entrycopy); } if ($this->_options['stripDelimiter']) { $value = $this->_stripDelimiter($value); } if ($this->_options['unwrap']) { $value = $this->_unwrap($value); } if ($this->_options['removeCurlyBraces']) { $value = $this->_removeCurlyBraces($value); } $position = strrpos($entry, ','); $field = strtolower(trim(substr($entry, $position + 1))); $ret[$field] = $value; $entry = substr($entry, 0, $position); } //Parsing cite and entry type $arr = explode('{', $entry); $ret['cite'] = trim($arr[1]); $ret['entryType'] = strtolower(trim($arr[0])); if ('@' == $ret['entryType']{0}) { $ret['entryType'] = substr($ret['entryType'], 1); } if ($this->_options['validate']) { if (!$this->_checkAllowedEntryType($ret['entryType'])) { $this->_generateWarning('WARNING_NOT_ALLOWED_ENTRY_TYPE', $ret['entryType'], $entry . '}'); } } //Handling the authors if (in_array('author', array_keys($ret)) && $this->_options['extractAuthors']) { $ret['author'] = $this->_extractAuthors($ret['author']); } } return $ret; }
php
function _parseEntry($entry) { $entrycopy = ''; if ($this->_options['validate']) { $entrycopy = $entry; //We need a copy for printing the warnings } $ret = array(); if ('@string' == strtolower(substr($entry, 0, 7))) { //String are not yet supported! if ($this->_options['validate']) { $this->_generateWarning('STRING_ENTRY_NOT_YET_SUPPORTED', '', $entry . '}'); } } elseif ('@preamble' == strtolower(substr($entry, 0, 9))) { //Preamble not yet supported! if ($this->_options['validate']) { $this->_generateWarning('PREAMBLE_ENTRY_NOT_YET_SUPPORTED', '', $entry . '}'); } } else { //Parsing all fields while (strrpos($entry, '=') !== false) { $position = strrpos($entry, '='); //Checking that the equal sign is not quoted or is not inside a equation (For example in an abstract) $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } if ($proceed) { $proceed = $this->_checkEqualSign($entry, $position); } while (!$proceed) { $substring = substr($entry, 0, $position); $position = strrpos($substring, '='); $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } if ($proceed) { $proceed = $this->_checkEqualSign($entry, $position); } } $value = trim(substr($entry, $position + 1)); $entry = substr($entry, 0, $position); if (',' == substr($value, strlen($value) - 1, 1)) { $value = substr($value, 0, -1); } if ($this->_options['validate']) { $this->_validateValue($value, $entrycopy); } if ($this->_options['stripDelimiter']) { $value = $this->_stripDelimiter($value); } if ($this->_options['unwrap']) { $value = $this->_unwrap($value); } if ($this->_options['removeCurlyBraces']) { $value = $this->_removeCurlyBraces($value); } $position = strrpos($entry, ','); $field = strtolower(trim(substr($entry, $position + 1))); $ret[$field] = $value; $entry = substr($entry, 0, $position); } //Parsing cite and entry type $arr = explode('{', $entry); $ret['cite'] = trim($arr[1]); $ret['entryType'] = strtolower(trim($arr[0])); if ('@' == $ret['entryType']{0}) { $ret['entryType'] = substr($ret['entryType'], 1); } if ($this->_options['validate']) { if (!$this->_checkAllowedEntryType($ret['entryType'])) { $this->_generateWarning('WARNING_NOT_ALLOWED_ENTRY_TYPE', $ret['entryType'], $entry . '}'); } } //Handling the authors if (in_array('author', array_keys($ret)) && $this->_options['extractAuthors']) { $ret['author'] = $this->_extractAuthors($ret['author']); } } return $ret; }
[ "function", "_parseEntry", "(", "$", "entry", ")", "{", "$", "entrycopy", "=", "''", ";", "if", "(", "$", "this", "->", "_options", "[", "'validate'", "]", ")", "{", "$", "entrycopy", "=", "$", "entry", ";", "//We need a copy for printing the warnings", "}", "$", "ret", "=", "array", "(", ")", ";", "if", "(", "'@string'", "==", "strtolower", "(", "substr", "(", "$", "entry", ",", "0", ",", "7", ")", ")", ")", "{", "//String are not yet supported!", "if", "(", "$", "this", "->", "_options", "[", "'validate'", "]", ")", "{", "$", "this", "->", "_generateWarning", "(", "'STRING_ENTRY_NOT_YET_SUPPORTED'", ",", "''", ",", "$", "entry", ".", "'}'", ")", ";", "}", "}", "elseif", "(", "'@preamble'", "==", "strtolower", "(", "substr", "(", "$", "entry", ",", "0", ",", "9", ")", ")", ")", "{", "//Preamble not yet supported!", "if", "(", "$", "this", "->", "_options", "[", "'validate'", "]", ")", "{", "$", "this", "->", "_generateWarning", "(", "'PREAMBLE_ENTRY_NOT_YET_SUPPORTED'", ",", "''", ",", "$", "entry", ".", "'}'", ")", ";", "}", "}", "else", "{", "//Parsing all fields", "while", "(", "strrpos", "(", "$", "entry", ",", "'='", ")", "!==", "false", ")", "{", "$", "position", "=", "strrpos", "(", "$", "entry", ",", "'='", ")", ";", "//Checking that the equal sign is not quoted or is not inside a equation (For example in an abstract)", "$", "proceed", "=", "true", ";", "if", "(", "substr", "(", "$", "entry", ",", "$", "position", "-", "1", ",", "1", ")", "==", "'\\\\'", ")", "{", "$", "proceed", "=", "false", ";", "}", "if", "(", "$", "proceed", ")", "{", "$", "proceed", "=", "$", "this", "->", "_checkEqualSign", "(", "$", "entry", ",", "$", "position", ")", ";", "}", "while", "(", "!", "$", "proceed", ")", "{", "$", "substring", "=", "substr", "(", "$", "entry", ",", "0", ",", "$", "position", ")", ";", "$", "position", "=", "strrpos", "(", "$", "substring", ",", "'='", ")", ";", "$", "proceed", "=", "true", ";", "if", "(", "substr", "(", "$", "entry", ",", "$", "position", "-", "1", ",", "1", ")", "==", "'\\\\'", ")", "{", "$", "proceed", "=", "false", ";", "}", "if", "(", "$", "proceed", ")", "{", "$", "proceed", "=", "$", "this", "->", "_checkEqualSign", "(", "$", "entry", ",", "$", "position", ")", ";", "}", "}", "$", "value", "=", "trim", "(", "substr", "(", "$", "entry", ",", "$", "position", "+", "1", ")", ")", ";", "$", "entry", "=", "substr", "(", "$", "entry", ",", "0", ",", "$", "position", ")", ";", "if", "(", "','", "==", "substr", "(", "$", "value", ",", "strlen", "(", "$", "value", ")", "-", "1", ",", "1", ")", ")", "{", "$", "value", "=", "substr", "(", "$", "value", ",", "0", ",", "-", "1", ")", ";", "}", "if", "(", "$", "this", "->", "_options", "[", "'validate'", "]", ")", "{", "$", "this", "->", "_validateValue", "(", "$", "value", ",", "$", "entrycopy", ")", ";", "}", "if", "(", "$", "this", "->", "_options", "[", "'stripDelimiter'", "]", ")", "{", "$", "value", "=", "$", "this", "->", "_stripDelimiter", "(", "$", "value", ")", ";", "}", "if", "(", "$", "this", "->", "_options", "[", "'unwrap'", "]", ")", "{", "$", "value", "=", "$", "this", "->", "_unwrap", "(", "$", "value", ")", ";", "}", "if", "(", "$", "this", "->", "_options", "[", "'removeCurlyBraces'", "]", ")", "{", "$", "value", "=", "$", "this", "->", "_removeCurlyBraces", "(", "$", "value", ")", ";", "}", "$", "position", "=", "strrpos", "(", "$", "entry", ",", "','", ")", ";", "$", "field", "=", "strtolower", "(", "trim", "(", "substr", "(", "$", "entry", ",", "$", "position", "+", "1", ")", ")", ")", ";", "$", "ret", "[", "$", "field", "]", "=", "$", "value", ";", "$", "entry", "=", "substr", "(", "$", "entry", ",", "0", ",", "$", "position", ")", ";", "}", "//Parsing cite and entry type", "$", "arr", "=", "explode", "(", "'{'", ",", "$", "entry", ")", ";", "$", "ret", "[", "'cite'", "]", "=", "trim", "(", "$", "arr", "[", "1", "]", ")", ";", "$", "ret", "[", "'entryType'", "]", "=", "strtolower", "(", "trim", "(", "$", "arr", "[", "0", "]", ")", ")", ";", "if", "(", "'@'", "==", "$", "ret", "[", "'entryType'", "]", "{", "0", "}", ")", "{", "$", "ret", "[", "'entryType'", "]", "=", "substr", "(", "$", "ret", "[", "'entryType'", "]", ",", "1", ")", ";", "}", "if", "(", "$", "this", "->", "_options", "[", "'validate'", "]", ")", "{", "if", "(", "!", "$", "this", "->", "_checkAllowedEntryType", "(", "$", "ret", "[", "'entryType'", "]", ")", ")", "{", "$", "this", "->", "_generateWarning", "(", "'WARNING_NOT_ALLOWED_ENTRY_TYPE'", ",", "$", "ret", "[", "'entryType'", "]", ",", "$", "entry", ".", "'}'", ")", ";", "}", "}", "//Handling the authors", "if", "(", "in_array", "(", "'author'", ",", "array_keys", "(", "$", "ret", ")", ")", "&&", "$", "this", "->", "_options", "[", "'extractAuthors'", "]", ")", "{", "$", "ret", "[", "'author'", "]", "=", "$", "this", "->", "_extractAuthors", "(", "$", "ret", "[", "'author'", "]", ")", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Extracting the data of one content The parse function splits the content into its entries. Then every entry is parsed by this function. It parses the entry backwards. First the last '=' is searched and the value extracted from that. A copy is made of the entry if warnings should be generated. This takes quite some memory but it is needed to get good warnings. If nor warnings are generated then you don have to worry about memory. Then the last ',' is searched and the field extracted from that. Again the entry is shortened. Finally after all field=>value pairs the cite and type is extraced and the authors are splitted. If there is a problem false is returned. @access private @param string $entry The entry @return array The representation of the entry or false if there is a problem
[ "Extracting", "the", "data", "of", "one", "content" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L349-L431
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._checkEqualSign
function _checkEqualSign($entry, $position) { $ret = true; //This is getting tricky //We check the string backwards until the position and count the closing an opening braces //If we reach the position the amount of opening and closing braces should be equal $length = strlen($entry); $open = 0; for ($i = $length - 1; $i >= $position; $i--) { $precedingchar = substr($entry, $i - 1, 1); $char = substr($entry, $i, 1); if (('{' == $char) && ('\\' != $precedingchar)) { $open++; } if (('}' == $char) && ('\\' != $precedingchar)) { $open--; } } if (0 != $open) { $ret = false; } //There is still the posibility that the entry is delimited by double quotes. //Then it is possible that the braces are equal even if the '=' is in an equation. if ($ret) { $entrycopy = trim($entry); $lastchar = $entrycopy{strlen($entrycopy) - 1}; if (',' == $lastchar) { $lastchar = $entrycopy{strlen($entrycopy) - 2}; } if ('"' == $lastchar) { //The return value is set to false //If we find the closing " before the '=' it is set to true again. //Remember we begin to search the entry backwards so the " has to show up twice - ending and beginning delimiter $ret = false; $found = 0; for ($i = $length; $i >= $position; $i--) { $precedingchar = substr($entry, $i - 1, 1); $char = substr($entry, $i, 1); if (('"' == $char) && ('\\' != $precedingchar)) { $found++; } if (2 == $found) { $ret = true; break; } } } } return $ret; }
php
function _checkEqualSign($entry, $position) { $ret = true; //This is getting tricky //We check the string backwards until the position and count the closing an opening braces //If we reach the position the amount of opening and closing braces should be equal $length = strlen($entry); $open = 0; for ($i = $length - 1; $i >= $position; $i--) { $precedingchar = substr($entry, $i - 1, 1); $char = substr($entry, $i, 1); if (('{' == $char) && ('\\' != $precedingchar)) { $open++; } if (('}' == $char) && ('\\' != $precedingchar)) { $open--; } } if (0 != $open) { $ret = false; } //There is still the posibility that the entry is delimited by double quotes. //Then it is possible that the braces are equal even if the '=' is in an equation. if ($ret) { $entrycopy = trim($entry); $lastchar = $entrycopy{strlen($entrycopy) - 1}; if (',' == $lastchar) { $lastchar = $entrycopy{strlen($entrycopy) - 2}; } if ('"' == $lastchar) { //The return value is set to false //If we find the closing " before the '=' it is set to true again. //Remember we begin to search the entry backwards so the " has to show up twice - ending and beginning delimiter $ret = false; $found = 0; for ($i = $length; $i >= $position; $i--) { $precedingchar = substr($entry, $i - 1, 1); $char = substr($entry, $i, 1); if (('"' == $char) && ('\\' != $precedingchar)) { $found++; } if (2 == $found) { $ret = true; break; } } } } return $ret; }
[ "function", "_checkEqualSign", "(", "$", "entry", ",", "$", "position", ")", "{", "$", "ret", "=", "true", ";", "//This is getting tricky", "//We check the string backwards until the position and count the closing an opening braces", "//If we reach the position the amount of opening and closing braces should be equal", "$", "length", "=", "strlen", "(", "$", "entry", ")", ";", "$", "open", "=", "0", ";", "for", "(", "$", "i", "=", "$", "length", "-", "1", ";", "$", "i", ">=", "$", "position", ";", "$", "i", "--", ")", "{", "$", "precedingchar", "=", "substr", "(", "$", "entry", ",", "$", "i", "-", "1", ",", "1", ")", ";", "$", "char", "=", "substr", "(", "$", "entry", ",", "$", "i", ",", "1", ")", ";", "if", "(", "(", "'{'", "==", "$", "char", ")", "&&", "(", "'\\\\'", "!=", "$", "precedingchar", ")", ")", "{", "$", "open", "++", ";", "}", "if", "(", "(", "'}'", "==", "$", "char", ")", "&&", "(", "'\\\\'", "!=", "$", "precedingchar", ")", ")", "{", "$", "open", "--", ";", "}", "}", "if", "(", "0", "!=", "$", "open", ")", "{", "$", "ret", "=", "false", ";", "}", "//There is still the posibility that the entry is delimited by double quotes.", "//Then it is possible that the braces are equal even if the '=' is in an equation.", "if", "(", "$", "ret", ")", "{", "$", "entrycopy", "=", "trim", "(", "$", "entry", ")", ";", "$", "lastchar", "=", "$", "entrycopy", "{", "strlen", "(", "$", "entrycopy", ")", "-", "1", "}", ";", "if", "(", "','", "==", "$", "lastchar", ")", "{", "$", "lastchar", "=", "$", "entrycopy", "{", "strlen", "(", "$", "entrycopy", ")", "-", "2", "}", ";", "}", "if", "(", "'\"'", "==", "$", "lastchar", ")", "{", "//The return value is set to false", "//If we find the closing \" before the '=' it is set to true again.", "//Remember we begin to search the entry backwards so the \" has to show up twice - ending and beginning delimiter", "$", "ret", "=", "false", ";", "$", "found", "=", "0", ";", "for", "(", "$", "i", "=", "$", "length", ";", "$", "i", ">=", "$", "position", ";", "$", "i", "--", ")", "{", "$", "precedingchar", "=", "substr", "(", "$", "entry", ",", "$", "i", "-", "1", ",", "1", ")", ";", "$", "char", "=", "substr", "(", "$", "entry", ",", "$", "i", ",", "1", ")", ";", "if", "(", "(", "'\"'", "==", "$", "char", ")", "&&", "(", "'\\\\'", "!=", "$", "precedingchar", ")", ")", "{", "$", "found", "++", ";", "}", "if", "(", "2", "==", "$", "found", ")", "{", "$", "ret", "=", "true", ";", "break", ";", "}", "}", "}", "}", "return", "$", "ret", ";", "}" ]
Checking whether the position of the '=' is correct Sometimes there is a problem if a '=' is used inside an entry (for example abstract). This method checks if the '=' is outside braces then the '=' is correct and true is returned. If the '=' is inside braces it contains to a equation and therefore false is returned. @access private @param string $entry The text of the whole remaining entry @param int the current used place of the '=' @return bool true if the '=' is correct, false if it contains to an equation
[ "Checking", "whether", "the", "position", "of", "the", "=", "is", "correct" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L445-L494
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._checkAt
function _checkAt($entry) { $ret = false; $opening = array_keys($this->_delimiters); $closing = array_values($this->_delimiters); //Getting the value (at is only allowd in values) if (strrpos($entry, '=') !== false) { $position = strrpos($entry, '='); $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } while (!$proceed) { $substring = substr($entry, 0, $position); $position = strrpos($substring, '='); $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } } $value = trim(substr($entry, $position + 1)); $open = 0; $char = ''; $lastchar = ''; for ($i = 0; $i < strlen($value); $i++) { $char = substr($this->content, $i, 1); if (in_array($char, $opening) && ('\\' != $lastchar)) { $open++; } elseif (in_array($char, $closing) && ('\\' != $lastchar)) { $open--; } $lastchar = $char; } //if open is grater zero were are inside an entry if ($open > 0) { $ret = true; } } return $ret; }
php
function _checkAt($entry) { $ret = false; $opening = array_keys($this->_delimiters); $closing = array_values($this->_delimiters); //Getting the value (at is only allowd in values) if (strrpos($entry, '=') !== false) { $position = strrpos($entry, '='); $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } while (!$proceed) { $substring = substr($entry, 0, $position); $position = strrpos($substring, '='); $proceed = true; if (substr($entry, $position - 1, 1) == '\\') { $proceed = false; } } $value = trim(substr($entry, $position + 1)); $open = 0; $char = ''; $lastchar = ''; for ($i = 0; $i < strlen($value); $i++) { $char = substr($this->content, $i, 1); if (in_array($char, $opening) && ('\\' != $lastchar)) { $open++; } elseif (in_array($char, $closing) && ('\\' != $lastchar)) { $open--; } $lastchar = $char; } //if open is grater zero were are inside an entry if ($open > 0) { $ret = true; } } return $ret; }
[ "function", "_checkAt", "(", "$", "entry", ")", "{", "$", "ret", "=", "false", ";", "$", "opening", "=", "array_keys", "(", "$", "this", "->", "_delimiters", ")", ";", "$", "closing", "=", "array_values", "(", "$", "this", "->", "_delimiters", ")", ";", "//Getting the value (at is only allowd in values)", "if", "(", "strrpos", "(", "$", "entry", ",", "'='", ")", "!==", "false", ")", "{", "$", "position", "=", "strrpos", "(", "$", "entry", ",", "'='", ")", ";", "$", "proceed", "=", "true", ";", "if", "(", "substr", "(", "$", "entry", ",", "$", "position", "-", "1", ",", "1", ")", "==", "'\\\\'", ")", "{", "$", "proceed", "=", "false", ";", "}", "while", "(", "!", "$", "proceed", ")", "{", "$", "substring", "=", "substr", "(", "$", "entry", ",", "0", ",", "$", "position", ")", ";", "$", "position", "=", "strrpos", "(", "$", "substring", ",", "'='", ")", ";", "$", "proceed", "=", "true", ";", "if", "(", "substr", "(", "$", "entry", ",", "$", "position", "-", "1", ",", "1", ")", "==", "'\\\\'", ")", "{", "$", "proceed", "=", "false", ";", "}", "}", "$", "value", "=", "trim", "(", "substr", "(", "$", "entry", ",", "$", "position", "+", "1", ")", ")", ";", "$", "open", "=", "0", ";", "$", "char", "=", "''", ";", "$", "lastchar", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "value", ")", ";", "$", "i", "++", ")", "{", "$", "char", "=", "substr", "(", "$", "this", "->", "content", ",", "$", "i", ",", "1", ")", ";", "if", "(", "in_array", "(", "$", "char", ",", "$", "opening", ")", "&&", "(", "'\\\\'", "!=", "$", "lastchar", ")", ")", "{", "$", "open", "++", ";", "}", "elseif", "(", "in_array", "(", "$", "char", ",", "$", "closing", ")", "&&", "(", "'\\\\'", "!=", "$", "lastchar", ")", ")", "{", "$", "open", "--", ";", "}", "$", "lastchar", "=", "$", "char", ";", "}", "//if open is grater zero were are inside an entry", "if", "(", "$", "open", ">", "0", ")", "{", "$", "ret", "=", "true", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Checking whether an at is outside an entry Sometimes an entry misses an entry brace. Then the at of the next entry seems to be inside an entry. This is checked here. When it is most likely that the at is an opening at of the next entry this method returns true. @access private @param string $entry The text of the entry until the at @return bool true if the at is correct, false if the at is likely to begin the next entry.
[ "Checking", "whether", "an", "at", "is", "outside", "an", "entry" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L519-L558
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._stripDelimiter
function _stripDelimiter($entry) { $beginningdels = array_keys($this->_delimiters); $length = strlen($entry); $firstchar = substr($entry, 0, 1); $lastchar = substr($entry, -1, 1); while (in_array($firstchar, $beginningdels)) { //The first character is an opening delimiter if ($lastchar == $this->_delimiters[$firstchar]) { //Matches to closing Delimiter $entry = substr($entry, 1, -1); } else { break; } $firstchar = substr($entry, 0, 1); $lastchar = substr($entry, -1, 1); } return $entry; }
php
function _stripDelimiter($entry) { $beginningdels = array_keys($this->_delimiters); $length = strlen($entry); $firstchar = substr($entry, 0, 1); $lastchar = substr($entry, -1, 1); while (in_array($firstchar, $beginningdels)) { //The first character is an opening delimiter if ($lastchar == $this->_delimiters[$firstchar]) { //Matches to closing Delimiter $entry = substr($entry, 1, -1); } else { break; } $firstchar = substr($entry, 0, 1); $lastchar = substr($entry, -1, 1); } return $entry; }
[ "function", "_stripDelimiter", "(", "$", "entry", ")", "{", "$", "beginningdels", "=", "array_keys", "(", "$", "this", "->", "_delimiters", ")", ";", "$", "length", "=", "strlen", "(", "$", "entry", ")", ";", "$", "firstchar", "=", "substr", "(", "$", "entry", ",", "0", ",", "1", ")", ";", "$", "lastchar", "=", "substr", "(", "$", "entry", ",", "-", "1", ",", "1", ")", ";", "while", "(", "in_array", "(", "$", "firstchar", ",", "$", "beginningdels", ")", ")", "{", "//The first character is an opening delimiter", "if", "(", "$", "lastchar", "==", "$", "this", "->", "_delimiters", "[", "$", "firstchar", "]", ")", "{", "//Matches to closing Delimiter", "$", "entry", "=", "substr", "(", "$", "entry", ",", "1", ",", "-", "1", ")", ";", "}", "else", "{", "break", ";", "}", "$", "firstchar", "=", "substr", "(", "$", "entry", ",", "0", ",", "1", ")", ";", "$", "lastchar", "=", "substr", "(", "$", "entry", ",", "-", "1", ",", "1", ")", ";", "}", "return", "$", "entry", ";", "}" ]
Stripping Delimiter @access private @param string $entry The entry where the Delimiter should be stripped from @return string Stripped entry
[ "Stripping", "Delimiter" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L567-L583
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._wordwrap
function _wordwrap($entry) { if (('' != $entry) && (is_string($entry))) { $entry = wordwrap($entry, $this->_options['wordWrapWidth'], $this->_options['wordWrapBreak'], $this->_options['wordWrapCut']); } return $entry; }
php
function _wordwrap($entry) { if (('' != $entry) && (is_string($entry))) { $entry = wordwrap($entry, $this->_options['wordWrapWidth'], $this->_options['wordWrapBreak'], $this->_options['wordWrapCut']); } return $entry; }
[ "function", "_wordwrap", "(", "$", "entry", ")", "{", "if", "(", "(", "''", "!=", "$", "entry", ")", "&&", "(", "is_string", "(", "$", "entry", ")", ")", ")", "{", "$", "entry", "=", "wordwrap", "(", "$", "entry", ",", "$", "this", "->", "_options", "[", "'wordWrapWidth'", "]", ",", "$", "this", "->", "_options", "[", "'wordWrapBreak'", "]", ",", "$", "this", "->", "_options", "[", "'wordWrapCut'", "]", ")", ";", "}", "return", "$", "entry", ";", "}" ]
Wordwrap an entry @access private @param string $entry The entry to wrap @return string wrapped entry
[ "Wordwrap", "an", "entry" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L605-L611
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._extractAuthors
function _extractAuthors($entry) { $entry = $this->_unwrap($entry); $authorarray = array(); $authorarray = explode(' and ', $entry); for ($i = 0; $i < sizeof($authorarray); $i++) { $author = trim($authorarray[$i]); /*The first version of how an author could be written (First von Last) has no commas in it*/ $first = ''; $von = ''; $last = ''; $jr = ''; if (strpos($author, ',') === false) { $tmparray = array(); $tmparray = preg_split('/[\s\~]/', $author); $size = sizeof($tmparray); if (1 == $size) { //There is only a last $last = $tmparray[0]; } elseif (2 == $size) { //There is a first and a last $first = $tmparray[0]; $last = $tmparray[1]; } else { $invon = false; $inlast = false; for ($j = 0; $j < ($size - 1); $j++) { if ($inlast) { $last .= ' ' . $tmparray[$j]; } elseif ($invon) { try { $case = $this->_determineCase($tmparray[$j]); if ((0 == $case) || (-1 == $case)) { //Change from von to last //You only change when there is no more lower case there $islast = true; for ($k = ($j + 1); $k < ($size - 1); $k++) { try { $futurecase = $this->_determineCase($tmparray[$k]); if (0 == $futurecase) { $islast = false; } } catch (BibtexException $sbe) { // Ignore } } if ($islast) { $inlast = true; if (-1 == $case) { //Caseless belongs to the last $last .= ' ' . $tmparray[$j]; } else { $von .= ' ' . $tmparray[$j]; } } else { $von .= ' ' . $tmparray[$j]; } } else { $von .= ' ' . $tmparray[$j]; } } catch (BibtexException $sbe) { // Ignore } } else { try { $case = $this->_determineCase($tmparray[$j]); if (0 == $case) { //Change from first to von $invon = true; $von .= ' ' . $tmparray[$j]; } else { $first .= ' ' . $tmparray[$j]; } } catch (BibtexException $sbe) { // Ignore } } } //The last entry is always the last! $last .= ' ' . $tmparray[$size - 1]; } } else { //Version 2 and 3 $tmparray = array(); $tmparray = explode(',', $author); //The first entry must contain von and last $vonlastarray = array(); $vonlastarray = explode(' ', $tmparray[0]); $size = sizeof($vonlastarray); if (1 == $size) { //Only one entry->got to be the last $last = $vonlastarray[0]; } else { $inlast = false; for ($j = 0; $j < ($size - 1); $j++) { if ($inlast) { $last .= ' ' . $vonlastarray[$j]; } else { if (0 != ($this->_determineCase($vonlastarray[$j]))) { //Change from von to last $islast = true; for ($k = ($j + 1); $k < ($size - 1); $k++) { try { $case = $this->_determineCase($vonlastarray[$k]); if (0 == $case) { $islast = false; } } catch (BibtexException $sbe) { // Ignore } } if ($islast) { $inlast = true; $last .= ' ' . $vonlastarray[$j]; } else { $von .= ' ' . $vonlastarray[$j]; } } else { $von .= ' ' . $vonlastarray[$j]; } } } $last .= ' ' . $vonlastarray[$size - 1]; } //Now we check if it is version three (three entries in the array (two commas) if (3 == sizeof($tmparray)) { $jr = $tmparray[1]; } //Everything in the last entry is first $first = $tmparray[sizeof($tmparray) - 1]; } $authorarray[$i] = array('first' => trim($first), 'von' => trim($von), 'last' => trim($last), 'jr' => trim($jr)); } return $authorarray; }
php
function _extractAuthors($entry) { $entry = $this->_unwrap($entry); $authorarray = array(); $authorarray = explode(' and ', $entry); for ($i = 0; $i < sizeof($authorarray); $i++) { $author = trim($authorarray[$i]); /*The first version of how an author could be written (First von Last) has no commas in it*/ $first = ''; $von = ''; $last = ''; $jr = ''; if (strpos($author, ',') === false) { $tmparray = array(); $tmparray = preg_split('/[\s\~]/', $author); $size = sizeof($tmparray); if (1 == $size) { //There is only a last $last = $tmparray[0]; } elseif (2 == $size) { //There is a first and a last $first = $tmparray[0]; $last = $tmparray[1]; } else { $invon = false; $inlast = false; for ($j = 0; $j < ($size - 1); $j++) { if ($inlast) { $last .= ' ' . $tmparray[$j]; } elseif ($invon) { try { $case = $this->_determineCase($tmparray[$j]); if ((0 == $case) || (-1 == $case)) { //Change from von to last //You only change when there is no more lower case there $islast = true; for ($k = ($j + 1); $k < ($size - 1); $k++) { try { $futurecase = $this->_determineCase($tmparray[$k]); if (0 == $futurecase) { $islast = false; } } catch (BibtexException $sbe) { // Ignore } } if ($islast) { $inlast = true; if (-1 == $case) { //Caseless belongs to the last $last .= ' ' . $tmparray[$j]; } else { $von .= ' ' . $tmparray[$j]; } } else { $von .= ' ' . $tmparray[$j]; } } else { $von .= ' ' . $tmparray[$j]; } } catch (BibtexException $sbe) { // Ignore } } else { try { $case = $this->_determineCase($tmparray[$j]); if (0 == $case) { //Change from first to von $invon = true; $von .= ' ' . $tmparray[$j]; } else { $first .= ' ' . $tmparray[$j]; } } catch (BibtexException $sbe) { // Ignore } } } //The last entry is always the last! $last .= ' ' . $tmparray[$size - 1]; } } else { //Version 2 and 3 $tmparray = array(); $tmparray = explode(',', $author); //The first entry must contain von and last $vonlastarray = array(); $vonlastarray = explode(' ', $tmparray[0]); $size = sizeof($vonlastarray); if (1 == $size) { //Only one entry->got to be the last $last = $vonlastarray[0]; } else { $inlast = false; for ($j = 0; $j < ($size - 1); $j++) { if ($inlast) { $last .= ' ' . $vonlastarray[$j]; } else { if (0 != ($this->_determineCase($vonlastarray[$j]))) { //Change from von to last $islast = true; for ($k = ($j + 1); $k < ($size - 1); $k++) { try { $case = $this->_determineCase($vonlastarray[$k]); if (0 == $case) { $islast = false; } } catch (BibtexException $sbe) { // Ignore } } if ($islast) { $inlast = true; $last .= ' ' . $vonlastarray[$j]; } else { $von .= ' ' . $vonlastarray[$j]; } } else { $von .= ' ' . $vonlastarray[$j]; } } } $last .= ' ' . $vonlastarray[$size - 1]; } //Now we check if it is version three (three entries in the array (two commas) if (3 == sizeof($tmparray)) { $jr = $tmparray[1]; } //Everything in the last entry is first $first = $tmparray[sizeof($tmparray) - 1]; } $authorarray[$i] = array('first' => trim($first), 'von' => trim($von), 'last' => trim($last), 'jr' => trim($jr)); } return $authorarray; }
[ "function", "_extractAuthors", "(", "$", "entry", ")", "{", "$", "entry", "=", "$", "this", "->", "_unwrap", "(", "$", "entry", ")", ";", "$", "authorarray", "=", "array", "(", ")", ";", "$", "authorarray", "=", "explode", "(", "' and '", ",", "$", "entry", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "sizeof", "(", "$", "authorarray", ")", ";", "$", "i", "++", ")", "{", "$", "author", "=", "trim", "(", "$", "authorarray", "[", "$", "i", "]", ")", ";", "/*The first version of how an author could be written (First von Last)\n has no commas in it*/", "$", "first", "=", "''", ";", "$", "von", "=", "''", ";", "$", "last", "=", "''", ";", "$", "jr", "=", "''", ";", "if", "(", "strpos", "(", "$", "author", ",", "','", ")", "===", "false", ")", "{", "$", "tmparray", "=", "array", "(", ")", ";", "$", "tmparray", "=", "preg_split", "(", "'/[\\s\\~]/'", ",", "$", "author", ")", ";", "$", "size", "=", "sizeof", "(", "$", "tmparray", ")", ";", "if", "(", "1", "==", "$", "size", ")", "{", "//There is only a last", "$", "last", "=", "$", "tmparray", "[", "0", "]", ";", "}", "elseif", "(", "2", "==", "$", "size", ")", "{", "//There is a first and a last", "$", "first", "=", "$", "tmparray", "[", "0", "]", ";", "$", "last", "=", "$", "tmparray", "[", "1", "]", ";", "}", "else", "{", "$", "invon", "=", "false", ";", "$", "inlast", "=", "false", ";", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "(", "$", "size", "-", "1", ")", ";", "$", "j", "++", ")", "{", "if", "(", "$", "inlast", ")", "{", "$", "last", ".=", "' '", ".", "$", "tmparray", "[", "$", "j", "]", ";", "}", "elseif", "(", "$", "invon", ")", "{", "try", "{", "$", "case", "=", "$", "this", "->", "_determineCase", "(", "$", "tmparray", "[", "$", "j", "]", ")", ";", "if", "(", "(", "0", "==", "$", "case", ")", "||", "(", "-", "1", "==", "$", "case", ")", ")", "{", "//Change from von to last", "//You only change when there is no more lower case there", "$", "islast", "=", "true", ";", "for", "(", "$", "k", "=", "(", "$", "j", "+", "1", ")", ";", "$", "k", "<", "(", "$", "size", "-", "1", ")", ";", "$", "k", "++", ")", "{", "try", "{", "$", "futurecase", "=", "$", "this", "->", "_determineCase", "(", "$", "tmparray", "[", "$", "k", "]", ")", ";", "if", "(", "0", "==", "$", "futurecase", ")", "{", "$", "islast", "=", "false", ";", "}", "}", "catch", "(", "BibtexException", "$", "sbe", ")", "{", "// Ignore", "}", "}", "if", "(", "$", "islast", ")", "{", "$", "inlast", "=", "true", ";", "if", "(", "-", "1", "==", "$", "case", ")", "{", "//Caseless belongs to the last", "$", "last", ".=", "' '", ".", "$", "tmparray", "[", "$", "j", "]", ";", "}", "else", "{", "$", "von", ".=", "' '", ".", "$", "tmparray", "[", "$", "j", "]", ";", "}", "}", "else", "{", "$", "von", ".=", "' '", ".", "$", "tmparray", "[", "$", "j", "]", ";", "}", "}", "else", "{", "$", "von", ".=", "' '", ".", "$", "tmparray", "[", "$", "j", "]", ";", "}", "}", "catch", "(", "BibtexException", "$", "sbe", ")", "{", "// Ignore", "}", "}", "else", "{", "try", "{", "$", "case", "=", "$", "this", "->", "_determineCase", "(", "$", "tmparray", "[", "$", "j", "]", ")", ";", "if", "(", "0", "==", "$", "case", ")", "{", "//Change from first to von", "$", "invon", "=", "true", ";", "$", "von", ".=", "' '", ".", "$", "tmparray", "[", "$", "j", "]", ";", "}", "else", "{", "$", "first", ".=", "' '", ".", "$", "tmparray", "[", "$", "j", "]", ";", "}", "}", "catch", "(", "BibtexException", "$", "sbe", ")", "{", "// Ignore", "}", "}", "}", "//The last entry is always the last!", "$", "last", ".=", "' '", ".", "$", "tmparray", "[", "$", "size", "-", "1", "]", ";", "}", "}", "else", "{", "//Version 2 and 3", "$", "tmparray", "=", "array", "(", ")", ";", "$", "tmparray", "=", "explode", "(", "','", ",", "$", "author", ")", ";", "//The first entry must contain von and last", "$", "vonlastarray", "=", "array", "(", ")", ";", "$", "vonlastarray", "=", "explode", "(", "' '", ",", "$", "tmparray", "[", "0", "]", ")", ";", "$", "size", "=", "sizeof", "(", "$", "vonlastarray", ")", ";", "if", "(", "1", "==", "$", "size", ")", "{", "//Only one entry->got to be the last", "$", "last", "=", "$", "vonlastarray", "[", "0", "]", ";", "}", "else", "{", "$", "inlast", "=", "false", ";", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "(", "$", "size", "-", "1", ")", ";", "$", "j", "++", ")", "{", "if", "(", "$", "inlast", ")", "{", "$", "last", ".=", "' '", ".", "$", "vonlastarray", "[", "$", "j", "]", ";", "}", "else", "{", "if", "(", "0", "!=", "(", "$", "this", "->", "_determineCase", "(", "$", "vonlastarray", "[", "$", "j", "]", ")", ")", ")", "{", "//Change from von to last", "$", "islast", "=", "true", ";", "for", "(", "$", "k", "=", "(", "$", "j", "+", "1", ")", ";", "$", "k", "<", "(", "$", "size", "-", "1", ")", ";", "$", "k", "++", ")", "{", "try", "{", "$", "case", "=", "$", "this", "->", "_determineCase", "(", "$", "vonlastarray", "[", "$", "k", "]", ")", ";", "if", "(", "0", "==", "$", "case", ")", "{", "$", "islast", "=", "false", ";", "}", "}", "catch", "(", "BibtexException", "$", "sbe", ")", "{", "// Ignore", "}", "}", "if", "(", "$", "islast", ")", "{", "$", "inlast", "=", "true", ";", "$", "last", ".=", "' '", ".", "$", "vonlastarray", "[", "$", "j", "]", ";", "}", "else", "{", "$", "von", ".=", "' '", ".", "$", "vonlastarray", "[", "$", "j", "]", ";", "}", "}", "else", "{", "$", "von", ".=", "' '", ".", "$", "vonlastarray", "[", "$", "j", "]", ";", "}", "}", "}", "$", "last", ".=", "' '", ".", "$", "vonlastarray", "[", "$", "size", "-", "1", "]", ";", "}", "//Now we check if it is version three (three entries in the array (two commas)", "if", "(", "3", "==", "sizeof", "(", "$", "tmparray", ")", ")", "{", "$", "jr", "=", "$", "tmparray", "[", "1", "]", ";", "}", "//Everything in the last entry is first", "$", "first", "=", "$", "tmparray", "[", "sizeof", "(", "$", "tmparray", ")", "-", "1", "]", ";", "}", "$", "authorarray", "[", "$", "i", "]", "=", "array", "(", "'first'", "=>", "trim", "(", "$", "first", ")", ",", "'von'", "=>", "trim", "(", "$", "von", ")", ",", "'last'", "=>", "trim", "(", "$", "last", ")", ",", "'jr'", "=>", "trim", "(", "$", "jr", ")", ")", ";", "}", "return", "$", "authorarray", ";", "}" ]
Extracting the authors @access private @param string $entry The entry with the authors @return array the extracted authors
[ "Extracting", "the", "authors" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L620-L753
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._determineCase
function _determineCase($word) { $ret = -1; $trimmedword = trim($word); /*We need this variable. Without the next of would not work (trim changes the variable automatically to a string!)*/ if (is_string($word) && (strlen($trimmedword) > 0)) { $i = 0; $found = false; $openbrace = 0; while (!$found && ($i <= strlen($word))) { $letter = substr($trimmedword, $i, 1); $ord = ord($letter); if ($ord == 123) { //Open brace $openbrace++; } if ($ord == 125) { //Closing brace $openbrace--; } if (($ord >= 65) && ($ord <= 90) && (0 == $openbrace)) { //The first character is uppercase $ret = 1; $found = true; } elseif (($ord >= 97) && ($ord <= 122) && (0 == $openbrace)) { //The first character is lowercase $ret = 0; $found = true; } else { //Not yet found $i++; } } } else { throw new BibtexException('Could not determine case on word: ' . (string)$word); } return $ret; }
php
function _determineCase($word) { $ret = -1; $trimmedword = trim($word); /*We need this variable. Without the next of would not work (trim changes the variable automatically to a string!)*/ if (is_string($word) && (strlen($trimmedword) > 0)) { $i = 0; $found = false; $openbrace = 0; while (!$found && ($i <= strlen($word))) { $letter = substr($trimmedword, $i, 1); $ord = ord($letter); if ($ord == 123) { //Open brace $openbrace++; } if ($ord == 125) { //Closing brace $openbrace--; } if (($ord >= 65) && ($ord <= 90) && (0 == $openbrace)) { //The first character is uppercase $ret = 1; $found = true; } elseif (($ord >= 97) && ($ord <= 122) && (0 == $openbrace)) { //The first character is lowercase $ret = 0; $found = true; } else { //Not yet found $i++; } } } else { throw new BibtexException('Could not determine case on word: ' . (string)$word); } return $ret; }
[ "function", "_determineCase", "(", "$", "word", ")", "{", "$", "ret", "=", "-", "1", ";", "$", "trimmedword", "=", "trim", "(", "$", "word", ")", ";", "/*We need this variable. Without the next of would not work\n (trim changes the variable automatically to a string!)*/", "if", "(", "is_string", "(", "$", "word", ")", "&&", "(", "strlen", "(", "$", "trimmedword", ")", ">", "0", ")", ")", "{", "$", "i", "=", "0", ";", "$", "found", "=", "false", ";", "$", "openbrace", "=", "0", ";", "while", "(", "!", "$", "found", "&&", "(", "$", "i", "<=", "strlen", "(", "$", "word", ")", ")", ")", "{", "$", "letter", "=", "substr", "(", "$", "trimmedword", ",", "$", "i", ",", "1", ")", ";", "$", "ord", "=", "ord", "(", "$", "letter", ")", ";", "if", "(", "$", "ord", "==", "123", ")", "{", "//Open brace", "$", "openbrace", "++", ";", "}", "if", "(", "$", "ord", "==", "125", ")", "{", "//Closing brace", "$", "openbrace", "--", ";", "}", "if", "(", "(", "$", "ord", ">=", "65", ")", "&&", "(", "$", "ord", "<=", "90", ")", "&&", "(", "0", "==", "$", "openbrace", ")", ")", "{", "//The first character is uppercase", "$", "ret", "=", "1", ";", "$", "found", "=", "true", ";", "}", "elseif", "(", "(", "$", "ord", ">=", "97", ")", "&&", "(", "$", "ord", "<=", "122", ")", "&&", "(", "0", "==", "$", "openbrace", ")", ")", "{", "//The first character is lowercase", "$", "ret", "=", "0", ";", "$", "found", "=", "true", ";", "}", "else", "{", "//Not yet found", "$", "i", "++", ";", "}", "}", "}", "else", "{", "throw", "new", "BibtexException", "(", "'Could not determine case on word: '", ".", "(", "string", ")", "$", "word", ")", ";", "}", "return", "$", "ret", ";", "}" ]
Case Determination according to the needs of BibTex To parse the Author(s) correctly a determination is needed to get the Case of a word. There are three possible values: - Upper Case (return value 1) - Lower Case (return value 0) - Caseless (return value -1) @access private @param string $word @return int The Case @throws BibtexException
[ "Case", "Determination", "according", "to", "the", "needs", "of", "BibTex" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L769-L802
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._validateValue
function _validateValue($entry, $wholeentry) { //There is no @ allowed if the entry is enclosed by braces if (preg_match('/^{.*@.*}$/', $entry)) { $this->_generateWarning('WARNING_AT_IN_BRACES', $entry, $wholeentry); } //No escaped " allowed if the entry is enclosed by double quotes if (preg_match('/^\".*\\".*\"$/', $entry)) { $this->_generateWarning('WARNING_ESCAPED_DOUBLE_QUOTE_INSIDE_DOUBLE_QUOTES', $entry, $wholeentry); } //Amount of Braces is not correct $open = 0; $lastchar = ''; $char = ''; for ($i = 0; $i < strlen($entry); $i++) { $char = substr($entry, $i, 1); if (('{' == $char) && ('\\' != $lastchar)) { $open++; } if (('}' == $char) && ('\\' != $lastchar)) { $open--; } $lastchar = $char; } if (0 != $open) { $this->_generateWarning('WARNING_UNBALANCED_AMOUNT_OF_BRACES', $entry, $wholeentry); } }
php
function _validateValue($entry, $wholeentry) { //There is no @ allowed if the entry is enclosed by braces if (preg_match('/^{.*@.*}$/', $entry)) { $this->_generateWarning('WARNING_AT_IN_BRACES', $entry, $wholeentry); } //No escaped " allowed if the entry is enclosed by double quotes if (preg_match('/^\".*\\".*\"$/', $entry)) { $this->_generateWarning('WARNING_ESCAPED_DOUBLE_QUOTE_INSIDE_DOUBLE_QUOTES', $entry, $wholeentry); } //Amount of Braces is not correct $open = 0; $lastchar = ''; $char = ''; for ($i = 0; $i < strlen($entry); $i++) { $char = substr($entry, $i, 1); if (('{' == $char) && ('\\' != $lastchar)) { $open++; } if (('}' == $char) && ('\\' != $lastchar)) { $open--; } $lastchar = $char; } if (0 != $open) { $this->_generateWarning('WARNING_UNBALANCED_AMOUNT_OF_BRACES', $entry, $wholeentry); } }
[ "function", "_validateValue", "(", "$", "entry", ",", "$", "wholeentry", ")", "{", "//There is no @ allowed if the entry is enclosed by braces", "if", "(", "preg_match", "(", "'/^{.*@.*}$/'", ",", "$", "entry", ")", ")", "{", "$", "this", "->", "_generateWarning", "(", "'WARNING_AT_IN_BRACES'", ",", "$", "entry", ",", "$", "wholeentry", ")", ";", "}", "//No escaped \" allowed if the entry is enclosed by double quotes", "if", "(", "preg_match", "(", "'/^\\\".*\\\\\".*\\\"$/'", ",", "$", "entry", ")", ")", "{", "$", "this", "->", "_generateWarning", "(", "'WARNING_ESCAPED_DOUBLE_QUOTE_INSIDE_DOUBLE_QUOTES'", ",", "$", "entry", ",", "$", "wholeentry", ")", ";", "}", "//Amount of Braces is not correct", "$", "open", "=", "0", ";", "$", "lastchar", "=", "''", ";", "$", "char", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "entry", ")", ";", "$", "i", "++", ")", "{", "$", "char", "=", "substr", "(", "$", "entry", ",", "$", "i", ",", "1", ")", ";", "if", "(", "(", "'{'", "==", "$", "char", ")", "&&", "(", "'\\\\'", "!=", "$", "lastchar", ")", ")", "{", "$", "open", "++", ";", "}", "if", "(", "(", "'}'", "==", "$", "char", ")", "&&", "(", "'\\\\'", "!=", "$", "lastchar", ")", ")", "{", "$", "open", "--", ";", "}", "$", "lastchar", "=", "$", "char", ";", "}", "if", "(", "0", "!=", "$", "open", ")", "{", "$", "this", "->", "_generateWarning", "(", "'WARNING_UNBALANCED_AMOUNT_OF_BRACES'", ",", "$", "entry", ",", "$", "wholeentry", ")", ";", "}", "}" ]
Validation of a value There may be several problems with the value of a field. These problems exist but do not break the parsing. If a problem is detected a warning is appended to the array warnings. @access private @param string $entry The entry aka one line which which should be validated @param string $wholeentry The whole BibTex Entry which the one line is part of @return void
[ "Validation", "of", "a", "value" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L816-L843
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._removeCurlyBraces
function _removeCurlyBraces($value) { //First we save the delimiters $beginningdels = array_keys($this->_delimiters); $firstchar = substr($value, 0, 1); $lastchar = substr($value, -1, 1); $begin = ''; $end = ''; while (in_array($firstchar, $beginningdels)) { //The first character is an opening delimiter if ($lastchar == $this->_delimiters[$firstchar]) { //Matches to closing Delimiter $begin .= $firstchar; $end .= $lastchar; $value = substr($value, 1, -1); } else { break; } $firstchar = substr($value, 0, 1); $lastchar = substr($value, -1, 1); } //Now we get rid of the curly braces $pattern = '/([^\\\\]|^)?\{(.*?[^\\\\])\}/'; $replacement = '$1$2'; $value = preg_replace($pattern, $replacement, $value); //Reattach delimiters $value = $begin . $value . $end; return $value; }
php
function _removeCurlyBraces($value) { //First we save the delimiters $beginningdels = array_keys($this->_delimiters); $firstchar = substr($value, 0, 1); $lastchar = substr($value, -1, 1); $begin = ''; $end = ''; while (in_array($firstchar, $beginningdels)) { //The first character is an opening delimiter if ($lastchar == $this->_delimiters[$firstchar]) { //Matches to closing Delimiter $begin .= $firstchar; $end .= $lastchar; $value = substr($value, 1, -1); } else { break; } $firstchar = substr($value, 0, 1); $lastchar = substr($value, -1, 1); } //Now we get rid of the curly braces $pattern = '/([^\\\\]|^)?\{(.*?[^\\\\])\}/'; $replacement = '$1$2'; $value = preg_replace($pattern, $replacement, $value); //Reattach delimiters $value = $begin . $value . $end; return $value; }
[ "function", "_removeCurlyBraces", "(", "$", "value", ")", "{", "//First we save the delimiters", "$", "beginningdels", "=", "array_keys", "(", "$", "this", "->", "_delimiters", ")", ";", "$", "firstchar", "=", "substr", "(", "$", "value", ",", "0", ",", "1", ")", ";", "$", "lastchar", "=", "substr", "(", "$", "value", ",", "-", "1", ",", "1", ")", ";", "$", "begin", "=", "''", ";", "$", "end", "=", "''", ";", "while", "(", "in_array", "(", "$", "firstchar", ",", "$", "beginningdels", ")", ")", "{", "//The first character is an opening delimiter", "if", "(", "$", "lastchar", "==", "$", "this", "->", "_delimiters", "[", "$", "firstchar", "]", ")", "{", "//Matches to closing Delimiter", "$", "begin", ".=", "$", "firstchar", ";", "$", "end", ".=", "$", "lastchar", ";", "$", "value", "=", "substr", "(", "$", "value", ",", "1", ",", "-", "1", ")", ";", "}", "else", "{", "break", ";", "}", "$", "firstchar", "=", "substr", "(", "$", "value", ",", "0", ",", "1", ")", ";", "$", "lastchar", "=", "substr", "(", "$", "value", ",", "-", "1", ",", "1", ")", ";", "}", "//Now we get rid of the curly braces", "$", "pattern", "=", "'/([^\\\\\\\\]|^)?\\{(.*?[^\\\\\\\\])\\}/'", ";", "$", "replacement", "=", "'$1$2'", ";", "$", "value", "=", "preg_replace", "(", "$", "pattern", ",", "$", "replacement", ",", "$", "value", ")", ";", "//Reattach delimiters", "$", "value", "=", "$", "begin", ".", "$", "value", ".", "$", "end", ";", "return", "$", "value", ";", "}" ]
Remove curly braces from entry @access private @param string $value The value in which curly braces to be removed @param string Value with removed curly braces
[ "Remove", "curly", "braces", "from", "entry" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L852-L878
academic/VipaBibTexBundle
Helper/Bibtex.php
Bibtex._generateWarning
function _generateWarning($type, $entry, $wholeentry = '') { $warning['warning'] = $type; $warning['entry'] = $entry; $warning['wholeentry'] = $wholeentry; $this->warnings[] = $warning; }
php
function _generateWarning($type, $entry, $wholeentry = '') { $warning['warning'] = $type; $warning['entry'] = $entry; $warning['wholeentry'] = $wholeentry; $this->warnings[] = $warning; }
[ "function", "_generateWarning", "(", "$", "type", ",", "$", "entry", ",", "$", "wholeentry", "=", "''", ")", "{", "$", "warning", "[", "'warning'", "]", "=", "$", "type", ";", "$", "warning", "[", "'entry'", "]", "=", "$", "entry", ";", "$", "warning", "[", "'wholeentry'", "]", "=", "$", "wholeentry", ";", "$", "this", "->", "warnings", "[", "]", "=", "$", "warning", ";", "}" ]
Generates a warning @access private @param string $type The type of the warning @param string $entry The line of the entry where the warning occurred @param string $wholeentry OPTIONAL The whole entry where the warning occurred
[ "Generates", "a", "warning" ]
train
https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L888-L894