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
fccn/oai-pmh-core
src/schemas/ands_lom.php
LOM_DataHolder.combine
public function combine($another) { debug_message(__CLASS__.'.'.__FUNCTION__." LLOM_DataHolder class is ".LOM_DataHolder::getKlass()); debug_message(__CLASS__.'.'.__FUNCTION__." another is ".get_class($another)); if (is_a($another, LOM_DataHolder::getKlass())) { debug_message('entering function '.__FUNCTION__.' in '.__CLASS__); // debug_var_dump("another", $another); //identifier if (empty($this->identifier)) { debug_message("LOM_DataHolder::identifier should not be empty!!"); $this->identifier = $another->identifier; } elseif (strcmp(substr($this->identifier, - strlen($another->identifier)), $another->identifier) !== 0) { // debug_var_dump('comparison', strcmp(substr($this->identifier, - strlen($another->identifier)), $another->identifier)); // debug_message("found a different identifier for this element ".$this->identifier." != ".$another->identifier); error_log("found a different identifier for this element ".$this->identifier." != ".$another->identifier); return; } debug_message("Identity ok. Adding elements"); //continue with other db elements $this->addElement('contributor', $another); $this->addElement('coverage', $another); $this->addElement('creator', $another); $this->addElement('date_', $another); $this->addElement('description', $another); $this->addElement('format_', $another); $this->addElement('language', $another); $this->addElement('publisher', $another); $this->addElement('relation', $another); $this->addElement('rights', $another); $this->addElement('source', $another); $this->addElement('subject', $another); $this->addElement('title', $another); $this->addElement('type_', $another); $this->addElement('thumbnail', $another); } }
php
public function combine($another) { debug_message(__CLASS__.'.'.__FUNCTION__." LLOM_DataHolder class is ".LOM_DataHolder::getKlass()); debug_message(__CLASS__.'.'.__FUNCTION__." another is ".get_class($another)); if (is_a($another, LOM_DataHolder::getKlass())) { debug_message('entering function '.__FUNCTION__.' in '.__CLASS__); // debug_var_dump("another", $another); //identifier if (empty($this->identifier)) { debug_message("LOM_DataHolder::identifier should not be empty!!"); $this->identifier = $another->identifier; } elseif (strcmp(substr($this->identifier, - strlen($another->identifier)), $another->identifier) !== 0) { // debug_var_dump('comparison', strcmp(substr($this->identifier, - strlen($another->identifier)), $another->identifier)); // debug_message("found a different identifier for this element ".$this->identifier." != ".$another->identifier); error_log("found a different identifier for this element ".$this->identifier." != ".$another->identifier); return; } debug_message("Identity ok. Adding elements"); //continue with other db elements $this->addElement('contributor', $another); $this->addElement('coverage', $another); $this->addElement('creator', $another); $this->addElement('date_', $another); $this->addElement('description', $another); $this->addElement('format_', $another); $this->addElement('language', $another); $this->addElement('publisher', $another); $this->addElement('relation', $another); $this->addElement('rights', $another); $this->addElement('source', $another); $this->addElement('subject', $another); $this->addElement('title', $another); $this->addElement('type_', $another); $this->addElement('thumbnail', $another); } }
[ "public", "function", "combine", "(", "$", "another", ")", "{", "debug_message", "(", "__CLASS__", ".", "'.'", ".", "__FUNCTION__", ".", "\" LLOM_DataHolder class is \"", ".", "LOM_DataHolder", "::", "getKlass", "(", ")", ")", ";", "debug_message", "(", "__CLASS__", ".", "'.'", ".", "__FUNCTION__", ".", "\" another is \"", ".", "get_class", "(", "$", "another", ")", ")", ";", "if", "(", "is_a", "(", "$", "another", ",", "LOM_DataHolder", "::", "getKlass", "(", ")", ")", ")", "{", "debug_message", "(", "'entering function '", ".", "__FUNCTION__", ".", "' in '", ".", "__CLASS__", ")", ";", "// debug_var_dump(\"another\", $another);", "//identifier", "if", "(", "empty", "(", "$", "this", "->", "identifier", ")", ")", "{", "debug_message", "(", "\"LOM_DataHolder::identifier should not be empty!!\"", ")", ";", "$", "this", "->", "identifier", "=", "$", "another", "->", "identifier", ";", "}", "elseif", "(", "strcmp", "(", "substr", "(", "$", "this", "->", "identifier", ",", "-", "strlen", "(", "$", "another", "->", "identifier", ")", ")", ",", "$", "another", "->", "identifier", ")", "!==", "0", ")", "{", "// debug_var_dump('comparison', strcmp(substr($this->identifier, - strlen($another->identifier)), $another->identifier));", "// debug_message(\"found a different identifier for this element \".$this->identifier.\" != \".$another->identifier);", "error_log", "(", "\"found a different identifier for this element \"", ".", "$", "this", "->", "identifier", ".", "\" != \"", ".", "$", "another", "->", "identifier", ")", ";", "return", ";", "}", "debug_message", "(", "\"Identity ok. Adding elements\"", ")", ";", "//continue with other db elements", "$", "this", "->", "addElement", "(", "'contributor'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'coverage'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'creator'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'date_'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'description'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'format_'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'language'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'publisher'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'relation'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'rights'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'source'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'subject'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'title'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'type_'", ",", "$", "another", ")", ";", "$", "this", "->", "addElement", "(", "'thumbnail'", ",", "$", "another", ")", ";", "}", "}" ]
Combines this object with another LOM_DataHolder object
[ "Combines", "this", "object", "with", "another", "LOM_DataHolder", "object" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_lom.php#L319-L354
fccn/oai-pmh-core
src/schemas/ands_lom.php
LOM_DataHolder.addElement
private function addElement($elem, $to_add) { //debug_var_dump("to_add->$elem", $to_add->$elem); if (isset($to_add->$elem) && !empty($to_add->$elem) && $to_add->$elem != ' ') {//&& !empty(str_replace(' ', '', $to_add->$elem)) ){ $elem_to_add = str_replace('&', '-and-', $to_add->$elem); //replace amperstamps for -and- if (!in_array($elem_to_add, $this->$elem)) { array_push($this->$elem, $elem_to_add); //debug_var_dump("this->$elem", $this->$elem); } } }
php
private function addElement($elem, $to_add) { //debug_var_dump("to_add->$elem", $to_add->$elem); if (isset($to_add->$elem) && !empty($to_add->$elem) && $to_add->$elem != ' ') {//&& !empty(str_replace(' ', '', $to_add->$elem)) ){ $elem_to_add = str_replace('&', '-and-', $to_add->$elem); //replace amperstamps for -and- if (!in_array($elem_to_add, $this->$elem)) { array_push($this->$elem, $elem_to_add); //debug_var_dump("this->$elem", $this->$elem); } } }
[ "private", "function", "addElement", "(", "$", "elem", ",", "$", "to_add", ")", "{", "//debug_var_dump(\"to_add->$elem\", $to_add->$elem);", "if", "(", "isset", "(", "$", "to_add", "->", "$", "elem", ")", "&&", "!", "empty", "(", "$", "to_add", "->", "$", "elem", ")", "&&", "$", "to_add", "->", "$", "elem", "!=", "' '", ")", "{", "//&& !empty(str_replace(' ', '', $to_add->$elem)) ){", "$", "elem_to_add", "=", "str_replace", "(", "'&'", ",", "'-and-'", ",", "$", "to_add", "->", "$", "elem", ")", ";", "//replace amperstamps for -and-", "if", "(", "!", "in_array", "(", "$", "elem_to_add", ",", "$", "this", "->", "$", "elem", ")", ")", "{", "array_push", "(", "$", "this", "->", "$", "elem", ",", "$", "elem_to_add", ")", ";", "//debug_var_dump(\"this->$elem\", $this->$elem);", "}", "}", "}" ]
adds a db element only if it is new
[ "adds", "a", "db", "element", "only", "if", "it", "is", "new" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_lom.php#L359-L369
fccn/oai-pmh-core
src/schemas/ands_lom.php
LOM_DataHolder.to_array
public function to_array() { debug_message('entering function '.__FUNCTION__.' in '.__CLASS__); //lomdata $lomdata = array( 'general' => array( 'identifier' => array( 'catalog' => $this->catalog, 'entry' => $this->identifier ) ),//general 'lifeCycle' => array(), 'educational' => array(), 'technical' => array(), 'rights' => array(), 'classification' => array(), 'metaMetadata' => array(), 'relation' => array() ); //-----general.title (M) if (empty($this->title)) { array_push($this->title, "Untitled"); } $lang = 'pt'; $lomdata['general']['title'] = array("string?language=$lang" => $this->title[0]); //-----general.keyword (M) //initialize keyword //keywords from subject have the form: Language::keyword1$$Language::keyword2 .. $lomdata['general']['keyword'] = array(); foreach ($this->subject as $elem) { $kw_elements = explode('$$', $elem); foreach ($kw_elements as $kw_elem) { $lang_kw = explode('::', $kw_elem); $kw = array_pop($lang_kw); if (empty($lang_kw)) { $lang = 'pt'; } else { $lang = array_pop($lang_kw); } //add keyword if (strlen($kw) > 2) { debug_message('adding keyword: '.$kw.' (length='.strlen($kw).') ; language '.$lang); array_push($lomdata['general']['keyword'], array("string?language=$lang" =>$kw)); } } } //-----general.description (M) //debug_var_dump('this->description', $this->description); //debug_var_dump('this', $this); if (empty($this->description)) { //repeat title in description if empty $_title = ""; if (is_array($this->title)) { $_title = end($this->title); } array_push($this->description, $_title); } //initialize description $lomdata['general']['description'] = array(); foreach ($this->description as $elem) { $lang = 'pt'; array_push($lomdata['general']['description'], array("string?language=$lang" =>$elem)); //add keywords from description if (strlen($elem) > 2) { array_push( $lomdata['general']['keyword'], array("string?language=pt" => implode(', ', array_keys($this->extractCommonWords($elem)))) ); } //debug_var_dump('lomdata->general->keyword', $lomdata['general']['keyword']); } //if after all this keyword is still empty.... if (empty($lomdata['general']['keyword'])) { if (is_array($this->type_) && $this->type_[0] == 'collection') { array_push($lomdata['general']['keyword'], array("string?language=pt" =>'canal')); } else { array_push($lomdata['general']['keyword'], array("string?language=pt" =>'video')); } } //-----general.language (M) if (empty($this->language)) { array_push($this->language, "pt"); } //initialize language $lomdata['general']['language'] = array(); foreach ($this->language as $elem) { array_push($lomdata['general']['language'], $elem); } //-----general.coverage if (!empty($this->coverage)) { $lomdata['general']['coverage'] = array(); foreach ($this->coverage as $elem) { $lang = 'pt'; array_push($lomdata['general']['coverage'], array("string?language=$lang" =>$elem)); } } //-----lifeCycle.contribute (M) if (empty($this->creator) && empty($this->publisher) && empty($this->contributor)) { //set unknown creator array_push($this->creator, "Unknown"); } //intialize contribute $lomdata['lifeCycle']['contribute'] = array(); //---lifeCycle.contribute -> creator if (!empty($this->creator)) { foreach ($this->creator as $elem) { array_push( $lomdata['lifeCycle']['contribute'], array( 'role' => array( 'source' => 'LOMv1.0', 'value' => 'author'), 'entity' => $this->asVcard($elem) ) ); } } //---lifeCycle.contribute -> publisher if (!empty($this->publisher)) { $date = ''; if (!empty($this->date_)) { $date = $this->date_[0]; } foreach ($this->publisher as $elem) { array_push( $lomdata['lifeCycle']['contribute'], array( 'role' => array( 'source' => 'LOMv1.0', 'value' => 'publisher'), 'entity' => $this->asVcard($elem), 'date' => array('dateTime' => $date) ) ); } } //---lifeCycle.contribute -> editor if (!empty($this->contributor)) { foreach ($this->contributor as $elem) { array_push( $lomdata['lifeCycle']['contribute'], array( 'role' => array( 'source' => 'LOMv1.0', 'value' => 'editor'), 'entity' => $this->asVcard($elem) ) ); } } //-----educational.learningResourceType $lomdata['educational']['learningResourceType'] = array( 'source' => 'LOMv1.0', 'value' => 'lecture'); //-----technical.location (M) if (empty($this->source)) { array_push($this->source, "undefined"); } //intialize location $lomdata['technical']['location'] = array(); foreach ($this->source as $elem) { array_push($lomdata['technical']['location'], $elem); } //-----technical.thumbnail (M) if (empty($this->thumbnail)) { array_push($this->thumbnail, 'none'); } $lomdata['technical']['thumbnail'] = $this->thumbnail[0]; //-----technical.format if (!empty($this->format_)) { //initialize format $lomdata['technical']['format'] = array(); foreach ($this->format_ as $elem) { array_push($lomdata['technical']['format'], $elem); } } //-----rights.description if (!empty($this->rights)) { //initialize description $lomdata['rights']['description'] = array(); foreach ($this->rights as $elem) { $lang = 'pt'; array_push($lomdata['rights']['description'], array("string?language=$lang" => $elem)); } } //metaMetadata.identifier $lomdata['metaMetadata']['identifier'] = array( 'catalog' => $lomdata['general']['identifier']['catalog'], 'entry' => $lomdata['general']['identifier']['entry'] ); //relation if (!empty($this->relation)) { foreach ($this->relation as $elem) { array_push($lomdata['relation'], array( 'kind' => array( 'source' => 'LOMv1.0', 'value' => 'ispartof'), 'resource' => array( 'description' => array("string?language=en" => $elem) ) )); } } return $lomdata; }
php
public function to_array() { debug_message('entering function '.__FUNCTION__.' in '.__CLASS__); //lomdata $lomdata = array( 'general' => array( 'identifier' => array( 'catalog' => $this->catalog, 'entry' => $this->identifier ) ),//general 'lifeCycle' => array(), 'educational' => array(), 'technical' => array(), 'rights' => array(), 'classification' => array(), 'metaMetadata' => array(), 'relation' => array() ); //-----general.title (M) if (empty($this->title)) { array_push($this->title, "Untitled"); } $lang = 'pt'; $lomdata['general']['title'] = array("string?language=$lang" => $this->title[0]); //-----general.keyword (M) //initialize keyword //keywords from subject have the form: Language::keyword1$$Language::keyword2 .. $lomdata['general']['keyword'] = array(); foreach ($this->subject as $elem) { $kw_elements = explode('$$', $elem); foreach ($kw_elements as $kw_elem) { $lang_kw = explode('::', $kw_elem); $kw = array_pop($lang_kw); if (empty($lang_kw)) { $lang = 'pt'; } else { $lang = array_pop($lang_kw); } //add keyword if (strlen($kw) > 2) { debug_message('adding keyword: '.$kw.' (length='.strlen($kw).') ; language '.$lang); array_push($lomdata['general']['keyword'], array("string?language=$lang" =>$kw)); } } } //-----general.description (M) //debug_var_dump('this->description', $this->description); //debug_var_dump('this', $this); if (empty($this->description)) { //repeat title in description if empty $_title = ""; if (is_array($this->title)) { $_title = end($this->title); } array_push($this->description, $_title); } //initialize description $lomdata['general']['description'] = array(); foreach ($this->description as $elem) { $lang = 'pt'; array_push($lomdata['general']['description'], array("string?language=$lang" =>$elem)); //add keywords from description if (strlen($elem) > 2) { array_push( $lomdata['general']['keyword'], array("string?language=pt" => implode(', ', array_keys($this->extractCommonWords($elem)))) ); } //debug_var_dump('lomdata->general->keyword', $lomdata['general']['keyword']); } //if after all this keyword is still empty.... if (empty($lomdata['general']['keyword'])) { if (is_array($this->type_) && $this->type_[0] == 'collection') { array_push($lomdata['general']['keyword'], array("string?language=pt" =>'canal')); } else { array_push($lomdata['general']['keyword'], array("string?language=pt" =>'video')); } } //-----general.language (M) if (empty($this->language)) { array_push($this->language, "pt"); } //initialize language $lomdata['general']['language'] = array(); foreach ($this->language as $elem) { array_push($lomdata['general']['language'], $elem); } //-----general.coverage if (!empty($this->coverage)) { $lomdata['general']['coverage'] = array(); foreach ($this->coverage as $elem) { $lang = 'pt'; array_push($lomdata['general']['coverage'], array("string?language=$lang" =>$elem)); } } //-----lifeCycle.contribute (M) if (empty($this->creator) && empty($this->publisher) && empty($this->contributor)) { //set unknown creator array_push($this->creator, "Unknown"); } //intialize contribute $lomdata['lifeCycle']['contribute'] = array(); //---lifeCycle.contribute -> creator if (!empty($this->creator)) { foreach ($this->creator as $elem) { array_push( $lomdata['lifeCycle']['contribute'], array( 'role' => array( 'source' => 'LOMv1.0', 'value' => 'author'), 'entity' => $this->asVcard($elem) ) ); } } //---lifeCycle.contribute -> publisher if (!empty($this->publisher)) { $date = ''; if (!empty($this->date_)) { $date = $this->date_[0]; } foreach ($this->publisher as $elem) { array_push( $lomdata['lifeCycle']['contribute'], array( 'role' => array( 'source' => 'LOMv1.0', 'value' => 'publisher'), 'entity' => $this->asVcard($elem), 'date' => array('dateTime' => $date) ) ); } } //---lifeCycle.contribute -> editor if (!empty($this->contributor)) { foreach ($this->contributor as $elem) { array_push( $lomdata['lifeCycle']['contribute'], array( 'role' => array( 'source' => 'LOMv1.0', 'value' => 'editor'), 'entity' => $this->asVcard($elem) ) ); } } //-----educational.learningResourceType $lomdata['educational']['learningResourceType'] = array( 'source' => 'LOMv1.0', 'value' => 'lecture'); //-----technical.location (M) if (empty($this->source)) { array_push($this->source, "undefined"); } //intialize location $lomdata['technical']['location'] = array(); foreach ($this->source as $elem) { array_push($lomdata['technical']['location'], $elem); } //-----technical.thumbnail (M) if (empty($this->thumbnail)) { array_push($this->thumbnail, 'none'); } $lomdata['technical']['thumbnail'] = $this->thumbnail[0]; //-----technical.format if (!empty($this->format_)) { //initialize format $lomdata['technical']['format'] = array(); foreach ($this->format_ as $elem) { array_push($lomdata['technical']['format'], $elem); } } //-----rights.description if (!empty($this->rights)) { //initialize description $lomdata['rights']['description'] = array(); foreach ($this->rights as $elem) { $lang = 'pt'; array_push($lomdata['rights']['description'], array("string?language=$lang" => $elem)); } } //metaMetadata.identifier $lomdata['metaMetadata']['identifier'] = array( 'catalog' => $lomdata['general']['identifier']['catalog'], 'entry' => $lomdata['general']['identifier']['entry'] ); //relation if (!empty($this->relation)) { foreach ($this->relation as $elem) { array_push($lomdata['relation'], array( 'kind' => array( 'source' => 'LOMv1.0', 'value' => 'ispartof'), 'resource' => array( 'description' => array("string?language=en" => $elem) ) )); } } return $lomdata; }
[ "public", "function", "to_array", "(", ")", "{", "debug_message", "(", "'entering function '", ".", "__FUNCTION__", ".", "' in '", ".", "__CLASS__", ")", ";", "//lomdata", "$", "lomdata", "=", "array", "(", "'general'", "=>", "array", "(", "'identifier'", "=>", "array", "(", "'catalog'", "=>", "$", "this", "->", "catalog", ",", "'entry'", "=>", "$", "this", "->", "identifier", ")", ")", ",", "//general", "'lifeCycle'", "=>", "array", "(", ")", ",", "'educational'", "=>", "array", "(", ")", ",", "'technical'", "=>", "array", "(", ")", ",", "'rights'", "=>", "array", "(", ")", ",", "'classification'", "=>", "array", "(", ")", ",", "'metaMetadata'", "=>", "array", "(", ")", ",", "'relation'", "=>", "array", "(", ")", ")", ";", "//-----general.title (M)", "if", "(", "empty", "(", "$", "this", "->", "title", ")", ")", "{", "array_push", "(", "$", "this", "->", "title", ",", "\"Untitled\"", ")", ";", "}", "$", "lang", "=", "'pt'", ";", "$", "lomdata", "[", "'general'", "]", "[", "'title'", "]", "=", "array", "(", "\"string?language=$lang\"", "=>", "$", "this", "->", "title", "[", "0", "]", ")", ";", "//-----general.keyword (M)", "//initialize keyword", "//keywords from subject have the form: Language::keyword1$$Language::keyword2 ..", "$", "lomdata", "[", "'general'", "]", "[", "'keyword'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "subject", "as", "$", "elem", ")", "{", "$", "kw_elements", "=", "explode", "(", "'$$'", ",", "$", "elem", ")", ";", "foreach", "(", "$", "kw_elements", "as", "$", "kw_elem", ")", "{", "$", "lang_kw", "=", "explode", "(", "'::'", ",", "$", "kw_elem", ")", ";", "$", "kw", "=", "array_pop", "(", "$", "lang_kw", ")", ";", "if", "(", "empty", "(", "$", "lang_kw", ")", ")", "{", "$", "lang", "=", "'pt'", ";", "}", "else", "{", "$", "lang", "=", "array_pop", "(", "$", "lang_kw", ")", ";", "}", "//add keyword", "if", "(", "strlen", "(", "$", "kw", ")", ">", "2", ")", "{", "debug_message", "(", "'adding keyword: '", ".", "$", "kw", ".", "' (length='", ".", "strlen", "(", "$", "kw", ")", ".", "') ; language '", ".", "$", "lang", ")", ";", "array_push", "(", "$", "lomdata", "[", "'general'", "]", "[", "'keyword'", "]", ",", "array", "(", "\"string?language=$lang\"", "=>", "$", "kw", ")", ")", ";", "}", "}", "}", "//-----general.description (M)", "//debug_var_dump('this->description', $this->description);", "//debug_var_dump('this', $this);", "if", "(", "empty", "(", "$", "this", "->", "description", ")", ")", "{", "//repeat title in description if empty", "$", "_title", "=", "\"\"", ";", "if", "(", "is_array", "(", "$", "this", "->", "title", ")", ")", "{", "$", "_title", "=", "end", "(", "$", "this", "->", "title", ")", ";", "}", "array_push", "(", "$", "this", "->", "description", ",", "$", "_title", ")", ";", "}", "//initialize description", "$", "lomdata", "[", "'general'", "]", "[", "'description'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "description", "as", "$", "elem", ")", "{", "$", "lang", "=", "'pt'", ";", "array_push", "(", "$", "lomdata", "[", "'general'", "]", "[", "'description'", "]", ",", "array", "(", "\"string?language=$lang\"", "=>", "$", "elem", ")", ")", ";", "//add keywords from description", "if", "(", "strlen", "(", "$", "elem", ")", ">", "2", ")", "{", "array_push", "(", "$", "lomdata", "[", "'general'", "]", "[", "'keyword'", "]", ",", "array", "(", "\"string?language=pt\"", "=>", "implode", "(", "', '", ",", "array_keys", "(", "$", "this", "->", "extractCommonWords", "(", "$", "elem", ")", ")", ")", ")", ")", ";", "}", "//debug_var_dump('lomdata->general->keyword', $lomdata['general']['keyword']);", "}", "//if after all this keyword is still empty....", "if", "(", "empty", "(", "$", "lomdata", "[", "'general'", "]", "[", "'keyword'", "]", ")", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "type_", ")", "&&", "$", "this", "->", "type_", "[", "0", "]", "==", "'collection'", ")", "{", "array_push", "(", "$", "lomdata", "[", "'general'", "]", "[", "'keyword'", "]", ",", "array", "(", "\"string?language=pt\"", "=>", "'canal'", ")", ")", ";", "}", "else", "{", "array_push", "(", "$", "lomdata", "[", "'general'", "]", "[", "'keyword'", "]", ",", "array", "(", "\"string?language=pt\"", "=>", "'video'", ")", ")", ";", "}", "}", "//-----general.language (M)", "if", "(", "empty", "(", "$", "this", "->", "language", ")", ")", "{", "array_push", "(", "$", "this", "->", "language", ",", "\"pt\"", ")", ";", "}", "//initialize language", "$", "lomdata", "[", "'general'", "]", "[", "'language'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "language", "as", "$", "elem", ")", "{", "array_push", "(", "$", "lomdata", "[", "'general'", "]", "[", "'language'", "]", ",", "$", "elem", ")", ";", "}", "//-----general.coverage", "if", "(", "!", "empty", "(", "$", "this", "->", "coverage", ")", ")", "{", "$", "lomdata", "[", "'general'", "]", "[", "'coverage'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "coverage", "as", "$", "elem", ")", "{", "$", "lang", "=", "'pt'", ";", "array_push", "(", "$", "lomdata", "[", "'general'", "]", "[", "'coverage'", "]", ",", "array", "(", "\"string?language=$lang\"", "=>", "$", "elem", ")", ")", ";", "}", "}", "//-----lifeCycle.contribute (M)", "if", "(", "empty", "(", "$", "this", "->", "creator", ")", "&&", "empty", "(", "$", "this", "->", "publisher", ")", "&&", "empty", "(", "$", "this", "->", "contributor", ")", ")", "{", "//set unknown creator", "array_push", "(", "$", "this", "->", "creator", ",", "\"Unknown\"", ")", ";", "}", "//intialize contribute", "$", "lomdata", "[", "'lifeCycle'", "]", "[", "'contribute'", "]", "=", "array", "(", ")", ";", "//---lifeCycle.contribute -> creator", "if", "(", "!", "empty", "(", "$", "this", "->", "creator", ")", ")", "{", "foreach", "(", "$", "this", "->", "creator", "as", "$", "elem", ")", "{", "array_push", "(", "$", "lomdata", "[", "'lifeCycle'", "]", "[", "'contribute'", "]", ",", "array", "(", "'role'", "=>", "array", "(", "'source'", "=>", "'LOMv1.0'", ",", "'value'", "=>", "'author'", ")", ",", "'entity'", "=>", "$", "this", "->", "asVcard", "(", "$", "elem", ")", ")", ")", ";", "}", "}", "//---lifeCycle.contribute -> publisher", "if", "(", "!", "empty", "(", "$", "this", "->", "publisher", ")", ")", "{", "$", "date", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "date_", ")", ")", "{", "$", "date", "=", "$", "this", "->", "date_", "[", "0", "]", ";", "}", "foreach", "(", "$", "this", "->", "publisher", "as", "$", "elem", ")", "{", "array_push", "(", "$", "lomdata", "[", "'lifeCycle'", "]", "[", "'contribute'", "]", ",", "array", "(", "'role'", "=>", "array", "(", "'source'", "=>", "'LOMv1.0'", ",", "'value'", "=>", "'publisher'", ")", ",", "'entity'", "=>", "$", "this", "->", "asVcard", "(", "$", "elem", ")", ",", "'date'", "=>", "array", "(", "'dateTime'", "=>", "$", "date", ")", ")", ")", ";", "}", "}", "//---lifeCycle.contribute -> editor", "if", "(", "!", "empty", "(", "$", "this", "->", "contributor", ")", ")", "{", "foreach", "(", "$", "this", "->", "contributor", "as", "$", "elem", ")", "{", "array_push", "(", "$", "lomdata", "[", "'lifeCycle'", "]", "[", "'contribute'", "]", ",", "array", "(", "'role'", "=>", "array", "(", "'source'", "=>", "'LOMv1.0'", ",", "'value'", "=>", "'editor'", ")", ",", "'entity'", "=>", "$", "this", "->", "asVcard", "(", "$", "elem", ")", ")", ")", ";", "}", "}", "//-----educational.learningResourceType", "$", "lomdata", "[", "'educational'", "]", "[", "'learningResourceType'", "]", "=", "array", "(", "'source'", "=>", "'LOMv1.0'", ",", "'value'", "=>", "'lecture'", ")", ";", "//-----technical.location (M)", "if", "(", "empty", "(", "$", "this", "->", "source", ")", ")", "{", "array_push", "(", "$", "this", "->", "source", ",", "\"undefined\"", ")", ";", "}", "//intialize location", "$", "lomdata", "[", "'technical'", "]", "[", "'location'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "source", "as", "$", "elem", ")", "{", "array_push", "(", "$", "lomdata", "[", "'technical'", "]", "[", "'location'", "]", ",", "$", "elem", ")", ";", "}", "//-----technical.thumbnail (M)", "if", "(", "empty", "(", "$", "this", "->", "thumbnail", ")", ")", "{", "array_push", "(", "$", "this", "->", "thumbnail", ",", "'none'", ")", ";", "}", "$", "lomdata", "[", "'technical'", "]", "[", "'thumbnail'", "]", "=", "$", "this", "->", "thumbnail", "[", "0", "]", ";", "//-----technical.format", "if", "(", "!", "empty", "(", "$", "this", "->", "format_", ")", ")", "{", "//initialize format", "$", "lomdata", "[", "'technical'", "]", "[", "'format'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "format_", "as", "$", "elem", ")", "{", "array_push", "(", "$", "lomdata", "[", "'technical'", "]", "[", "'format'", "]", ",", "$", "elem", ")", ";", "}", "}", "//-----rights.description", "if", "(", "!", "empty", "(", "$", "this", "->", "rights", ")", ")", "{", "//initialize description", "$", "lomdata", "[", "'rights'", "]", "[", "'description'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "rights", "as", "$", "elem", ")", "{", "$", "lang", "=", "'pt'", ";", "array_push", "(", "$", "lomdata", "[", "'rights'", "]", "[", "'description'", "]", ",", "array", "(", "\"string?language=$lang\"", "=>", "$", "elem", ")", ")", ";", "}", "}", "//metaMetadata.identifier", "$", "lomdata", "[", "'metaMetadata'", "]", "[", "'identifier'", "]", "=", "array", "(", "'catalog'", "=>", "$", "lomdata", "[", "'general'", "]", "[", "'identifier'", "]", "[", "'catalog'", "]", ",", "'entry'", "=>", "$", "lomdata", "[", "'general'", "]", "[", "'identifier'", "]", "[", "'entry'", "]", ")", ";", "//relation", "if", "(", "!", "empty", "(", "$", "this", "->", "relation", ")", ")", "{", "foreach", "(", "$", "this", "->", "relation", "as", "$", "elem", ")", "{", "array_push", "(", "$", "lomdata", "[", "'relation'", "]", ",", "array", "(", "'kind'", "=>", "array", "(", "'source'", "=>", "'LOMv1.0'", ",", "'value'", "=>", "'ispartof'", ")", ",", "'resource'", "=>", "array", "(", "'description'", "=>", "array", "(", "\"string?language=en\"", "=>", "$", "elem", ")", ")", ")", ")", ";", "}", "}", "return", "$", "lomdata", ";", "}" ]
puts db information in LOM format as an array
[ "puts", "db", "information", "in", "LOM", "format", "as", "an", "array" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_lom.php#L376-L579
fccn/oai-pmh-core
src/schemas/ands_lom.php
LOM_DataHolder.asVcard
private function asVcard($name) { $name = preg_replace('/\s\s+/i', '', $name); //remove extra white spaces $name = preg_replace('/[^A-Za-z0-9\x{002D}\x{002E}\x{00C0}-\x{00FF} -]/', '', $name); //remove special chars $name = trim($name); // trim $nm_expl = explode(' ', $name); $head = ''; if (in_array($nm_expl[0], array('Prof.', 'Professor', 'Dr.', 'Doutor' ))) { $head = array_shift($nm_expl); } $lastnm = array_pop($nm_expl); $n = $lastnm.';'.implode(' ', $nm_expl).';'.$head.';'; return "BEGIN:VCARD\nVERSION:4.0\nN:$n\nFN:$name\nEND:VCARD"; }
php
private function asVcard($name) { $name = preg_replace('/\s\s+/i', '', $name); //remove extra white spaces $name = preg_replace('/[^A-Za-z0-9\x{002D}\x{002E}\x{00C0}-\x{00FF} -]/', '', $name); //remove special chars $name = trim($name); // trim $nm_expl = explode(' ', $name); $head = ''; if (in_array($nm_expl[0], array('Prof.', 'Professor', 'Dr.', 'Doutor' ))) { $head = array_shift($nm_expl); } $lastnm = array_pop($nm_expl); $n = $lastnm.';'.implode(' ', $nm_expl).';'.$head.';'; return "BEGIN:VCARD\nVERSION:4.0\nN:$n\nFN:$name\nEND:VCARD"; }
[ "private", "function", "asVcard", "(", "$", "name", ")", "{", "$", "name", "=", "preg_replace", "(", "'/\\s\\s+/i'", ",", "''", ",", "$", "name", ")", ";", "//remove extra white spaces", "$", "name", "=", "preg_replace", "(", "'/[^A-Za-z0-9\\x{002D}\\x{002E}\\x{00C0}-\\x{00FF} -]/'", ",", "''", ",", "$", "name", ")", ";", "//remove special chars", "$", "name", "=", "trim", "(", "$", "name", ")", ";", "// trim", "$", "nm_expl", "=", "explode", "(", "' '", ",", "$", "name", ")", ";", "$", "head", "=", "''", ";", "if", "(", "in_array", "(", "$", "nm_expl", "[", "0", "]", ",", "array", "(", "'Prof.'", ",", "'Professor'", ",", "'Dr.'", ",", "'Doutor'", ")", ")", ")", "{", "$", "head", "=", "array_shift", "(", "$", "nm_expl", ")", ";", "}", "$", "lastnm", "=", "array_pop", "(", "$", "nm_expl", ")", ";", "$", "n", "=", "$", "lastnm", ".", "';'", ".", "implode", "(", "' '", ",", "$", "nm_expl", ")", ".", "';'", ".", "$", "head", ".", "';'", ";", "return", "\"BEGIN:VCARD\\nVERSION:4.0\\nN:$n\\nFN:$name\\nEND:VCARD\"", ";", "}" ]
turns the elements into a string formatted for VCard
[ "turns", "the", "elements", "into", "a", "string", "formatted", "for", "VCard" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_lom.php#L582-L595
fccn/oai-pmh-core
src/schemas/ands_lom.php
LOM_DataHolder.extractCommonWords
private function extractCommonWords($string) { debug_message('entering function '.__FUNCTION__.' in '.__CLASS__); $stopWords = array('i','a','about','an','and','-and-','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the', 'de', 'a', 'o', 'que', 'e', 'do', 'da', 'em', 'um', 'para', 'é', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'foi', 'ao', 'ele', 'das', 'tem', 'à', 'seu', 'sua', 'ou', 'ser', 'quando', 'muito', 'há', 'nos', 'já', 'está', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'era', 'depois', 'sem', 'mesmo', 'aos', 'ter', 'seus', 'quem', 'nas', 'me', 'esse', 'eles', 'estão', 'você', 'tinha', 'foram', 'essa', 'num', 'nem', 'suas', 'meu', 'às', 'minha', 'têm', 'numa', 'pelos', 'elas', 'havia', 'seja', 'qual', 'será', 'nós', 'tenho', 'lhe', 'deles', 'essas', 'esses', 'pelas', 'este', 'fosse', 'dele', 'tu', 'te', 'vocês', 'vos', 'lhes', 'meus', 'minhas','teu', 'tua', 'teus', 'tuas', 'nosso', 'nossa', 'nossos', 'nossas', 'dela', 'delas', 'esta', 'estes', 'estas', 'aquele', 'aquela', 'aqueles', 'aquelas', 'isto', 'aquilo', 'estou', 'está', 'estamos', 'estão', 'estive', 'esteve', 'estivemos', 'estiveram', 'estava', 'estávamos', 'estavam', 'estivera', 'estivéramos', 'esteja', 'estejamos', 'estejam', 'estivesse', 'estivéssemos', 'estivessem', 'estiver', 'estivermos', 'estiverem', 'hei', 'há', 'havemos', 'hão', 'houve', 'houvemos', 'houveram', 'houvera', 'houvéramos', 'haja', 'hajamos', 'hajam', 'houvesse', 'houvéssemos', 'houvessem', 'houver', 'houvermos', 'houverem', 'houverei', 'houverá', 'houveremos', 'houverão', 'houveria', 'houveríamos', 'houveriam', 'sou', 'somos', 'são', 'era', 'éramos', 'eram', 'fui', 'foi', 'fomos', 'foram', 'fora', 'fôramos', 'seja', 'sejamos', 'sejam', 'fosse', 'fôssemos', 'fossem', 'for', 'formos', 'forem', 'serei', 'será', 'seremos', 'serão', 'seria', 'seríamos', 'seriam', 'tenho', 'tem', 'temos', 'tém', 'tinha', 'tínhamos', 'tinham', 'tive', 'teve', 'tivemos', 'tiveram', 'tivera', 'tivéramos', 'tenha', 'tenhamos', 'tenham', 'tivesse', 'tivéssemos', 'tivessem', 'tiver', 'tivermos', 'tiverem', 'terei', 'terá', 'teremos', 'terão', 'teria', 'teríamos', 'teriam'); //debug_var_dump('string0', $string); //$string = utf8_encode($string); //debug_var_dump('string1', $string); $string = preg_replace('/\s\s+/i', '', $string); // replace whitespace //debug_var_dump('string2', $string); $string = trim($string); // trim the string //debug_var_dump('string3', $string); $string = preg_replace('/[^A-Za-z0-9\x{002D}\x{002E}\x{00C0}-\x{00FF} -]/', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too… // debug_var_dump('string4', $string); $string = strtolower($string); // make it lowercase // debug_var_dump('string5', $string); // preg_match_all('/\b.*?\b/U', $string, $matchWords); // $matchWords = $matchWords[0]; // debug_var_dump('matchwords', $matchWords); $wordCountArr = array(); foreach (explode(' ', $string) as $word) { if ($word !== '' && !in_array(strtolower($word), $stopWords) && strlen($word) >= 3) { if (array_key_exists($word, $wordCountArr)) { $wordCountArr[$word]++; } else { $wordCountArr[$word] = 1; } //debug_var_dump('wordCountArr', $wordCountArr); } } // foreach ( $matchWords as $key=>$item ) { // if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) { // unset($matchWords[$key]); // } // } // $wordCountArr = array(); // if ( is_array($matchWords) ) { // foreach ( $matchWords as $key => $val ) { // $val = strtolower($val); // if ( isset($wordCountArr[$val]) ) { // $wordCountArr[$val]++; // } else { // $wordCountArr[$val] = 1; // } // } // } arsort($wordCountArr); //debug_var_dump('wordCountArr', $wordCountArr); $wordCountArr = array_slice($wordCountArr, 0, 10); return $wordCountArr; }
php
private function extractCommonWords($string) { debug_message('entering function '.__FUNCTION__.' in '.__CLASS__); $stopWords = array('i','a','about','an','and','-and-','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the', 'de', 'a', 'o', 'que', 'e', 'do', 'da', 'em', 'um', 'para', 'é', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'foi', 'ao', 'ele', 'das', 'tem', 'à', 'seu', 'sua', 'ou', 'ser', 'quando', 'muito', 'há', 'nos', 'já', 'está', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'era', 'depois', 'sem', 'mesmo', 'aos', 'ter', 'seus', 'quem', 'nas', 'me', 'esse', 'eles', 'estão', 'você', 'tinha', 'foram', 'essa', 'num', 'nem', 'suas', 'meu', 'às', 'minha', 'têm', 'numa', 'pelos', 'elas', 'havia', 'seja', 'qual', 'será', 'nós', 'tenho', 'lhe', 'deles', 'essas', 'esses', 'pelas', 'este', 'fosse', 'dele', 'tu', 'te', 'vocês', 'vos', 'lhes', 'meus', 'minhas','teu', 'tua', 'teus', 'tuas', 'nosso', 'nossa', 'nossos', 'nossas', 'dela', 'delas', 'esta', 'estes', 'estas', 'aquele', 'aquela', 'aqueles', 'aquelas', 'isto', 'aquilo', 'estou', 'está', 'estamos', 'estão', 'estive', 'esteve', 'estivemos', 'estiveram', 'estava', 'estávamos', 'estavam', 'estivera', 'estivéramos', 'esteja', 'estejamos', 'estejam', 'estivesse', 'estivéssemos', 'estivessem', 'estiver', 'estivermos', 'estiverem', 'hei', 'há', 'havemos', 'hão', 'houve', 'houvemos', 'houveram', 'houvera', 'houvéramos', 'haja', 'hajamos', 'hajam', 'houvesse', 'houvéssemos', 'houvessem', 'houver', 'houvermos', 'houverem', 'houverei', 'houverá', 'houveremos', 'houverão', 'houveria', 'houveríamos', 'houveriam', 'sou', 'somos', 'são', 'era', 'éramos', 'eram', 'fui', 'foi', 'fomos', 'foram', 'fora', 'fôramos', 'seja', 'sejamos', 'sejam', 'fosse', 'fôssemos', 'fossem', 'for', 'formos', 'forem', 'serei', 'será', 'seremos', 'serão', 'seria', 'seríamos', 'seriam', 'tenho', 'tem', 'temos', 'tém', 'tinha', 'tínhamos', 'tinham', 'tive', 'teve', 'tivemos', 'tiveram', 'tivera', 'tivéramos', 'tenha', 'tenhamos', 'tenham', 'tivesse', 'tivéssemos', 'tivessem', 'tiver', 'tivermos', 'tiverem', 'terei', 'terá', 'teremos', 'terão', 'teria', 'teríamos', 'teriam'); //debug_var_dump('string0', $string); //$string = utf8_encode($string); //debug_var_dump('string1', $string); $string = preg_replace('/\s\s+/i', '', $string); // replace whitespace //debug_var_dump('string2', $string); $string = trim($string); // trim the string //debug_var_dump('string3', $string); $string = preg_replace('/[^A-Za-z0-9\x{002D}\x{002E}\x{00C0}-\x{00FF} -]/', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too… // debug_var_dump('string4', $string); $string = strtolower($string); // make it lowercase // debug_var_dump('string5', $string); // preg_match_all('/\b.*?\b/U', $string, $matchWords); // $matchWords = $matchWords[0]; // debug_var_dump('matchwords', $matchWords); $wordCountArr = array(); foreach (explode(' ', $string) as $word) { if ($word !== '' && !in_array(strtolower($word), $stopWords) && strlen($word) >= 3) { if (array_key_exists($word, $wordCountArr)) { $wordCountArr[$word]++; } else { $wordCountArr[$word] = 1; } //debug_var_dump('wordCountArr', $wordCountArr); } } // foreach ( $matchWords as $key=>$item ) { // if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) { // unset($matchWords[$key]); // } // } // $wordCountArr = array(); // if ( is_array($matchWords) ) { // foreach ( $matchWords as $key => $val ) { // $val = strtolower($val); // if ( isset($wordCountArr[$val]) ) { // $wordCountArr[$val]++; // } else { // $wordCountArr[$val] = 1; // } // } // } arsort($wordCountArr); //debug_var_dump('wordCountArr', $wordCountArr); $wordCountArr = array_slice($wordCountArr, 0, 10); return $wordCountArr; }
[ "private", "function", "extractCommonWords", "(", "$", "string", ")", "{", "debug_message", "(", "'entering function '", ".", "__FUNCTION__", ".", "' in '", ".", "__CLASS__", ")", ";", "$", "stopWords", "=", "array", "(", "'i'", ",", "'a'", ",", "'about'", ",", "'an'", ",", "'and'", ",", "'-and-'", ",", "'are'", ",", "'as'", ",", "'at'", ",", "'be'", ",", "'by'", ",", "'com'", ",", "'de'", ",", "'en'", ",", "'for'", ",", "'from'", ",", "'how'", ",", "'in'", ",", "'is'", ",", "'it'", ",", "'la'", ",", "'of'", ",", "'on'", ",", "'or'", ",", "'that'", ",", "'the'", ",", "'this'", ",", "'to'", ",", "'was'", ",", "'what'", ",", "'when'", ",", "'where'", ",", "'who'", ",", "'will'", ",", "'with'", ",", "'und'", ",", "'the'", ",", "'de'", ",", "'a'", ",", "'o'", ",", "'que'", ",", "'e'", ",", "'do'", ",", "'da'", ",", "'em'", ",", "'um'", ",", "'para'", ",", "'é',", " ", "com',", " ", "não', ", "'", "ma', ", "'", "s', ", "'", "o', ", "'", "e', ", "'", "a', ", "'", "or', ", "'", "ais', ", "'", "s', ", "'", "os', ", "'", "omo', ", "'", "as', ", "'", "oi', ", "'", "o', ", "'", "le', ", "'", "as', ", "'", "em', ", "'", "', '", "s", "u', '", "s", "a',", "", "'ou'", ",", "'ser'", ",", "'quando'", ",", "'muito'", ",", "'há',", " ", "nos',", " ", "já', ", "'", "stá', '", "e", "', '", "t", "mbém', 's", "ó", ", 'pe", "l", "', 'pe", "l", "', 'at", "é", ", 'iss", "o", ", 'ela", "'", " 'ent", "r", "', 'era", "'", " 'dep", "o", "s', 'sem", "'", " 'mes", "m", "', 'aos", "'", " 'ter", "'", " 'seu", "s", ", 'que", "m", ", 'nas", "'", " 'me'", ",", "", "", "'esse'", ",", "'eles'", ",", "'estão',", " ", "você', ", "'", "inha', ", "'", "oram', ", "'", "ssa', ", "'", "um', ", "'", "em', ", "'", "uas', ", "'", "eu', ", "'", "s', '", "m", "nha', '", "t", "m', 'n", "u", "a', 'p", "e", "os', 'e", "l", "s', 'h", "a", "ia', 's", "e", "a', 'q", "u", "l', 's", "e", "á', 'nó", "s", ", 'ten", "h", "', 'lhe", "'", " 'del", "e", "', 'ess", "a", "',", "", "'esses'", ",", "'pelas'", ",", "'este'", ",", "'fosse'", ",", "'dele'", ",", "'tu'", ",", "'te'", ",", "'vocês',", " ", "vos',", " ", "lhes',", " ", "meus',", " ", "minhas',", "'", "teu',", " ", "tua',", " ", "teus',", " ", "tuas',", " ", "nosso',", " ", "nossa',", " ", "nossos',", " ", "nossas',", " ", "dela',", " ", "delas',", " ", "esta',", " ", "estes',", " ", "estas',", "", "'aquele'", ",", "'aquela'", ",", "'aqueles'", ",", "'aquelas'", ",", "'isto'", ",", "'aquilo'", ",", "'estou'", ",", "'está',", " ", "estamos',", " ", "estão', ", "'", "stive', ", "'", "steve', ", "'", "stivemos', ", "'", "stiveram', ", "'", "stava', ", "'", "stávamos', '", "e", "tavam', '", "e", "tivera', '", "e", "tivéramos', 'e", "s", "eja',", "", "'estejamos'", ",", "'estejam'", ",", "'estivesse'", ",", "'estivéssemos',", " ", "estivessem',", " ", "estiver',", " ", "estivermos',", " ", "estiverem',", " ", "hei',", " ", "há', ", "'", "avemos', ", "'", "ão', '", "h", "uve', '", "h", "uvemos', '", "h", "uveram', '", "h", "uvera', '", "h", "uvéramos', 'h", "a", "a', 'h", "a", "amos',", "", "'hajam'", ",", "'houvesse'", ",", "'houvéssemos',", " ", "houvessem',", " ", "houver',", " ", "houvermos',", " ", "houverem',", " ", "houverei',", " ", "houverá', ", "'", "ouveremos', ", "'", "ouverão', '", "h", "uveria', '", "h", "uveríamos', 'h", "o", "veriam', 's", "o", "', 's", "o", "os', 's", "ã", "', 'er", "a", ", 'ér", "a", "os',", "", "'eram'", ",", "'fui'", ",", "'foi'", ",", "'fomos'", ",", "'foram'", ",", "'fora'", ",", "'fôramos',", " ", "seja',", " ", "sejamos',", " ", "sejam',", " ", "fosse',", " ", "fôssemos', ", "'", "ossem', ", "'", "or', ", "'", "ormos', ", "'", "orem', ", "'", "erei', ", "'", "erá', '", "s", "remos', '", "s", "rão', 's", "e", "ia', 's", "e", "íamos', 'se", "r", "am',", "", "'tenho'", ",", "'tem'", ",", "'temos'", ",", "'tém',", " ", "tinha',", " ", "tínhamos', ", "'", "inham', ", "'", "ive', ", "'", "eve', ", "'", "ivemos', ", "'", "iveram', ", "'", "ivera', ", "'", "ivéramos', '", "t", "nha', '", "t", "nhamos', '", "t", "nham', '", "t", "vesse', '", "t", "véssemos', 't", "i", "essem', 't", "i", "er', 't", "i", "ermos',", "", "'tiverem'", ",", "'terei'", ",", "'terá',", " ", "teremos',", " ", "terão', ", "'", "eria', ", "'", "eríamos', '", "t", "riam');", "", "", "//debug_var_dump('string0', $string);", "//$string = utf8_encode($string);", "//debug_var_dump('string1', $string);", "$", "string", "=", "preg_replace", "(", "'/\\s\\s+/i'", ",", "''", ",", "$", "string", ")", ";", "// replace whitespace", "//debug_var_dump('string2', $string);", "$", "string", "=", "trim", "(", "$", "string", ")", ";", "// trim the string", "//debug_var_dump('string3', $string);", "$", "string", "=", "preg_replace", "(", "'/[^A-Za-z0-9\\x{002D}\\x{002E}\\x{00C0}-\\x{00FF} -]/'", ",", "''", ",", "$", "string", ")", ";", "// only take alphanumerical characters, but keep the spaces and dashes too…", "// debug_var_dump('string4', $string);", "$", "string", "=", "strtolower", "(", "$", "string", ")", ";", "// make it lowercase", "// debug_var_dump('string5', $string);", "// preg_match_all('/\\b.*?\\b/U', $string, $matchWords);", "// $matchWords = $matchWords[0];", "// debug_var_dump('matchwords', $matchWords);", "$", "wordCountArr", "=", "array", "(", ")", ";", "foreach", "(", "explode", "(", "' '", ",", "$", "string", ")", "as", "$", "word", ")", "{", "if", "(", "$", "word", "!==", "''", "&&", "!", "in_array", "(", "strtolower", "(", "$", "word", ")", ",", "$", "stopWords", ")", "&&", "strlen", "(", "$", "word", ")", ">=", "3", ")", "{", "if", "(", "array_key_exists", "(", "$", "word", ",", "$", "wordCountArr", ")", ")", "{", "$", "wordCountArr", "[", "$", "word", "]", "++", ";", "}", "else", "{", "$", "wordCountArr", "[", "$", "word", "]", "=", "1", ";", "}", "//debug_var_dump('wordCountArr', $wordCountArr);", "}", "}", "// foreach ( $matchWords as $key=>$item ) {", "// if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {", "// unset($matchWords[$key]);", "// }", "// }", "// $wordCountArr = array();", "// if ( is_array($matchWords) ) {", "// foreach ( $matchWords as $key => $val ) {", "// $val = strtolower($val);", "// if ( isset($wordCountArr[$val]) ) {", "// $wordCountArr[$val]++;", "// } else {", "// $wordCountArr[$val] = 1;", "// }", "// }", "// }", "arsort", "(", "$", "wordCountArr", ")", ";", "//debug_var_dump('wordCountArr', $wordCountArr);", "$", "wordCountArr", "=", "array_slice", "(", "$", "wordCountArr", ",", "0", ",", "10", ")", ";", "return", "$", "wordCountArr", ";", "}" ]
TODO include this in keyword generation
[ "TODO", "include", "this", "in", "keyword", "generation" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/schemas/ands_lom.php#L598-L661
php-lug/lug
src/Bundle/ResourceBundle/DataFixtures/ORM/AbstractDriverFixture.php
AbstractDriverFixture.load
public function load(ObjectManager $manager) { if ($this->getResource()->getDriver() === $this->getDriver()) { $this->doLoad($manager); } }
php
public function load(ObjectManager $manager) { if ($this->getResource()->getDriver() === $this->getDriver()) { $this->doLoad($manager); } }
[ "public", "function", "load", "(", "ObjectManager", "$", "manager", ")", "{", "if", "(", "$", "this", "->", "getResource", "(", ")", "->", "getDriver", "(", ")", "===", "$", "this", "->", "getDriver", "(", ")", ")", "{", "$", "this", "->", "doLoad", "(", "$", "manager", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/DataFixtures/ORM/AbstractDriverFixture.php#L24-L29
Laralum/Events
src/Migrations/2017_04_30_233148_create_laralum_events.php
CreateLaralumEvents.up
public function up() { Schema::create('laralum_events', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->string('title'); $table->string('color')->nullable(); $table->string('place')->nullable(); $table->text('description'); $table->boolean('public'); $table->date('start_date'); $table->time('start_time'); $table->date('end_date'); $table->time('end_time'); $table->decimal('price', 11, 2); $table->timestamps(); }); }
php
public function up() { Schema::create('laralum_events', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->string('title'); $table->string('color')->nullable(); $table->string('place')->nullable(); $table->text('description'); $table->boolean('public'); $table->date('start_date'); $table->time('start_time'); $table->date('end_date'); $table->time('end_time'); $table->decimal('price', 11, 2); $table->timestamps(); }); }
[ "public", "function", "up", "(", ")", "{", "Schema", "::", "create", "(", "'laralum_events'", ",", "function", "(", "Blueprint", "$", "table", ")", "{", "$", "table", "->", "increments", "(", "'id'", ")", ";", "$", "table", "->", "integer", "(", "'user_id'", ")", ";", "$", "table", "->", "string", "(", "'title'", ")", ";", "$", "table", "->", "string", "(", "'color'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "string", "(", "'place'", ")", "->", "nullable", "(", ")", ";", "$", "table", "->", "text", "(", "'description'", ")", ";", "$", "table", "->", "boolean", "(", "'public'", ")", ";", "$", "table", "->", "date", "(", "'start_date'", ")", ";", "$", "table", "->", "time", "(", "'start_time'", ")", ";", "$", "table", "->", "date", "(", "'end_date'", ")", ";", "$", "table", "->", "time", "(", "'end_time'", ")", ";", "$", "table", "->", "decimal", "(", "'price'", ",", "11", ",", "2", ")", ";", "$", "table", "->", "timestamps", "(", ")", ";", "}", ")", ";", "}" ]
Run the migrations. @return void
[ "Run", "the", "migrations", "." ]
train
https://github.com/Laralum/Events/blob/9dc36468f4253e7d040863a115ea94cded0e6aa5/src/Migrations/2017_04_30_233148_create_laralum_events.php#L14-L31
inhere/php-librarys
src/Files/Directory.php
Directory.simpleInfo
public static function simpleInfo($dir, $ext = null, $recursive = false): array { $list = []; $dir = self::pathFormat($dir); $ext = \is_array($ext) ? implode('|', $ext) : trim($ext); if (!is_dir($dir)) { throw new NotFoundException("directory not exists! DIR: $dir"); } // glob()寻找与模式匹配的文件路径 $file is pull path foreach (glob($dir . '*') as $file) { // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 if (is_file($file) && (!$ext || preg_match("/\.($ext)$/i", $file))) { //basename — 返回路径中的 文件名部分 $list[] = basename($file); // is directory } else { $list[] = '/' . basename($file); if ($recursive) { $list = array_merge($list, self::simpleInfo($file, $ext, $recursive)); } } } return $list; }
php
public static function simpleInfo($dir, $ext = null, $recursive = false): array { $list = []; $dir = self::pathFormat($dir); $ext = \is_array($ext) ? implode('|', $ext) : trim($ext); if (!is_dir($dir)) { throw new NotFoundException("directory not exists! DIR: $dir"); } // glob()寻找与模式匹配的文件路径 $file is pull path foreach (glob($dir . '*') as $file) { // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 if (is_file($file) && (!$ext || preg_match("/\.($ext)$/i", $file))) { //basename — 返回路径中的 文件名部分 $list[] = basename($file); // is directory } else { $list[] = '/' . basename($file); if ($recursive) { $list = array_merge($list, self::simpleInfo($file, $ext, $recursive)); } } } return $list; }
[ "public", "static", "function", "simpleInfo", "(", "$", "dir", ",", "$", "ext", "=", "null", ",", "$", "recursive", "=", "false", ")", ":", "array", "{", "$", "list", "=", "[", "]", ";", "$", "dir", "=", "self", "::", "pathFormat", "(", "$", "dir", ")", ";", "$", "ext", "=", "\\", "is_array", "(", "$", "ext", ")", "?", "implode", "(", "'|'", ",", "$", "ext", ")", ":", "trim", "(", "$", "ext", ")", ";", "if", "(", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"directory not exists! DIR: $dir\"", ")", ";", "}", "// glob()寻找与模式匹配的文件路径 $file is pull path", "foreach", "(", "glob", "(", "$", "dir", ".", "'*'", ")", "as", "$", "file", ")", "{", "// 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找", "if", "(", "is_file", "(", "$", "file", ")", "&&", "(", "!", "$", "ext", "||", "preg_match", "(", "\"/\\.($ext)$/i\"", ",", "$", "file", ")", ")", ")", "{", "//basename — 返回路径中的 文件名部分", "$", "list", "[", "]", "=", "basename", "(", "$", "file", ")", ";", "// is directory", "}", "else", "{", "$", "list", "[", "]", "=", "'/'", ".", "basename", "(", "$", "file", ")", ";", "if", "(", "$", "recursive", ")", "{", "$", "list", "=", "array_merge", "(", "$", "list", ",", "self", "::", "simpleInfo", "(", "$", "file", ",", "$", "ext", ",", "$", "recursive", ")", ")", ";", "}", "}", "}", "return", "$", "list", ";", "}" ]
获得目录下的文件,可选择类型、是否遍历子文件夹 @param string $dir string 目标目录 @param string|array $ext array('css','html','php') css|html|php @param bool $recursive int|bool 是否包含子目录 @return array @throws NotFoundException
[ "获得目录下的文件,可选择类型、是否遍历子文件夹" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/Directory.php#L183-L212
inhere/php-librarys
src/Files/Directory.php
Directory.getFiles
public static function getFiles($path, $ext = null, $recursive = false, $parent = null, array $list = []): array { $path = self::pathFormat($path); if (!is_dir($path)) { throw new NotFoundException("directory not exists! DIR: $path"); } $len = \strlen($path); $ext = \is_array($ext) ? implode('|', $ext) : trim($ext); foreach (glob($path . '*') as $v) { $relatePath = substr($v, $len); // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 if (is_file($v) && (!$ext || preg_match("/\.($ext)$/i", $v))) { $list[] = $parent . $relatePath; } elseif ($recursive) { $list = self::getFiles($v, $ext, $recursive, $relatePath . '/', $list); } } return $list; }
php
public static function getFiles($path, $ext = null, $recursive = false, $parent = null, array $list = []): array { $path = self::pathFormat($path); if (!is_dir($path)) { throw new NotFoundException("directory not exists! DIR: $path"); } $len = \strlen($path); $ext = \is_array($ext) ? implode('|', $ext) : trim($ext); foreach (glob($path . '*') as $v) { $relatePath = substr($v, $len); // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 if (is_file($v) && (!$ext || preg_match("/\.($ext)$/i", $v))) { $list[] = $parent . $relatePath; } elseif ($recursive) { $list = self::getFiles($v, $ext, $recursive, $relatePath . '/', $list); } } return $list; }
[ "public", "static", "function", "getFiles", "(", "$", "path", ",", "$", "ext", "=", "null", ",", "$", "recursive", "=", "false", ",", "$", "parent", "=", "null", ",", "array", "$", "list", "=", "[", "]", ")", ":", "array", "{", "$", "path", "=", "self", "::", "pathFormat", "(", "$", "path", ")", ";", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"directory not exists! DIR: $path\"", ")", ";", "}", "$", "len", "=", "\\", "strlen", "(", "$", "path", ")", ";", "$", "ext", "=", "\\", "is_array", "(", "$", "ext", ")", "?", "implode", "(", "'|'", ",", "$", "ext", ")", ":", "trim", "(", "$", "ext", ")", ";", "foreach", "(", "glob", "(", "$", "path", ".", "'*'", ")", "as", "$", "v", ")", "{", "$", "relatePath", "=", "substr", "(", "$", "v", ",", "$", "len", ")", ";", "// 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找", "if", "(", "is_file", "(", "$", "v", ")", "&&", "(", "!", "$", "ext", "||", "preg_match", "(", "\"/\\.($ext)$/i\"", ",", "$", "v", ")", ")", ")", "{", "$", "list", "[", "]", "=", "$", "parent", ".", "$", "relatePath", ";", "}", "elseif", "(", "$", "recursive", ")", "{", "$", "list", "=", "self", "::", "getFiles", "(", "$", "v", ",", "$", "ext", ",", "$", "recursive", ",", "$", "relatePath", ".", "'/'", ",", "$", "list", ")", ";", "}", "}", "return", "$", "list", ";", "}" ]
获得目录下的文件,可选择类型、是否遍历子文件夹 @param string $path string 目标目录 @param array|string $ext array('css','html','php') css|html|php @param bool $recursive 是否包含子目录 @param null|string $parent @param array $list @return array @throws NotFoundException
[ "获得目录下的文件,可选择类型、是否遍历子文件夹" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/Directory.php#L224-L248
inhere/php-librarys
src/Files/Directory.php
Directory.getFilesInfo
public static function getFilesInfo($path, $ext = null, $recursive = 0, &$list): array { $path = self::pathFormat($path); if (!is_dir($path)) { throw new NotFoundException("directory not exists! DIR: $path"); } $ext = \is_array($ext) ? implode('|', $ext) : trim($ext); static $id = 0; //glob()寻找与模式匹配的文件路径 foreach (glob($path . '*') as $file) { $id++; // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 if (is_file($file) && (!$ext || preg_match("/\.($ext)$/i", $file))) { $list[$id] = File::info($file); //是否遍历子目录 } elseif ($recursive) { $list = self::getFilesInfo($file, $ext, $recursive, $list); } } return $list; }
php
public static function getFilesInfo($path, $ext = null, $recursive = 0, &$list): array { $path = self::pathFormat($path); if (!is_dir($path)) { throw new NotFoundException("directory not exists! DIR: $path"); } $ext = \is_array($ext) ? implode('|', $ext) : trim($ext); static $id = 0; //glob()寻找与模式匹配的文件路径 foreach (glob($path . '*') as $file) { $id++; // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 if (is_file($file) && (!$ext || preg_match("/\.($ext)$/i", $file))) { $list[$id] = File::info($file); //是否遍历子目录 } elseif ($recursive) { $list = self::getFilesInfo($file, $ext, $recursive, $list); } } return $list; }
[ "public", "static", "function", "getFilesInfo", "(", "$", "path", ",", "$", "ext", "=", "null", ",", "$", "recursive", "=", "0", ",", "&", "$", "list", ")", ":", "array", "{", "$", "path", "=", "self", "::", "pathFormat", "(", "$", "path", ")", ";", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"directory not exists! DIR: $path\"", ")", ";", "}", "$", "ext", "=", "\\", "is_array", "(", "$", "ext", ")", "?", "implode", "(", "'|'", ",", "$", "ext", ")", ":", "trim", "(", "$", "ext", ")", ";", "static", "$", "id", "=", "0", ";", "//glob()寻找与模式匹配的文件路径", "foreach", "(", "glob", "(", "$", "path", ".", "'*'", ")", "as", "$", "file", ")", "{", "$", "id", "++", ";", "// 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找", "if", "(", "is_file", "(", "$", "file", ")", "&&", "(", "!", "$", "ext", "||", "preg_match", "(", "\"/\\.($ext)$/i\"", ",", "$", "file", ")", ")", ")", "{", "$", "list", "[", "$", "id", "]", "=", "File", "::", "info", "(", "$", "file", ")", ";", "//是否遍历子目录", "}", "elseif", "(", "$", "recursive", ")", "{", "$", "list", "=", "self", "::", "getFilesInfo", "(", "$", "file", ",", "$", "ext", ",", "$", "recursive", ",", "$", "list", ")", ";", "}", "}", "return", "$", "list", ";", "}" ]
获得目录下的文件以及详细信息,可选择类型、是否遍历子文件夹 @param $path string 目标目录 @param array|string $ext array('css','html','php') css|html|php @param $recursive int|bool 是否包含子目录 @param array $list @return array @throws \InvalidArgumentException @throws NotFoundException
[ "获得目录下的文件以及详细信息,可选择类型、是否遍历子文件夹" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/Directory.php#L274-L301
inhere/php-librarys
src/Files/Directory.php
Directory.copy
public static function copy($oldDir, $newDir): bool { $oldDir = self::pathFormat($oldDir); $newDir = self::pathFormat($newDir); if (!is_dir($oldDir)) { throw new NotFoundException('复制失败:' . $oldDir . ' 不存在!'); } $newDir = self::create($newDir); foreach (glob($oldDir . '*') as $v) { $newFile = $newDir . basename($v);//文件 //文件存在,跳过复制它 if (file_exists($newFile)) { continue; } if (is_dir($v)) { self::copy($v, $newFile); } else { copy($v, $newFile);//是文件就复制过来 @chmod($newFile, 0664);// 权限 0777 } } return true; }
php
public static function copy($oldDir, $newDir): bool { $oldDir = self::pathFormat($oldDir); $newDir = self::pathFormat($newDir); if (!is_dir($oldDir)) { throw new NotFoundException('复制失败:' . $oldDir . ' 不存在!'); } $newDir = self::create($newDir); foreach (glob($oldDir . '*') as $v) { $newFile = $newDir . basename($v);//文件 //文件存在,跳过复制它 if (file_exists($newFile)) { continue; } if (is_dir($v)) { self::copy($v, $newFile); } else { copy($v, $newFile);//是文件就复制过来 @chmod($newFile, 0664);// 权限 0777 } } return true; }
[ "public", "static", "function", "copy", "(", "$", "oldDir", ",", "$", "newDir", ")", ":", "bool", "{", "$", "oldDir", "=", "self", "::", "pathFormat", "(", "$", "oldDir", ")", ";", "$", "newDir", "=", "self", "::", "pathFormat", "(", "$", "newDir", ")", ";", "if", "(", "!", "is_dir", "(", "$", "oldDir", ")", ")", "{", "throw", "new", "NotFoundException", "(", "'复制失败:' . $oldDir", ".", "'", " 不存在!'", ";", "", "", "", "}", "$", "newDir", "=", "self", "::", "create", "(", "$", "newDir", ")", ";", "foreach", "(", "glob", "(", "$", "oldDir", ".", "'*'", ")", "as", "$", "v", ")", "{", "$", "newFile", "=", "$", "newDir", ".", "basename", "(", "$", "v", ")", ";", "//文件", "//文件存在,跳过复制它", "if", "(", "file_exists", "(", "$", "newFile", ")", ")", "{", "continue", ";", "}", "if", "(", "is_dir", "(", "$", "v", ")", ")", "{", "self", "::", "copy", "(", "$", "v", ",", "$", "newFile", ")", ";", "}", "else", "{", "copy", "(", "$", "v", ",", "$", "newFile", ")", ";", "//是文件就复制过来", "@", "chmod", "(", "$", "newFile", ",", "0664", ")", ";", "// 权限 0777", "}", "}", "return", "true", ";", "}" ]
复制目录内容 @param $oldDir @param $newDir @return bool @throws NotFoundException
[ "复制目录内容" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/Directory.php#L322-L350
inhere/php-librarys
src/Files/Directory.php
Directory.comparePath
public static function comparePath($newPath, $oldPath): string { $oldDirName = basename(rtrim($oldPath, '/')); $newPath_arr = explode('/', rtrim($newPath, '/')); $oldPath_arr = explode('/', rtrim($oldPath, '/')); $reOne = array_diff($newPath_arr, $oldPath_arr); $numOne = \count((array)$reOne);// /** * 跟框架在同一个父目录[phpTest]下 * projectPath 'F:/www/phpTest/xxx/yyy/[zzz]'--应用目录 zzz, * yzonePath 'F:/www/phpTest/[yzonefk]'---框架目录 [yzonefk] * 从应用'F:/www/phpTest/xxx/yyy/[zzz]/'目录回滚到共同的父目录[这里是从zzz/web回滚到phpTest] * 入口文件 在 zzz/web/index.php */ $dirStr = '__DIR__'; for ($i = 0; $i <= $numOne; $i++) { $dirStr = 'dirname( ' . $dirStr . ' )'; } $dirStr .= '.\''; /** * 跟框架在不同父目录下,在回滚到共同的父目录后,再加上到框架的路径 * newPath 'F:/www/otherDir/ddd/eee/xxx/yyy/[zzz]'--应用目录 zzz * oldPath 'F:/www/phpTest/[yzonefk]'---框架目录[yzonefk] */ if (\dirname($newPath) !== \dirname($oldPath)) { $reTwo = array_diff($oldPath_arr, $newPath_arr); $reTwo = array_shift($reTwo); // $numTwo = count($reTwo);// 从框架目录向上回滚,找到相同的父节点,得到相隔几层 $dirStr .= implode('/', (array)$reTwo); } $dirStr = $dirStr . '/' . $oldDirName . '/Gee.php\''; return $dirStr; }
php
public static function comparePath($newPath, $oldPath): string { $oldDirName = basename(rtrim($oldPath, '/')); $newPath_arr = explode('/', rtrim($newPath, '/')); $oldPath_arr = explode('/', rtrim($oldPath, '/')); $reOne = array_diff($newPath_arr, $oldPath_arr); $numOne = \count((array)$reOne);// /** * 跟框架在同一个父目录[phpTest]下 * projectPath 'F:/www/phpTest/xxx/yyy/[zzz]'--应用目录 zzz, * yzonePath 'F:/www/phpTest/[yzonefk]'---框架目录 [yzonefk] * 从应用'F:/www/phpTest/xxx/yyy/[zzz]/'目录回滚到共同的父目录[这里是从zzz/web回滚到phpTest] * 入口文件 在 zzz/web/index.php */ $dirStr = '__DIR__'; for ($i = 0; $i <= $numOne; $i++) { $dirStr = 'dirname( ' . $dirStr . ' )'; } $dirStr .= '.\''; /** * 跟框架在不同父目录下,在回滚到共同的父目录后,再加上到框架的路径 * newPath 'F:/www/otherDir/ddd/eee/xxx/yyy/[zzz]'--应用目录 zzz * oldPath 'F:/www/phpTest/[yzonefk]'---框架目录[yzonefk] */ if (\dirname($newPath) !== \dirname($oldPath)) { $reTwo = array_diff($oldPath_arr, $newPath_arr); $reTwo = array_shift($reTwo); // $numTwo = count($reTwo);// 从框架目录向上回滚,找到相同的父节点,得到相隔几层 $dirStr .= implode('/', (array)$reTwo); } $dirStr = $dirStr . '/' . $oldDirName . '/Gee.php\''; return $dirStr; }
[ "public", "static", "function", "comparePath", "(", "$", "newPath", ",", "$", "oldPath", ")", ":", "string", "{", "$", "oldDirName", "=", "basename", "(", "rtrim", "(", "$", "oldPath", ",", "'/'", ")", ")", ";", "$", "newPath_arr", "=", "explode", "(", "'/'", ",", "rtrim", "(", "$", "newPath", ",", "'/'", ")", ")", ";", "$", "oldPath_arr", "=", "explode", "(", "'/'", ",", "rtrim", "(", "$", "oldPath", ",", "'/'", ")", ")", ";", "$", "reOne", "=", "array_diff", "(", "$", "newPath_arr", ",", "$", "oldPath_arr", ")", ";", "$", "numOne", "=", "\\", "count", "(", "(", "array", ")", "$", "reOne", ")", ";", "//", "/**\n * 跟框架在同一个父目录[phpTest]下\n * projectPath 'F:/www/phpTest/xxx/yyy/[zzz]'--应用目录 zzz,\n * yzonePath 'F:/www/phpTest/[yzonefk]'---框架目录 [yzonefk]\n * 从应用'F:/www/phpTest/xxx/yyy/[zzz]/'目录回滚到共同的父目录[这里是从zzz/web回滚到phpTest]\n * 入口文件 在 zzz/web/index.php\n */", "$", "dirStr", "=", "'__DIR__'", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<=", "$", "numOne", ";", "$", "i", "++", ")", "{", "$", "dirStr", "=", "'dirname( '", ".", "$", "dirStr", ".", "' )'", ";", "}", "$", "dirStr", ".=", "'.\\''", ";", "/**\n * 跟框架在不同父目录下,在回滚到共同的父目录后,再加上到框架的路径\n * newPath 'F:/www/otherDir/ddd/eee/xxx/yyy/[zzz]'--应用目录 zzz\n * oldPath 'F:/www/phpTest/[yzonefk]'---框架目录[yzonefk]\n */", "if", "(", "\\", "dirname", "(", "$", "newPath", ")", "!==", "\\", "dirname", "(", "$", "oldPath", ")", ")", "{", "$", "reTwo", "=", "array_diff", "(", "$", "oldPath_arr", ",", "$", "newPath_arr", ")", ";", "$", "reTwo", "=", "array_shift", "(", "$", "reTwo", ")", ";", "// $numTwo = count($reTwo);// 从框架目录向上回滚,找到相同的父节点,得到相隔几层", "$", "dirStr", ".=", "implode", "(", "'/'", ",", "(", "array", ")", "$", "reTwo", ")", ";", "}", "$", "dirStr", "=", "$", "dirStr", ".", "'/'", ".", "$", "oldDirName", ".", "'/Gee.php\\''", ";", "return", "$", "dirStr", ";", "}" ]
比较文件路径 @param $newPath @param $oldPath @return string
[ "比较文件路径" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Files/Directory.php#L381-L420
nabab/bbn
src/bbn/mvc/view.php
view.get
public function get(array $data=null) { if ( $this->check() ){ if ( \is_null($this->content) ){ $this->content = file_get_contents($this->file); } if ( empty($this->content) ){ return ''; } if ( $this->checkers ){ $st = ''; foreach ( $this->checkers as $chk ){ $st .= file_get_contents($chk); } $this->content = $st.$this->content; } switch ( $this->ext ){ case 'js': // Language variables inclusions in the javascript files if ( !empty($this->lang_file) ){ $tmp = json_decode(file_get_contents($this->lang_file), true); $path = $this->plugin ? substr($this->path, \strlen($this->plugin) + 1) : $this->path; //die(var_dump(count($tmp), 'components/'.$this->path.'/'.$this->path, $tmp)); if ( $translations = $tmp['mvc/'.$path] ?? ($tmp['components/'.$path] ?? null) ){ $json = json_encode($translations); $tmp = <<<JAVASCRIPT (data) => { bbn.fn.autoExtend("lng", $json) }; JAVASCRIPT; $this->content = $tmp.$this->content; } unset($tmp, $translations); } return $this->content; case 'coffee': return $this->content; case 'css': return $this->content; case 'less': $less = new \lessc(); return $less->compile($this->content); case 'scss': $scss = new \Leafo\ScssPhp\Compiler(); return $scss->compile($this->content); case 'html': return empty($data) ? $this->content : bbn\tpl::render($this->content, $data); case 'php': $dir = getcwd(); chdir(dirname($this->file)); $r = bbn\mvc::include_php_view($this->file, $this->content, $data ?: []); chdir($dir); return $r; } } return false; }
php
public function get(array $data=null) { if ( $this->check() ){ if ( \is_null($this->content) ){ $this->content = file_get_contents($this->file); } if ( empty($this->content) ){ return ''; } if ( $this->checkers ){ $st = ''; foreach ( $this->checkers as $chk ){ $st .= file_get_contents($chk); } $this->content = $st.$this->content; } switch ( $this->ext ){ case 'js': // Language variables inclusions in the javascript files if ( !empty($this->lang_file) ){ $tmp = json_decode(file_get_contents($this->lang_file), true); $path = $this->plugin ? substr($this->path, \strlen($this->plugin) + 1) : $this->path; //die(var_dump(count($tmp), 'components/'.$this->path.'/'.$this->path, $tmp)); if ( $translations = $tmp['mvc/'.$path] ?? ($tmp['components/'.$path] ?? null) ){ $json = json_encode($translations); $tmp = <<<JAVASCRIPT (data) => { bbn.fn.autoExtend("lng", $json) }; JAVASCRIPT; $this->content = $tmp.$this->content; } unset($tmp, $translations); } return $this->content; case 'coffee': return $this->content; case 'css': return $this->content; case 'less': $less = new \lessc(); return $less->compile($this->content); case 'scss': $scss = new \Leafo\ScssPhp\Compiler(); return $scss->compile($this->content); case 'html': return empty($data) ? $this->content : bbn\tpl::render($this->content, $data); case 'php': $dir = getcwd(); chdir(dirname($this->file)); $r = bbn\mvc::include_php_view($this->file, $this->content, $data ?: []); chdir($dir); return $r; } } return false; }
[ "public", "function", "get", "(", "array", "$", "data", "=", "null", ")", "{", "if", "(", "$", "this", "->", "check", "(", ")", ")", "{", "if", "(", "\\", "is_null", "(", "$", "this", "->", "content", ")", ")", "{", "$", "this", "->", "content", "=", "file_get_contents", "(", "$", "this", "->", "file", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "content", ")", ")", "{", "return", "''", ";", "}", "if", "(", "$", "this", "->", "checkers", ")", "{", "$", "st", "=", "''", ";", "foreach", "(", "$", "this", "->", "checkers", "as", "$", "chk", ")", "{", "$", "st", ".=", "file_get_contents", "(", "$", "chk", ")", ";", "}", "$", "this", "->", "content", "=", "$", "st", ".", "$", "this", "->", "content", ";", "}", "switch", "(", "$", "this", "->", "ext", ")", "{", "case", "'js'", ":", "// Language variables inclusions in the javascript files", "if", "(", "!", "empty", "(", "$", "this", "->", "lang_file", ")", ")", "{", "$", "tmp", "=", "json_decode", "(", "file_get_contents", "(", "$", "this", "->", "lang_file", ")", ",", "true", ")", ";", "$", "path", "=", "$", "this", "->", "plugin", "?", "substr", "(", "$", "this", "->", "path", ",", "\\", "strlen", "(", "$", "this", "->", "plugin", ")", "+", "1", ")", ":", "$", "this", "->", "path", ";", "//die(var_dump(count($tmp), 'components/'.$this->path.'/'.$this->path, $tmp));", "if", "(", "$", "translations", "=", "$", "tmp", "[", "'mvc/'", ".", "$", "path", "]", "??", "(", "$", "tmp", "[", "'components/'", ".", "$", "path", "]", "??", "null", ")", ")", "{", "$", "json", "=", "json_encode", "(", "$", "translations", ")", ";", "$", "tmp", "=", " <<<JAVASCRIPT\n(data) => {\n bbn.fn.autoExtend(\"lng\", $json)\n};\nJAVASCRIPT", ";", "$", "this", "->", "content", "=", "$", "tmp", ".", "$", "this", "->", "content", ";", "}", "unset", "(", "$", "tmp", ",", "$", "translations", ")", ";", "}", "return", "$", "this", "->", "content", ";", "case", "'coffee'", ":", "return", "$", "this", "->", "content", ";", "case", "'css'", ":", "return", "$", "this", "->", "content", ";", "case", "'less'", ":", "$", "less", "=", "new", "\\", "lessc", "(", ")", ";", "return", "$", "less", "->", "compile", "(", "$", "this", "->", "content", ")", ";", "case", "'scss'", ":", "$", "scss", "=", "new", "\\", "Leafo", "\\", "ScssPhp", "\\", "Compiler", "(", ")", ";", "return", "$", "scss", "->", "compile", "(", "$", "this", "->", "content", ")", ";", "case", "'html'", ":", "return", "empty", "(", "$", "data", ")", "?", "$", "this", "->", "content", ":", "bbn", "\\", "tpl", "::", "render", "(", "$", "this", "->", "content", ",", "$", "data", ")", ";", "case", "'php'", ":", "$", "dir", "=", "getcwd", "(", ")", ";", "chdir", "(", "dirname", "(", "$", "this", "->", "file", ")", ")", ";", "$", "r", "=", "bbn", "\\", "mvc", "::", "include_php_view", "(", "$", "this", "->", "file", ",", "$", "this", "->", "content", ",", "$", "data", "?", ":", "[", "]", ")", ";", "chdir", "(", "$", "dir", ")", ";", "return", "$", "r", ";", "}", "}", "return", "false", ";", "}" ]
Processes the controller and checks whether it has been routed or not. @return bool
[ "Processes", "the", "controller", "and", "checks", "whether", "it", "has", "been", "routed", "or", "not", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc/view.php#L88-L144
odiaseo/pagebuilder
src/PageBuilder/Model/AbstractModelFactory.php
AbstractModelFactory.canCreate
public function canCreate(ContainerInterface $container, $requestedName) { if (substr($requestedName, 0, strlen($this->_configPrefix)) != $this->_configPrefix) { return false; } return true; }
php
public function canCreate(ContainerInterface $container, $requestedName) { if (substr($requestedName, 0, strlen($this->_configPrefix)) != $this->_configPrefix) { return false; } return true; }
[ "public", "function", "canCreate", "(", "ContainerInterface", "$", "container", ",", "$", "requestedName", ")", "{", "if", "(", "substr", "(", "$", "requestedName", ",", "0", ",", "strlen", "(", "$", "this", "->", "_configPrefix", ")", ")", "!=", "$", "this", "->", "_configPrefix", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
@param ContainerInterface $container @param string $requestedName @return bool
[ "@param", "ContainerInterface", "$container", "@param", "string", "$requestedName" ]
train
https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Model/AbstractModelFactory.php#L32-L39
odiaseo/pagebuilder
src/PageBuilder/Model/AbstractModelFactory.php
AbstractModelFactory.resolveEntityClassName
private function resolveEntityClassName(ContainerInterface $serviceLocator, $id, $default) { /** @var $sampleService \SynergyCommon\Service\BaseService */ $reverseFilter = new CamelCaseToDash(); $entityId = strtolower($reverseFilter->filter($id)); $sampleService = $serviceLocator->get('synergycommon\service\base'); $entityClassName = $sampleService->getClassnameFromEntityKey($entityId); if ($entityClassName) { return new $entityClassName; } return $serviceLocator->get($default); }
php
private function resolveEntityClassName(ContainerInterface $serviceLocator, $id, $default) { /** @var $sampleService \SynergyCommon\Service\BaseService */ $reverseFilter = new CamelCaseToDash(); $entityId = strtolower($reverseFilter->filter($id)); $sampleService = $serviceLocator->get('synergycommon\service\base'); $entityClassName = $sampleService->getClassnameFromEntityKey($entityId); if ($entityClassName) { return new $entityClassName; } return $serviceLocator->get($default); }
[ "private", "function", "resolveEntityClassName", "(", "ContainerInterface", "$", "serviceLocator", ",", "$", "id", ",", "$", "default", ")", "{", "/** @var $sampleService \\SynergyCommon\\Service\\BaseService */", "$", "reverseFilter", "=", "new", "CamelCaseToDash", "(", ")", ";", "$", "entityId", "=", "strtolower", "(", "$", "reverseFilter", "->", "filter", "(", "$", "id", ")", ")", ";", "$", "sampleService", "=", "$", "serviceLocator", "->", "get", "(", "'synergycommon\\service\\base'", ")", ";", "$", "entityClassName", "=", "$", "sampleService", "->", "getClassnameFromEntityKey", "(", "$", "entityId", ")", ";", "if", "(", "$", "entityClassName", ")", "{", "return", "new", "$", "entityClassName", ";", "}", "return", "$", "serviceLocator", "->", "get", "(", "$", "default", ")", ";", "}" ]
@param ContainerInterface $serviceLocator @param $id @param $default @return mixed
[ "@param", "ContainerInterface", "$serviceLocator", "@param", "$id", "@param", "$default" ]
train
https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Model/AbstractModelFactory.php#L82-L95
songshenzong/log
src/SymfonyHttpDriver.php
SymfonyHttpDriver.setSessionValue
public function setSessionValue($name, $value) { // In Laravel 5.4 the session changed to use their own custom implementation // instead of the one from Symfony. One of the changes was the set method // that was changed to put. Here we check if we are using the new one. if (method_exists($this->session, 'driver') && $this->session->driver() instanceof \Illuminate\Contracts\Session\Session) { $this->session->put($name, $value); return; } $this->session->set($name, $value); }
php
public function setSessionValue($name, $value) { // In Laravel 5.4 the session changed to use their own custom implementation // instead of the one from Symfony. One of the changes was the set method // that was changed to put. Here we check if we are using the new one. if (method_exists($this->session, 'driver') && $this->session->driver() instanceof \Illuminate\Contracts\Session\Session) { $this->session->put($name, $value); return; } $this->session->set($name, $value); }
[ "public", "function", "setSessionValue", "(", "$", "name", ",", "$", "value", ")", "{", "// In Laravel 5.4 the session changed to use their own custom implementation", "// instead of the one from Symfony. One of the changes was the set method", "// that was changed to put. Here we check if we are using the new one.", "if", "(", "method_exists", "(", "$", "this", "->", "session", ",", "'driver'", ")", "&&", "$", "this", "->", "session", "->", "driver", "(", ")", "instanceof", "\\", "Illuminate", "\\", "Contracts", "\\", "Session", "\\", "Session", ")", "{", "$", "this", "->", "session", "->", "put", "(", "$", "name", ",", "$", "value", ")", ";", "return", ";", "}", "$", "this", "->", "session", "->", "set", "(", "$", "name", ",", "$", "value", ")", ";", "}" ]
Sets a value in the session @param string $name @param string $value
[ "Sets", "a", "value", "in", "the", "session" ]
train
https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/SymfonyHttpDriver.php#L63-L73
Eresus/EresusCMS
src/core/classes.php
ContentPlugin.__item
public function __item($item = null) { $result = parent::__item($item); $result['content'] = true; return $result; }
php
public function __item($item = null) { $result = parent::__item($item); $result['content'] = true; return $result; }
[ "public", "function", "__item", "(", "$", "item", "=", "null", ")", "{", "$", "result", "=", "parent", "::", "__item", "(", "$", "item", ")", ";", "$", "result", "[", "'content'", "]", "=", "true", ";", "return", "$", "result", ";", "}" ]
Возвращает информацию о плагине @param array $item Предыдущая версия информации (по умолчанию null) @return array Массив информации, пригодный для записи в БД
[ "Возвращает", "информацию", "о", "плагине" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L76-L81
Eresus/EresusCMS
src/core/classes.php
ContentPlugin.onSectionDelete
public function onSectionDelete($id, $table = '') { if (count($this->dbTable($table))) { $this->dbDelete($table, $id, 'section'); } }
php
public function onSectionDelete($id, $table = '') { if (count($this->dbTable($table))) { $this->dbDelete($table, $id, 'section'); } }
[ "public", "function", "onSectionDelete", "(", "$", "id", ",", "$", "table", "=", "''", ")", "{", "if", "(", "count", "(", "$", "this", "->", "dbTable", "(", "$", "table", ")", ")", ")", "{", "$", "this", "->", "dbDelete", "(", "$", "table", ",", "$", "id", ",", "'section'", ")", ";", "}", "}" ]
Действия при удалении раздела данного типа @param int $id Идентификатор удаляемого раздела @param string $table Имя таблицы
[ "Действия", "при", "удалении", "раздела", "данного", "типа" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L88-L94
Eresus/EresusCMS
src/core/classes.php
ContentPlugin.updateContent
public function updateContent($content) { $db = Eresus_CMS::getLegacyKernel()->db; $item = $db->selectItem('pages', "`id`='".Eresus_Kernel::app()->getPage()->id."'"); $item['content'] = $content; $db->updateItem('pages', $item, "`id`='".Eresus_Kernel::app()->getPage()->id."'"); }
php
public function updateContent($content) { $db = Eresus_CMS::getLegacyKernel()->db; $item = $db->selectItem('pages', "`id`='".Eresus_Kernel::app()->getPage()->id."'"); $item['content'] = $content; $db->updateItem('pages', $item, "`id`='".Eresus_Kernel::app()->getPage()->id."'"); }
[ "public", "function", "updateContent", "(", "$", "content", ")", "{", "$", "db", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", ";", "$", "item", "=", "$", "db", "->", "selectItem", "(", "'pages'", ",", "\"`id`='\"", ".", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "id", ".", "\"'\"", ")", ";", "$", "item", "[", "'content'", "]", "=", "$", "content", ";", "$", "db", "->", "updateItem", "(", "'pages'", ",", "$", "item", ",", "\"`id`='\"", ".", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "id", ".", "\"'\"", ")", ";", "}" ]
Обновляет контент страницы в БД @param string $content Контент
[ "Обновляет", "контент", "страницы", "в", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L101-L107
Eresus/EresusCMS
src/core/classes.php
ContentPlugin.clientRenderContent
public function clientRenderContent() { /** @var TClientUI $page */ $page = Eresus_Kernel::app()->getPage(); $request = Eresus_CMS::getLegacyKernel()->request; /* Если в URL указано что-либо кроме адреса раздела, отправляет ответ 404 */ if ($request['file'] || $request['query'] || $page->subpage || $page->topic) { throw new Eresus_CMS_Exception_NotFound; } return $page->content; }
php
public function clientRenderContent() { /** @var TClientUI $page */ $page = Eresus_Kernel::app()->getPage(); $request = Eresus_CMS::getLegacyKernel()->request; /* Если в URL указано что-либо кроме адреса раздела, отправляет ответ 404 */ if ($request['file'] || $request['query'] || $page->subpage || $page->topic) { throw new Eresus_CMS_Exception_NotFound; } return $page->content; }
[ "public", "function", "clientRenderContent", "(", ")", "{", "/** @var TClientUI $page */", "$", "page", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", ";", "$", "request", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "request", ";", "/* Если в URL указано что-либо кроме адреса раздела, отправляет ответ 404 */", "if", "(", "$", "request", "[", "'file'", "]", "||", "$", "request", "[", "'query'", "]", "||", "$", "page", "->", "subpage", "||", "$", "page", "->", "topic", ")", "{", "throw", "new", "Eresus_CMS_Exception_NotFound", ";", "}", "return", "$", "page", "->", "content", ";", "}" ]
Отрисовка клиентской части @return string Контент @throws Eresus_CMS_Exception_NotFound
[ "Отрисовка", "клиентской", "части" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L125-L138
Eresus/EresusCMS
src/core/classes.php
ContentPlugin.adminRenderContent
public function adminRenderContent() { if (arg('action') == 'update') $this->adminUpdate(); $item = Eresus_CMS::getLegacyKernel()->db->selectItem('pages', "`id`='". Eresus_Kernel::app()->getPage()->id."'"); $form = array( 'name' => 'editForm', 'caption' => Eresus_Kernel::app()->getPage()->title, 'width' => '100%', 'fields' => array ( array ('type'=>'hidden','name'=>'action', 'value' => 'update'), array ('type' => 'memo', 'name' => 'content', 'label' => strEdit, 'height' => '30'), ), 'buttons' => array('apply', 'reset'), ); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->renderForm($form, $item); return $result; }
php
public function adminRenderContent() { if (arg('action') == 'update') $this->adminUpdate(); $item = Eresus_CMS::getLegacyKernel()->db->selectItem('pages', "`id`='". Eresus_Kernel::app()->getPage()->id."'"); $form = array( 'name' => 'editForm', 'caption' => Eresus_Kernel::app()->getPage()->title, 'width' => '100%', 'fields' => array ( array ('type'=>'hidden','name'=>'action', 'value' => 'update'), array ('type' => 'memo', 'name' => 'content', 'label' => strEdit, 'height' => '30'), ), 'buttons' => array('apply', 'reset'), ); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $result = $page->renderForm($form, $item); return $result; }
[ "public", "function", "adminRenderContent", "(", ")", "{", "if", "(", "arg", "(", "'action'", ")", "==", "'update'", ")", "$", "this", "->", "adminUpdate", "(", ")", ";", "$", "item", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "selectItem", "(", "'pages'", ",", "\"`id`='\"", ".", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "id", ".", "\"'\"", ")", ";", "$", "form", "=", "array", "(", "'name'", "=>", "'editForm'", ",", "'caption'", "=>", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "title", ",", "'width'", "=>", "'100%'", ",", "'fields'", "=>", "array", "(", "array", "(", "'type'", "=>", "'hidden'", ",", "'name'", "=>", "'action'", ",", "'value'", "=>", "'update'", ")", ",", "array", "(", "'type'", "=>", "'memo'", ",", "'name'", "=>", "'content'", ",", "'label'", "=>", "strEdit", ",", "'height'", "=>", "'30'", ")", ",", ")", ",", "'buttons'", "=>", "array", "(", "'apply'", ",", "'reset'", ")", ",", ")", ";", "/** @var TAdminUI $page */", "$", "page", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", ";", "$", "result", "=", "$", "page", "->", "renderForm", "(", "$", "form", ",", "$", "item", ")", ";", "return", "$", "result", ";", "}" ]
Отрисовка административной части @return string Контент
[ "Отрисовка", "административной", "части" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L145-L165
Eresus/EresusCMS
src/core/classes.php
EresusExtensionConnector.replaceMacros
protected function replaceMacros($text) { $request = Eresus_CMS::getLegacyKernel()->request; $text = str_replace( array( '$(httpHost)', '$(httpPath)', '$(httpRoot)', '$(styleRoot)', '$(dataRoot)', ), array( $request['host'], $request['path'], Eresus_CMS::getLegacyKernel()->root, Eresus_CMS::getLegacyKernel()->style, Eresus_CMS::getLegacyKernel()->data ), $text ); return $text; }
php
protected function replaceMacros($text) { $request = Eresus_CMS::getLegacyKernel()->request; $text = str_replace( array( '$(httpHost)', '$(httpPath)', '$(httpRoot)', '$(styleRoot)', '$(dataRoot)', ), array( $request['host'], $request['path'], Eresus_CMS::getLegacyKernel()->root, Eresus_CMS::getLegacyKernel()->style, Eresus_CMS::getLegacyKernel()->data ), $text ); return $text; }
[ "protected", "function", "replaceMacros", "(", "$", "text", ")", "{", "$", "request", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "request", ";", "$", "text", "=", "str_replace", "(", "array", "(", "'$(httpHost)'", ",", "'$(httpPath)'", ",", "'$(httpRoot)'", ",", "'$(styleRoot)'", ",", "'$(dataRoot)'", ",", ")", ",", "array", "(", "$", "request", "[", "'host'", "]", ",", "$", "request", "[", "'path'", "]", ",", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "root", ",", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "style", ",", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "data", ")", ",", "$", "text", ")", ";", "return", "$", "text", ";", "}" ]
Заменяет глобальные макросы @param string $text @return string
[ "Заменяет", "глобальные", "макросы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L208-L230
Eresus/EresusCMS
src/core/classes.php
EresusExtensionConnector.proxy
function proxy() { if (!UserRights(EDITOR)) die; $filename = Eresus_CMS::getLegacyKernel()->request['path'] . Eresus_CMS::getLegacyKernel()->request['file']; $filename = Eresus_CMS::getLegacyKernel()->froot . substr($filename, strlen(Eresus_CMS::getLegacyKernel()->root)); if (is_dir($filename)) { $filename = Eresus_FS_Tool::normalize($filename . '/index.php'); } if (!is_file($filename)) { header('Not found', true, 404); die('<h1>Not found.</h1>'); } $ext = strtolower(substr($filename, strrpos($filename, '.') + 1)); switch (true) { case in_array($ext, array('png', 'jpg', 'jpeg', 'gif')): $info = getimagesize($filename); header('Content-type: '.$info['mime']); echo file_get_contents($filename); break; case $ext == 'js': header('Content-type: text/javascript'); $s = file_get_contents($filename); $s = $this->replaceMacros($s); echo $s; break; case $ext == 'css': header('Content-type: text/css'); $s = file_get_contents($filename); $s = $this->replaceMacros($s); echo $s; break; case $ext == 'html': case $ext == 'htm': header('Content-type: text/html'); $s = file_get_contents($filename); $s = $this->replaceMacros($s); echo $s; break; case $ext == 'php': Eresus_CMS::getLegacyKernel()->conf['debug']['enable'] = false; restore_error_handler(); chdir(dirname($filename)); require $filename; break; } }
php
function proxy() { if (!UserRights(EDITOR)) die; $filename = Eresus_CMS::getLegacyKernel()->request['path'] . Eresus_CMS::getLegacyKernel()->request['file']; $filename = Eresus_CMS::getLegacyKernel()->froot . substr($filename, strlen(Eresus_CMS::getLegacyKernel()->root)); if (is_dir($filename)) { $filename = Eresus_FS_Tool::normalize($filename . '/index.php'); } if (!is_file($filename)) { header('Not found', true, 404); die('<h1>Not found.</h1>'); } $ext = strtolower(substr($filename, strrpos($filename, '.') + 1)); switch (true) { case in_array($ext, array('png', 'jpg', 'jpeg', 'gif')): $info = getimagesize($filename); header('Content-type: '.$info['mime']); echo file_get_contents($filename); break; case $ext == 'js': header('Content-type: text/javascript'); $s = file_get_contents($filename); $s = $this->replaceMacros($s); echo $s; break; case $ext == 'css': header('Content-type: text/css'); $s = file_get_contents($filename); $s = $this->replaceMacros($s); echo $s; break; case $ext == 'html': case $ext == 'htm': header('Content-type: text/html'); $s = file_get_contents($filename); $s = $this->replaceMacros($s); echo $s; break; case $ext == 'php': Eresus_CMS::getLegacyKernel()->conf['debug']['enable'] = false; restore_error_handler(); chdir(dirname($filename)); require $filename; break; } }
[ "function", "proxy", "(", ")", "{", "if", "(", "!", "UserRights", "(", "EDITOR", ")", ")", "die", ";", "$", "filename", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "request", "[", "'path'", "]", ".", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "request", "[", "'file'", "]", ";", "$", "filename", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "froot", ".", "substr", "(", "$", "filename", ",", "strlen", "(", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "root", ")", ")", ";", "if", "(", "is_dir", "(", "$", "filename", ")", ")", "{", "$", "filename", "=", "Eresus_FS_Tool", "::", "normalize", "(", "$", "filename", ".", "'/index.php'", ")", ";", "}", "if", "(", "!", "is_file", "(", "$", "filename", ")", ")", "{", "header", "(", "'Not found'", ",", "true", ",", "404", ")", ";", "die", "(", "'<h1>Not found.</h1>'", ")", ";", "}", "$", "ext", "=", "strtolower", "(", "substr", "(", "$", "filename", ",", "strrpos", "(", "$", "filename", ",", "'.'", ")", "+", "1", ")", ")", ";", "switch", "(", "true", ")", "{", "case", "in_array", "(", "$", "ext", ",", "array", "(", "'png'", ",", "'jpg'", ",", "'jpeg'", ",", "'gif'", ")", ")", ":", "$", "info", "=", "getimagesize", "(", "$", "filename", ")", ";", "header", "(", "'Content-type: '", ".", "$", "info", "[", "'mime'", "]", ")", ";", "echo", "file_get_contents", "(", "$", "filename", ")", ";", "break", ";", "case", "$", "ext", "==", "'js'", ":", "header", "(", "'Content-type: text/javascript'", ")", ";", "$", "s", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "s", "=", "$", "this", "->", "replaceMacros", "(", "$", "s", ")", ";", "echo", "$", "s", ";", "break", ";", "case", "$", "ext", "==", "'css'", ":", "header", "(", "'Content-type: text/css'", ")", ";", "$", "s", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "s", "=", "$", "this", "->", "replaceMacros", "(", "$", "s", ")", ";", "echo", "$", "s", ";", "break", ";", "case", "$", "ext", "==", "'html'", ":", "case", "$", "ext", "==", "'htm'", ":", "header", "(", "'Content-type: text/html'", ")", ";", "$", "s", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "s", "=", "$", "this", "->", "replaceMacros", "(", "$", "s", ")", ";", "echo", "$", "s", ";", "break", ";", "case", "$", "ext", "==", "'php'", ":", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "conf", "[", "'debug'", "]", "[", "'enable'", "]", "=", "false", ";", "restore_error_handler", "(", ")", ";", "chdir", "(", "dirname", "(", "$", "filename", ")", ")", ";", "require", "$", "filename", ";", "break", ";", "}", "}" ]
Метод вызывается при проксировании прямых запросов к расширению
[ "Метод", "вызывается", "при", "проксировании", "прямых", "запросов", "к", "расширению" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L236-L296
Eresus/EresusCMS
src/core/classes.php
EresusExtensions.get_name
function get_name($class, $function, $name = null) { $result = false; if (isset(Eresus_CMS::getLegacyKernel()->conf['extensions'])) { if (isset(Eresus_CMS::getLegacyKernel()->conf['extensions'][$class])) { if (isset(Eresus_CMS::getLegacyKernel()->conf['extensions'][$class][$function])) { $items = Eresus_CMS::getLegacyKernel()->conf['extensions'][$class][$function]; reset($items); $result = isset($items[$name]) ? $name : key($items); } } } return $result; }
php
function get_name($class, $function, $name = null) { $result = false; if (isset(Eresus_CMS::getLegacyKernel()->conf['extensions'])) { if (isset(Eresus_CMS::getLegacyKernel()->conf['extensions'][$class])) { if (isset(Eresus_CMS::getLegacyKernel()->conf['extensions'][$class][$function])) { $items = Eresus_CMS::getLegacyKernel()->conf['extensions'][$class][$function]; reset($items); $result = isset($items[$name]) ? $name : key($items); } } } return $result; }
[ "function", "get_name", "(", "$", "class", ",", "$", "function", ",", "$", "name", "=", "null", ")", "{", "$", "result", "=", "false", ";", "if", "(", "isset", "(", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "conf", "[", "'extensions'", "]", ")", ")", "{", "if", "(", "isset", "(", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "conf", "[", "'extensions'", "]", "[", "$", "class", "]", ")", ")", "{", "if", "(", "isset", "(", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "conf", "[", "'extensions'", "]", "[", "$", "class", "]", "[", "$", "function", "]", ")", ")", "{", "$", "items", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "conf", "[", "'extensions'", "]", "[", "$", "class", "]", "[", "$", "function", "]", ";", "reset", "(", "$", "items", ")", ";", "$", "result", "=", "isset", "(", "$", "items", "[", "$", "name", "]", ")", "?", "$", "name", ":", "key", "(", "$", "items", ")", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Определение имени расширения @param string $class Класс расширения @param string $function Расширяемая функция @param string $name Имя расширения @return mixed Имя расширения или false если подходящего расширения не найдено
[ "Определение", "имени", "расширения" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L324-L341
Eresus/EresusCMS
src/core/classes.php
EresusExtensions.load
function load($class, $function, $name = null) { $result = false; $name = $this->get_name($class, $function, $name); if (isset($this->items[$name])) { $result = $this->items[$name]; } else { $filename = Eresus_CMS::getLegacyKernel()->froot.'ext-3rd/' . $name . '/eresus-connector.php'; if (is_file($filename)) { include_once $filename; $class = $name.'Connector'; if (class_exists($class)) { $this->items[$name] = new $class(); $result = $this->items[$name]; } } } return $result; }
php
function load($class, $function, $name = null) { $result = false; $name = $this->get_name($class, $function, $name); if (isset($this->items[$name])) { $result = $this->items[$name]; } else { $filename = Eresus_CMS::getLegacyKernel()->froot.'ext-3rd/' . $name . '/eresus-connector.php'; if (is_file($filename)) { include_once $filename; $class = $name.'Connector'; if (class_exists($class)) { $this->items[$name] = new $class(); $result = $this->items[$name]; } } } return $result; }
[ "function", "load", "(", "$", "class", ",", "$", "function", ",", "$", "name", "=", "null", ")", "{", "$", "result", "=", "false", ";", "$", "name", "=", "$", "this", "->", "get_name", "(", "$", "class", ",", "$", "function", ",", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "items", "[", "$", "name", "]", ")", ")", "{", "$", "result", "=", "$", "this", "->", "items", "[", "$", "name", "]", ";", "}", "else", "{", "$", "filename", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "froot", ".", "'ext-3rd/'", ".", "$", "name", ".", "'/eresus-connector.php'", ";", "if", "(", "is_file", "(", "$", "filename", ")", ")", "{", "include_once", "$", "filename", ";", "$", "class", "=", "$", "name", ".", "'Connector'", ";", "if", "(", "class_exists", "(", "$", "class", ")", ")", "{", "$", "this", "->", "items", "[", "$", "name", "]", "=", "new", "$", "class", "(", ")", ";", "$", "result", "=", "$", "this", "->", "items", "[", "$", "name", "]", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Загрузка расширения @param string $class Класс расширения @param string $function Расширяемая функция @param string $name Имя расширения @return mixed Экземпляр класса EresusExtensionConnector или false если не удалось загрузить расширение
[ "Загрузка", "расширения" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/classes.php#L352-L377
SergioMadness/query-builder
src/traits/SelectBuilder.php
SelectBuilder.union
public function union(\pwf\components\querybuilder\interfaces\QueryBuilder $query) { $this->union[] = $query; return $this; }
php
public function union(\pwf\components\querybuilder\interfaces\QueryBuilder $query) { $this->union[] = $query; return $this; }
[ "public", "function", "union", "(", "\\", "pwf", "\\", "components", "\\", "querybuilder", "\\", "interfaces", "\\", "QueryBuilder", "$", "query", ")", "{", "$", "this", "->", "union", "[", "]", "=", "$", "query", ";", "return", "$", "this", ";", "}" ]
Add union @param \pwf\components\querybuilder\interfaces\QueryBuilder $query @return \pwf\components\querybuilder\interfaces\SelectBuilder
[ "Add", "union" ]
train
https://github.com/SergioMadness/query-builder/blob/95b7a46bba4c4d369101c6f0d37f133fecb3956d/src/traits/SelectBuilder.php#L180-L184
SergioMadness/query-builder
src/traits/SelectBuilder.php
SelectBuilder.join
public function join($table, $condition, $joinType = self::JOIN_LEFT) { $this->join[] = [ 'table' => $table, 'condition' => $condition, 'jointType' => $joinType ]; return $this; }
php
public function join($table, $condition, $joinType = self::JOIN_LEFT) { $this->join[] = [ 'table' => $table, 'condition' => $condition, 'jointType' => $joinType ]; return $this; }
[ "public", "function", "join", "(", "$", "table", ",", "$", "condition", ",", "$", "joinType", "=", "self", "::", "JOIN_LEFT", ")", "{", "$", "this", "->", "join", "[", "]", "=", "[", "'table'", "=>", "$", "table", ",", "'condition'", "=>", "$", "condition", ",", "'jointType'", "=>", "$", "joinType", "]", ";", "return", "$", "this", ";", "}" ]
Join table @param string $table @param mixed $condition @param int $joinType @return \pwf\components\querybuilder\interfaces\SelectBuilder
[ "Join", "table" ]
train
https://github.com/SergioMadness/query-builder/blob/95b7a46bba4c4d369101c6f0d37f133fecb3956d/src/traits/SelectBuilder.php#L204-L212
chubbyphp/chubbyphp-model-doctrine-dbal
src/Command/RunSqlCommand.php
RunSqlCommand.getSql
private function getSql(InputInterface $input): string { if (($sql = $input->getArgument('sql')) === null) { throw new \RuntimeException("Argument 'SQL' is required in order to execute this command correctly."); } return $sql; }
php
private function getSql(InputInterface $input): string { if (($sql = $input->getArgument('sql')) === null) { throw new \RuntimeException("Argument 'SQL' is required in order to execute this command correctly."); } return $sql; }
[ "private", "function", "getSql", "(", "InputInterface", "$", "input", ")", ":", "string", "{", "if", "(", "(", "$", "sql", "=", "$", "input", "->", "getArgument", "(", "'sql'", ")", ")", "===", "null", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Argument 'SQL' is required in order to execute this command correctly.\"", ")", ";", "}", "return", "$", "sql", ";", "}" ]
@param InputInterface $input @return string
[ "@param", "InputInterface", "$input" ]
train
https://github.com/chubbyphp/chubbyphp-model-doctrine-dbal/blob/1079c28f5bffc2e2bec04122742d5008464c167f/src/Command/RunSqlCommand.php#L57-L64
chubbyphp/chubbyphp-model-doctrine-dbal
src/Command/RunSqlCommand.php
RunSqlCommand.getDepth
private function getDepth(InputInterface $input): int { $depth = $input->getOption('depth'); if (!is_numeric($depth)) { throw new \InvalidArgumentException("Option 'depth' must contains an integer value"); } return (int) $depth; }
php
private function getDepth(InputInterface $input): int { $depth = $input->getOption('depth'); if (!is_numeric($depth)) { throw new \InvalidArgumentException("Option 'depth' must contains an integer value"); } return (int) $depth; }
[ "private", "function", "getDepth", "(", "InputInterface", "$", "input", ")", ":", "int", "{", "$", "depth", "=", "$", "input", "->", "getOption", "(", "'depth'", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "depth", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Option 'depth' must contains an integer value\"", ")", ";", "}", "return", "(", "int", ")", "$", "depth", ";", "}" ]
@param InputInterface $input @return int
[ "@param", "InputInterface", "$input" ]
train
https://github.com/chubbyphp/chubbyphp-model-doctrine-dbal/blob/1079c28f5bffc2e2bec04122742d5008464c167f/src/Command/RunSqlCommand.php#L71-L80
gregorybesson/PlaygroundCms
src/Form/Admin/Page.php
Page.getCmsCategories
public function getCmsCategories() { $categories = array('' => 'No category'); $results = $this->getEventManager() ->trigger(__FUNCTION__, $this, array( 'categories' => $categories )) ->last(); if ($results) { $categories = $results; } return $categories; }
php
public function getCmsCategories() { $categories = array('' => 'No category'); $results = $this->getEventManager() ->trigger(__FUNCTION__, $this, array( 'categories' => $categories )) ->last(); if ($results) { $categories = $results; } return $categories; }
[ "public", "function", "getCmsCategories", "(", ")", "{", "$", "categories", "=", "array", "(", "''", "=>", "'No category'", ")", ";", "$", "results", "=", "$", "this", "->", "getEventManager", "(", ")", "->", "trigger", "(", "__FUNCTION__", ",", "$", "this", ",", "array", "(", "'categories'", "=>", "$", "categories", ")", ")", "->", "last", "(", ")", ";", "if", "(", "$", "results", ")", "{", "$", "categories", "=", "$", "results", ";", "}", "return", "$", "categories", ";", "}" ]
An event is triggered so that the modules wishing to associate a category to a CMS page can add their own categories without adherence between the 2 modules @return array
[ "An", "event", "is", "triggered", "so", "that", "the", "modules", "wishing", "to", "associate", "a", "category", "to", "a", "CMS", "page", "can", "add", "their", "own", "categories", "without", "adherence", "between", "the", "2", "modules" ]
train
https://github.com/gregorybesson/PlaygroundCms/blob/e929a283f2a6e82d4f248c930f7aa454ce20cbc3/src/Form/Admin/Page.php#L208-L223
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.checkSchemaReader
static private function checkSchemaReader( ezcDbSchemaReader $obj, $type ) { if ( !( ( $obj->getReaderType() & $type ) == $type ) ) { throw new ezcDbSchemaInvalidReaderClassException( get_class( $obj ), $type ); } }
php
static private function checkSchemaReader( ezcDbSchemaReader $obj, $type ) { if ( !( ( $obj->getReaderType() & $type ) == $type ) ) { throw new ezcDbSchemaInvalidReaderClassException( get_class( $obj ), $type ); } }
[ "static", "private", "function", "checkSchemaReader", "(", "ezcDbSchemaReader", "$", "obj", ",", "$", "type", ")", "{", "if", "(", "!", "(", "(", "$", "obj", "->", "getReaderType", "(", ")", "&", "$", "type", ")", "==", "$", "type", ")", ")", "{", "throw", "new", "ezcDbSchemaInvalidReaderClassException", "(", "get_class", "(", "$", "obj", ")", ",", "$", "type", ")", ";", "}", "}" ]
Checks whether the object in $obj implements the correct $type of reader handler. @throws ezcDbSchemaInvalidReaderClassException if the object in $obj is not a schema reader of the correct type. @param ezcDbSchemaReader $obj @param int $type
[ "Checks", "whether", "the", "object", "in", "$obj", "implements", "the", "correct", "$type", "of", "reader", "handler", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L124-L130
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.createFromFile
static public function createFromFile( $format, $file ) { $className = ezcDbSchemaHandlerManager::getReaderByFormat( $format ); $reader = new $className(); self::checkSchemaReader( $reader, self::FILE ); return $reader->loadFromFile( $file ); }
php
static public function createFromFile( $format, $file ) { $className = ezcDbSchemaHandlerManager::getReaderByFormat( $format ); $reader = new $className(); self::checkSchemaReader( $reader, self::FILE ); return $reader->loadFromFile( $file ); }
[ "static", "public", "function", "createFromFile", "(", "$", "format", ",", "$", "file", ")", "{", "$", "className", "=", "ezcDbSchemaHandlerManager", "::", "getReaderByFormat", "(", "$", "format", ")", ";", "$", "reader", "=", "new", "$", "className", "(", ")", ";", "self", "::", "checkSchemaReader", "(", "$", "reader", ",", "self", "::", "FILE", ")", ";", "return", "$", "reader", "->", "loadFromFile", "(", "$", "file", ")", ";", "}" ]
Factory method to create a ezcDbSchema object from the file $file with the format $format. @throws ezcDbSchemaInvalidReaderClassException if the handler associated with the $format is not a file schema reader. @param string $format @param string $file
[ "Factory", "method", "to", "create", "a", "ezcDbSchema", "object", "from", "the", "file", "$file", "with", "the", "format", "$format", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L141-L147
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.createFromDb
static public function createFromDb( ezcDbHandler $db ) { self::initOptions(); $className = ezcDbSchemaHandlerManager::getReaderByFormat( $db->getName() ); $reader = new $className(); self::checkSchemaReader( $reader, self::DATABASE ); return $reader->loadFromDb( $db ); }
php
static public function createFromDb( ezcDbHandler $db ) { self::initOptions(); $className = ezcDbSchemaHandlerManager::getReaderByFormat( $db->getName() ); $reader = new $className(); self::checkSchemaReader( $reader, self::DATABASE ); return $reader->loadFromDb( $db ); }
[ "static", "public", "function", "createFromDb", "(", "ezcDbHandler", "$", "db", ")", "{", "self", "::", "initOptions", "(", ")", ";", "$", "className", "=", "ezcDbSchemaHandlerManager", "::", "getReaderByFormat", "(", "$", "db", "->", "getName", "(", ")", ")", ";", "$", "reader", "=", "new", "$", "className", "(", ")", ";", "self", "::", "checkSchemaReader", "(", "$", "reader", ",", "self", "::", "DATABASE", ")", ";", "return", "$", "reader", "->", "loadFromDb", "(", "$", "db", ")", ";", "}" ]
Factory method to create a ezcDbSchema object from the database $db. @throws ezcDbSchemaInvalidReaderClassException if the handler associated with the $format is not a database schema reader. @param ezcDbHandler $db
[ "Factory", "method", "to", "create", "a", "ezcDbSchema", "object", "from", "the", "database", "$db", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L157-L164
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.checkSchemaWriter
static private function checkSchemaWriter( $obj, $type ) { if ( !( ( $obj->getWriterType() & $type ) == $type ) ) { throw new ezcDbSchemaInvalidWriterClassException( get_class( $obj ), $type ); } }
php
static private function checkSchemaWriter( $obj, $type ) { if ( !( ( $obj->getWriterType() & $type ) == $type ) ) { throw new ezcDbSchemaInvalidWriterClassException( get_class( $obj ), $type ); } }
[ "static", "private", "function", "checkSchemaWriter", "(", "$", "obj", ",", "$", "type", ")", "{", "if", "(", "!", "(", "(", "$", "obj", "->", "getWriterType", "(", ")", "&", "$", "type", ")", "==", "$", "type", ")", ")", "{", "throw", "new", "ezcDbSchemaInvalidWriterClassException", "(", "get_class", "(", "$", "obj", ")", ",", "$", "type", ")", ";", "}", "}" ]
Checks whether the object in $obj implements the correct $type of writer handler. @throws ezcDbSchemaInvalidWriterClassException if the object in $obj is not a schema writer of the correct type. @param ezcDbSchemaWriter $obj @param int $type
[ "Checks", "whether", "the", "object", "in", "$obj", "implements", "the", "correct", "$type", "of", "writer", "handler", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L175-L181
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.writeToFile
public function writeToFile( $format, $file ) { $className = ezcDbSchemaHandlerManager::getWriterByFormat( $format ); $reader = new $className(); self::checkSchemaWriter( $reader, self::FILE ); $reader->saveToFile( $file, $this ); }
php
public function writeToFile( $format, $file ) { $className = ezcDbSchemaHandlerManager::getWriterByFormat( $format ); $reader = new $className(); self::checkSchemaWriter( $reader, self::FILE ); $reader->saveToFile( $file, $this ); }
[ "public", "function", "writeToFile", "(", "$", "format", ",", "$", "file", ")", "{", "$", "className", "=", "ezcDbSchemaHandlerManager", "::", "getWriterByFormat", "(", "$", "format", ")", ";", "$", "reader", "=", "new", "$", "className", "(", ")", ";", "self", "::", "checkSchemaWriter", "(", "$", "reader", ",", "self", "::", "FILE", ")", ";", "$", "reader", "->", "saveToFile", "(", "$", "file", ",", "$", "this", ")", ";", "}" ]
Writes the schema to the file $file in format $format. @throws ezcDbSchemaInvalidWriterClassException if the handler associated with the $format is not a file schema writer. @param string $format Available formats are at least: 'array' and 'xml'. @param string $file
[ "Writes", "the", "schema", "to", "the", "file", "$file", "in", "format", "$format", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L192-L198
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.writeToDb
public function writeToDb( ezcDbHandler $db ) { self::initOptions(); $className = ezcDbSchemaHandlerManager::getWriterByFormat( $db->getName() ); $writer = new $className(); self::checkSchemaWriter( $writer, self::DATABASE ); $writer->saveToDb( $db, $this ); }
php
public function writeToDb( ezcDbHandler $db ) { self::initOptions(); $className = ezcDbSchemaHandlerManager::getWriterByFormat( $db->getName() ); $writer = new $className(); self::checkSchemaWriter( $writer, self::DATABASE ); $writer->saveToDb( $db, $this ); }
[ "public", "function", "writeToDb", "(", "ezcDbHandler", "$", "db", ")", "{", "self", "::", "initOptions", "(", ")", ";", "$", "className", "=", "ezcDbSchemaHandlerManager", "::", "getWriterByFormat", "(", "$", "db", "->", "getName", "(", ")", ")", ";", "$", "writer", "=", "new", "$", "className", "(", ")", ";", "self", "::", "checkSchemaWriter", "(", "$", "writer", ",", "self", "::", "DATABASE", ")", ";", "$", "writer", "->", "saveToDb", "(", "$", "db", ",", "$", "this", ")", ";", "}" ]
Creates the tables defined in the schema into the database specified through $db. @throws ezcDbSchemaInvalidWriterClassException if the handler associated with the $format is not a database schema writer. @param ezcDbHandler $db
[ "Creates", "the", "tables", "defined", "in", "the", "schema", "into", "the", "database", "specified", "through", "$db", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L208-L215
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.convertToDDL
public function convertToDDL( $db ) { self::initOptions(); if ( $db instanceof ezcDbHandler ) { $db = $db->getName(); } $className = ezcDbSchemaHandlerManager::getDiffWriterByFormat( $db ); $writer = new $className(); self::checkSchemaWriter( $writer, self::DATABASE ); return $writer->convertToDDL( $this ); }
php
public function convertToDDL( $db ) { self::initOptions(); if ( $db instanceof ezcDbHandler ) { $db = $db->getName(); } $className = ezcDbSchemaHandlerManager::getDiffWriterByFormat( $db ); $writer = new $className(); self::checkSchemaWriter( $writer, self::DATABASE ); return $writer->convertToDDL( $this ); }
[ "public", "function", "convertToDDL", "(", "$", "db", ")", "{", "self", "::", "initOptions", "(", ")", ";", "if", "(", "$", "db", "instanceof", "ezcDbHandler", ")", "{", "$", "db", "=", "$", "db", "->", "getName", "(", ")", ";", "}", "$", "className", "=", "ezcDbSchemaHandlerManager", "::", "getDiffWriterByFormat", "(", "$", "db", ")", ";", "$", "writer", "=", "new", "$", "className", "(", ")", ";", "self", "::", "checkSchemaWriter", "(", "$", "writer", ",", "self", "::", "DATABASE", ")", ";", "return", "$", "writer", "->", "convertToDDL", "(", "$", "this", ")", ";", "}" ]
Returns the $db specific SQL queries that would create the tables defined in the schema. The database type can be given as both a database handler (instanceof ezcDbHandler) or the name of the database as string as retrieved through calling getName() on the database handler object. @see ezcDbHandler::getName() @throws ezcDbSchemaInvalidWriterClassException if the handler associated with the $format is not a database schema writer. @param string|ezcDbHandler $db @return array(string)
[ "Returns", "the", "$db", "specific", "SQL", "queries", "that", "would", "create", "the", "tables", "defined", "in", "the", "schema", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L233-L244
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.createNewTable
static public function createNewTable( $fields, $indexes ) { self::initOptions(); $className = ezcDbSchema::$options->tableClassName; return new $className( $fields, $indexes ); }
php
static public function createNewTable( $fields, $indexes ) { self::initOptions(); $className = ezcDbSchema::$options->tableClassName; return new $className( $fields, $indexes ); }
[ "static", "public", "function", "createNewTable", "(", "$", "fields", ",", "$", "indexes", ")", "{", "self", "::", "initOptions", "(", ")", ";", "$", "className", "=", "ezcDbSchema", "::", "$", "options", "->", "tableClassName", ";", "return", "new", "$", "className", "(", "$", "fields", ",", "$", "indexes", ")", ";", "}" ]
Returns an object to represent a table in the schema. @param array(string=>ezcDbSchemaField) $fields @param array(string=>ezcDbSchemaIndex) $indexes @return ezcDbSchemaTable or an inherited class
[ "Returns", "an", "object", "to", "represent", "a", "table", "in", "the", "schema", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L304-L309
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.createNewField
static public function createNewField( $fieldType, $fieldLength, $fieldNotNull, $fieldDefault, $fieldAutoIncrement, $fieldUnsigned ) { self::initOptions(); $className = ezcDbSchema::$options->fieldClassName; return new $className( $fieldType, $fieldLength, $fieldNotNull, $fieldDefault, $fieldAutoIncrement, $fieldUnsigned ); }
php
static public function createNewField( $fieldType, $fieldLength, $fieldNotNull, $fieldDefault, $fieldAutoIncrement, $fieldUnsigned ) { self::initOptions(); $className = ezcDbSchema::$options->fieldClassName; return new $className( $fieldType, $fieldLength, $fieldNotNull, $fieldDefault, $fieldAutoIncrement, $fieldUnsigned ); }
[ "static", "public", "function", "createNewField", "(", "$", "fieldType", ",", "$", "fieldLength", ",", "$", "fieldNotNull", ",", "$", "fieldDefault", ",", "$", "fieldAutoIncrement", ",", "$", "fieldUnsigned", ")", "{", "self", "::", "initOptions", "(", ")", ";", "$", "className", "=", "ezcDbSchema", "::", "$", "options", "->", "fieldClassName", ";", "return", "new", "$", "className", "(", "$", "fieldType", ",", "$", "fieldLength", ",", "$", "fieldNotNull", ",", "$", "fieldDefault", ",", "$", "fieldAutoIncrement", ",", "$", "fieldUnsigned", ")", ";", "}" ]
Returns an object to represent a table's field in the schema. @param string $fieldType @param integer $fieldLength @param bool $fieldNotNull @param mixed $fieldDefault @param bool $fieldAutoIncrement @param bool $fieldUnsigned @return ezcDbSchemaField or an inherited class
[ "Returns", "an", "object", "to", "represent", "a", "table", "s", "field", "in", "the", "schema", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L322-L327
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.createNewIndex
static public function createNewIndex( $fields, $primary, $unique ) { self::initOptions(); $className = ezcDbSchema::$options->indexClassName; return new $className( $fields, $primary, $unique ); }
php
static public function createNewIndex( $fields, $primary, $unique ) { self::initOptions(); $className = ezcDbSchema::$options->indexClassName; return new $className( $fields, $primary, $unique ); }
[ "static", "public", "function", "createNewIndex", "(", "$", "fields", ",", "$", "primary", ",", "$", "unique", ")", "{", "self", "::", "initOptions", "(", ")", ";", "$", "className", "=", "ezcDbSchema", "::", "$", "options", "->", "indexClassName", ";", "return", "new", "$", "className", "(", "$", "fields", ",", "$", "primary", ",", "$", "unique", ")", ";", "}" ]
Returns an object to represent a table's field in the schema. @param array(string=>ezcDbSchemaIndexField) $fields @param bool $primary @param bool $unique @return ezcDbSchemaIndex or an inherited class
[ "Returns", "an", "object", "to", "represent", "a", "table", "s", "field", "in", "the", "schema", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L337-L342
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php
ezcDbSchema.createNewIndexField
static public function createNewIndexField( $sorting = null ) { self::initOptions(); $className = ezcDbSchema::$options->indexFieldClassName; return new $className( $sorting ); }
php
static public function createNewIndexField( $sorting = null ) { self::initOptions(); $className = ezcDbSchema::$options->indexFieldClassName; return new $className( $sorting ); }
[ "static", "public", "function", "createNewIndexField", "(", "$", "sorting", "=", "null", ")", "{", "self", "::", "initOptions", "(", ")", ";", "$", "className", "=", "ezcDbSchema", "::", "$", "options", "->", "indexFieldClassName", ";", "return", "new", "$", "className", "(", "$", "sorting", ")", ";", "}" ]
Returns an object to represent a table's field in the schema. @param int $sorting @return ezcDbSchemaIndexField or an inherited class
[ "Returns", "an", "object", "to", "represent", "a", "table", "s", "field", "in", "the", "schema", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/schema.php#L350-L355
oroinc/OroLayoutComponent
Extension/Theme/ThemeExtension.php
ThemeExtension.loadLayoutUpdates
protected function loadLayoutUpdates(ContextInterface $context) { if ($context->getOr(self::THEME_KEY)) { $paths = $this->getPaths($context); $files = $this->resourceProvider->findApplicableResources($paths); foreach ($files as $file) { $this->loadLayoutUpdate($file); } } foreach ($this->visitors as $visitor) { $visitor->walkUpdates($this->updates, $context); } return $this->updates; }
php
protected function loadLayoutUpdates(ContextInterface $context) { if ($context->getOr(self::THEME_KEY)) { $paths = $this->getPaths($context); $files = $this->resourceProvider->findApplicableResources($paths); foreach ($files as $file) { $this->loadLayoutUpdate($file); } } foreach ($this->visitors as $visitor) { $visitor->walkUpdates($this->updates, $context); } return $this->updates; }
[ "protected", "function", "loadLayoutUpdates", "(", "ContextInterface", "$", "context", ")", "{", "if", "(", "$", "context", "->", "getOr", "(", "self", "::", "THEME_KEY", ")", ")", "{", "$", "paths", "=", "$", "this", "->", "getPaths", "(", "$", "context", ")", ";", "$", "files", "=", "$", "this", "->", "resourceProvider", "->", "findApplicableResources", "(", "$", "paths", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "this", "->", "loadLayoutUpdate", "(", "$", "file", ")", ";", "}", "}", "foreach", "(", "$", "this", "->", "visitors", "as", "$", "visitor", ")", "{", "$", "visitor", "->", "walkUpdates", "(", "$", "this", "->", "updates", ",", "$", "context", ")", ";", "}", "return", "$", "this", "->", "updates", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/ThemeExtension.php#L66-L81
oroinc/OroLayoutComponent
Extension/Theme/ThemeExtension.php
ThemeExtension.loadLayoutUpdate
protected function loadLayoutUpdate($file) { $update = $this->loader->load($file); if ($update) { $el = $update instanceof ElementDependentLayoutUpdateInterface ? $update->getElement() : 'root'; $this->updates[$el][] = $update; $this->dependencyInitializer->initialize($update); } }
php
protected function loadLayoutUpdate($file) { $update = $this->loader->load($file); if ($update) { $el = $update instanceof ElementDependentLayoutUpdateInterface ? $update->getElement() : 'root'; $this->updates[$el][] = $update; $this->dependencyInitializer->initialize($update); } }
[ "protected", "function", "loadLayoutUpdate", "(", "$", "file", ")", "{", "$", "update", "=", "$", "this", "->", "loader", "->", "load", "(", "$", "file", ")", ";", "if", "(", "$", "update", ")", "{", "$", "el", "=", "$", "update", "instanceof", "ElementDependentLayoutUpdateInterface", "?", "$", "update", "->", "getElement", "(", ")", ":", "'root'", ";", "$", "this", "->", "updates", "[", "$", "el", "]", "[", "]", "=", "$", "update", ";", "$", "this", "->", "dependencyInitializer", "->", "initialize", "(", "$", "update", ")", ";", "}", "}" ]
@param string $file @return array
[ "@param", "string", "$file" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/ThemeExtension.php#L88-L99
oroinc/OroLayoutComponent
Extension/Theme/ThemeExtension.php
ThemeExtension.getPaths
protected function getPaths(ContextInterface $context) { if ($this->pathProvider instanceof ContextAwareInterface) { $this->pathProvider->setContext($context); } return $this->pathProvider->getPaths([]); }
php
protected function getPaths(ContextInterface $context) { if ($this->pathProvider instanceof ContextAwareInterface) { $this->pathProvider->setContext($context); } return $this->pathProvider->getPaths([]); }
[ "protected", "function", "getPaths", "(", "ContextInterface", "$", "context", ")", "{", "if", "(", "$", "this", "->", "pathProvider", "instanceof", "ContextAwareInterface", ")", "{", "$", "this", "->", "pathProvider", "->", "setContext", "(", "$", "context", ")", ";", "}", "return", "$", "this", "->", "pathProvider", "->", "getPaths", "(", "[", "]", ")", ";", "}" ]
Return paths that comes from provider and returns array of resource files @param ContextInterface $context @return array
[ "Return", "paths", "that", "comes", "from", "provider", "and", "returns", "array", "of", "resource", "files" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/ThemeExtension.php#L108-L115
inhere/php-librarys
src/Helpers/CurlHelper.php
CurlHelper.get
public static function get($url, array $params = [], array $headers = []) { if ($params) { $url .= (strpos($url, '?') ? '&' : '?') . http_build_query($params); } // $headers = [ 'Content-Type: application/json' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //伪造网页来源地址,伪造来自百度的表单提交 // curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com"); return self::execute($ch); }
php
public static function get($url, array $params = [], array $headers = []) { if ($params) { $url .= (strpos($url, '?') ? '&' : '?') . http_build_query($params); } // $headers = [ 'Content-Type: application/json' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //伪造网页来源地址,伪造来自百度的表单提交 // curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com"); return self::execute($ch); }
[ "public", "static", "function", "get", "(", "$", "url", ",", "array", "$", "params", "=", "[", "]", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "if", "(", "$", "params", ")", "{", "$", "url", ".=", "(", "strpos", "(", "$", "url", ",", "'?'", ")", "?", "'&'", ":", "'?'", ")", ".", "http_build_query", "(", "$", "params", ")", ";", "}", "// $headers = [ 'Content-Type: application/json' ];", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "$", "headers", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "//伪造网页来源地址,伪造来自百度的表单提交", "// curl_setopt($ch, CURLOPT_REFERER, \"http://www.baidu.com\");", "return", "self", "::", "execute", "(", "$", "ch", ")", ";", "}" ]
send GET request @param string $url url @param array $params url params @param array $headers HEADER info @return string
[ "send", "GET", "request" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/CurlHelper.php#L89-L106
inhere/php-librarys
src/Helpers/CurlHelper.php
CurlHelper.post
public static function post($url, array $data = [], array $headers = []) { // $headers = [ 'Content-Type: application/json' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 发送数据 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行HTTP请求 return self::execute($ch); }
php
public static function post($url, array $data = [], array $headers = []) { // $headers = [ 'Content-Type: application/json' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 发送数据 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行HTTP请求 return self::execute($ch); }
[ "public", "static", "function", "post", "(", "$", "url", ",", "array", "$", "data", "=", "[", "]", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "// $headers = [ 'Content-Type: application/json' ];", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "data", ")", ";", "// 发送数据", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "$", "headers", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "// 执行HTTP请求", "return", "self", "::", "execute", "(", "$", "ch", ")", ";", "}" ]
send POST request @param string $url submit url @param array|string $data post data. array: form data, string: json data @param array $headers HEADER info @return string
[ "send", "POST", "request" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/CurlHelper.php#L115-L129
inhere/php-librarys
src/Helpers/CurlHelper.php
CurlHelper.execute
public static function execute($ch, $retries = 3, $closeAfterDone = true) { $ret = ''; while ($retries--) { if (($ret = curl_exec($ch)) === false) { $curlErrNo = curl_errno($ch); if (false === \in_array($curlErrNo, self::$canRetryErrorCodes, true) || !$retries) { $curlError = curl_error($ch); if ($closeAfterDone) { curl_close($ch); } throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrNo, $curlError)); } continue; } if ($closeAfterDone) { curl_close($ch); } break; } return $ret; }
php
public static function execute($ch, $retries = 3, $closeAfterDone = true) { $ret = ''; while ($retries--) { if (($ret = curl_exec($ch)) === false) { $curlErrNo = curl_errno($ch); if (false === \in_array($curlErrNo, self::$canRetryErrorCodes, true) || !$retries) { $curlError = curl_error($ch); if ($closeAfterDone) { curl_close($ch); } throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrNo, $curlError)); } continue; } if ($closeAfterDone) { curl_close($ch); } break; } return $ret; }
[ "public", "static", "function", "execute", "(", "$", "ch", ",", "$", "retries", "=", "3", ",", "$", "closeAfterDone", "=", "true", ")", "{", "$", "ret", "=", "''", ";", "while", "(", "$", "retries", "--", ")", "{", "if", "(", "(", "$", "ret", "=", "curl_exec", "(", "$", "ch", ")", ")", "===", "false", ")", "{", "$", "curlErrNo", "=", "curl_errno", "(", "$", "ch", ")", ";", "if", "(", "false", "===", "\\", "in_array", "(", "$", "curlErrNo", ",", "self", "::", "$", "canRetryErrorCodes", ",", "true", ")", "||", "!", "$", "retries", ")", "{", "$", "curlError", "=", "curl_error", "(", "$", "ch", ")", ";", "if", "(", "$", "closeAfterDone", ")", "{", "curl_close", "(", "$", "ch", ")", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Curl error (code %s): %s'", ",", "$", "curlErrNo", ",", "$", "curlError", ")", ")", ";", "}", "continue", ";", "}", "if", "(", "$", "closeAfterDone", ")", "{", "curl_close", "(", "$", "ch", ")", ";", "}", "break", ";", "}", "return", "$", "ret", ";", "}" ]
Executes a CURL request with optional retries and exception on failure @param resource $ch curl handler @param int $retries 重试 @param bool $closeAfterDone @return string @throws \RuntimeException
[ "Executes", "a", "CURL", "request", "with", "optional", "retries", "and", "exception", "on", "failure" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/CurlHelper.php#L139-L166
php-lug/lug
src/Bundle/GridBundle/Form/Type/GridLimitType.php
GridLimitType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'label' => 'lug.limit', 'empty_data' => function (Options $options) { $grid = $options['grid']; return $grid->hasOption('limit_default') ? (string) $grid->getOption('limit_default') : '10'; }, 'constraints' => function (Options $options) { $grid = $options['grid']; return new Range([ 'min' => $grid->hasOption('limit_min') ? $grid->getOption('limit_min') : 1, 'max' => $grid->hasOption('limit_max') ? $grid->getOption('limit_max') : 100, 'minMessage' => 'lug.grid.limit.min', 'maxMessage' => 'lug.grid.limit.max', ]); }, ]) ->setRequired('grid') ->setAllowedTypes('grid', GridInterface::class); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'label' => 'lug.limit', 'empty_data' => function (Options $options) { $grid = $options['grid']; return $grid->hasOption('limit_default') ? (string) $grid->getOption('limit_default') : '10'; }, 'constraints' => function (Options $options) { $grid = $options['grid']; return new Range([ 'min' => $grid->hasOption('limit_min') ? $grid->getOption('limit_min') : 1, 'max' => $grid->hasOption('limit_max') ? $grid->getOption('limit_max') : 100, 'minMessage' => 'lug.grid.limit.min', 'maxMessage' => 'lug.grid.limit.max', ]); }, ]) ->setRequired('grid') ->setAllowedTypes('grid', GridInterface::class); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "$", "resolver", "->", "setDefaults", "(", "[", "'label'", "=>", "'lug.limit'", ",", "'empty_data'", "=>", "function", "(", "Options", "$", "options", ")", "{", "$", "grid", "=", "$", "options", "[", "'grid'", "]", ";", "return", "$", "grid", "->", "hasOption", "(", "'limit_default'", ")", "?", "(", "string", ")", "$", "grid", "->", "getOption", "(", "'limit_default'", ")", ":", "'10'", ";", "}", ",", "'constraints'", "=>", "function", "(", "Options", "$", "options", ")", "{", "$", "grid", "=", "$", "options", "[", "'grid'", "]", ";", "return", "new", "Range", "(", "[", "'min'", "=>", "$", "grid", "->", "hasOption", "(", "'limit_min'", ")", "?", "$", "grid", "->", "getOption", "(", "'limit_min'", ")", ":", "1", ",", "'max'", "=>", "$", "grid", "->", "hasOption", "(", "'limit_max'", ")", "?", "$", "grid", "->", "getOption", "(", "'limit_max'", ")", ":", "100", ",", "'minMessage'", "=>", "'lug.grid.limit.min'", ",", "'maxMessage'", "=>", "'lug.grid.limit.max'", ",", "]", ")", ";", "}", ",", "]", ")", "->", "setRequired", "(", "'grid'", ")", "->", "setAllowedTypes", "(", "'grid'", ",", "GridInterface", "::", "class", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Form/Type/GridLimitType.php#L29-L52
adman9000/laravel-bittrex
src/BittrexAPI.php
BittrexAPI.marketRequest
public function marketRequest($segment, array $parameters=[]) { $baseUrl = $this->market_url; return $this->privateRequest($baseUrl, $segment, $parameters); }
php
public function marketRequest($segment, array $parameters=[]) { $baseUrl = $this->market_url; return $this->privateRequest($baseUrl, $segment, $parameters); }
[ "public", "function", "marketRequest", "(", "$", "segment", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "$", "baseUrl", "=", "$", "this", "->", "market_url", ";", "return", "$", "this", "->", "privateRequest", "(", "$", "baseUrl", ",", "$", "segment", ",", "$", "parameters", ")", ";", "}" ]
Execute a market API request @param $segment @param array $parameters @return array
[ "Execute", "a", "market", "API", "request" ]
train
https://github.com/adman9000/laravel-bittrex/blob/bd82b7926b23bd5e450b0a4232a91f176a78072d/src/BittrexAPI.php#L324-L327
adman9000/laravel-bittrex
src/BittrexAPI.php
BittrexAPI.accountRequest
public function accountRequest($segment, array $parameters=[]) { $baseUrl = $this->account_url; return $this->privateRequest($baseUrl, $segment, $parameters); }
php
public function accountRequest($segment, array $parameters=[]) { $baseUrl = $this->account_url; return $this->privateRequest($baseUrl, $segment, $parameters); }
[ "public", "function", "accountRequest", "(", "$", "segment", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "$", "baseUrl", "=", "$", "this", "->", "account_url", ";", "return", "$", "this", "->", "privateRequest", "(", "$", "baseUrl", ",", "$", "segment", ",", "$", "parameters", ")", ";", "}" ]
Execute an account API request @param $segment @param array $parameters @return array
[ "Execute", "an", "account", "API", "request" ]
train
https://github.com/adman9000/laravel-bittrex/blob/bd82b7926b23bd5e450b0a4232a91f176a78072d/src/BittrexAPI.php#L336-L339
Eresus/EresusCMS
src/core/lib/templates.php
Templates.enum
public function enum($type = '') { $result = array(); $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $dir = $legacyKernel->froot . 'templates/'; if ($type) { $dir .= "$type/"; } $list = glob("$dir*.html"); if ($list) { foreach ($list as $filename) { $file = file_get_contents($filename); $title = trim(mb_substr($file, 0, mb_strpos($file, "\n"))); if (preg_match('/^\{\*(.+)\*\}/', $title, $title)) { $title = trim($title[1]); } else { $title = 'n/a'; } $result[basename($filename, '.html')] = $title; } } return $result; }
php
public function enum($type = '') { $result = array(); $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $dir = $legacyKernel->froot . 'templates/'; if ($type) { $dir .= "$type/"; } $list = glob("$dir*.html"); if ($list) { foreach ($list as $filename) { $file = file_get_contents($filename); $title = trim(mb_substr($file, 0, mb_strpos($file, "\n"))); if (preg_match('/^\{\*(.+)\*\}/', $title, $title)) { $title = trim($title[1]); } else { $title = 'n/a'; } $result[basename($filename, '.html')] = $title; } } return $result; }
[ "public", "function", "enum", "(", "$", "type", "=", "''", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "legacyKernel", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getLegacyKernel", "(", ")", ";", "$", "dir", "=", "$", "legacyKernel", "->", "froot", ".", "'templates/'", ";", "if", "(", "$", "type", ")", "{", "$", "dir", ".=", "\"$type/\"", ";", "}", "$", "list", "=", "glob", "(", "\"$dir*.html\"", ")", ";", "if", "(", "$", "list", ")", "{", "foreach", "(", "$", "list", "as", "$", "filename", ")", "{", "$", "file", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "title", "=", "trim", "(", "mb_substr", "(", "$", "file", ",", "0", ",", "mb_strpos", "(", "$", "file", ",", "\"\\n\"", ")", ")", ")", ";", "if", "(", "preg_match", "(", "'/^\\{\\*(.+)\\*\\}/'", ",", "$", "title", ",", "$", "title", ")", ")", "{", "$", "title", "=", "trim", "(", "$", "title", "[", "1", "]", ")", ";", "}", "else", "{", "$", "title", "=", "'n/a'", ";", "}", "$", "result", "[", "basename", "(", "$", "filename", ",", "'.html'", ")", "]", "=", "$", "title", ";", "}", "}", "return", "$", "result", ";", "}" ]
Возвращает список шаблонов @param string $type Тип шаблонов (соответствует поддиректории в /templates) @return array
[ "Возвращает", "список", "шаблонов" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/lib/templates.php#L77-L105
Eresus/EresusCMS
src/core/lib/templates.php
Templates.get
public function get($name = '', $type = '', $array = false) { $filename = $this->composeFilename($name, $type); if (!file_exists($filename)) { return false; } $result = file_get_contents($filename); if ($array) { $desc = preg_match($this->pattern, $result); $result = array( 'name' => $name, 'desc' => $desc ? trim(preg_replace($this->pattern, '$1', $result)) : ADM_NA, 'code' => $desc ? trim(mb_substr($result, mb_strpos($result, "\n"))) : $result, ); } else { if (preg_match($this->pattern, $result)) { $result = trim(mb_substr($result, mb_strpos($result, "\n"))); } } return $result; }
php
public function get($name = '', $type = '', $array = false) { $filename = $this->composeFilename($name, $type); if (!file_exists($filename)) { return false; } $result = file_get_contents($filename); if ($array) { $desc = preg_match($this->pattern, $result); $result = array( 'name' => $name, 'desc' => $desc ? trim(preg_replace($this->pattern, '$1', $result)) : ADM_NA, 'code' => $desc ? trim(mb_substr($result, mb_strpos($result, "\n"))) : $result, ); } else { if (preg_match($this->pattern, $result)) { $result = trim(mb_substr($result, mb_strpos($result, "\n"))); } } return $result; }
[ "public", "function", "get", "(", "$", "name", "=", "''", ",", "$", "type", "=", "''", ",", "$", "array", "=", "false", ")", "{", "$", "filename", "=", "$", "this", "->", "composeFilename", "(", "$", "name", ",", "$", "type", ")", ";", "if", "(", "!", "file_exists", "(", "$", "filename", ")", ")", "{", "return", "false", ";", "}", "$", "result", "=", "file_get_contents", "(", "$", "filename", ")", ";", "if", "(", "$", "array", ")", "{", "$", "desc", "=", "preg_match", "(", "$", "this", "->", "pattern", ",", "$", "result", ")", ";", "$", "result", "=", "array", "(", "'name'", "=>", "$", "name", ",", "'desc'", "=>", "$", "desc", "?", "trim", "(", "preg_replace", "(", "$", "this", "->", "pattern", ",", "'$1'", ",", "$", "result", ")", ")", ":", "ADM_NA", ",", "'code'", "=>", "$", "desc", "?", "trim", "(", "mb_substr", "(", "$", "result", ",", "mb_strpos", "(", "$", "result", ",", "\"\\n\"", ")", ")", ")", ":", "$", "result", ",", ")", ";", "}", "else", "{", "if", "(", "preg_match", "(", "$", "this", "->", "pattern", ",", "$", "result", ")", ")", "{", "$", "result", "=", "trim", "(", "mb_substr", "(", "$", "result", ",", "mb_strpos", "(", "$", "result", ",", "\"\\n\"", ")", ")", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Возвращает содержимое шаблона Если имя ($name) не указано, будет использовано имя «default». Если шаблон не найден и имя ($name) НЕ «default», будет предпринята попытка загрузить шаблон с именем «default» из той же папки ($type). @param string $name имя шаблона @param string $type тип шаблона (соответствует поддиректории в /templates) @param bool $array вернуть шаблон в виде массива @return string|bool содержимое шаблона или false, если шаблон не найден
[ "Возвращает", "содержимое", "шаблона" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/lib/templates.php#L121-L146
Eresus/EresusCMS
src/core/lib/templates.php
Templates.load
public function load($name = '', $type = '') { $filename = $this->composeFilename($name, $type); if (!file_exists($filename)) { return null; } $template = Eresus_Template::loadFromFile($filename); return $template; }
php
public function load($name = '', $type = '') { $filename = $this->composeFilename($name, $type); if (!file_exists($filename)) { return null; } $template = Eresus_Template::loadFromFile($filename); return $template; }
[ "public", "function", "load", "(", "$", "name", "=", "''", ",", "$", "type", "=", "''", ")", "{", "$", "filename", "=", "$", "this", "->", "composeFilename", "(", "$", "name", ",", "$", "type", ")", ";", "if", "(", "!", "file_exists", "(", "$", "filename", ")", ")", "{", "return", "null", ";", "}", "$", "template", "=", "Eresus_Template", "::", "loadFromFile", "(", "$", "filename", ")", ";", "return", "$", "template", ";", "}" ]
Возвращает шаблон Если имя ($name) не указано, будет использовано имя «default». Если шаблон не найден и имя ($name) НЕ «default», будет предпринята попытка загрузить шаблон с именем «default» из той же папки ($type). @param string $name имя шаблона @param string $type тип шаблона (соответствует поддиректории в /templates) @return Eresus_Template|null шаблон или null, если шаблон не найден @since 3.01
[ "Возвращает", "шаблон" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/lib/templates.php#L163-L172
Eresus/EresusCMS
src/core/lib/templates.php
Templates.add
public function add($name, $type, $code, $desc = '') { $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $filename = $legacyKernel->froot . 'templates/'; if ($type) { $filename .= "$type/"; } $filename .= "$name.html"; $content = "{* $desc *}\n$code"; $result = file_put_contents($filename, $content) > 0; return $result; }
php
public function add($name, $type, $code, $desc = '') { $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $filename = $legacyKernel->froot . 'templates/'; if ($type) { $filename .= "$type/"; } $filename .= "$name.html"; $content = "{* $desc *}\n$code"; $result = file_put_contents($filename, $content) > 0; return $result; }
[ "public", "function", "add", "(", "$", "name", ",", "$", "type", ",", "$", "code", ",", "$", "desc", "=", "''", ")", "{", "$", "legacyKernel", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getLegacyKernel", "(", ")", ";", "$", "filename", "=", "$", "legacyKernel", "->", "froot", ".", "'templates/'", ";", "if", "(", "$", "type", ")", "{", "$", "filename", ".=", "\"$type/\"", ";", "}", "$", "filename", ".=", "\"$name.html\"", ";", "$", "content", "=", "\"{* $desc *}\\n$code\"", ";", "$", "result", "=", "file_put_contents", "(", "$", "filename", ",", "$", "content", ")", ">", "0", ";", "return", "$", "result", ";", "}" ]
Новый шаблон @param string $name Имя шаблона @param string $type Тип шаблона (соответствует поддиректории в /templates) @param string $code Содержимое шаблона @param string $desc Описание шаблона (необязательно) @return bool Результат выполнения
[ "Новый", "шаблон" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/lib/templates.php#L183-L195
Eresus/EresusCMS
src/core/lib/templates.php
Templates.update
public function update($name, $type, $code, $desc = null) { $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $filename = $legacyKernel->froot . 'templates/'; if ($type) { $filename .= "$type/"; } $filename .= "$name.html"; $item = $this->get($name, $type, true); $item['code'] = $code; if (!is_null($desc)) { $item['desc'] = $desc; } $content = "{* {$item['desc']} *}\n{$item['code']}"; $result = file_put_contents($filename, $content) > 0; return $result; }
php
public function update($name, $type, $code, $desc = null) { $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $filename = $legacyKernel->froot . 'templates/'; if ($type) { $filename .= "$type/"; } $filename .= "$name.html"; $item = $this->get($name, $type, true); $item['code'] = $code; if (!is_null($desc)) { $item['desc'] = $desc; } $content = "{* {$item['desc']} *}\n{$item['code']}"; $result = file_put_contents($filename, $content) > 0; return $result; }
[ "public", "function", "update", "(", "$", "name", ",", "$", "type", ",", "$", "code", ",", "$", "desc", "=", "null", ")", "{", "$", "legacyKernel", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getLegacyKernel", "(", ")", ";", "$", "filename", "=", "$", "legacyKernel", "->", "froot", ".", "'templates/'", ";", "if", "(", "$", "type", ")", "{", "$", "filename", ".=", "\"$type/\"", ";", "}", "$", "filename", ".=", "\"$name.html\"", ";", "$", "item", "=", "$", "this", "->", "get", "(", "$", "name", ",", "$", "type", ",", "true", ")", ";", "$", "item", "[", "'code'", "]", "=", "$", "code", ";", "if", "(", "!", "is_null", "(", "$", "desc", ")", ")", "{", "$", "item", "[", "'desc'", "]", "=", "$", "desc", ";", "}", "$", "content", "=", "\"{* {$item['desc']} *}\\n{$item['code']}\"", ";", "$", "result", "=", "file_put_contents", "(", "$", "filename", ",", "$", "content", ")", ">", "0", ";", "return", "$", "result", ";", "}" ]
Изменяет шаблон @param string $name Имя шаблона @param string $type Тип шаблона (соответствует поддиректории в /templates) @param string $code Содержимое шаблона @param string $desc Описание шаблона (необязательно) @return bool Результат выполнения
[ "Изменяет", "шаблон" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/lib/templates.php#L206-L224
Eresus/EresusCMS
src/core/lib/templates.php
Templates.delete
public function delete($name, $type = '') { $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $filename = $legacyKernel->froot . 'templates/'; if ($type) { $filename .= "$type/"; } $filename .= "$name.html"; $result = filedelete($filename); return $result; }
php
public function delete($name, $type = '') { $legacyKernel = Eresus_Kernel::app()->getLegacyKernel(); $filename = $legacyKernel->froot . 'templates/'; if ($type) { $filename .= "$type/"; } $filename .= "$name.html"; $result = filedelete($filename); return $result; }
[ "public", "function", "delete", "(", "$", "name", ",", "$", "type", "=", "''", ")", "{", "$", "legacyKernel", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getLegacyKernel", "(", ")", ";", "$", "filename", "=", "$", "legacyKernel", "->", "froot", ".", "'templates/'", ";", "if", "(", "$", "type", ")", "{", "$", "filename", ".=", "\"$type/\"", ";", "}", "$", "filename", ".=", "\"$name.html\"", ";", "$", "result", "=", "filedelete", "(", "$", "filename", ")", ";", "return", "$", "result", ";", "}" ]
Удаляет шаблон @param string $name Имя шаблона @param string $type Тип шаблона (соответствует поддиректории в /templates) @return bool Результат выполнения
[ "Удаляет", "шаблон" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/lib/templates.php#L234-L245
Eresus/EresusCMS
src/core/lib/templates.php
Templates.composeFilename
private function composeFilename($name, $type) { if (empty($name)) { $name = 'default'; } $folder = Eresus_Kernel::app()->getFsRoot() . '/templates/'; if ($type) { $folder .= $type . '/'; } $filename = $folder . $name . '.html'; if (!file_exists($filename) && 'default' != $name) { $filename = $folder . 'default.html'; } return $filename; }
php
private function composeFilename($name, $type) { if (empty($name)) { $name = 'default'; } $folder = Eresus_Kernel::app()->getFsRoot() . '/templates/'; if ($type) { $folder .= $type . '/'; } $filename = $folder . $name . '.html'; if (!file_exists($filename) && 'default' != $name) { $filename = $folder . 'default.html'; } return $filename; }
[ "private", "function", "composeFilename", "(", "$", "name", ",", "$", "type", ")", "{", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "$", "name", "=", "'default'", ";", "}", "$", "folder", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getFsRoot", "(", ")", ".", "'/templates/'", ";", "if", "(", "$", "type", ")", "{", "$", "folder", ".=", "$", "type", ".", "'/'", ";", "}", "$", "filename", "=", "$", "folder", ".", "$", "name", ".", "'.html'", ";", "if", "(", "!", "file_exists", "(", "$", "filename", ")", "&&", "'default'", "!=", "$", "name", ")", "{", "$", "filename", "=", "$", "folder", ".", "'default.html'", ";", "}", "return", "$", "filename", ";", "}" ]
Строит имя файла по правилам, описанным в {@link get()} @param string $name имя шаблона @param string $type тип шаблона @return string @since 3.01
[ "Строит", "имя", "файла", "по", "правилам", "описанным", "в", "{", "@link", "get", "()", "}" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/lib/templates.php#L264-L281
99designs/ergo-http
src/Transport.php
Transport._curlConnection
private function _curlConnection($request) { // create a new curl resource $curl = curl_init(); $method = $request->getRequestMethod(); $headers = array('Expect:'); // add existing headers into a flat string format foreach ($request->getHeaders() as $header) { $headers[] = rtrim($header->__toString()); } // set URL and other appropriate options curl_setopt($curl, CURLOPT_URL, $request->getUrl()); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_VERBOSE, false); curl_setopt($curl, CURLOPT_TIMEOUT_MS, $this->_timeout * 1000); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, $this->_connectTimeoutMs); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_PROTOCOLS, (CURLPROTO_HTTP | CURLPROTO_HTTPS)); curl_setopt($curl, CURLOPT_REDIR_PROTOCOLS, (CURLPROTO_HTTP | CURLPROTO_HTTPS)); // Prevents issues with curl timing out much faster than the specified timeout curl_setopt($curl, CURLOPT_NOSIGNAL, 1); if (isset($this->_ipFamily)) { curl_setopt($curl, CURLOPT_IPRESOLVE, $this->_ipFamily); } // enable proxy support if (isset($this->_proxy)) { curl_setopt($curl, CURLOPT_PROXY, $this->_proxy); } // enable http authentication if (isset($this->_auth)) { curl_setopt($curl, CURLOPT_USERPWD, $this->_auth); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } if ($method == 'PUT' || $method == 'POST') { $headers[] = 'Content-Length: ' . strlen($request->getBody()); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getBody()); } elseif ($method == 'DELETE') { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); } // add HTTP headers curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); return $curl; }
php
private function _curlConnection($request) { // create a new curl resource $curl = curl_init(); $method = $request->getRequestMethod(); $headers = array('Expect:'); // add existing headers into a flat string format foreach ($request->getHeaders() as $header) { $headers[] = rtrim($header->__toString()); } // set URL and other appropriate options curl_setopt($curl, CURLOPT_URL, $request->getUrl()); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_VERBOSE, false); curl_setopt($curl, CURLOPT_TIMEOUT_MS, $this->_timeout * 1000); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, $this->_connectTimeoutMs); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_PROTOCOLS, (CURLPROTO_HTTP | CURLPROTO_HTTPS)); curl_setopt($curl, CURLOPT_REDIR_PROTOCOLS, (CURLPROTO_HTTP | CURLPROTO_HTTPS)); // Prevents issues with curl timing out much faster than the specified timeout curl_setopt($curl, CURLOPT_NOSIGNAL, 1); if (isset($this->_ipFamily)) { curl_setopt($curl, CURLOPT_IPRESOLVE, $this->_ipFamily); } // enable proxy support if (isset($this->_proxy)) { curl_setopt($curl, CURLOPT_PROXY, $this->_proxy); } // enable http authentication if (isset($this->_auth)) { curl_setopt($curl, CURLOPT_USERPWD, $this->_auth); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } if ($method == 'PUT' || $method == 'POST') { $headers[] = 'Content-Length: ' . strlen($request->getBody()); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getBody()); } elseif ($method == 'DELETE') { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); } // add HTTP headers curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); return $curl; }
[ "private", "function", "_curlConnection", "(", "$", "request", ")", "{", "// create a new curl resource", "$", "curl", "=", "curl_init", "(", ")", ";", "$", "method", "=", "$", "request", "->", "getRequestMethod", "(", ")", ";", "$", "headers", "=", "array", "(", "'Expect:'", ")", ";", "// add existing headers into a flat string format", "foreach", "(", "$", "request", "->", "getHeaders", "(", ")", "as", "$", "header", ")", "{", "$", "headers", "[", "]", "=", "rtrim", "(", "$", "header", "->", "__toString", "(", ")", ")", ";", "}", "// set URL and other appropriate options", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_URL", ",", "$", "request", "->", "getUrl", "(", ")", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_HEADER", ",", "true", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_VERBOSE", ",", "false", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_TIMEOUT_MS", ",", "$", "this", "->", "_timeout", "*", "1000", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_CONNECTTIMEOUT_MS", ",", "$", "this", "->", "_connectTimeoutMs", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_SSL_VERIFYPEER", ",", "false", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_SSL_VERIFYHOST", ",", "false", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_PROTOCOLS", ",", "(", "CURLPROTO_HTTP", "|", "CURLPROTO_HTTPS", ")", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_REDIR_PROTOCOLS", ",", "(", "CURLPROTO_HTTP", "|", "CURLPROTO_HTTPS", ")", ")", ";", "// Prevents issues with curl timing out much faster than the specified timeout", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_NOSIGNAL", ",", "1", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "_ipFamily", ")", ")", "{", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_IPRESOLVE", ",", "$", "this", "->", "_ipFamily", ")", ";", "}", "// enable proxy support", "if", "(", "isset", "(", "$", "this", "->", "_proxy", ")", ")", "{", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_PROXY", ",", "$", "this", "->", "_proxy", ")", ";", "}", "// enable http authentication", "if", "(", "isset", "(", "$", "this", "->", "_auth", ")", ")", "{", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_USERPWD", ",", "$", "this", "->", "_auth", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_HTTPAUTH", ",", "CURLAUTH_BASIC", ")", ";", "}", "if", "(", "$", "method", "==", "'PUT'", "||", "$", "method", "==", "'POST'", ")", "{", "$", "headers", "[", "]", "=", "'Content-Length: '", ".", "strlen", "(", "$", "request", "->", "getBody", "(", ")", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_CUSTOMREQUEST", ",", "$", "method", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_POSTFIELDS", ",", "$", "request", "->", "getBody", "(", ")", ")", ";", "}", "elseif", "(", "$", "method", "==", "'DELETE'", ")", "{", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_CUSTOMREQUEST", ",", "$", "method", ")", ";", "}", "// add HTTP headers", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_HTTPHEADER", ",", "$", "headers", ")", ";", "return", "$", "curl", ";", "}" ]
Initializes the curl connection
[ "Initializes", "the", "curl", "connection" ]
train
https://github.com/99designs/ergo-http/blob/979b789f2e011a1cb70a00161e6b7bcd0d2e9c71/src/Transport.php#L75-L129
99designs/ergo-http
src/Transport.php
Transport._buildResponse
private function _buildResponse($response) { $sections = explode("\r\n\r\n", $response, 2); $body = isset($sections[1]) ? $sections[1] : NULL; $headers = array(); $headerlines = explode("\n", $sections[0]); // process status list($http, $code, $message) = explode(' ', $headerlines[0], 3); // process headers foreach (array_slice($headerlines, 1) as $headerline) { $headers[] = HeaderField::fromString($headerline); } $response = new Response($code, $headers, $body); return $response; }
php
private function _buildResponse($response) { $sections = explode("\r\n\r\n", $response, 2); $body = isset($sections[1]) ? $sections[1] : NULL; $headers = array(); $headerlines = explode("\n", $sections[0]); // process status list($http, $code, $message) = explode(' ', $headerlines[0], 3); // process headers foreach (array_slice($headerlines, 1) as $headerline) { $headers[] = HeaderField::fromString($headerline); } $response = new Response($code, $headers, $body); return $response; }
[ "private", "function", "_buildResponse", "(", "$", "response", ")", "{", "$", "sections", "=", "explode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "response", ",", "2", ")", ";", "$", "body", "=", "isset", "(", "$", "sections", "[", "1", "]", ")", "?", "$", "sections", "[", "1", "]", ":", "NULL", ";", "$", "headers", "=", "array", "(", ")", ";", "$", "headerlines", "=", "explode", "(", "\"\\n\"", ",", "$", "sections", "[", "0", "]", ")", ";", "// process status", "list", "(", "$", "http", ",", "$", "code", ",", "$", "message", ")", "=", "explode", "(", "' '", ",", "$", "headerlines", "[", "0", "]", ",", "3", ")", ";", "// process headers", "foreach", "(", "array_slice", "(", "$", "headerlines", ",", "1", ")", "as", "$", "headerline", ")", "{", "$", "headers", "[", "]", "=", "HeaderField", "::", "fromString", "(", "$", "headerline", ")", ";", "}", "$", "response", "=", "new", "Response", "(", "$", "code", ",", "$", "headers", ",", "$", "body", ")", ";", "return", "$", "response", ";", "}" ]
Parses a response into headers and a body
[ "Parses", "a", "response", "into", "headers", "and", "a", "body" ]
train
https://github.com/99designs/ergo-http/blob/979b789f2e011a1cb70a00161e6b7bcd0d2e9c71/src/Transport.php#L134-L152
mothership-ec/composer
src/Composer/Util/RemoteFilesystem.php
RemoteFilesystem.get
protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true) { if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) { $originUrl = 'github.com'; } $this->bytesMax = 0; $this->originUrl = $originUrl; $this->fileUrl = $fileUrl; $this->fileName = $fileName; $this->progress = $progress; $this->lastProgress = null; $this->retryAuthFailure = true; $this->lastHeaders = array(); // capture username/password from URL if there is one if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) { $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2])); } if (isset($additionalOptions['retry-auth-failure'])) { $this->retryAuthFailure = (bool) $additionalOptions['retry-auth-failure']; unset($additionalOptions['retry-auth-failure']); } $options = $this->getOptionsForUrl($originUrl, $additionalOptions); if ($this->io->isDebug()) { $this->io->writeError((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl); } if (isset($options['github-token'])) { $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token']; unset($options['github-token']); } if (isset($options['http'])) { $options['http']['ignore_errors'] = true; } $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet'))); if ($this->progress) { $this->io->writeError(" Downloading: <comment>Connecting...</comment>", false); } $errorMessage = ''; $errorCode = 0; $result = false; set_error_handler(function ($code, $msg) use (&$errorMessage) { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg); }); try { $result = file_get_contents($fileUrl, false, $ctx); } catch (\Exception $e) { if ($e instanceof TransportException && !empty($http_response_header[0])) { $e->setHeaders($http_response_header); } if ($e instanceof TransportException && $result !== false) { $e->setResponse($result); } $result = false; } if ($errorMessage && !ini_get('allow_url_fopen')) { $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')'; } restore_error_handler(); if (isset($e) && !$this->retry) { throw $e; } // fail 4xx and 5xx responses and capture the response if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) { $errorCode = $match[1]; if (!$this->retry) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $errorCode); $e->setHeaders($http_response_header); $e->setResponse($result); throw $e; } $result = false; } // decode gzip if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') { $decode = false; foreach ($http_response_header as $header) { if (preg_match('{^content-encoding: *gzip *$}i', $header)) { $decode = true; continue; } elseif (preg_match('{^HTTP/}i', $header)) { $decode = false; } } if ($decode) { if (PHP_VERSION_ID >= 50400) { $result = zlib_decode($result); } else { // work around issue with gzuncompress & co that do not work with all gzip checksums $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result)); } if (!$result) { throw new TransportException('Failed to decode zlib stream'); } } } if ($this->progress && !$this->retry) { $this->io->overwriteError(" Downloading: <comment>100%</comment>"); } // handle copy command if download was successful if (false !== $result && null !== $fileName) { if ('' === $result) { throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response'); } $errorMessage = ''; set_error_handler(function ($code, $msg) use (&$errorMessage) { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg); }); $result = (bool) file_put_contents($fileName, $result); restore_error_handler(); if (false === $result) { throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage); } } if ($this->retry) { $this->retry = false; $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); $authHelper = new AuthHelper($this->io, $this->config); $authHelper->storeAuth($this->originUrl, $this->storeAuth); $this->storeAuth = false; return $result; } if (false === $result) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode); if (!empty($http_response_header[0])) { $e->setHeaders($http_response_header); } throw $e; } if (!empty($http_response_header[0])) { $this->lastHeaders = $http_response_header; } return $result; }
php
protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true) { if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) { $originUrl = 'github.com'; } $this->bytesMax = 0; $this->originUrl = $originUrl; $this->fileUrl = $fileUrl; $this->fileName = $fileName; $this->progress = $progress; $this->lastProgress = null; $this->retryAuthFailure = true; $this->lastHeaders = array(); // capture username/password from URL if there is one if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) { $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2])); } if (isset($additionalOptions['retry-auth-failure'])) { $this->retryAuthFailure = (bool) $additionalOptions['retry-auth-failure']; unset($additionalOptions['retry-auth-failure']); } $options = $this->getOptionsForUrl($originUrl, $additionalOptions); if ($this->io->isDebug()) { $this->io->writeError((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl); } if (isset($options['github-token'])) { $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token']; unset($options['github-token']); } if (isset($options['http'])) { $options['http']['ignore_errors'] = true; } $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet'))); if ($this->progress) { $this->io->writeError(" Downloading: <comment>Connecting...</comment>", false); } $errorMessage = ''; $errorCode = 0; $result = false; set_error_handler(function ($code, $msg) use (&$errorMessage) { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg); }); try { $result = file_get_contents($fileUrl, false, $ctx); } catch (\Exception $e) { if ($e instanceof TransportException && !empty($http_response_header[0])) { $e->setHeaders($http_response_header); } if ($e instanceof TransportException && $result !== false) { $e->setResponse($result); } $result = false; } if ($errorMessage && !ini_get('allow_url_fopen')) { $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')'; } restore_error_handler(); if (isset($e) && !$this->retry) { throw $e; } // fail 4xx and 5xx responses and capture the response if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) { $errorCode = $match[1]; if (!$this->retry) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $errorCode); $e->setHeaders($http_response_header); $e->setResponse($result); throw $e; } $result = false; } // decode gzip if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') { $decode = false; foreach ($http_response_header as $header) { if (preg_match('{^content-encoding: *gzip *$}i', $header)) { $decode = true; continue; } elseif (preg_match('{^HTTP/}i', $header)) { $decode = false; } } if ($decode) { if (PHP_VERSION_ID >= 50400) { $result = zlib_decode($result); } else { // work around issue with gzuncompress & co that do not work with all gzip checksums $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result)); } if (!$result) { throw new TransportException('Failed to decode zlib stream'); } } } if ($this->progress && !$this->retry) { $this->io->overwriteError(" Downloading: <comment>100%</comment>"); } // handle copy command if download was successful if (false !== $result && null !== $fileName) { if ('' === $result) { throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response'); } $errorMessage = ''; set_error_handler(function ($code, $msg) use (&$errorMessage) { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg); }); $result = (bool) file_put_contents($fileName, $result); restore_error_handler(); if (false === $result) { throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage); } } if ($this->retry) { $this->retry = false; $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); $authHelper = new AuthHelper($this->io, $this->config); $authHelper->storeAuth($this->originUrl, $this->storeAuth); $this->storeAuth = false; return $result; } if (false === $result) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode); if (!empty($http_response_header[0])) { $e->setHeaders($http_response_header); } throw $e; } if (!empty($http_response_header[0])) { $this->lastHeaders = $http_response_header; } return $result; }
[ "protected", "function", "get", "(", "$", "originUrl", ",", "$", "fileUrl", ",", "$", "additionalOptions", "=", "array", "(", ")", ",", "$", "fileName", "=", "null", ",", "$", "progress", "=", "true", ")", "{", "if", "(", "strpos", "(", "$", "originUrl", ",", "'.github.com'", ")", "===", "(", "strlen", "(", "$", "originUrl", ")", "-", "11", ")", ")", "{", "$", "originUrl", "=", "'github.com'", ";", "}", "$", "this", "->", "bytesMax", "=", "0", ";", "$", "this", "->", "originUrl", "=", "$", "originUrl", ";", "$", "this", "->", "fileUrl", "=", "$", "fileUrl", ";", "$", "this", "->", "fileName", "=", "$", "fileName", ";", "$", "this", "->", "progress", "=", "$", "progress", ";", "$", "this", "->", "lastProgress", "=", "null", ";", "$", "this", "->", "retryAuthFailure", "=", "true", ";", "$", "this", "->", "lastHeaders", "=", "array", "(", ")", ";", "// capture username/password from URL if there is one", "if", "(", "preg_match", "(", "'{^https?://(.+):(.+)@([^/]+)}i'", ",", "$", "fileUrl", ",", "$", "match", ")", ")", "{", "$", "this", "->", "io", "->", "setAuthentication", "(", "$", "originUrl", ",", "urldecode", "(", "$", "match", "[", "1", "]", ")", ",", "urldecode", "(", "$", "match", "[", "2", "]", ")", ")", ";", "}", "if", "(", "isset", "(", "$", "additionalOptions", "[", "'retry-auth-failure'", "]", ")", ")", "{", "$", "this", "->", "retryAuthFailure", "=", "(", "bool", ")", "$", "additionalOptions", "[", "'retry-auth-failure'", "]", ";", "unset", "(", "$", "additionalOptions", "[", "'retry-auth-failure'", "]", ")", ";", "}", "$", "options", "=", "$", "this", "->", "getOptionsForUrl", "(", "$", "originUrl", ",", "$", "additionalOptions", ")", ";", "if", "(", "$", "this", "->", "io", "->", "isDebug", "(", ")", ")", "{", "$", "this", "->", "io", "->", "writeError", "(", "(", "substr", "(", "$", "fileUrl", ",", "0", ",", "4", ")", "===", "'http'", "?", "'Downloading '", ":", "'Reading '", ")", ".", "$", "fileUrl", ")", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'github-token'", "]", ")", ")", "{", "$", "fileUrl", ".=", "(", "false", "===", "strpos", "(", "$", "fileUrl", ",", "'?'", ")", "?", "'?'", ":", "'&'", ")", ".", "'access_token='", ".", "$", "options", "[", "'github-token'", "]", ";", "unset", "(", "$", "options", "[", "'github-token'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'http'", "]", ")", ")", "{", "$", "options", "[", "'http'", "]", "[", "'ignore_errors'", "]", "=", "true", ";", "}", "$", "ctx", "=", "StreamContextFactory", "::", "getContext", "(", "$", "fileUrl", ",", "$", "options", ",", "array", "(", "'notification'", "=>", "array", "(", "$", "this", ",", "'callbackGet'", ")", ")", ")", ";", "if", "(", "$", "this", "->", "progress", ")", "{", "$", "this", "->", "io", "->", "writeError", "(", "\" Downloading: <comment>Connecting...</comment>\"", ",", "false", ")", ";", "}", "$", "errorMessage", "=", "''", ";", "$", "errorCode", "=", "0", ";", "$", "result", "=", "false", ";", "set_error_handler", "(", "function", "(", "$", "code", ",", "$", "msg", ")", "use", "(", "&", "$", "errorMessage", ")", "{", "if", "(", "$", "errorMessage", ")", "{", "$", "errorMessage", ".=", "\"\\n\"", ";", "}", "$", "errorMessage", ".=", "preg_replace", "(", "'{^file_get_contents\\(.*?\\): }'", ",", "''", ",", "$", "msg", ")", ";", "}", ")", ";", "try", "{", "$", "result", "=", "file_get_contents", "(", "$", "fileUrl", ",", "false", ",", "$", "ctx", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "e", "instanceof", "TransportException", "&&", "!", "empty", "(", "$", "http_response_header", "[", "0", "]", ")", ")", "{", "$", "e", "->", "setHeaders", "(", "$", "http_response_header", ")", ";", "}", "if", "(", "$", "e", "instanceof", "TransportException", "&&", "$", "result", "!==", "false", ")", "{", "$", "e", "->", "setResponse", "(", "$", "result", ")", ";", "}", "$", "result", "=", "false", ";", "}", "if", "(", "$", "errorMessage", "&&", "!", "ini_get", "(", "'allow_url_fopen'", ")", ")", "{", "$", "errorMessage", "=", "'allow_url_fopen must be enabled in php.ini ('", ".", "$", "errorMessage", ".", "')'", ";", "}", "restore_error_handler", "(", ")", ";", "if", "(", "isset", "(", "$", "e", ")", "&&", "!", "$", "this", "->", "retry", ")", "{", "throw", "$", "e", ";", "}", "// fail 4xx and 5xx responses and capture the response", "if", "(", "!", "empty", "(", "$", "http_response_header", "[", "0", "]", ")", "&&", "preg_match", "(", "'{^HTTP/\\S+ ([45]\\d\\d)}i'", ",", "$", "http_response_header", "[", "0", "]", ",", "$", "match", ")", ")", "{", "$", "errorCode", "=", "$", "match", "[", "1", "]", ";", "if", "(", "!", "$", "this", "->", "retry", ")", "{", "$", "e", "=", "new", "TransportException", "(", "'The \"'", ".", "$", "this", "->", "fileUrl", ".", "'\" file could not be downloaded ('", ".", "$", "http_response_header", "[", "0", "]", ".", "')'", ",", "$", "errorCode", ")", ";", "$", "e", "->", "setHeaders", "(", "$", "http_response_header", ")", ";", "$", "e", "->", "setResponse", "(", "$", "result", ")", ";", "throw", "$", "e", ";", "}", "$", "result", "=", "false", ";", "}", "// decode gzip", "if", "(", "$", "result", "&&", "extension_loaded", "(", "'zlib'", ")", "&&", "substr", "(", "$", "fileUrl", ",", "0", ",", "4", ")", "===", "'http'", ")", "{", "$", "decode", "=", "false", ";", "foreach", "(", "$", "http_response_header", "as", "$", "header", ")", "{", "if", "(", "preg_match", "(", "'{^content-encoding: *gzip *$}i'", ",", "$", "header", ")", ")", "{", "$", "decode", "=", "true", ";", "continue", ";", "}", "elseif", "(", "preg_match", "(", "'{^HTTP/}i'", ",", "$", "header", ")", ")", "{", "$", "decode", "=", "false", ";", "}", "}", "if", "(", "$", "decode", ")", "{", "if", "(", "PHP_VERSION_ID", ">=", "50400", ")", "{", "$", "result", "=", "zlib_decode", "(", "$", "result", ")", ";", "}", "else", "{", "// work around issue with gzuncompress & co that do not work with all gzip checksums", "$", "result", "=", "file_get_contents", "(", "'compress.zlib://data:application/octet-stream;base64,'", ".", "base64_encode", "(", "$", "result", ")", ")", ";", "}", "if", "(", "!", "$", "result", ")", "{", "throw", "new", "TransportException", "(", "'Failed to decode zlib stream'", ")", ";", "}", "}", "}", "if", "(", "$", "this", "->", "progress", "&&", "!", "$", "this", "->", "retry", ")", "{", "$", "this", "->", "io", "->", "overwriteError", "(", "\" Downloading: <comment>100%</comment>\"", ")", ";", "}", "// handle copy command if download was successful", "if", "(", "false", "!==", "$", "result", "&&", "null", "!==", "$", "fileName", ")", "{", "if", "(", "''", "===", "$", "result", ")", "{", "throw", "new", "TransportException", "(", "'\"'", ".", "$", "this", "->", "fileUrl", ".", "'\" appears broken, and returned an empty 200 response'", ")", ";", "}", "$", "errorMessage", "=", "''", ";", "set_error_handler", "(", "function", "(", "$", "code", ",", "$", "msg", ")", "use", "(", "&", "$", "errorMessage", ")", "{", "if", "(", "$", "errorMessage", ")", "{", "$", "errorMessage", ".=", "\"\\n\"", ";", "}", "$", "errorMessage", ".=", "preg_replace", "(", "'{^file_put_contents\\(.*?\\): }'", ",", "''", ",", "$", "msg", ")", ";", "}", ")", ";", "$", "result", "=", "(", "bool", ")", "file_put_contents", "(", "$", "fileName", ",", "$", "result", ")", ";", "restore_error_handler", "(", ")", ";", "if", "(", "false", "===", "$", "result", ")", "{", "throw", "new", "TransportException", "(", "'The \"'", ".", "$", "this", "->", "fileUrl", ".", "'\" file could not be written to '", ".", "$", "fileName", ".", "': '", ".", "$", "errorMessage", ")", ";", "}", "}", "if", "(", "$", "this", "->", "retry", ")", "{", "$", "this", "->", "retry", "=", "false", ";", "$", "result", "=", "$", "this", "->", "get", "(", "$", "this", "->", "originUrl", ",", "$", "this", "->", "fileUrl", ",", "$", "additionalOptions", ",", "$", "this", "->", "fileName", ",", "$", "this", "->", "progress", ")", ";", "$", "authHelper", "=", "new", "AuthHelper", "(", "$", "this", "->", "io", ",", "$", "this", "->", "config", ")", ";", "$", "authHelper", "->", "storeAuth", "(", "$", "this", "->", "originUrl", ",", "$", "this", "->", "storeAuth", ")", ";", "$", "this", "->", "storeAuth", "=", "false", ";", "return", "$", "result", ";", "}", "if", "(", "false", "===", "$", "result", ")", "{", "$", "e", "=", "new", "TransportException", "(", "'The \"'", ".", "$", "this", "->", "fileUrl", ".", "'\" file could not be downloaded: '", ".", "$", "errorMessage", ",", "$", "errorCode", ")", ";", "if", "(", "!", "empty", "(", "$", "http_response_header", "[", "0", "]", ")", ")", "{", "$", "e", "->", "setHeaders", "(", "$", "http_response_header", ")", ";", "}", "throw", "$", "e", ";", "}", "if", "(", "!", "empty", "(", "$", "http_response_header", "[", "0", "]", ")", ")", "{", "$", "this", "->", "lastHeaders", "=", "$", "http_response_header", ";", "}", "return", "$", "result", ";", "}" ]
Get file content or copy action. @param string $originUrl The origin URL @param string $fileUrl The file URL @param array $additionalOptions context options @param string $fileName the local filename @param boolean $progress Display the progression @throws TransportException|\Exception @throws TransportException When the file could not be downloaded @return bool|string
[ "Get", "file", "content", "or", "copy", "action", "." ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Util/RemoteFilesystem.php#L120-L280
mothership-ec/composer
src/Composer/Util/RemoteFilesystem.php
RemoteFilesystem.callbackGet
protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax) { switch ($notificationCode) { case STREAM_NOTIFY_FAILURE: case STREAM_NOTIFY_AUTH_REQUIRED: if (401 === $messageCode) { // Bail if the caller is going to handle authentication failures itself. if (!$this->retryAuthFailure) { break; } $this->promptAuthAndRetry($messageCode); break; } break; case STREAM_NOTIFY_AUTH_RESULT: if (403 === $messageCode) { // Bail if the caller is going to handle authentication failures itself. if (!$this->retryAuthFailure) { break; } $this->promptAuthAndRetry($messageCode, $message); break; } break; case STREAM_NOTIFY_FILE_SIZE_IS: if ($this->bytesMax < $bytesMax) { $this->bytesMax = $bytesMax; } break; case STREAM_NOTIFY_PROGRESS: if ($this->bytesMax > 0 && $this->progress) { $progression = 0; if ($this->bytesMax > 0) { $progression = round($bytesTransferred / $this->bytesMax * 100); } if ((0 === $progression % 5) && 100 !== $progression && $progression !== $this->lastProgress) { $this->lastProgress = $progression; $this->io->overwriteError(" Downloading: <comment>$progression%</comment>", false); } } break; default: break; } }
php
protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax) { switch ($notificationCode) { case STREAM_NOTIFY_FAILURE: case STREAM_NOTIFY_AUTH_REQUIRED: if (401 === $messageCode) { // Bail if the caller is going to handle authentication failures itself. if (!$this->retryAuthFailure) { break; } $this->promptAuthAndRetry($messageCode); break; } break; case STREAM_NOTIFY_AUTH_RESULT: if (403 === $messageCode) { // Bail if the caller is going to handle authentication failures itself. if (!$this->retryAuthFailure) { break; } $this->promptAuthAndRetry($messageCode, $message); break; } break; case STREAM_NOTIFY_FILE_SIZE_IS: if ($this->bytesMax < $bytesMax) { $this->bytesMax = $bytesMax; } break; case STREAM_NOTIFY_PROGRESS: if ($this->bytesMax > 0 && $this->progress) { $progression = 0; if ($this->bytesMax > 0) { $progression = round($bytesTransferred / $this->bytesMax * 100); } if ((0 === $progression % 5) && 100 !== $progression && $progression !== $this->lastProgress) { $this->lastProgress = $progression; $this->io->overwriteError(" Downloading: <comment>$progression%</comment>", false); } } break; default: break; } }
[ "protected", "function", "callbackGet", "(", "$", "notificationCode", ",", "$", "severity", ",", "$", "message", ",", "$", "messageCode", ",", "$", "bytesTransferred", ",", "$", "bytesMax", ")", "{", "switch", "(", "$", "notificationCode", ")", "{", "case", "STREAM_NOTIFY_FAILURE", ":", "case", "STREAM_NOTIFY_AUTH_REQUIRED", ":", "if", "(", "401", "===", "$", "messageCode", ")", "{", "// Bail if the caller is going to handle authentication failures itself.", "if", "(", "!", "$", "this", "->", "retryAuthFailure", ")", "{", "break", ";", "}", "$", "this", "->", "promptAuthAndRetry", "(", "$", "messageCode", ")", ";", "break", ";", "}", "break", ";", "case", "STREAM_NOTIFY_AUTH_RESULT", ":", "if", "(", "403", "===", "$", "messageCode", ")", "{", "// Bail if the caller is going to handle authentication failures itself.", "if", "(", "!", "$", "this", "->", "retryAuthFailure", ")", "{", "break", ";", "}", "$", "this", "->", "promptAuthAndRetry", "(", "$", "messageCode", ",", "$", "message", ")", ";", "break", ";", "}", "break", ";", "case", "STREAM_NOTIFY_FILE_SIZE_IS", ":", "if", "(", "$", "this", "->", "bytesMax", "<", "$", "bytesMax", ")", "{", "$", "this", "->", "bytesMax", "=", "$", "bytesMax", ";", "}", "break", ";", "case", "STREAM_NOTIFY_PROGRESS", ":", "if", "(", "$", "this", "->", "bytesMax", ">", "0", "&&", "$", "this", "->", "progress", ")", "{", "$", "progression", "=", "0", ";", "if", "(", "$", "this", "->", "bytesMax", ">", "0", ")", "{", "$", "progression", "=", "round", "(", "$", "bytesTransferred", "/", "$", "this", "->", "bytesMax", "*", "100", ")", ";", "}", "if", "(", "(", "0", "===", "$", "progression", "%", "5", ")", "&&", "100", "!==", "$", "progression", "&&", "$", "progression", "!==", "$", "this", "->", "lastProgress", ")", "{", "$", "this", "->", "lastProgress", "=", "$", "progression", ";", "$", "this", "->", "io", "->", "overwriteError", "(", "\" Downloading: <comment>$progression%</comment>\"", ",", "false", ")", ";", "}", "}", "break", ";", "default", ":", "break", ";", "}", "}" ]
Get notification action. @param integer $notificationCode The notification code @param integer $severity The severity level @param string $message The message @param integer $messageCode The message code @param integer $bytesTransferred The loaded size @param integer $bytesMax The total size @throws TransportException
[ "Get", "notification", "action", "." ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Util/RemoteFilesystem.php#L293-L345
thelia-modules/CustomerGroup
EventListener/CustomerCustomerGroup.php
CustomerCustomerGroup.addCustomer
public function addCustomer(AddCustomerToCustomerGroupEvent $event) { (new CustomerCustomerGroupQuery()) ->filterByCustomerId($event->getCustomerId()) ->filterByCustomerGroupId($event->getCustomerGroupId()) ->findOneOrCreate() ->save(); }
php
public function addCustomer(AddCustomerToCustomerGroupEvent $event) { (new CustomerCustomerGroupQuery()) ->filterByCustomerId($event->getCustomerId()) ->filterByCustomerGroupId($event->getCustomerGroupId()) ->findOneOrCreate() ->save(); }
[ "public", "function", "addCustomer", "(", "AddCustomerToCustomerGroupEvent", "$", "event", ")", "{", "(", "new", "CustomerCustomerGroupQuery", "(", ")", ")", "->", "filterByCustomerId", "(", "$", "event", "->", "getCustomerId", "(", ")", ")", "->", "filterByCustomerGroupId", "(", "$", "event", "->", "getCustomerGroupId", "(", ")", ")", "->", "findOneOrCreate", "(", ")", "->", "save", "(", ")", ";", "}" ]
Add a customer to a customer group. @param AddCustomerToCustomerGroupEvent $event
[ "Add", "a", "customer", "to", "a", "customer", "group", "." ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/EventListener/CustomerCustomerGroup.php#L42-L49
thelia-modules/CustomerGroup
EventListener/CustomerCustomerGroup.php
CustomerCustomerGroup.addDefaultCustomerGroupToCustomer
public function addDefaultCustomerGroupToCustomer(CustomerEvent $event) { $defaultCustomerGroup = CustomerGroupQuery::create()->findOneByIsDefault(true); if (null === $defaultCustomerGroup) { return; } (new CustomerCustomerGroupQuery()) ->filterByCustomerId($event->getCustomer()->getId()) ->filterByCustomerGroupId($defaultCustomerGroup->getId()) ->findOneOrCreate() ->save(); }
php
public function addDefaultCustomerGroupToCustomer(CustomerEvent $event) { $defaultCustomerGroup = CustomerGroupQuery::create()->findOneByIsDefault(true); if (null === $defaultCustomerGroup) { return; } (new CustomerCustomerGroupQuery()) ->filterByCustomerId($event->getCustomer()->getId()) ->filterByCustomerGroupId($defaultCustomerGroup->getId()) ->findOneOrCreate() ->save(); }
[ "public", "function", "addDefaultCustomerGroupToCustomer", "(", "CustomerEvent", "$", "event", ")", "{", "$", "defaultCustomerGroup", "=", "CustomerGroupQuery", "::", "create", "(", ")", "->", "findOneByIsDefault", "(", "true", ")", ";", "if", "(", "null", "===", "$", "defaultCustomerGroup", ")", "{", "return", ";", "}", "(", "new", "CustomerCustomerGroupQuery", "(", ")", ")", "->", "filterByCustomerId", "(", "$", "event", "->", "getCustomer", "(", ")", "->", "getId", "(", ")", ")", "->", "filterByCustomerGroupId", "(", "$", "defaultCustomerGroup", "->", "getId", "(", ")", ")", "->", "findOneOrCreate", "(", ")", "->", "save", "(", ")", ";", "}" ]
Add the customer to the default customer group (if there is one). @todo Only if there is no customer group in the event ! @param CustomerEvent $event
[ "Add", "the", "customer", "to", "the", "default", "customer", "group", "(", "if", "there", "is", "one", ")", "." ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/EventListener/CustomerCustomerGroup.php#L56-L68
thelia-modules/CustomerGroup
EventListener/CustomerCustomerGroup.php
CustomerCustomerGroup.addCustomerGroupToSession
public function addCustomerGroupToSession(CustomerLoginEvent $event) { $customerGroup = CustomerGroupQuery::create() ->useCustomerCustomerGroupQuery() ->filterByCustomerId($event->getCustomer()->getId()) ->endUse() ->findOne(); if ($customerGroup === null) { return; } $this->request->getSession()->set( CustomerGroup::getModuleCode(), [ "id" => $customerGroup->getId(), "code" => $customerGroup->getCode(), "default" => $customerGroup->getIsDefault(), ] ); }
php
public function addCustomerGroupToSession(CustomerLoginEvent $event) { $customerGroup = CustomerGroupQuery::create() ->useCustomerCustomerGroupQuery() ->filterByCustomerId($event->getCustomer()->getId()) ->endUse() ->findOne(); if ($customerGroup === null) { return; } $this->request->getSession()->set( CustomerGroup::getModuleCode(), [ "id" => $customerGroup->getId(), "code" => $customerGroup->getCode(), "default" => $customerGroup->getIsDefault(), ] ); }
[ "public", "function", "addCustomerGroupToSession", "(", "CustomerLoginEvent", "$", "event", ")", "{", "$", "customerGroup", "=", "CustomerGroupQuery", "::", "create", "(", ")", "->", "useCustomerCustomerGroupQuery", "(", ")", "->", "filterByCustomerId", "(", "$", "event", "->", "getCustomer", "(", ")", "->", "getId", "(", ")", ")", "->", "endUse", "(", ")", "->", "findOne", "(", ")", ";", "if", "(", "$", "customerGroup", "===", "null", ")", "{", "return", ";", "}", "$", "this", "->", "request", "->", "getSession", "(", ")", "->", "set", "(", "CustomerGroup", "::", "getModuleCode", "(", ")", ",", "[", "\"id\"", "=>", "$", "customerGroup", "->", "getId", "(", ")", ",", "\"code\"", "=>", "$", "customerGroup", "->", "getCode", "(", ")", ",", "\"default\"", "=>", "$", "customerGroup", "->", "getIsDefault", "(", ")", ",", "]", ")", ";", "}" ]
Add customer group information for the customer in the session. Only information on the first group is added. Group information is added to the session attributes with this module code as a key. Structure: "id" => group id "code" => group code "default" => whether the group is the default group @param CustomerLoginEvent $event @todo Clarify if a customer can have multiple groups.
[ "Add", "customer", "group", "information", "for", "the", "customer", "in", "the", "session", ".", "Only", "information", "on", "the", "first", "group", "is", "added", ".", "Group", "information", "is", "added", "to", "the", "session", "attributes", "with", "this", "module", "code", "as", "a", "key", ".", "Structure", ":", "id", "=", ">", "group", "id", "code", "=", ">", "group", "code", "default", "=", ">", "whether", "the", "group", "is", "the", "default", "group" ]
train
https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/EventListener/CustomerCustomerGroup.php#L83-L102
nabab/bbn
src/bbn/time.php
time.get_interval
private function get_interval(string $interval = '') { if ( !empty($interval) ){ $this->interval = new \DateInterval($interval); return $this->interval; } else { return $this->interval; } }
php
private function get_interval(string $interval = '') { if ( !empty($interval) ){ $this->interval = new \DateInterval($interval); return $this->interval; } else { return $this->interval; } }
[ "private", "function", "get_interval", "(", "string", "$", "interval", "=", "''", ")", "{", "if", "(", "!", "empty", "(", "$", "interval", ")", ")", "{", "$", "this", "->", "interval", "=", "new", "\\", "DateInterval", "(", "$", "interval", ")", ";", "return", "$", "this", "->", "interval", ";", "}", "else", "{", "return", "$", "this", "->", "interval", ";", "}", "}" ]
Return the property $interval if it is set @param string $interval @return void
[ "Return", "the", "property", "$interval", "if", "it", "is", "set" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L55-L64
nabab/bbn
src/bbn/time.php
time.format
public function format($format = '') { if ( !empty($format) ){ return $this->time->format($format); } else { return $this->time->format('Y-m-d H:i:s'); } }
php
public function format($format = '') { if ( !empty($format) ){ return $this->time->format($format); } else { return $this->time->format('Y-m-d H:i:s'); } }
[ "public", "function", "format", "(", "$", "format", "=", "''", ")", "{", "if", "(", "!", "empty", "(", "$", "format", ")", ")", "{", "return", "$", "this", "->", "time", "->", "format", "(", "$", "format", ")", ";", "}", "else", "{", "return", "$", "this", "->", "time", "->", "format", "(", "'Y-m-d H:i:s'", ")", ";", "}", "}" ]
return the date in the given $format of in 'Y-m-d H:i:s' format if no argument is given to the function @param string $format @return void
[ "return", "the", "date", "in", "the", "given", "$format", "of", "in", "Y", "-", "m", "-", "d", "H", ":", "i", ":", "s", "format", "if", "no", "argument", "is", "given", "to", "the", "function" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L72-L80
nabab/bbn
src/bbn/time.php
time.compare
public function compare($date, $comparator) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } switch ( $comparator ){ case $comparator === '>': return $this->get_time() > $tmp->get_time(); break; case $comparator === '>=': return $this->get_time() >= $tmp->get_time(); break; case $comparator === '<': return $this->get_time() < $tmp->get_time(); break; case $comparator === '<=': return $this->get_time() <= $tmp->get_time(); break; case $comparator === '=': return $this->get_time() == $tmp->get_time(); break; } }
php
public function compare($date, $comparator) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } switch ( $comparator ){ case $comparator === '>': return $this->get_time() > $tmp->get_time(); break; case $comparator === '>=': return $this->get_time() >= $tmp->get_time(); break; case $comparator === '<': return $this->get_time() < $tmp->get_time(); break; case $comparator === '<=': return $this->get_time() <= $tmp->get_time(); break; case $comparator === '=': return $this->get_time() == $tmp->get_time(); break; } }
[ "public", "function", "compare", "(", "$", "date", ",", "$", "comparator", ")", "{", "//check if the argument $date is an instance of this class", "if", "(", "$", "date", "instanceof", "$", "this", ")", "{", "$", "tmp", "=", "$", "date", ";", "}", "else", "{", "$", "tmp", "=", "new", "\\", "bbn", "\\", "time", "(", "$", "date", ")", ";", "}", "switch", "(", "$", "comparator", ")", "{", "case", "$", "comparator", "===", "'>'", ":", "return", "$", "this", "->", "get_time", "(", ")", ">", "$", "tmp", "->", "get_time", "(", ")", ";", "break", ";", "case", "$", "comparator", "===", "'>='", ":", "return", "$", "this", "->", "get_time", "(", ")", ">=", "$", "tmp", "->", "get_time", "(", ")", ";", "break", ";", "case", "$", "comparator", "===", "'<'", ":", "return", "$", "this", "->", "get_time", "(", ")", "<", "$", "tmp", "->", "get_time", "(", ")", ";", "break", ";", "case", "$", "comparator", "===", "'<='", ":", "return", "$", "this", "->", "get_time", "(", ")", "<=", "$", "tmp", "->", "get_time", "(", ")", ";", "break", ";", "case", "$", "comparator", "===", "'='", ":", "return", "$", "this", "->", "get_time", "(", ")", "==", "$", "tmp", "->", "get_time", "(", ")", ";", "break", ";", "}", "}" ]
Compares two dates @param [String|Object] $date the string of the date to compare or an object of this class @param [String] $comparator allowed comparators '>','>=', '<','<=', '=' @return Boolean
[ "Compares", "two", "dates" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L98-L124
nabab/bbn
src/bbn/time.php
time.is_before
public function is_before($date) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } return $this->get_time() < $tmp->get_time(); }
php
public function is_before($date) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } return $this->get_time() < $tmp->get_time(); }
[ "public", "function", "is_before", "(", "$", "date", ")", "{", "//check if the argument $date is an instance of this class", "if", "(", "$", "date", "instanceof", "$", "this", ")", "{", "$", "tmp", "=", "$", "date", ";", "}", "else", "{", "$", "tmp", "=", "new", "\\", "bbn", "\\", "time", "(", "$", "date", ")", ";", "}", "return", "$", "this", "->", "get_time", "(", ")", "<", "$", "tmp", "->", "get_time", "(", ")", ";", "}" ]
Return if $this->time is before of the given $date @param [String|Object] $date the string of the date to compare or an object of this class @return boolean
[ "Return", "if", "$this", "-", ">", "time", "is", "before", "of", "the", "given", "$date" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L132-L142
nabab/bbn
src/bbn/time.php
time.is_after
public function is_after($date) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } return $this->get_time() > $tmp->get_time(); }
php
public function is_after($date) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } return $this->get_time() > $tmp->get_time(); }
[ "public", "function", "is_after", "(", "$", "date", ")", "{", "//check if the argument $date is an instance of this class", "if", "(", "$", "date", "instanceof", "$", "this", ")", "{", "$", "tmp", "=", "$", "date", ";", "}", "else", "{", "$", "tmp", "=", "new", "\\", "bbn", "\\", "time", "(", "$", "date", ")", ";", "}", "return", "$", "this", "->", "get_time", "(", ")", ">", "$", "tmp", "->", "get_time", "(", ")", ";", "}" ]
Return if $this->time is after of the given $date @param [String|Object] $date the string of the date to compare or an object of this class @return boolean
[ "Return", "if", "$this", "-", ">", "time", "is", "after", "of", "the", "given", "$date" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L151-L161
nabab/bbn
src/bbn/time.php
time.is_same
public function is_same($date) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } return $this->get_time() == $tmp->get_time(); }
php
public function is_same($date) { //check if the argument $date is an instance of this class if ( $date instanceof $this){ $tmp = $date; } else { $tmp = new \bbn\time($date); } return $this->get_time() == $tmp->get_time(); }
[ "public", "function", "is_same", "(", "$", "date", ")", "{", "//check if the argument $date is an instance of this class", "if", "(", "$", "date", "instanceof", "$", "this", ")", "{", "$", "tmp", "=", "$", "date", ";", "}", "else", "{", "$", "tmp", "=", "new", "\\", "bbn", "\\", "time", "(", "$", "date", ")", ";", "}", "return", "$", "this", "->", "get_time", "(", ")", "==", "$", "tmp", "->", "get_time", "(", ")", ";", "}" ]
Return if $this->time is the same of the given $date @param [String|Object] $date the string of the date to compare or an object of this class @return boolean
[ "Return", "if", "$this", "-", ">", "time", "is", "the", "same", "of", "the", "given", "$date" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L170-L180
nabab/bbn
src/bbn/time.php
time.add
public function add(string $interval, $format = ''){ $tmp = new \bbn\time($this->format()); $tmp->time->add($this->get_interval($interval)); return $tmp->format($format); }
php
public function add(string $interval, $format = ''){ $tmp = new \bbn\time($this->format()); $tmp->time->add($this->get_interval($interval)); return $tmp->format($format); }
[ "public", "function", "add", "(", "string", "$", "interval", ",", "$", "format", "=", "''", ")", "{", "$", "tmp", "=", "new", "\\", "bbn", "\\", "time", "(", "$", "this", "->", "format", "(", ")", ")", ";", "$", "tmp", "->", "time", "->", "add", "(", "$", "this", "->", "get_interval", "(", "$", "interval", ")", ")", ";", "return", "$", "tmp", "->", "format", "(", "$", "format", ")", ";", "}" ]
Add an the given $interval to $this->time and return a reference to the original object If the argument $format is not given it returns the sql format 'Y-m-d H:i:s' @param string $interval @param string $format optional @return void
[ "Add", "an", "the", "given", "$interval", "to", "$this", "-", ">", "time", "and", "return", "a", "reference", "to", "the", "original", "object", "If", "the", "argument", "$format", "is", "not", "given", "it", "returns", "the", "sql", "format", "Y", "-", "m", "-", "d", "H", ":", "i", ":", "s" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L191-L195
nabab/bbn
src/bbn/time.php
time.modif
public function modif($modif, $format = '') { $tmp = new \bbn\time($this->format()); $tmp->time->modify($modif); return $tmp->format($format); }
php
public function modif($modif, $format = '') { $tmp = new \bbn\time($this->format()); $tmp->time->modify($modif); return $tmp->format($format); }
[ "public", "function", "modif", "(", "$", "modif", ",", "$", "format", "=", "''", ")", "{", "$", "tmp", "=", "new", "\\", "bbn", "\\", "time", "(", "$", "this", "->", "format", "(", ")", ")", ";", "$", "tmp", "->", "time", "->", "modify", "(", "$", "modif", ")", ";", "return", "$", "tmp", "->", "format", "(", "$", "format", ")", ";", "}" ]
Return a reference to $this->time modified of the $modif @param [type] $modif @param string $format @return void
[ "Return", "a", "reference", "to", "$this", "-", ">", "time", "modified", "of", "the", "$modif" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L218-L223
nabab/bbn
src/bbn/time.php
time.end_of_month
public function end_of_month(){ $m = $this->get_month(); $y = $this->get_year(); return cal_days_in_month(CAL_GREGORIAN, $m, $y); }
php
public function end_of_month(){ $m = $this->get_month(); $y = $this->get_year(); return cal_days_in_month(CAL_GREGORIAN, $m, $y); }
[ "public", "function", "end_of_month", "(", ")", "{", "$", "m", "=", "$", "this", "->", "get_month", "(", ")", ";", "$", "y", "=", "$", "this", "->", "get_year", "(", ")", ";", "return", "cal_days_in_month", "(", "CAL_GREGORIAN", ",", "$", "m", ",", "$", "y", ")", ";", "}" ]
return the end of the month of $this->time @return Number
[ "return", "the", "end", "of", "the", "month", "of", "$this", "-", ">", "time" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/time.php#L230-L234
AbuseIO/parser-webiron
src/Webiron.php
Webiron.parse
public function parse() { /** * Try to find ARF report. * Some notification emails do not contain an ARF report. Instead they * contain a 'table row'-ish with abuse info. In that case we jump down * and parse the email body. */ $foundArf = false; foreach ($this->parsedMail->getAttachments() as $attachment) { // Only use the Webiron formatted reports, skip all others if (preg_match(config("{$this->configBase}.parser.report_file"), $attachment->filename)) { $raw_report = $attachment->getContent(); // We found an ARF report, yay! if (!empty($raw_report)) { $foundArf = true; if (!preg_match_all('/([\w\-]+): (.*)[ ]*\r?\n/', $raw_report, $matches)) { $this->warningCount++; continue; } $report = array_combine($matches[1], array_map('trim', $matches[2])); if (!empty($report['Report-Type'])) { $this->feedName = $report['Report-Type']; // If feed is known and enabled, validate data and save report if ($this->isKnownFeed() && $this->isEnabledFeed()) { // Sanity check if ($this->hasRequiredFields($report) === true) { // incident has all requirements met, filter and add! $report = $this->applyFilters($report); $incident = new Incident(); $incident->source = config("{$this->configBase}.parser.name"); $incident->source_id = false; $incident->ip = $report['Source']; $incident->domain = false; $incident->class = config("{$this->configBase}.feeds.{$this->feedName}.class"); $incident->type = config("{$this->configBase}.feeds.{$this->feedName}.type"); $incident->timestamp = strtotime(str_replace('\'', '', $report['Date'])); $incident->information = json_encode($report); $this->incidents[] = $incident; } } } else { $this->warningCount++; } } } } if ($foundArf === false) { // Didn't find an ARF report, go scrape the email body! $body = $this->parsedMail->getMessageBody(); $this->feedName = 'botnet-infection'; // If feed is known and enabled, validate data and save report if ($this->isKnownFeed() && $this->isEnabledFeed()) { if (preg_match_all('/ - ([^:]+): ([^\n]+)\n/', $body, $matches)) { $report = array_combine($matches[1], array_map('trim', $matches[2])); // Get IP address is not in the report if (empty($report['ip'])) { if (preg_match( '/(?:Offending|Source) IP:[ ]+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\n/', $body, $matches )) { $report['ip'] = $matches[1]; } elseif (preg_match( '/(?:Offending|Source) IP:[ ]+(?>(?>([a-f0-9]{1,4})(?>:(?1)){7}|'. '(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>('. '?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:('. '?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?4)){3}))/', $body, $matches )) { $matches = explode('IP:', $matches[0]); $report['ip'] = trim($matches[1]); } else { $this->warningCount++; } } // Sanity check if ($this->hasRequiredFields($report) === true) { // incident has all requirements met, filter and add! $report = $this->applyFilters($report); $incident = new Incident(); $incident->source = config("{$this->configBase}.parser.name"); $incident->source_id = false; $incident->ip = $report['ip']; $incident->domain = false; $incident->class = config("{$this->configBase}.feeds.{$this->feedName}.class"); $incident->type = config("{$this->configBase}.feeds.{$this->feedName}.type"); $incident->timestamp = strtotime($report['Time']); $incident->information = json_encode($report); $this->incidents[] = $incident; } } else { $this->warningCount++; } } } return $this->success(); }
php
public function parse() { /** * Try to find ARF report. * Some notification emails do not contain an ARF report. Instead they * contain a 'table row'-ish with abuse info. In that case we jump down * and parse the email body. */ $foundArf = false; foreach ($this->parsedMail->getAttachments() as $attachment) { // Only use the Webiron formatted reports, skip all others if (preg_match(config("{$this->configBase}.parser.report_file"), $attachment->filename)) { $raw_report = $attachment->getContent(); // We found an ARF report, yay! if (!empty($raw_report)) { $foundArf = true; if (!preg_match_all('/([\w\-]+): (.*)[ ]*\r?\n/', $raw_report, $matches)) { $this->warningCount++; continue; } $report = array_combine($matches[1], array_map('trim', $matches[2])); if (!empty($report['Report-Type'])) { $this->feedName = $report['Report-Type']; // If feed is known and enabled, validate data and save report if ($this->isKnownFeed() && $this->isEnabledFeed()) { // Sanity check if ($this->hasRequiredFields($report) === true) { // incident has all requirements met, filter and add! $report = $this->applyFilters($report); $incident = new Incident(); $incident->source = config("{$this->configBase}.parser.name"); $incident->source_id = false; $incident->ip = $report['Source']; $incident->domain = false; $incident->class = config("{$this->configBase}.feeds.{$this->feedName}.class"); $incident->type = config("{$this->configBase}.feeds.{$this->feedName}.type"); $incident->timestamp = strtotime(str_replace('\'', '', $report['Date'])); $incident->information = json_encode($report); $this->incidents[] = $incident; } } } else { $this->warningCount++; } } } } if ($foundArf === false) { // Didn't find an ARF report, go scrape the email body! $body = $this->parsedMail->getMessageBody(); $this->feedName = 'botnet-infection'; // If feed is known and enabled, validate data and save report if ($this->isKnownFeed() && $this->isEnabledFeed()) { if (preg_match_all('/ - ([^:]+): ([^\n]+)\n/', $body, $matches)) { $report = array_combine($matches[1], array_map('trim', $matches[2])); // Get IP address is not in the report if (empty($report['ip'])) { if (preg_match( '/(?:Offending|Source) IP:[ ]+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\n/', $body, $matches )) { $report['ip'] = $matches[1]; } elseif (preg_match( '/(?:Offending|Source) IP:[ ]+(?>(?>([a-f0-9]{1,4})(?>:(?1)){7}|'. '(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>('. '?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:('. '?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?4)){3}))/', $body, $matches )) { $matches = explode('IP:', $matches[0]); $report['ip'] = trim($matches[1]); } else { $this->warningCount++; } } // Sanity check if ($this->hasRequiredFields($report) === true) { // incident has all requirements met, filter and add! $report = $this->applyFilters($report); $incident = new Incident(); $incident->source = config("{$this->configBase}.parser.name"); $incident->source_id = false; $incident->ip = $report['ip']; $incident->domain = false; $incident->class = config("{$this->configBase}.feeds.{$this->feedName}.class"); $incident->type = config("{$this->configBase}.feeds.{$this->feedName}.type"); $incident->timestamp = strtotime($report['Time']); $incident->information = json_encode($report); $this->incidents[] = $incident; } } else { $this->warningCount++; } } } return $this->success(); }
[ "public", "function", "parse", "(", ")", "{", "/**\n * Try to find ARF report.\n * Some notification emails do not contain an ARF report. Instead they\n * contain a 'table row'-ish with abuse info. In that case we jump down\n * and parse the email body.\n */", "$", "foundArf", "=", "false", ";", "foreach", "(", "$", "this", "->", "parsedMail", "->", "getAttachments", "(", ")", "as", "$", "attachment", ")", "{", "// Only use the Webiron formatted reports, skip all others", "if", "(", "preg_match", "(", "config", "(", "\"{$this->configBase}.parser.report_file\"", ")", ",", "$", "attachment", "->", "filename", ")", ")", "{", "$", "raw_report", "=", "$", "attachment", "->", "getContent", "(", ")", ";", "// We found an ARF report, yay!", "if", "(", "!", "empty", "(", "$", "raw_report", ")", ")", "{", "$", "foundArf", "=", "true", ";", "if", "(", "!", "preg_match_all", "(", "'/([\\w\\-]+): (.*)[ ]*\\r?\\n/'", ",", "$", "raw_report", ",", "$", "matches", ")", ")", "{", "$", "this", "->", "warningCount", "++", ";", "continue", ";", "}", "$", "report", "=", "array_combine", "(", "$", "matches", "[", "1", "]", ",", "array_map", "(", "'trim'", ",", "$", "matches", "[", "2", "]", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "report", "[", "'Report-Type'", "]", ")", ")", "{", "$", "this", "->", "feedName", "=", "$", "report", "[", "'Report-Type'", "]", ";", "// If feed is known and enabled, validate data and save report", "if", "(", "$", "this", "->", "isKnownFeed", "(", ")", "&&", "$", "this", "->", "isEnabledFeed", "(", ")", ")", "{", "// Sanity check", "if", "(", "$", "this", "->", "hasRequiredFields", "(", "$", "report", ")", "===", "true", ")", "{", "// incident has all requirements met, filter and add!", "$", "report", "=", "$", "this", "->", "applyFilters", "(", "$", "report", ")", ";", "$", "incident", "=", "new", "Incident", "(", ")", ";", "$", "incident", "->", "source", "=", "config", "(", "\"{$this->configBase}.parser.name\"", ")", ";", "$", "incident", "->", "source_id", "=", "false", ";", "$", "incident", "->", "ip", "=", "$", "report", "[", "'Source'", "]", ";", "$", "incident", "->", "domain", "=", "false", ";", "$", "incident", "->", "class", "=", "config", "(", "\"{$this->configBase}.feeds.{$this->feedName}.class\"", ")", ";", "$", "incident", "->", "type", "=", "config", "(", "\"{$this->configBase}.feeds.{$this->feedName}.type\"", ")", ";", "$", "incident", "->", "timestamp", "=", "strtotime", "(", "str_replace", "(", "'\\''", ",", "''", ",", "$", "report", "[", "'Date'", "]", ")", ")", ";", "$", "incident", "->", "information", "=", "json_encode", "(", "$", "report", ")", ";", "$", "this", "->", "incidents", "[", "]", "=", "$", "incident", ";", "}", "}", "}", "else", "{", "$", "this", "->", "warningCount", "++", ";", "}", "}", "}", "}", "if", "(", "$", "foundArf", "===", "false", ")", "{", "// Didn't find an ARF report, go scrape the email body!", "$", "body", "=", "$", "this", "->", "parsedMail", "->", "getMessageBody", "(", ")", ";", "$", "this", "->", "feedName", "=", "'botnet-infection'", ";", "// If feed is known and enabled, validate data and save report", "if", "(", "$", "this", "->", "isKnownFeed", "(", ")", "&&", "$", "this", "->", "isEnabledFeed", "(", ")", ")", "{", "if", "(", "preg_match_all", "(", "'/ - ([^:]+): ([^\\n]+)\\n/'", ",", "$", "body", ",", "$", "matches", ")", ")", "{", "$", "report", "=", "array_combine", "(", "$", "matches", "[", "1", "]", ",", "array_map", "(", "'trim'", ",", "$", "matches", "[", "2", "]", ")", ")", ";", "// Get IP address is not in the report", "if", "(", "empty", "(", "$", "report", "[", "'ip'", "]", ")", ")", "{", "if", "(", "preg_match", "(", "'/(?:Offending|Source) IP:[ ]+([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})\\n/'", ",", "$", "body", ",", "$", "matches", ")", ")", "{", "$", "report", "[", "'ip'", "]", "=", "$", "matches", "[", "1", "]", ";", "}", "elseif", "(", "preg_match", "(", "'/(?:Offending|Source) IP:[ ]+(?>(?>([a-f0-9]{1,4})(?>:(?1)){7}|'", ".", "'(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>('", ".", "'?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:('", ".", "'?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\\.(?4)){3}))/'", ",", "$", "body", ",", "$", "matches", ")", ")", "{", "$", "matches", "=", "explode", "(", "'IP:'", ",", "$", "matches", "[", "0", "]", ")", ";", "$", "report", "[", "'ip'", "]", "=", "trim", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "else", "{", "$", "this", "->", "warningCount", "++", ";", "}", "}", "// Sanity check", "if", "(", "$", "this", "->", "hasRequiredFields", "(", "$", "report", ")", "===", "true", ")", "{", "// incident has all requirements met, filter and add!", "$", "report", "=", "$", "this", "->", "applyFilters", "(", "$", "report", ")", ";", "$", "incident", "=", "new", "Incident", "(", ")", ";", "$", "incident", "->", "source", "=", "config", "(", "\"{$this->configBase}.parser.name\"", ")", ";", "$", "incident", "->", "source_id", "=", "false", ";", "$", "incident", "->", "ip", "=", "$", "report", "[", "'ip'", "]", ";", "$", "incident", "->", "domain", "=", "false", ";", "$", "incident", "->", "class", "=", "config", "(", "\"{$this->configBase}.feeds.{$this->feedName}.class\"", ")", ";", "$", "incident", "->", "type", "=", "config", "(", "\"{$this->configBase}.feeds.{$this->feedName}.type\"", ")", ";", "$", "incident", "->", "timestamp", "=", "strtotime", "(", "$", "report", "[", "'Time'", "]", ")", ";", "$", "incident", "->", "information", "=", "json_encode", "(", "$", "report", ")", ";", "$", "this", "->", "incidents", "[", "]", "=", "$", "incident", ";", "}", "}", "else", "{", "$", "this", "->", "warningCount", "++", ";", "}", "}", "}", "return", "$", "this", "->", "success", "(", ")", ";", "}" ]
Parse attachments @return array Returns array with failed or success data (See parser-common/src/Parser.php) for more info.
[ "Parse", "attachments" ]
train
https://github.com/AbuseIO/parser-webiron/blob/e54f43b940f8c1ec12ead3d7e16faabc59342612/src/Webiron.php#L29-L144
wenbinye/PhalconX
src/Session/Adapter/Cache.php
Cache.write
public function write($sessionId, $data) { $this->cache->save($this->prefix . $sessionId, $data, $this->lifetime); }
php
public function write($sessionId, $data) { $this->cache->save($this->prefix . $sessionId, $data, $this->lifetime); }
[ "public", "function", "write", "(", "$", "sessionId", ",", "$", "data", ")", "{", "$", "this", "->", "cache", "->", "save", "(", "$", "this", "->", "prefix", ".", "$", "sessionId", ",", "$", "data", ",", "$", "this", "->", "lifetime", ")", ";", "}" ]
Writes the data to the table @param string $sessionId @param string $data
[ "Writes", "the", "data", "to", "the", "table" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Session/Adapter/Cache.php#L94-L97
wenbinye/PhalconX
src/Session/Adapter/Cache.php
Cache.destroy
public function destroy($session_id = null) { @session_unset(); if ($session_id === null) { $session_id = $this->getId(); } return $this->cache->delete($this->prefix.$session_id); }
php
public function destroy($session_id = null) { @session_unset(); if ($session_id === null) { $session_id = $this->getId(); } return $this->cache->delete($this->prefix.$session_id); }
[ "public", "function", "destroy", "(", "$", "session_id", "=", "null", ")", "{", "@", "session_unset", "(", ")", ";", "if", "(", "$", "session_id", "===", "null", ")", "{", "$", "session_id", "=", "$", "this", "->", "getId", "(", ")", ";", "}", "return", "$", "this", "->", "cache", "->", "delete", "(", "$", "this", "->", "prefix", ".", "$", "session_id", ")", ";", "}" ]
Destroyes the session
[ "Destroyes", "the", "session" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Session/Adapter/Cache.php#L103-L110
PHPPowertools/HTML5
src/PowerTools/HTML5/Serializer/OutputRules.php
HTML5_Serializer_OutputRules.text
public function text($ele) { if (isset($ele->parentNode) && isset($ele->parentNode->tagName) && HTML5_Elements::isA($ele->parentNode->localName, HTML5_Elements::TEXT_RAW)) { $this->wr($ele->data); return; } // FIXME: This probably needs some flags set. $this->wr($this->enc($ele->data)); }
php
public function text($ele) { if (isset($ele->parentNode) && isset($ele->parentNode->tagName) && HTML5_Elements::isA($ele->parentNode->localName, HTML5_Elements::TEXT_RAW)) { $this->wr($ele->data); return; } // FIXME: This probably needs some flags set. $this->wr($this->enc($ele->data)); }
[ "public", "function", "text", "(", "$", "ele", ")", "{", "if", "(", "isset", "(", "$", "ele", "->", "parentNode", ")", "&&", "isset", "(", "$", "ele", "->", "parentNode", "->", "tagName", ")", "&&", "HTML5_Elements", "::", "isA", "(", "$", "ele", "->", "parentNode", "->", "localName", ",", "HTML5_Elements", "::", "TEXT_RAW", ")", ")", "{", "$", "this", "->", "wr", "(", "$", "ele", "->", "data", ")", ";", "return", ";", "}", "// FIXME: This probably needs some flags set.", "$", "this", "->", "wr", "(", "$", "this", "->", "enc", "(", "$", "ele", "->", "data", ")", ")", ";", "}" ]
Write a text node. @param \DOMText $ele The text node to write.
[ "Write", "a", "text", "node", "." ]
train
https://github.com/PHPPowertools/HTML5/blob/4ea8caf5b2618a82ca5061dcbb7421b31065c1c7/src/PowerTools/HTML5/Serializer/OutputRules.php#L244-L252
PHPPowertools/HTML5
src/PowerTools/HTML5/Serializer/OutputRules.php
HTML5_Serializer_OutputRules.namespaceAttrs
protected function namespaceAttrs($ele) { if (!$this->xpath || $this->xpath->document !== $ele->ownerDocument) { $this->xpath = new \DOMXPath($ele->ownerDocument); } foreach ($this->xpath->query('namespace::*[not(.=../../namespace::*)]', $ele) as $nsNode) { if (!in_array($nsNode->nodeValue, $this->implicitNamespaces)) { $this->wr(' ')->wr($nsNode->nodeName)->wr('="')->wr($nsNode->nodeValue)->wr('"'); } } }
php
protected function namespaceAttrs($ele) { if (!$this->xpath || $this->xpath->document !== $ele->ownerDocument) { $this->xpath = new \DOMXPath($ele->ownerDocument); } foreach ($this->xpath->query('namespace::*[not(.=../../namespace::*)]', $ele) as $nsNode) { if (!in_array($nsNode->nodeValue, $this->implicitNamespaces)) { $this->wr(' ')->wr($nsNode->nodeName)->wr('="')->wr($nsNode->nodeValue)->wr('"'); } } }
[ "protected", "function", "namespaceAttrs", "(", "$", "ele", ")", "{", "if", "(", "!", "$", "this", "->", "xpath", "||", "$", "this", "->", "xpath", "->", "document", "!==", "$", "ele", "->", "ownerDocument", ")", "{", "$", "this", "->", "xpath", "=", "new", "\\", "DOMXPath", "(", "$", "ele", "->", "ownerDocument", ")", ";", "}", "foreach", "(", "$", "this", "->", "xpath", "->", "query", "(", "'namespace::*[not(.=../../namespace::*)]'", ",", "$", "ele", ")", "as", "$", "nsNode", ")", "{", "if", "(", "!", "in_array", "(", "$", "nsNode", "->", "nodeValue", ",", "$", "this", "->", "implicitNamespaces", ")", ")", "{", "$", "this", "->", "wr", "(", "' '", ")", "->", "wr", "(", "$", "nsNode", "->", "nodeName", ")", "->", "wr", "(", "'=\"'", ")", "->", "wr", "(", "$", "nsNode", "->", "nodeValue", ")", "->", "wr", "(", "'\"'", ")", ";", "}", "}", "}" ]
Write the namespace attributes @param \DOMNode $ele The element being written.
[ "Write", "the", "namespace", "attributes" ]
train
https://github.com/PHPPowertools/HTML5/blob/4ea8caf5b2618a82ca5061dcbb7421b31065c1c7/src/PowerTools/HTML5/Serializer/OutputRules.php#L280-L290
PHPPowertools/HTML5
src/PowerTools/HTML5/Serializer/OutputRules.php
HTML5_Serializer_OutputRules.closeTag
protected function closeTag($ele) { if ($this->outputMode == static::IM_IN_HTML || $ele->hasChildNodes()) { $this->wr('</')->wr($this->traverser->isLocalElement($ele) ? $ele->localName : $ele->tagName)->wr('>'); } }
php
protected function closeTag($ele) { if ($this->outputMode == static::IM_IN_HTML || $ele->hasChildNodes()) { $this->wr('</')->wr($this->traverser->isLocalElement($ele) ? $ele->localName : $ele->tagName)->wr('>'); } }
[ "protected", "function", "closeTag", "(", "$", "ele", ")", "{", "if", "(", "$", "this", "->", "outputMode", "==", "static", "::", "IM_IN_HTML", "||", "$", "ele", "->", "hasChildNodes", "(", ")", ")", "{", "$", "this", "->", "wr", "(", "'</'", ")", "->", "wr", "(", "$", "this", "->", "traverser", "->", "isLocalElement", "(", "$", "ele", ")", "?", "$", "ele", "->", "localName", ":", "$", "ele", "->", "tagName", ")", "->", "wr", "(", "'>'", ")", ";", "}", "}" ]
Write the closing tag. Tags for HTML, MathML, and SVG are in the local name. Otherwise, use the qualified name (8.3). @param \DOMNode $ele The element being written.
[ "Write", "the", "closing", "tag", "." ]
train
https://github.com/PHPPowertools/HTML5/blob/4ea8caf5b2618a82ca5061dcbb7421b31065c1c7/src/PowerTools/HTML5/Serializer/OutputRules.php#L415-L419
PHPPowertools/HTML5
src/PowerTools/HTML5/Serializer/OutputRules.php
HTML5_Serializer_OutputRules.enc
protected function enc($text, $attribute = false) { // Escape the text rather than convert to named character references. if (!$this->encode) { return $this->escape($text, $attribute); } // If we are in PHP 5.4+ we can use the native html5 entity functionality to // convert the named character references. if ($this->hasHTML5) { return htmlentities($text, ENT_HTML5 | ENT_SUBSTITUTE | ENT_QUOTES, 'UTF-8', false); } // If a version earlier than 5.4 html5 entities are not entirely handled. // This manually handles them. else { return strtr($text, HTML5_Serializer_HTML5Entities::$map); } }
php
protected function enc($text, $attribute = false) { // Escape the text rather than convert to named character references. if (!$this->encode) { return $this->escape($text, $attribute); } // If we are in PHP 5.4+ we can use the native html5 entity functionality to // convert the named character references. if ($this->hasHTML5) { return htmlentities($text, ENT_HTML5 | ENT_SUBSTITUTE | ENT_QUOTES, 'UTF-8', false); } // If a version earlier than 5.4 html5 entities are not entirely handled. // This manually handles them. else { return strtr($text, HTML5_Serializer_HTML5Entities::$map); } }
[ "protected", "function", "enc", "(", "$", "text", ",", "$", "attribute", "=", "false", ")", "{", "// Escape the text rather than convert to named character references.", "if", "(", "!", "$", "this", "->", "encode", ")", "{", "return", "$", "this", "->", "escape", "(", "$", "text", ",", "$", "attribute", ")", ";", "}", "// If we are in PHP 5.4+ we can use the native html5 entity functionality to", "// convert the named character references.", "if", "(", "$", "this", "->", "hasHTML5", ")", "{", "return", "htmlentities", "(", "$", "text", ",", "ENT_HTML5", "|", "ENT_SUBSTITUTE", "|", "ENT_QUOTES", ",", "'UTF-8'", ",", "false", ")", ";", "}", "// If a version earlier than 5.4 html5 entities are not entirely handled.", "// This manually handles them.", "else", "{", "return", "strtr", "(", "$", "text", ",", "HTML5_Serializer_HTML5Entities", "::", "$", "map", ")", ";", "}", "}" ]
Encode text. When encode is set to false, the default value, the text passed in is escaped per section 8.3 of the html5 spec. For details on how text is escaped see the escape() method. When encoding is set to true the text is converted to named character references where appropriate. Section 8.1.4 Character references of the html5 spec refers to using named character references. This is useful for characters that can't otherwise legally be used in the text. The named character references are listed in section 8.5. @see http://www.w3.org/TR/2013/CR-html5-20130806/syntax.html#named-character-references True encoding will turn all named character references into their entities. This includes such characters as +.# and many other common ones. By default encoding here will just escape &'<>". Note, PHP 5.4+ has better html5 encoding. @todo Use the Entities class in php 5.3 to have html5 entities. @param string $text text to encode. @param boolean $attribute True if we are encoding an attrubute, false otherwise @return string The encoded text.
[ "Encode", "text", "." ]
train
https://github.com/PHPPowertools/HTML5/blob/4ea8caf5b2618a82ca5061dcbb7421b31065c1c7/src/PowerTools/HTML5/Serializer/OutputRules.php#L473-L490
zhouyl/mellivora
Mellivora/Encryption/Crypt.php
Crypt.padText
protected function padText($text, $mode, $blockSize, $paddingType) { $paddingSize = 0; $padding = ''; if ($mode === 'cbc' || $mode === 'ecb') { $paddingSize = $blockSize - (strlen($text) % $blockSize); if ($paddingSize >= 256) { throw new InvalidArgumentException("Block size [$blockSize] is bigger than 256"); } switch ($paddingType) { case self::PADDING_ANSI_X_923: $padding = str_repeat(chr(0), $paddingSize - 1) . chr($paddingSize); break; case self::PADDING_PKCS7: $padding = str_repeat(chr($paddingSize), $paddingSize); break; case self::PADDING_ISO_10126: $padding = ''; foreach (range(0, $paddingSize - 2) as $i) { $padding .= chr(rand()); } $padding .= chr($paddingSize); break; case self::PADDING_ISO_IEC_7816_4: $padding = chr(0x80) . str_repeat(chr(0), $paddingSize - 1); break; case self::PADDING_ZERO: $padding = str_repeat(chr(0), $paddingSize); break; case self::PADDING_SPACE: $padding = str_repeat(' ', $paddingSize); break; default: $paddingSize = 0; break; } } if (!$paddingSize) { return $text; } if ($paddingSize > $blockSize) { throw new InvalidArgumentException("Invalid padding size [$paddingSize]"); } return $text . substr($padding, 0, $paddingSize); }
php
protected function padText($text, $mode, $blockSize, $paddingType) { $paddingSize = 0; $padding = ''; if ($mode === 'cbc' || $mode === 'ecb') { $paddingSize = $blockSize - (strlen($text) % $blockSize); if ($paddingSize >= 256) { throw new InvalidArgumentException("Block size [$blockSize] is bigger than 256"); } switch ($paddingType) { case self::PADDING_ANSI_X_923: $padding = str_repeat(chr(0), $paddingSize - 1) . chr($paddingSize); break; case self::PADDING_PKCS7: $padding = str_repeat(chr($paddingSize), $paddingSize); break; case self::PADDING_ISO_10126: $padding = ''; foreach (range(0, $paddingSize - 2) as $i) { $padding .= chr(rand()); } $padding .= chr($paddingSize); break; case self::PADDING_ISO_IEC_7816_4: $padding = chr(0x80) . str_repeat(chr(0), $paddingSize - 1); break; case self::PADDING_ZERO: $padding = str_repeat(chr(0), $paddingSize); break; case self::PADDING_SPACE: $padding = str_repeat(' ', $paddingSize); break; default: $paddingSize = 0; break; } } if (!$paddingSize) { return $text; } if ($paddingSize > $blockSize) { throw new InvalidArgumentException("Invalid padding size [$paddingSize]"); } return $text . substr($padding, 0, $paddingSize); }
[ "protected", "function", "padText", "(", "$", "text", ",", "$", "mode", ",", "$", "blockSize", ",", "$", "paddingType", ")", "{", "$", "paddingSize", "=", "0", ";", "$", "padding", "=", "''", ";", "if", "(", "$", "mode", "===", "'cbc'", "||", "$", "mode", "===", "'ecb'", ")", "{", "$", "paddingSize", "=", "$", "blockSize", "-", "(", "strlen", "(", "$", "text", ")", "%", "$", "blockSize", ")", ";", "if", "(", "$", "paddingSize", ">=", "256", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Block size [$blockSize] is bigger than 256\"", ")", ";", "}", "switch", "(", "$", "paddingType", ")", "{", "case", "self", "::", "PADDING_ANSI_X_923", ":", "$", "padding", "=", "str_repeat", "(", "chr", "(", "0", ")", ",", "$", "paddingSize", "-", "1", ")", ".", "chr", "(", "$", "paddingSize", ")", ";", "break", ";", "case", "self", "::", "PADDING_PKCS7", ":", "$", "padding", "=", "str_repeat", "(", "chr", "(", "$", "paddingSize", ")", ",", "$", "paddingSize", ")", ";", "break", ";", "case", "self", "::", "PADDING_ISO_10126", ":", "$", "padding", "=", "''", ";", "foreach", "(", "range", "(", "0", ",", "$", "paddingSize", "-", "2", ")", "as", "$", "i", ")", "{", "$", "padding", ".=", "chr", "(", "rand", "(", ")", ")", ";", "}", "$", "padding", ".=", "chr", "(", "$", "paddingSize", ")", ";", "break", ";", "case", "self", "::", "PADDING_ISO_IEC_7816_4", ":", "$", "padding", "=", "chr", "(", "0x80", ")", ".", "str_repeat", "(", "chr", "(", "0", ")", ",", "$", "paddingSize", "-", "1", ")", ";", "break", ";", "case", "self", "::", "PADDING_ZERO", ":", "$", "padding", "=", "str_repeat", "(", "chr", "(", "0", ")", ",", "$", "paddingSize", ")", ";", "break", ";", "case", "self", "::", "PADDING_SPACE", ":", "$", "padding", "=", "str_repeat", "(", "' '", ",", "$", "paddingSize", ")", ";", "break", ";", "default", ":", "$", "paddingSize", "=", "0", ";", "break", ";", "}", "}", "if", "(", "!", "$", "paddingSize", ")", "{", "return", "$", "text", ";", "}", "if", "(", "$", "paddingSize", ">", "$", "blockSize", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid padding size [$paddingSize]\"", ")", ";", "}", "return", "$", "text", ".", "substr", "(", "$", "padding", ",", "0", ",", "$", "paddingSize", ")", ";", "}" ]
Pads texts before encryption @see http://www.di-mgt.com.au/cryptopad.html @param mixed $text @param mixed $mode @param mixed $blockSize @param mixed $paddingType
[ "Pads", "texts", "before", "encryption" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Encryption/Crypt.php#L121-L177
zhouyl/mellivora
Mellivora/Encryption/Crypt.php
Crypt.unpadText
protected function unpadText($text, $mode, $blockSize, $paddingType) { $paddingSize = 0; $length = strlen(text); if ($length > 0 && ($length % $blockSize === 0) && ($mode === 'cbc' || $mode === 'ecb')) { switch ($paddingType) { case self::PADDING_ANSI_X_923: $last = substr($text, $length - 1, 1); $ord = (int) ord($last); if ($ord <= $blockSize) { $paddingSize = $ord; $padding = str_repeat(chr(0), $paddingSize - 1) . $last; if (substr($text, $length - $paddingSize) !== $padding) { $paddingSize = 0; } } break; case self::PADDING_PKCS7: $last = substr($text, $length - 1, 1); $ord = (int) ord($last); if ($ord <= $blockSize) { $paddingSize = $ord; $padding = str_repeat(chr($paddingSize), $paddingSize); if (substr($text, $length - $paddingSize) !== $padding) { $paddingSize = 0; } } break; case self::PADDING_ISO_10126: $last = substr($text, $length - 1, 1); $paddingSize = (int) ord($last); break; case self::PADDING_ISO_IEC_7816_4: $i = $length - 1; while ($i > 0 && $text[$i] === 0x00 && $paddingSize < $blockSize) { ++$paddingSize; --$i; } if ($text[$i] === 0x80) { ++$paddingSize; } else { $paddingSize = 0; } break; case self::PADDING_ZERO: $i = $length - 1; while ($i >= 0 && $text[$i] === 0x00 && $paddingSize <= $blockSize) { ++$paddingSize; --$i; } break; case self::PADDING_SPACE: $i = $length - 1; while ($i >= 0 && $text[$i] === 0x20 && $paddingSize <= $blockSize) { ++$paddingSize; --$i; } break; default: break; } if ($paddingSize && $paddingSize <= $blockSize) { if ($paddingSize < $length) { return substr($text, 0, $length - $paddingSize); } return ''; } $paddingSize = 0; } if (!$paddingSize) { return $text; } return ''; }
php
protected function unpadText($text, $mode, $blockSize, $paddingType) { $paddingSize = 0; $length = strlen(text); if ($length > 0 && ($length % $blockSize === 0) && ($mode === 'cbc' || $mode === 'ecb')) { switch ($paddingType) { case self::PADDING_ANSI_X_923: $last = substr($text, $length - 1, 1); $ord = (int) ord($last); if ($ord <= $blockSize) { $paddingSize = $ord; $padding = str_repeat(chr(0), $paddingSize - 1) . $last; if (substr($text, $length - $paddingSize) !== $padding) { $paddingSize = 0; } } break; case self::PADDING_PKCS7: $last = substr($text, $length - 1, 1); $ord = (int) ord($last); if ($ord <= $blockSize) { $paddingSize = $ord; $padding = str_repeat(chr($paddingSize), $paddingSize); if (substr($text, $length - $paddingSize) !== $padding) { $paddingSize = 0; } } break; case self::PADDING_ISO_10126: $last = substr($text, $length - 1, 1); $paddingSize = (int) ord($last); break; case self::PADDING_ISO_IEC_7816_4: $i = $length - 1; while ($i > 0 && $text[$i] === 0x00 && $paddingSize < $blockSize) { ++$paddingSize; --$i; } if ($text[$i] === 0x80) { ++$paddingSize; } else { $paddingSize = 0; } break; case self::PADDING_ZERO: $i = $length - 1; while ($i >= 0 && $text[$i] === 0x00 && $paddingSize <= $blockSize) { ++$paddingSize; --$i; } break; case self::PADDING_SPACE: $i = $length - 1; while ($i >= 0 && $text[$i] === 0x20 && $paddingSize <= $blockSize) { ++$paddingSize; --$i; } break; default: break; } if ($paddingSize && $paddingSize <= $blockSize) { if ($paddingSize < $length) { return substr($text, 0, $length - $paddingSize); } return ''; } $paddingSize = 0; } if (!$paddingSize) { return $text; } return ''; }
[ "protected", "function", "unpadText", "(", "$", "text", ",", "$", "mode", ",", "$", "blockSize", ",", "$", "paddingType", ")", "{", "$", "paddingSize", "=", "0", ";", "$", "length", "=", "strlen", "(", "text", ")", ";", "if", "(", "$", "length", ">", "0", "&&", "(", "$", "length", "%", "$", "blockSize", "===", "0", ")", "&&", "(", "$", "mode", "===", "'cbc'", "||", "$", "mode", "===", "'ecb'", ")", ")", "{", "switch", "(", "$", "paddingType", ")", "{", "case", "self", "::", "PADDING_ANSI_X_923", ":", "$", "last", "=", "substr", "(", "$", "text", ",", "$", "length", "-", "1", ",", "1", ")", ";", "$", "ord", "=", "(", "int", ")", "ord", "(", "$", "last", ")", ";", "if", "(", "$", "ord", "<=", "$", "blockSize", ")", "{", "$", "paddingSize", "=", "$", "ord", ";", "$", "padding", "=", "str_repeat", "(", "chr", "(", "0", ")", ",", "$", "paddingSize", "-", "1", ")", ".", "$", "last", ";", "if", "(", "substr", "(", "$", "text", ",", "$", "length", "-", "$", "paddingSize", ")", "!==", "$", "padding", ")", "{", "$", "paddingSize", "=", "0", ";", "}", "}", "break", ";", "case", "self", "::", "PADDING_PKCS7", ":", "$", "last", "=", "substr", "(", "$", "text", ",", "$", "length", "-", "1", ",", "1", ")", ";", "$", "ord", "=", "(", "int", ")", "ord", "(", "$", "last", ")", ";", "if", "(", "$", "ord", "<=", "$", "blockSize", ")", "{", "$", "paddingSize", "=", "$", "ord", ";", "$", "padding", "=", "str_repeat", "(", "chr", "(", "$", "paddingSize", ")", ",", "$", "paddingSize", ")", ";", "if", "(", "substr", "(", "$", "text", ",", "$", "length", "-", "$", "paddingSize", ")", "!==", "$", "padding", ")", "{", "$", "paddingSize", "=", "0", ";", "}", "}", "break", ";", "case", "self", "::", "PADDING_ISO_10126", ":", "$", "last", "=", "substr", "(", "$", "text", ",", "$", "length", "-", "1", ",", "1", ")", ";", "$", "paddingSize", "=", "(", "int", ")", "ord", "(", "$", "last", ")", ";", "break", ";", "case", "self", "::", "PADDING_ISO_IEC_7816_4", ":", "$", "i", "=", "$", "length", "-", "1", ";", "while", "(", "$", "i", ">", "0", "&&", "$", "text", "[", "$", "i", "]", "===", "0x00", "&&", "$", "paddingSize", "<", "$", "blockSize", ")", "{", "++", "$", "paddingSize", ";", "--", "$", "i", ";", "}", "if", "(", "$", "text", "[", "$", "i", "]", "===", "0x80", ")", "{", "++", "$", "paddingSize", ";", "}", "else", "{", "$", "paddingSize", "=", "0", ";", "}", "break", ";", "case", "self", "::", "PADDING_ZERO", ":", "$", "i", "=", "$", "length", "-", "1", ";", "while", "(", "$", "i", ">=", "0", "&&", "$", "text", "[", "$", "i", "]", "===", "0x00", "&&", "$", "paddingSize", "<=", "$", "blockSize", ")", "{", "++", "$", "paddingSize", ";", "--", "$", "i", ";", "}", "break", ";", "case", "self", "::", "PADDING_SPACE", ":", "$", "i", "=", "$", "length", "-", "1", ";", "while", "(", "$", "i", ">=", "0", "&&", "$", "text", "[", "$", "i", "]", "===", "0x20", "&&", "$", "paddingSize", "<=", "$", "blockSize", ")", "{", "++", "$", "paddingSize", ";", "--", "$", "i", ";", "}", "break", ";", "default", ":", "break", ";", "}", "if", "(", "$", "paddingSize", "&&", "$", "paddingSize", "<=", "$", "blockSize", ")", "{", "if", "(", "$", "paddingSize", "<", "$", "length", ")", "{", "return", "substr", "(", "$", "text", ",", "0", ",", "$", "length", "-", "$", "paddingSize", ")", ";", "}", "return", "''", ";", "}", "$", "paddingSize", "=", "0", ";", "}", "if", "(", "!", "$", "paddingSize", ")", "{", "return", "$", "text", ";", "}", "return", "''", ";", "}" ]
Removes padding @a padding_type from @a text If the function detects that the text was not padded, it will return it unmodified @param string text Message to be unpadded @param string mode Encryption mode; unpadding is applied only in CBC or ECB mode @param int $blockSize Cipher block size @param int $paddingType Padding scheme @param mixed $text @param mixed $mode
[ "Removes", "padding", "@a", "padding_type", "from", "@a", "text", "If", "the", "function", "detects", "that", "the", "text", "was", "not", "padded", "it", "will", "return", "it", "unmodified" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Encryption/Crypt.php#L190-L273
zhouyl/mellivora
Mellivora/Encryption/Crypt.php
Crypt.encrypt
public function encrypt($text, $key = null) { if (!function_exists('openssl_cipher_iv_length')) { throw new RuntimeException('openssl extension is required'); } if ($key === null) { $encryptKey = $this->key; } else { $encryptKey = $key; } if (empty($encryptKey)) { throw new InvalidArgumentException('Encryption key cannot be empty'); } $cipher = $this->cipher; $mode = strtolower(substr($cipher, strrpos($cipher, '-') - strlen($cipher))); if (!in_array($cipher, openssl_get_cipher_methods(true))) { throw new UnexpectedValueException("Cipher algorithm is unknown [$cipher]"); } $ivSize = openssl_cipher_iv_length($cipher); if ($ivSize > 0) { $blockSize = $ivSize; } else { $blockSize = openssl_cipher_iv_length(str_ireplace('-' . $mode, '', $cipher)); } $iv = openssl_random_pseudo_bytes($ivSize); $paddingType = $this->padding; if ($paddingType !== 0 && ($mode === 'cbc' || $mode === 'ecb')) { $padded = $this->padText($text, $mode, $blockSize, $paddingType); } else { $padded = $text; } return $iv . openssl_encrypt($padded, $cipher, $encryptKey, OPENSSL_RAW_DATA, $iv); }
php
public function encrypt($text, $key = null) { if (!function_exists('openssl_cipher_iv_length')) { throw new RuntimeException('openssl extension is required'); } if ($key === null) { $encryptKey = $this->key; } else { $encryptKey = $key; } if (empty($encryptKey)) { throw new InvalidArgumentException('Encryption key cannot be empty'); } $cipher = $this->cipher; $mode = strtolower(substr($cipher, strrpos($cipher, '-') - strlen($cipher))); if (!in_array($cipher, openssl_get_cipher_methods(true))) { throw new UnexpectedValueException("Cipher algorithm is unknown [$cipher]"); } $ivSize = openssl_cipher_iv_length($cipher); if ($ivSize > 0) { $blockSize = $ivSize; } else { $blockSize = openssl_cipher_iv_length(str_ireplace('-' . $mode, '', $cipher)); } $iv = openssl_random_pseudo_bytes($ivSize); $paddingType = $this->padding; if ($paddingType !== 0 && ($mode === 'cbc' || $mode === 'ecb')) { $padded = $this->padText($text, $mode, $blockSize, $paddingType); } else { $padded = $text; } return $iv . openssl_encrypt($padded, $cipher, $encryptKey, OPENSSL_RAW_DATA, $iv); }
[ "public", "function", "encrypt", "(", "$", "text", ",", "$", "key", "=", "null", ")", "{", "if", "(", "!", "function_exists", "(", "'openssl_cipher_iv_length'", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'openssl extension is required'", ")", ";", "}", "if", "(", "$", "key", "===", "null", ")", "{", "$", "encryptKey", "=", "$", "this", "->", "key", ";", "}", "else", "{", "$", "encryptKey", "=", "$", "key", ";", "}", "if", "(", "empty", "(", "$", "encryptKey", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Encryption key cannot be empty'", ")", ";", "}", "$", "cipher", "=", "$", "this", "->", "cipher", ";", "$", "mode", "=", "strtolower", "(", "substr", "(", "$", "cipher", ",", "strrpos", "(", "$", "cipher", ",", "'-'", ")", "-", "strlen", "(", "$", "cipher", ")", ")", ")", ";", "if", "(", "!", "in_array", "(", "$", "cipher", ",", "openssl_get_cipher_methods", "(", "true", ")", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "\"Cipher algorithm is unknown [$cipher]\"", ")", ";", "}", "$", "ivSize", "=", "openssl_cipher_iv_length", "(", "$", "cipher", ")", ";", "if", "(", "$", "ivSize", ">", "0", ")", "{", "$", "blockSize", "=", "$", "ivSize", ";", "}", "else", "{", "$", "blockSize", "=", "openssl_cipher_iv_length", "(", "str_ireplace", "(", "'-'", ".", "$", "mode", ",", "''", ",", "$", "cipher", ")", ")", ";", "}", "$", "iv", "=", "openssl_random_pseudo_bytes", "(", "$", "ivSize", ")", ";", "$", "paddingType", "=", "$", "this", "->", "padding", ";", "if", "(", "$", "paddingType", "!==", "0", "&&", "(", "$", "mode", "===", "'cbc'", "||", "$", "mode", "===", "'ecb'", ")", ")", "{", "$", "padded", "=", "$", "this", "->", "padText", "(", "$", "text", ",", "$", "mode", ",", "$", "blockSize", ",", "$", "paddingType", ")", ";", "}", "else", "{", "$", "padded", "=", "$", "text", ";", "}", "return", "$", "iv", ".", "openssl_encrypt", "(", "$", "padded", ",", "$", "cipher", ",", "$", "encryptKey", ",", "OPENSSL_RAW_DATA", ",", "$", "iv", ")", ";", "}" ]
Encrypts a text <code> $encrypted = $crypt->encrypt("Ultra-secret text", "encrypt password"); </code> @param mixed $text @param null|mixed $key
[ "Encrypts", "a", "text" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Encryption/Crypt.php#L285-L325
zhouyl/mellivora
Mellivora/Encryption/Crypt.php
Crypt.decrypt
public function decrypt($text, $key = null) { if (!function_exists('openssl_cipher_iv_length')) { throw new RuntimeException('openssl extension is required'); } if ($key === null) { $decryptKey = $this->key; } else { $decryptKey = $key; } if (empty($decryptKey)) { throw new InvalidArgumentException('Decryption key cannot be empty'); } $cipher = $this->cipher; $mode = strtolower(substr($cipher, strrpos($cipher, '-') - strlen($cipher))); if (!in_array($cipher, openssl_get_cipher_methods(true))) { throw new UnexpectedValueException("Cipher algorithm is unknown [$cipher]"); } $ivSize = openssl_cipher_iv_length($cipher); if ($ivSize > 0) { $blockSize = $ivSize; } else { $blockSize = openssl_cipher_iv_length(str_ireplace('-' . $mode, '', $cipher)); } $decrypted = openssl_decrypt(substr($text, $ivSize), $cipher, $decryptKey, OPENSSL_RAW_DATA, substr($text, 0, $ivSize)); $paddingType = $this->padding; if ($mode === 'cbc' || $mode === 'ecb') { return $this->unpadText($decrypted, $mode, $blockSize, $paddingType); } return $decrypted; }
php
public function decrypt($text, $key = null) { if (!function_exists('openssl_cipher_iv_length')) { throw new RuntimeException('openssl extension is required'); } if ($key === null) { $decryptKey = $this->key; } else { $decryptKey = $key; } if (empty($decryptKey)) { throw new InvalidArgumentException('Decryption key cannot be empty'); } $cipher = $this->cipher; $mode = strtolower(substr($cipher, strrpos($cipher, '-') - strlen($cipher))); if (!in_array($cipher, openssl_get_cipher_methods(true))) { throw new UnexpectedValueException("Cipher algorithm is unknown [$cipher]"); } $ivSize = openssl_cipher_iv_length($cipher); if ($ivSize > 0) { $blockSize = $ivSize; } else { $blockSize = openssl_cipher_iv_length(str_ireplace('-' . $mode, '', $cipher)); } $decrypted = openssl_decrypt(substr($text, $ivSize), $cipher, $decryptKey, OPENSSL_RAW_DATA, substr($text, 0, $ivSize)); $paddingType = $this->padding; if ($mode === 'cbc' || $mode === 'ecb') { return $this->unpadText($decrypted, $mode, $blockSize, $paddingType); } return $decrypted; }
[ "public", "function", "decrypt", "(", "$", "text", ",", "$", "key", "=", "null", ")", "{", "if", "(", "!", "function_exists", "(", "'openssl_cipher_iv_length'", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'openssl extension is required'", ")", ";", "}", "if", "(", "$", "key", "===", "null", ")", "{", "$", "decryptKey", "=", "$", "this", "->", "key", ";", "}", "else", "{", "$", "decryptKey", "=", "$", "key", ";", "}", "if", "(", "empty", "(", "$", "decryptKey", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Decryption key cannot be empty'", ")", ";", "}", "$", "cipher", "=", "$", "this", "->", "cipher", ";", "$", "mode", "=", "strtolower", "(", "substr", "(", "$", "cipher", ",", "strrpos", "(", "$", "cipher", ",", "'-'", ")", "-", "strlen", "(", "$", "cipher", ")", ")", ")", ";", "if", "(", "!", "in_array", "(", "$", "cipher", ",", "openssl_get_cipher_methods", "(", "true", ")", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "\"Cipher algorithm is unknown [$cipher]\"", ")", ";", "}", "$", "ivSize", "=", "openssl_cipher_iv_length", "(", "$", "cipher", ")", ";", "if", "(", "$", "ivSize", ">", "0", ")", "{", "$", "blockSize", "=", "$", "ivSize", ";", "}", "else", "{", "$", "blockSize", "=", "openssl_cipher_iv_length", "(", "str_ireplace", "(", "'-'", ".", "$", "mode", ",", "''", ",", "$", "cipher", ")", ")", ";", "}", "$", "decrypted", "=", "openssl_decrypt", "(", "substr", "(", "$", "text", ",", "$", "ivSize", ")", ",", "$", "cipher", ",", "$", "decryptKey", ",", "OPENSSL_RAW_DATA", ",", "substr", "(", "$", "text", ",", "0", ",", "$", "ivSize", ")", ")", ";", "$", "paddingType", "=", "$", "this", "->", "padding", ";", "if", "(", "$", "mode", "===", "'cbc'", "||", "$", "mode", "===", "'ecb'", ")", "{", "return", "$", "this", "->", "unpadText", "(", "$", "decrypted", ",", "$", "mode", ",", "$", "blockSize", ",", "$", "paddingType", ")", ";", "}", "return", "$", "decrypted", ";", "}" ]
Decrypts an encrypted text <code> echo $crypt->decrypt($encrypted, "decrypt password"); </code> @param mixed $text @param null|mixed $key
[ "Decrypts", "an", "encrypted", "text" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Encryption/Crypt.php#L337-L376
zhouyl/mellivora
Mellivora/Encryption/Crypt.php
Crypt.encryptBase64
public function encryptBase64($text, $key = null, $safe = false) { if ($safe === true) { return strtr(base64_encode($this->encrypt($text, $key)), '+/', '-_'); } return base64_encode($this->encrypt($text, $key)); }
php
public function encryptBase64($text, $key = null, $safe = false) { if ($safe === true) { return strtr(base64_encode($this->encrypt($text, $key)), '+/', '-_'); } return base64_encode($this->encrypt($text, $key)); }
[ "public", "function", "encryptBase64", "(", "$", "text", ",", "$", "key", "=", "null", ",", "$", "safe", "=", "false", ")", "{", "if", "(", "$", "safe", "===", "true", ")", "{", "return", "strtr", "(", "base64_encode", "(", "$", "this", "->", "encrypt", "(", "$", "text", ",", "$", "key", ")", ")", ",", "'+/'", ",", "'-_'", ")", ";", "}", "return", "base64_encode", "(", "$", "this", "->", "encrypt", "(", "$", "text", ",", "$", "key", ")", ")", ";", "}" ]
Encrypts a text returning the result as a base64 string @param mixed $text @param null|mixed $key @param mixed $safe
[ "Encrypts", "a", "text", "returning", "the", "result", "as", "a", "base64", "string" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Encryption/Crypt.php#L385-L392
zhouyl/mellivora
Mellivora/Encryption/Crypt.php
Crypt.decryptBase64
public function decryptBase64($text, $key = null, $safe = false) { if ($safe === true) { return $this->decrypt(base64_decode(strtr($text, '-_', '+/')), $key); } return $this->decrypt(base64_decode($text), $key); }
php
public function decryptBase64($text, $key = null, $safe = false) { if ($safe === true) { return $this->decrypt(base64_decode(strtr($text, '-_', '+/')), $key); } return $this->decrypt(base64_decode($text), $key); }
[ "public", "function", "decryptBase64", "(", "$", "text", ",", "$", "key", "=", "null", ",", "$", "safe", "=", "false", ")", "{", "if", "(", "$", "safe", "===", "true", ")", "{", "return", "$", "this", "->", "decrypt", "(", "base64_decode", "(", "strtr", "(", "$", "text", ",", "'-_'", ",", "'+/'", ")", ")", ",", "$", "key", ")", ";", "}", "return", "$", "this", "->", "decrypt", "(", "base64_decode", "(", "$", "text", ")", ",", "$", "key", ")", ";", "}" ]
Decrypt a text that is coded as a base64 string @param mixed $text @param null|mixed $key @param mixed $safe
[ "Decrypt", "a", "text", "that", "is", "coded", "as", "a", "base64", "string" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Encryption/Crypt.php#L401-L408
grozzzny/catalog
models/Category.php
Category.queryFilter
public static function queryFilter(ActiveQuery &$query, array $get) { if(!empty($get['text'])){ $query->andFilterWhere(['LIKE', 'title', $get['text']]); }else{ if(!empty($get['category_id'])){ $query->andFilterWhere(['parent_id' => $get['category_id']]); }else { $query->andFilterWhere(['parent_id' => 0]); } } }
php
public static function queryFilter(ActiveQuery &$query, array $get) { if(!empty($get['text'])){ $query->andFilterWhere(['LIKE', 'title', $get['text']]); }else{ if(!empty($get['category_id'])){ $query->andFilterWhere(['parent_id' => $get['category_id']]); }else { $query->andFilterWhere(['parent_id' => 0]); } } }
[ "public", "static", "function", "queryFilter", "(", "ActiveQuery", "&", "$", "query", ",", "array", "$", "get", ")", "{", "if", "(", "!", "empty", "(", "$", "get", "[", "'text'", "]", ")", ")", "{", "$", "query", "->", "andFilterWhere", "(", "[", "'LIKE'", ",", "'title'", ",", "$", "get", "[", "'text'", "]", "]", ")", ";", "}", "else", "{", "if", "(", "!", "empty", "(", "$", "get", "[", "'category_id'", "]", ")", ")", "{", "$", "query", "->", "andFilterWhere", "(", "[", "'parent_id'", "=>", "$", "get", "[", "'category_id'", "]", "]", ")", ";", "}", "else", "{", "$", "query", "->", "andFilterWhere", "(", "[", "'parent_id'", "=>", "0", "]", ")", ";", "}", "}", "}" ]
Фильтр @param $query @param $get
[ "Фильтр" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Category.php#L162-L173
grozzzny/catalog
models/Category.php
Category.querySort
public function querySort(&$provider) { $sort = []; $attributes = [ 'id', 'status', 'title', 'slug', 'order_num' ]; if(self::ORDER_NUM){ $sort = $sort + ['defaultOrder' => ['order_num' => SORT_DESC]]; $attributes = $attributes + ['order_num']; } $sort = $sort + ['attributes' => $attributes]; $provider->setSort($sort); }
php
public function querySort(&$provider) { $sort = []; $attributes = [ 'id', 'status', 'title', 'slug', 'order_num' ]; if(self::ORDER_NUM){ $sort = $sort + ['defaultOrder' => ['order_num' => SORT_DESC]]; $attributes = $attributes + ['order_num']; } $sort = $sort + ['attributes' => $attributes]; $provider->setSort($sort); }
[ "public", "function", "querySort", "(", "&", "$", "provider", ")", "{", "$", "sort", "=", "[", "]", ";", "$", "attributes", "=", "[", "'id'", ",", "'status'", ",", "'title'", ",", "'slug'", ",", "'order_num'", "]", ";", "if", "(", "self", "::", "ORDER_NUM", ")", "{", "$", "sort", "=", "$", "sort", "+", "[", "'defaultOrder'", "=>", "[", "'order_num'", "=>", "SORT_DESC", "]", "]", ";", "$", "attributes", "=", "$", "attributes", "+", "[", "'order_num'", "]", ";", "}", "$", "sort", "=", "$", "sort", "+", "[", "'attributes'", "=>", "$", "attributes", "]", ";", "$", "provider", "->", "setSort", "(", "$", "sort", ")", ";", "}" ]
Сортировка @param $provider
[ "Сортировка" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Category.php#L205-L225
grozzzny/catalog
models/Category.php
Category.getListItems
public function getListItems() { $item_arr = []; foreach ($this->items as $item) { $item_arr[$item->id] = $item->title; } return $item_arr; }
php
public function getListItems() { $item_arr = []; foreach ($this->items as $item) { $item_arr[$item->id] = $item->title; } return $item_arr; }
[ "public", "function", "getListItems", "(", ")", "{", "$", "item_arr", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "$", "item_arr", "[", "$", "item", "->", "id", "]", "=", "$", "item", "->", "title", ";", "}", "return", "$", "item_arr", ";", "}" ]
For special widget
[ "For", "special", "widget" ]
train
https://github.com/grozzzny/catalog/blob/ff1cac10a5f3a89f3ef2767f9ede6b2d74e1849a/models/Category.php#L293-L301
zhouyl/mellivora
Mellivora/Support/Arr.php
Arr.convert
public static function convert($object, $recursive = false) { if ($object instanceof \Traversable) { $array = iterator_to_array($object); } elseif (method_exists($object, 'toArray')) { $array = $object->toArray(); } elseif (method_exists($object, 'asArray')) { $array = $object->toArray(); } elseif (method_exists($object, 'as_array')) { $array = $object->toArray(); } elseif (method_exists($object, 'getArrayCopy')) { $array = $object->toArray(); } elseif (is_object($object)) { $array = get_object_vars($object); } else { $array = (array) $object; } if (!$recursive) { return $array; } $data = []; foreach ($array as $key => $value) { $data[$key] = is_object($value) ? self::convert($value, $recursive) : $value; } return $data; }
php
public static function convert($object, $recursive = false) { if ($object instanceof \Traversable) { $array = iterator_to_array($object); } elseif (method_exists($object, 'toArray')) { $array = $object->toArray(); } elseif (method_exists($object, 'asArray')) { $array = $object->toArray(); } elseif (method_exists($object, 'as_array')) { $array = $object->toArray(); } elseif (method_exists($object, 'getArrayCopy')) { $array = $object->toArray(); } elseif (is_object($object)) { $array = get_object_vars($object); } else { $array = (array) $object; } if (!$recursive) { return $array; } $data = []; foreach ($array as $key => $value) { $data[$key] = is_object($value) ? self::convert($value, $recursive) : $value; } return $data; }
[ "public", "static", "function", "convert", "(", "$", "object", ",", "$", "recursive", "=", "false", ")", "{", "if", "(", "$", "object", "instanceof", "\\", "Traversable", ")", "{", "$", "array", "=", "iterator_to_array", "(", "$", "object", ")", ";", "}", "elseif", "(", "method_exists", "(", "$", "object", ",", "'toArray'", ")", ")", "{", "$", "array", "=", "$", "object", "->", "toArray", "(", ")", ";", "}", "elseif", "(", "method_exists", "(", "$", "object", ",", "'asArray'", ")", ")", "{", "$", "array", "=", "$", "object", "->", "toArray", "(", ")", ";", "}", "elseif", "(", "method_exists", "(", "$", "object", ",", "'as_array'", ")", ")", "{", "$", "array", "=", "$", "object", "->", "toArray", "(", ")", ";", "}", "elseif", "(", "method_exists", "(", "$", "object", ",", "'getArrayCopy'", ")", ")", "{", "$", "array", "=", "$", "object", "->", "toArray", "(", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "object", ")", ")", "{", "$", "array", "=", "get_object_vars", "(", "$", "object", ")", ";", "}", "else", "{", "$", "array", "=", "(", "array", ")", "$", "object", ";", "}", "if", "(", "!", "$", "recursive", ")", "{", "return", "$", "array", ";", "}", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "data", "[", "$", "key", "]", "=", "is_object", "(", "$", "value", ")", "?", "self", "::", "convert", "(", "$", "value", ",", "$", "recursive", ")", ":", "$", "value", ";", "}", "return", "$", "data", ";", "}" ]
将对像转换为数组 @param mixed $object @param bool $recursive @return array
[ "将对像转换为数组" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Support/Arr.php#L565-L595
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/Builder/Reflector/FunctionAssembler.php
FunctionAssembler.mapReflectorPropertiesOntoDescriptor
protected function mapReflectorPropertiesOntoDescriptor($reflector, $descriptor) { $packages = new Collection(); $package = $this->extractPackageFromDocBlock($reflector->getDocBlock()); if ($package) { $tag = new TagDescriptor('package'); $tag->setDescription($package); $packages->add($tag); } $descriptor->getTags()->set('package', $packages); $descriptor->setFullyQualifiedStructuralElementName($reflector->getName() . '()'); $descriptor->setName($reflector->getShortName()); $descriptor->setLine($reflector->getLinenumber()); $descriptor->setNamespace($this->getFullyQualifiedNamespaceName($reflector)); }
php
protected function mapReflectorPropertiesOntoDescriptor($reflector, $descriptor) { $packages = new Collection(); $package = $this->extractPackageFromDocBlock($reflector->getDocBlock()); if ($package) { $tag = new TagDescriptor('package'); $tag->setDescription($package); $packages->add($tag); } $descriptor->getTags()->set('package', $packages); $descriptor->setFullyQualifiedStructuralElementName($reflector->getName() . '()'); $descriptor->setName($reflector->getShortName()); $descriptor->setLine($reflector->getLinenumber()); $descriptor->setNamespace($this->getFullyQualifiedNamespaceName($reflector)); }
[ "protected", "function", "mapReflectorPropertiesOntoDescriptor", "(", "$", "reflector", ",", "$", "descriptor", ")", "{", "$", "packages", "=", "new", "Collection", "(", ")", ";", "$", "package", "=", "$", "this", "->", "extractPackageFromDocBlock", "(", "$", "reflector", "->", "getDocBlock", "(", ")", ")", ";", "if", "(", "$", "package", ")", "{", "$", "tag", "=", "new", "TagDescriptor", "(", "'package'", ")", ";", "$", "tag", "->", "setDescription", "(", "$", "package", ")", ";", "$", "packages", "->", "add", "(", "$", "tag", ")", ";", "}", "$", "descriptor", "->", "getTags", "(", ")", "->", "set", "(", "'package'", ",", "$", "packages", ")", ";", "$", "descriptor", "->", "setFullyQualifiedStructuralElementName", "(", "$", "reflector", "->", "getName", "(", ")", ".", "'()'", ")", ";", "$", "descriptor", "->", "setName", "(", "$", "reflector", "->", "getShortName", "(", ")", ")", ";", "$", "descriptor", "->", "setLine", "(", "$", "reflector", "->", "getLinenumber", "(", ")", ")", ";", "$", "descriptor", "->", "setNamespace", "(", "$", "this", "->", "getFullyQualifiedNamespaceName", "(", "$", "reflector", ")", ")", ";", "}" ]
Maps the properties of the Function reflector onto the Descriptor. @param FunctionReflector $reflector @param FunctionDescriptor $descriptor @return void
[ "Maps", "the", "properties", "of", "the", "Function", "reflector", "onto", "the", "Descriptor", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/Builder/Reflector/FunctionAssembler.php#L62-L77
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/Builder/Reflector/FunctionAssembler.php
FunctionAssembler.createArgumentDescriptor
protected function createArgumentDescriptor($functionDescriptor, $argument) { $params = $functionDescriptor->getTags()->get('param', array()); if (!$this->argumentAssembler->getBuilder()) { $this->argumentAssembler->setBuilder($this->builder); } return $this->argumentAssembler->create($argument, $params); }
php
protected function createArgumentDescriptor($functionDescriptor, $argument) { $params = $functionDescriptor->getTags()->get('param', array()); if (!$this->argumentAssembler->getBuilder()) { $this->argumentAssembler->setBuilder($this->builder); } return $this->argumentAssembler->create($argument, $params); }
[ "protected", "function", "createArgumentDescriptor", "(", "$", "functionDescriptor", ",", "$", "argument", ")", "{", "$", "params", "=", "$", "functionDescriptor", "->", "getTags", "(", ")", "->", "get", "(", "'param'", ",", "array", "(", ")", ")", ";", "if", "(", "!", "$", "this", "->", "argumentAssembler", "->", "getBuilder", "(", ")", ")", "{", "$", "this", "->", "argumentAssembler", "->", "setBuilder", "(", "$", "this", "->", "builder", ")", ";", "}", "return", "$", "this", "->", "argumentAssembler", "->", "create", "(", "$", "argument", ",", "$", "params", ")", ";", "}" ]
Creates a new ArgumentDescriptor from the given Reflector and Param. @param FunctionDescriptor $functionDescriptor @param FunctionReflector\ArgumentReflector $argument @return ArgumentDescriptor
[ "Creates", "a", "new", "ArgumentDescriptor", "from", "the", "given", "Reflector", "and", "Param", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/Builder/Reflector/FunctionAssembler.php#L118-L127
php-lug/lug
src/Bundle/LocaleBundle/DependencyInjection/LugLocaleExtension.php
LugLocaleExtension.loadBundle
protected function loadBundle(array $config, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); foreach (['context', 'event_subscriber', 'form', 'negotiator', 'provider', 'validator'] as $resource) { $loader->load($resource.'.xml'); } $this->loadForm($container); $this->loadProvider($config, $container); }
php
protected function loadBundle(array $config, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); foreach (['context', 'event_subscriber', 'form', 'negotiator', 'provider', 'validator'] as $resource) { $loader->load($resource.'.xml'); } $this->loadForm($container); $this->loadProvider($config, $container); }
[ "protected", "function", "loadBundle", "(", "array", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "loader", "=", "new", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "foreach", "(", "[", "'context'", ",", "'event_subscriber'", ",", "'form'", ",", "'negotiator'", ",", "'provider'", ",", "'validator'", "]", "as", "$", "resource", ")", "{", "$", "loader", "->", "load", "(", "$", "resource", ".", "'.xml'", ")", ";", "}", "$", "this", "->", "loadForm", "(", "$", "container", ")", ";", "$", "this", "->", "loadProvider", "(", "$", "config", ",", "$", "container", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/LocaleBundle/DependencyInjection/LugLocaleExtension.php#L28-L38
jakubkratina/larachartie
src/DataTable/Factory/CellsFactory.php
CellsFactory.create
public function create($value, $format = null) { if (is_array($value)) { return $this->create($value['value'], $value['format']); } if ($value instanceof Carbon) { return new CarbonCell($value, $format); } return new Cell($value, $format); }
php
public function create($value, $format = null) { if (is_array($value)) { return $this->create($value['value'], $value['format']); } if ($value instanceof Carbon) { return new CarbonCell($value, $format); } return new Cell($value, $format); }
[ "public", "function", "create", "(", "$", "value", ",", "$", "format", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "return", "$", "this", "->", "create", "(", "$", "value", "[", "'value'", "]", ",", "$", "value", "[", "'format'", "]", ")", ";", "}", "if", "(", "$", "value", "instanceof", "Carbon", ")", "{", "return", "new", "CarbonCell", "(", "$", "value", ",", "$", "format", ")", ";", "}", "return", "new", "Cell", "(", "$", "value", ",", "$", "format", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/jakubkratina/larachartie/blob/96c535650d61a2a6c1c1b12d374e5e59d33239f6/src/DataTable/Factory/CellsFactory.php#L18-L29
kecik-framework/kecik
Kecik/Kecik.php
Kecik.autoload
public function autoload( $class ) { $ClassArray = explode( '\\', $class ); if ( count( $ClassArray ) > 1 ) { if ( php_sapi_name() == 'cli' ) { $MvcPath = $this->config->get( 'path.basepath' ) . $this->config->get( 'path.mvc' ); } else { $MvcPath = $this->config->get( 'path.mvc' ); } //** if count $ClassArray = 3 is HMVC if ( count( $ClassArray ) >= 3 ) { $HmvcPath = ''; for ( $i = 0; $i < count( $ClassArray ) - 2; $i ++ ) { $HmvcPath .= $ClassArray[ $i ] . '/'; } //** MVC Path / Module Controllers/Models / Class.php $FileLoad = $MvcPath . '/' . $HmvcPath . $ClassArray[ count( $ClassArray ) - 2 ] . '/' . $ClassArray[ count( $ClassArray ) - 1 ] . '.php'; } else { //** MVC Path / Controller/Models / Class.php $FileLoad = $MvcPath . '/' . $ClassArray[0] . '/' . $ClassArray[1] . '.php'; } if ( file_exists( $FileLoad ) ) { include $FileLoad; } } }
php
public function autoload( $class ) { $ClassArray = explode( '\\', $class ); if ( count( $ClassArray ) > 1 ) { if ( php_sapi_name() == 'cli' ) { $MvcPath = $this->config->get( 'path.basepath' ) . $this->config->get( 'path.mvc' ); } else { $MvcPath = $this->config->get( 'path.mvc' ); } //** if count $ClassArray = 3 is HMVC if ( count( $ClassArray ) >= 3 ) { $HmvcPath = ''; for ( $i = 0; $i < count( $ClassArray ) - 2; $i ++ ) { $HmvcPath .= $ClassArray[ $i ] . '/'; } //** MVC Path / Module Controllers/Models / Class.php $FileLoad = $MvcPath . '/' . $HmvcPath . $ClassArray[ count( $ClassArray ) - 2 ] . '/' . $ClassArray[ count( $ClassArray ) - 1 ] . '.php'; } else { //** MVC Path / Controller/Models / Class.php $FileLoad = $MvcPath . '/' . $ClassArray[0] . '/' . $ClassArray[1] . '.php'; } if ( file_exists( $FileLoad ) ) { include $FileLoad; } } }
[ "public", "function", "autoload", "(", "$", "class", ")", "{", "$", "ClassArray", "=", "explode", "(", "'\\\\'", ",", "$", "class", ")", ";", "if", "(", "count", "(", "$", "ClassArray", ")", ">", "1", ")", "{", "if", "(", "php_sapi_name", "(", ")", "==", "'cli'", ")", "{", "$", "MvcPath", "=", "$", "this", "->", "config", "->", "get", "(", "'path.basepath'", ")", ".", "$", "this", "->", "config", "->", "get", "(", "'path.mvc'", ")", ";", "}", "else", "{", "$", "MvcPath", "=", "$", "this", "->", "config", "->", "get", "(", "'path.mvc'", ")", ";", "}", "//** if count $ClassArray = 3 is HMVC\r", "if", "(", "count", "(", "$", "ClassArray", ")", ">=", "3", ")", "{", "$", "HmvcPath", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "ClassArray", ")", "-", "2", ";", "$", "i", "++", ")", "{", "$", "HmvcPath", ".=", "$", "ClassArray", "[", "$", "i", "]", ".", "'/'", ";", "}", "//** MVC Path / Module Controllers/Models / Class.php\r", "$", "FileLoad", "=", "$", "MvcPath", ".", "'/'", ".", "$", "HmvcPath", ".", "$", "ClassArray", "[", "count", "(", "$", "ClassArray", ")", "-", "2", "]", ".", "'/'", ".", "$", "ClassArray", "[", "count", "(", "$", "ClassArray", ")", "-", "1", "]", ".", "'.php'", ";", "}", "else", "{", "//** MVC Path / Controller/Models / Class.php\r", "$", "FileLoad", "=", "$", "MvcPath", ".", "'/'", ".", "$", "ClassArray", "[", "0", "]", ".", "'/'", ".", "$", "ClassArray", "[", "1", "]", ".", "'.php'", ";", "}", "if", "(", "file_exists", "(", "$", "FileLoad", ")", ")", "{", "include", "$", "FileLoad", ";", "}", "}", "}" ]
Autoload for MVC/HMVC concept @param $class
[ "Autoload", "for", "MVC", "/", "HMVC", "concept" ]
train
https://github.com/kecik-framework/kecik/blob/fa87e593affe1c9c51a2acd264b85ec06df31d7c/Kecik/Kecik.php#L207-L239
kecik-framework/kecik
Kecik/Kecik.php
Kecik.setCallable
private function setCallable( $args ) { $route = array_shift( $args ); $RealParams = array(); // Before Middleware if ( is_array( $args[0] ) && isset( $args[0][0] ) ) { $this->middleware['before'] = array_shift( $args ); } if ( ! is_callable( $args[0] ) && ! is_string( $args[0] ) && ! is_array( $args[0] ) ) { $controller = array_shift( $args ); $RealParams['controller'] = $controller; } //if ($route == '/' && count( $this->route->_getParams() ) <= 0 ) { if ( preg_match( '/(^\\/$)|(^\\/(\\?(\\w|\\d|\\=|\\&|\\-|\\.|_|\\/){0,}){0,}$)/', $route . $this->route->getParamStr(), $matches, PREG_OFFSET_CAPTURE ) ) { //$this->callable = array_pop($args); $callFunc = array_pop( $args ); $params = array(); if ( is_array( $callFunc ) ) { $keys = array_keys( $callFunc ); $params = $callFunc[ $keys[0] ]; if ( ! is_array( $params ) ) { $params = array( $params ); } $callFunc = $keys[0]; } $callFunc = $this->createCallbackFromString( $callFunc, $params ); $this->callable = Closure::bind( $callFunc, $this, get_class() ); $this->RoutedStatus = TRUE; } else { $RoutePattern = str_replace( '/', '\\/', $route ); /** * ID: Konversi route kedalam pattern parameter optional * EN: Convert route in optional parameter pattern */ $RoutePattern = preg_replace( '/\\\\\\/\\(:\\w+\\)/', '(\\/\\\\w+){0,}', $RoutePattern, - 1 ); /** * ID: Konversi route kedalam pattern parameter wajib * EN: Cover route in required parameter pattern */ $RoutePattern = preg_replace( '/:\\w+/', '([\\w+|\\=|\\-|\\_|\\.]){1,}', $RoutePattern, - 1 ); $RoutePattern = str_replace( '\\/\\w++', '(((\/){0,}\\w+){0,})', $RoutePattern ); if ( $route != '/' && preg_match( '/(^' . $RoutePattern . '$)|((^' . $RoutePattern . ')+(\\?(\\w|\\d|\\=|\\&|\\-|\\.|_|\\/){0,}){0,}$)/', $this->route->getParamStr(), $matches, PREG_OFFSET_CAPTURE ) ) { $callFunc = array_shift( $args ); $params = array(); if ( is_array( $callFunc ) ) { $keys = array_keys( $callFunc ); $params = $callFunc[ $keys[0] ]; if ( ! is_array( $params ) ) { $params = array( $params ); } $callFunc = $keys[0]; } $callFunc = $this->createCallbackFromString( $callFunc, $params ); //$this->callable = array_pop($args); $this->callable = Closure::bind( $callFunc, $this, get_class() ); $this->RoutedStatus = TRUE; $p = explode( '/', $route ); while ( list( $key, $value ) = each( $p ) ) { if ( substr( trim( $value ), - 1 ) == '+' ) { if ( isset( $matches[2][0] ) && ! empty( $matches[2][0] ) ) { $RealParams[ $value ] = explode( '/', substr( $matches[2][0], 1 ) ); } elseif ( isset( $matches[7][0] ) && ! empty( $matches[7][0] ) ) { $RealParams[ $value ] = explode( '/', substr( $matches[7][0] ), 1 ); } else { $RealParams[ $value ] = array(); } } elseif ( substr( trim( $value, '/' ), 0, 1 ) == ':' ) { $getpos = ( strpos( $this->route->_getParams( $key ), '?' ) > 0 ) ? strpos( $this->route->_getParams( $key ), '?' ) : strlen( $this->route->_getParams( $key ) ); $RealParams[ $value ] = substr( $this->route->_getParams( $key ), 0, $getpos ); } elseif ( substr( trim( $value, '/' ), 0, 2 ) == '(:' && substr( trim( $value, '/' ), - 1, 1 ) == ')' ) { if ( $this->route->_getParams( $key ) != NULL ) { $getpos = ( strpos( $this->route->_getParams( $key ), '?' ) > 0 ) ? strpos( $this->route->_getParams( $key ), '?' ) : strlen( $this->route->_getParams( $key ) ); $RealParams[ $value ] = substr( $this->route->_getParams( $key ), 0, $getpos ); } } } } } Route::$destination = $route; $this->route->setParams( $RealParams ); //print_r($args); // After Middleware if ( count( $args ) > 0 && is_array( $args[0] ) ) { $this->middleware['after'] = array_shift( $args ); } }
php
private function setCallable( $args ) { $route = array_shift( $args ); $RealParams = array(); // Before Middleware if ( is_array( $args[0] ) && isset( $args[0][0] ) ) { $this->middleware['before'] = array_shift( $args ); } if ( ! is_callable( $args[0] ) && ! is_string( $args[0] ) && ! is_array( $args[0] ) ) { $controller = array_shift( $args ); $RealParams['controller'] = $controller; } //if ($route == '/' && count( $this->route->_getParams() ) <= 0 ) { if ( preg_match( '/(^\\/$)|(^\\/(\\?(\\w|\\d|\\=|\\&|\\-|\\.|_|\\/){0,}){0,}$)/', $route . $this->route->getParamStr(), $matches, PREG_OFFSET_CAPTURE ) ) { //$this->callable = array_pop($args); $callFunc = array_pop( $args ); $params = array(); if ( is_array( $callFunc ) ) { $keys = array_keys( $callFunc ); $params = $callFunc[ $keys[0] ]; if ( ! is_array( $params ) ) { $params = array( $params ); } $callFunc = $keys[0]; } $callFunc = $this->createCallbackFromString( $callFunc, $params ); $this->callable = Closure::bind( $callFunc, $this, get_class() ); $this->RoutedStatus = TRUE; } else { $RoutePattern = str_replace( '/', '\\/', $route ); /** * ID: Konversi route kedalam pattern parameter optional * EN: Convert route in optional parameter pattern */ $RoutePattern = preg_replace( '/\\\\\\/\\(:\\w+\\)/', '(\\/\\\\w+){0,}', $RoutePattern, - 1 ); /** * ID: Konversi route kedalam pattern parameter wajib * EN: Cover route in required parameter pattern */ $RoutePattern = preg_replace( '/:\\w+/', '([\\w+|\\=|\\-|\\_|\\.]){1,}', $RoutePattern, - 1 ); $RoutePattern = str_replace( '\\/\\w++', '(((\/){0,}\\w+){0,})', $RoutePattern ); if ( $route != '/' && preg_match( '/(^' . $RoutePattern . '$)|((^' . $RoutePattern . ')+(\\?(\\w|\\d|\\=|\\&|\\-|\\.|_|\\/){0,}){0,}$)/', $this->route->getParamStr(), $matches, PREG_OFFSET_CAPTURE ) ) { $callFunc = array_shift( $args ); $params = array(); if ( is_array( $callFunc ) ) { $keys = array_keys( $callFunc ); $params = $callFunc[ $keys[0] ]; if ( ! is_array( $params ) ) { $params = array( $params ); } $callFunc = $keys[0]; } $callFunc = $this->createCallbackFromString( $callFunc, $params ); //$this->callable = array_pop($args); $this->callable = Closure::bind( $callFunc, $this, get_class() ); $this->RoutedStatus = TRUE; $p = explode( '/', $route ); while ( list( $key, $value ) = each( $p ) ) { if ( substr( trim( $value ), - 1 ) == '+' ) { if ( isset( $matches[2][0] ) && ! empty( $matches[2][0] ) ) { $RealParams[ $value ] = explode( '/', substr( $matches[2][0], 1 ) ); } elseif ( isset( $matches[7][0] ) && ! empty( $matches[7][0] ) ) { $RealParams[ $value ] = explode( '/', substr( $matches[7][0] ), 1 ); } else { $RealParams[ $value ] = array(); } } elseif ( substr( trim( $value, '/' ), 0, 1 ) == ':' ) { $getpos = ( strpos( $this->route->_getParams( $key ), '?' ) > 0 ) ? strpos( $this->route->_getParams( $key ), '?' ) : strlen( $this->route->_getParams( $key ) ); $RealParams[ $value ] = substr( $this->route->_getParams( $key ), 0, $getpos ); } elseif ( substr( trim( $value, '/' ), 0, 2 ) == '(:' && substr( trim( $value, '/' ), - 1, 1 ) == ')' ) { if ( $this->route->_getParams( $key ) != NULL ) { $getpos = ( strpos( $this->route->_getParams( $key ), '?' ) > 0 ) ? strpos( $this->route->_getParams( $key ), '?' ) : strlen( $this->route->_getParams( $key ) ); $RealParams[ $value ] = substr( $this->route->_getParams( $key ), 0, $getpos ); } } } } } Route::$destination = $route; $this->route->setParams( $RealParams ); //print_r($args); // After Middleware if ( count( $args ) > 0 && is_array( $args[0] ) ) { $this->middleware['after'] = array_shift( $args ); } }
[ "private", "function", "setCallable", "(", "$", "args", ")", "{", "$", "route", "=", "array_shift", "(", "$", "args", ")", ";", "$", "RealParams", "=", "array", "(", ")", ";", "// Before Middleware\r", "if", "(", "is_array", "(", "$", "args", "[", "0", "]", ")", "&&", "isset", "(", "$", "args", "[", "0", "]", "[", "0", "]", ")", ")", "{", "$", "this", "->", "middleware", "[", "'before'", "]", "=", "array_shift", "(", "$", "args", ")", ";", "}", "if", "(", "!", "is_callable", "(", "$", "args", "[", "0", "]", ")", "&&", "!", "is_string", "(", "$", "args", "[", "0", "]", ")", "&&", "!", "is_array", "(", "$", "args", "[", "0", "]", ")", ")", "{", "$", "controller", "=", "array_shift", "(", "$", "args", ")", ";", "$", "RealParams", "[", "'controller'", "]", "=", "$", "controller", ";", "}", "//if ($route == '/' && count( $this->route->_getParams() ) <= 0 ) {\r", "if", "(", "preg_match", "(", "'/(^\\\\/$)|(^\\\\/(\\\\?(\\\\w|\\\\d|\\\\=|\\\\&|\\\\-|\\\\.|_|\\\\/){0,}){0,}$)/'", ",", "$", "route", ".", "$", "this", "->", "route", "->", "getParamStr", "(", ")", ",", "$", "matches", ",", "PREG_OFFSET_CAPTURE", ")", ")", "{", "//$this->callable = array_pop($args);\r", "$", "callFunc", "=", "array_pop", "(", "$", "args", ")", ";", "$", "params", "=", "array", "(", ")", ";", "if", "(", "is_array", "(", "$", "callFunc", ")", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "callFunc", ")", ";", "$", "params", "=", "$", "callFunc", "[", "$", "keys", "[", "0", "]", "]", ";", "if", "(", "!", "is_array", "(", "$", "params", ")", ")", "{", "$", "params", "=", "array", "(", "$", "params", ")", ";", "}", "$", "callFunc", "=", "$", "keys", "[", "0", "]", ";", "}", "$", "callFunc", "=", "$", "this", "->", "createCallbackFromString", "(", "$", "callFunc", ",", "$", "params", ")", ";", "$", "this", "->", "callable", "=", "Closure", "::", "bind", "(", "$", "callFunc", ",", "$", "this", ",", "get_class", "(", ")", ")", ";", "$", "this", "->", "RoutedStatus", "=", "TRUE", ";", "}", "else", "{", "$", "RoutePattern", "=", "str_replace", "(", "'/'", ",", "'\\\\/'", ",", "$", "route", ")", ";", "/**\r\n\t\t\t * ID: Konversi route kedalam pattern parameter optional\r\n\t\t\t * EN: Convert route in optional parameter pattern\r\n\t\t\t */", "$", "RoutePattern", "=", "preg_replace", "(", "'/\\\\\\\\\\\\/\\\\(:\\\\w+\\\\)/'", ",", "'(\\\\/\\\\\\\\w+){0,}'", ",", "$", "RoutePattern", ",", "-", "1", ")", ";", "/**\r\n\t\t\t * ID: Konversi route kedalam pattern parameter wajib\r\n\t\t\t * EN: Cover route in required parameter pattern\r\n\t\t\t */", "$", "RoutePattern", "=", "preg_replace", "(", "'/:\\\\w+/'", ",", "'([\\\\w+|\\\\=|\\\\-|\\\\_|\\\\.]){1,}'", ",", "$", "RoutePattern", ",", "-", "1", ")", ";", "$", "RoutePattern", "=", "str_replace", "(", "'\\\\/\\\\w++'", ",", "'(((\\/){0,}\\\\w+){0,})'", ",", "$", "RoutePattern", ")", ";", "if", "(", "$", "route", "!=", "'/'", "&&", "preg_match", "(", "'/(^'", ".", "$", "RoutePattern", ".", "'$)|((^'", ".", "$", "RoutePattern", ".", "')+(\\\\?(\\\\w|\\\\d|\\\\=|\\\\&|\\\\-|\\\\.|_|\\\\/){0,}){0,}$)/'", ",", "$", "this", "->", "route", "->", "getParamStr", "(", ")", ",", "$", "matches", ",", "PREG_OFFSET_CAPTURE", ")", ")", "{", "$", "callFunc", "=", "array_shift", "(", "$", "args", ")", ";", "$", "params", "=", "array", "(", ")", ";", "if", "(", "is_array", "(", "$", "callFunc", ")", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "callFunc", ")", ";", "$", "params", "=", "$", "callFunc", "[", "$", "keys", "[", "0", "]", "]", ";", "if", "(", "!", "is_array", "(", "$", "params", ")", ")", "{", "$", "params", "=", "array", "(", "$", "params", ")", ";", "}", "$", "callFunc", "=", "$", "keys", "[", "0", "]", ";", "}", "$", "callFunc", "=", "$", "this", "->", "createCallbackFromString", "(", "$", "callFunc", ",", "$", "params", ")", ";", "//$this->callable = array_pop($args);\r", "$", "this", "->", "callable", "=", "Closure", "::", "bind", "(", "$", "callFunc", ",", "$", "this", ",", "get_class", "(", ")", ")", ";", "$", "this", "->", "RoutedStatus", "=", "TRUE", ";", "$", "p", "=", "explode", "(", "'/'", ",", "$", "route", ")", ";", "while", "(", "list", "(", "$", "key", ",", "$", "value", ")", "=", "each", "(", "$", "p", ")", ")", "{", "if", "(", "substr", "(", "trim", "(", "$", "value", ")", ",", "-", "1", ")", "==", "'+'", ")", "{", "if", "(", "isset", "(", "$", "matches", "[", "2", "]", "[", "0", "]", ")", "&&", "!", "empty", "(", "$", "matches", "[", "2", "]", "[", "0", "]", ")", ")", "{", "$", "RealParams", "[", "$", "value", "]", "=", "explode", "(", "'/'", ",", "substr", "(", "$", "matches", "[", "2", "]", "[", "0", "]", ",", "1", ")", ")", ";", "}", "elseif", "(", "isset", "(", "$", "matches", "[", "7", "]", "[", "0", "]", ")", "&&", "!", "empty", "(", "$", "matches", "[", "7", "]", "[", "0", "]", ")", ")", "{", "$", "RealParams", "[", "$", "value", "]", "=", "explode", "(", "'/'", ",", "substr", "(", "$", "matches", "[", "7", "]", "[", "0", "]", ")", ",", "1", ")", ";", "}", "else", "{", "$", "RealParams", "[", "$", "value", "]", "=", "array", "(", ")", ";", "}", "}", "elseif", "(", "substr", "(", "trim", "(", "$", "value", ",", "'/'", ")", ",", "0", ",", "1", ")", "==", "':'", ")", "{", "$", "getpos", "=", "(", "strpos", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ",", "'?'", ")", ">", "0", ")", "?", "strpos", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ",", "'?'", ")", ":", "strlen", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ")", ";", "$", "RealParams", "[", "$", "value", "]", "=", "substr", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ",", "0", ",", "$", "getpos", ")", ";", "}", "elseif", "(", "substr", "(", "trim", "(", "$", "value", ",", "'/'", ")", ",", "0", ",", "2", ")", "==", "'(:'", "&&", "substr", "(", "trim", "(", "$", "value", ",", "'/'", ")", ",", "-", "1", ",", "1", ")", "==", "')'", ")", "{", "if", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", "!=", "NULL", ")", "{", "$", "getpos", "=", "(", "strpos", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ",", "'?'", ")", ">", "0", ")", "?", "strpos", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ",", "'?'", ")", ":", "strlen", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ")", ";", "$", "RealParams", "[", "$", "value", "]", "=", "substr", "(", "$", "this", "->", "route", "->", "_getParams", "(", "$", "key", ")", ",", "0", ",", "$", "getpos", ")", ";", "}", "}", "}", "}", "}", "Route", "::", "$", "destination", "=", "$", "route", ";", "$", "this", "->", "route", "->", "setParams", "(", "$", "RealParams", ")", ";", "//print_r($args);\r", "// After Middleware\r", "if", "(", "count", "(", "$", "args", ")", ">", "0", "&&", "is_array", "(", "$", "args", "[", "0", "]", ")", ")", "{", "$", "this", "->", "middleware", "[", "'after'", "]", "=", "array_shift", "(", "$", "args", ")", ";", "}", "}" ]
Set Callback variable for execute when route is matched @param $args
[ "Set", "Callback", "variable", "for", "execute", "when", "route", "is", "matched" ]
train
https://github.com/kecik-framework/kecik/blob/fa87e593affe1c9c51a2acd264b85ec06df31d7c/Kecik/Kecik.php#L246-L366
kecik-framework/kecik
Kecik/Kecik.php
Kecik.createCallbackFromString
private function createCallbackFromString( $callFunc, $params ) { if ( is_string( $callFunc ) ) { $callFunc = function () use ( $callFunc, $params ) { $controllerParts = explode( '@', $callFunc ); $controllerParts[0] = explode( '\\', $controllerParts[0] ); $hmvc = ''; $controllerPaths = count( $controllerParts[0] ); if ( $controllerPaths > 1 ) { foreach ( $controllerParts[0] as $idx => $controllerPart ) { if ( $idx == ( $controllerPaths - 1 ) ) { break; } $hmvc .= '\\' . $controllerPart; } } $controller = $hmvc . '\\Controllers\\' . $controllerParts[0][ $controllerPaths - 1 ]; $c = new \ReflectionClass( $controller ); $c = $c->newInstanceArgs( $params ); return call_user_func_array( array( $c, $controllerParts[1] ), $this->route->getParams() ); }; return $callFunc; } return $callFunc; }
php
private function createCallbackFromString( $callFunc, $params ) { if ( is_string( $callFunc ) ) { $callFunc = function () use ( $callFunc, $params ) { $controllerParts = explode( '@', $callFunc ); $controllerParts[0] = explode( '\\', $controllerParts[0] ); $hmvc = ''; $controllerPaths = count( $controllerParts[0] ); if ( $controllerPaths > 1 ) { foreach ( $controllerParts[0] as $idx => $controllerPart ) { if ( $idx == ( $controllerPaths - 1 ) ) { break; } $hmvc .= '\\' . $controllerPart; } } $controller = $hmvc . '\\Controllers\\' . $controllerParts[0][ $controllerPaths - 1 ]; $c = new \ReflectionClass( $controller ); $c = $c->newInstanceArgs( $params ); return call_user_func_array( array( $c, $controllerParts[1] ), $this->route->getParams() ); }; return $callFunc; } return $callFunc; }
[ "private", "function", "createCallbackFromString", "(", "$", "callFunc", ",", "$", "params", ")", "{", "if", "(", "is_string", "(", "$", "callFunc", ")", ")", "{", "$", "callFunc", "=", "function", "(", ")", "use", "(", "$", "callFunc", ",", "$", "params", ")", "{", "$", "controllerParts", "=", "explode", "(", "'@'", ",", "$", "callFunc", ")", ";", "$", "controllerParts", "[", "0", "]", "=", "explode", "(", "'\\\\'", ",", "$", "controllerParts", "[", "0", "]", ")", ";", "$", "hmvc", "=", "''", ";", "$", "controllerPaths", "=", "count", "(", "$", "controllerParts", "[", "0", "]", ")", ";", "if", "(", "$", "controllerPaths", ">", "1", ")", "{", "foreach", "(", "$", "controllerParts", "[", "0", "]", "as", "$", "idx", "=>", "$", "controllerPart", ")", "{", "if", "(", "$", "idx", "==", "(", "$", "controllerPaths", "-", "1", ")", ")", "{", "break", ";", "}", "$", "hmvc", ".=", "'\\\\'", ".", "$", "controllerPart", ";", "}", "}", "$", "controller", "=", "$", "hmvc", ".", "'\\\\Controllers\\\\'", ".", "$", "controllerParts", "[", "0", "]", "[", "$", "controllerPaths", "-", "1", "]", ";", "$", "c", "=", "new", "\\", "ReflectionClass", "(", "$", "controller", ")", ";", "$", "c", "=", "$", "c", "->", "newInstanceArgs", "(", "$", "params", ")", ";", "return", "call_user_func_array", "(", "array", "(", "$", "c", ",", "$", "controllerParts", "[", "1", "]", ")", ",", "$", "this", "->", "route", "->", "getParams", "(", ")", ")", ";", "}", ";", "return", "$", "callFunc", ";", "}", "return", "$", "callFunc", ";", "}" ]
Create Callback from string @param $callFunc @param $params @return Closure
[ "Create", "Callback", "from", "string" ]
train
https://github.com/kecik-framework/kecik/blob/fa87e593affe1c9c51a2acd264b85ec06df31d7c/Kecik/Kecik.php#L376-L410
kecik-framework/kecik
Kecik/Kecik.php
Kecik.get
public function get() { $this->RoutedStatus = FALSE; if ( ! $this->route->isGet() ) { return $this; } if ( is_callable( $this->callable ) ) { //$this->RoutedStatus = FALSE; return $this; } $this->middleware = array( 'before' => array(), 'after' => array() ); self::$FullRender = ''; $args = func_get_args(); if ( ! empty( self::$group ) ) { if ( $args[0] == '/' ) { $args[0] = substr( self::$group, 0, - 1 ); } else { $args[0] = self::$group . $args[0]; } } array_push( Route::$list, $args[0] ); $this->setCallable( $args ); return $this; }
php
public function get() { $this->RoutedStatus = FALSE; if ( ! $this->route->isGet() ) { return $this; } if ( is_callable( $this->callable ) ) { //$this->RoutedStatus = FALSE; return $this; } $this->middleware = array( 'before' => array(), 'after' => array() ); self::$FullRender = ''; $args = func_get_args(); if ( ! empty( self::$group ) ) { if ( $args[0] == '/' ) { $args[0] = substr( self::$group, 0, - 1 ); } else { $args[0] = self::$group . $args[0]; } } array_push( Route::$list, $args[0] ); $this->setCallable( $args ); return $this; }
[ "public", "function", "get", "(", ")", "{", "$", "this", "->", "RoutedStatus", "=", "FALSE", ";", "if", "(", "!", "$", "this", "->", "route", "->", "isGet", "(", ")", ")", "{", "return", "$", "this", ";", "}", "if", "(", "is_callable", "(", "$", "this", "->", "callable", ")", ")", "{", "//$this->RoutedStatus = FALSE;\r", "return", "$", "this", ";", "}", "$", "this", "->", "middleware", "=", "array", "(", "'before'", "=>", "array", "(", ")", ",", "'after'", "=>", "array", "(", ")", ")", ";", "self", "::", "$", "FullRender", "=", "''", ";", "$", "args", "=", "func_get_args", "(", ")", ";", "if", "(", "!", "empty", "(", "self", "::", "$", "group", ")", ")", "{", "if", "(", "$", "args", "[", "0", "]", "==", "'/'", ")", "{", "$", "args", "[", "0", "]", "=", "substr", "(", "self", "::", "$", "group", ",", "0", ",", "-", "1", ")", ";", "}", "else", "{", "$", "args", "[", "0", "]", "=", "self", "::", "$", "group", ".", "$", "args", "[", "0", "]", ";", "}", "}", "array_push", "(", "Route", "::", "$", "list", ",", "$", "args", "[", "0", "]", ")", ";", "$", "this", "->", "setCallable", "(", "$", "args", ")", ";", "return", "$", "this", ";", "}" ]
Set route for Get Method request @return $this
[ "Set", "route", "for", "Get", "Method", "request" ]
train
https://github.com/kecik-framework/kecik/blob/fa87e593affe1c9c51a2acd264b85ec06df31d7c/Kecik/Kecik.php#L417-L447
kecik-framework/kecik
Kecik/Kecik.php
Kecik.group
public function group() { if ( is_callable( $this->callable ) ) { //$this->RoutedStatus = FALSE; return $this; } self::$FullRender = ''; $args = func_get_args(); self::$group .= $args[0] . '/'; if ( is_callable( $args[1] ) ) { $this->GroupFunc = Closure::bind( $args[1], $this, get_class() ); call_user_func_array( $this->GroupFunc, array() ); } self::$group = ''; }
php
public function group() { if ( is_callable( $this->callable ) ) { //$this->RoutedStatus = FALSE; return $this; } self::$FullRender = ''; $args = func_get_args(); self::$group .= $args[0] . '/'; if ( is_callable( $args[1] ) ) { $this->GroupFunc = Closure::bind( $args[1], $this, get_class() ); call_user_func_array( $this->GroupFunc, array() ); } self::$group = ''; }
[ "public", "function", "group", "(", ")", "{", "if", "(", "is_callable", "(", "$", "this", "->", "callable", ")", ")", "{", "//$this->RoutedStatus = FALSE;\r", "return", "$", "this", ";", "}", "self", "::", "$", "FullRender", "=", "''", ";", "$", "args", "=", "func_get_args", "(", ")", ";", "self", "::", "$", "group", ".=", "$", "args", "[", "0", "]", ".", "'/'", ";", "if", "(", "is_callable", "(", "$", "args", "[", "1", "]", ")", ")", "{", "$", "this", "->", "GroupFunc", "=", "Closure", "::", "bind", "(", "$", "args", "[", "1", "]", ",", "$", "this", ",", "get_class", "(", ")", ")", ";", "call_user_func_array", "(", "$", "this", "->", "GroupFunc", ",", "array", "(", ")", ")", ";", "}", "self", "::", "$", "group", "=", "''", ";", "}" ]
Set of Group route @return $this
[ "Set", "of", "Group", "route" ]
train
https://github.com/kecik-framework/kecik/blob/fa87e593affe1c9c51a2acd264b85ec06df31d7c/Kecik/Kecik.php#L639-L656
kecik-framework/kecik
Kecik/Kecik.php
Kecik.template
public function template( $template, $replace = FALSE ) { if ( $this->RoutedStatus || $replace === TRUE ) { self::$FullRender = $template; } return $this; }
php
public function template( $template, $replace = FALSE ) { if ( $this->RoutedStatus || $replace === TRUE ) { self::$FullRender = $template; } return $this; }
[ "public", "function", "template", "(", "$", "template", ",", "$", "replace", "=", "FALSE", ")", "{", "if", "(", "$", "this", "->", "RoutedStatus", "||", "$", "replace", "===", "TRUE", ")", "{", "self", "::", "$", "FullRender", "=", "$", "template", ";", "}", "return", "$", "this", ";", "}" ]
Set template before render @param $template @param bool $replace @return $this
[ "Set", "template", "before", "render" ]
train
https://github.com/kecik-framework/kecik/blob/fa87e593affe1c9c51a2acd264b85ec06df31d7c/Kecik/Kecik.php#L693-L699