repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
black-lamp/blcms-nova-poshta
frontend/controllers/DefaultController.php
DefaultController.getResponse
private function getResponse($modelName, $calledMethod, $methodProperties = []) { if (\Yii::$app->request->isAjax) { $data = [ 'apiKey' => $this->module->apiKey, 'modelName' => $modelName, 'calledMethod' => $calledMethod, 'methodProperties' => $methodProperties ]; $client = new Client(); $response = $client->createRequest() ->setFormat($this->module->format) ->setMethod('post') ->setUrl("{$this->module->requestUrl}/{$this->module->apiVersion}/{$this->module->format}/") ->setData($data) ->send(); if ($response->isOk) { return $response; } else throw new BadRequestHttpException(); } else throw new NotFoundHttpException(); }
php
private function getResponse($modelName, $calledMethod, $methodProperties = []) { if (\Yii::$app->request->isAjax) { $data = [ 'apiKey' => $this->module->apiKey, 'modelName' => $modelName, 'calledMethod' => $calledMethod, 'methodProperties' => $methodProperties ]; $client = new Client(); $response = $client->createRequest() ->setFormat($this->module->format) ->setMethod('post') ->setUrl("{$this->module->requestUrl}/{$this->module->apiVersion}/{$this->module->format}/") ->setData($data) ->send(); if ($response->isOk) { return $response; } else throw new BadRequestHttpException(); } else throw new NotFoundHttpException(); }
[ "private", "function", "getResponse", "(", "$", "modelName", ",", "$", "calledMethod", ",", "$", "methodProperties", "=", "[", "]", ")", "{", "if", "(", "\\", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", ")", "{", "$", "data", "=", "[", ...
This method makes request to the API. @property \bl\cms\novaposhta\frontend\Module $module @param string $modelName @param string $calledMethod @param array $methodProperties @return string @throws BadRequestHttpException @throws NotFoundHttpException
[ "This", "method", "makes", "request", "to", "the", "API", ".", "@property", "\\", "bl", "\\", "cms", "\\", "novaposhta", "\\", "frontend", "\\", "Module", "$module" ]
train
https://github.com/black-lamp/blcms-nova-poshta/blob/75b7d4b2034dd636c0bd59c87dc695c25de36f59/frontend/controllers/DefaultController.php#L26-L51
black-lamp/blcms-nova-poshta
frontend/controllers/DefaultController.php
DefaultController.actionGetWarehouses
public function actionGetWarehouses() { $street = $_GET['street']; $warehouses = $this->getResponse('AddressGeneral', 'getWarehouses', ['CityName' => $_GET['CityName']]); $warehousesByStreet = []; foreach ($warehouses->data['data'] as $warehouse) { if (substr_count(mb_strtolower($warehouse['Description']), mb_strtolower($street)) != 0 || substr_count(mb_strtolower($warehouse['DescriptionRu']), mb_strtolower($street))) { $warehousesByStreet[] = $warehouse; } } return json_encode($warehousesByStreet); }
php
public function actionGetWarehouses() { $street = $_GET['street']; $warehouses = $this->getResponse('AddressGeneral', 'getWarehouses', ['CityName' => $_GET['CityName']]); $warehousesByStreet = []; foreach ($warehouses->data['data'] as $warehouse) { if (substr_count(mb_strtolower($warehouse['Description']), mb_strtolower($street)) != 0 || substr_count(mb_strtolower($warehouse['DescriptionRu']), mb_strtolower($street))) { $warehousesByStreet[] = $warehouse; } } return json_encode($warehousesByStreet); }
[ "public", "function", "actionGetWarehouses", "(", ")", "{", "$", "street", "=", "$", "_GET", "[", "'street'", "]", ";", "$", "warehouses", "=", "$", "this", "->", "getResponse", "(", "'AddressGeneral'", ",", "'getWarehouses'", ",", "[", "'CityName'", "=>", ...
Gets warehouses by city and street. @return string
[ "Gets", "warehouses", "by", "city", "and", "street", "." ]
train
https://github.com/black-lamp/blcms-nova-poshta/blob/75b7d4b2034dd636c0bd59c87dc695c25de36f59/frontend/controllers/DefaultController.php#L69-L85
PenoaksDev/Milky-Framework
src/Milky/Hooks/HookDispatcher.php
HookDispatcher.addHook
public function addHook( $triggers, callable $callable, $key = null ) { if ( !is_array( $triggers ) ) $triggers = [$triggers]; if ( is_null( $key ) ) { $key = 0; while ( array_key_exists( $key, $this->hooks ) ) { $key++; } } $this->hooks[$key] = ['triggers' => $triggers, 'callable' => $callable]; $this->bakeTriggers(); }
php
public function addHook( $triggers, callable $callable, $key = null ) { if ( !is_array( $triggers ) ) $triggers = [$triggers]; if ( is_null( $key ) ) { $key = 0; while ( array_key_exists( $key, $this->hooks ) ) { $key++; } } $this->hooks[$key] = ['triggers' => $triggers, 'callable' => $callable]; $this->bakeTriggers(); }
[ "public", "function", "addHook", "(", "$", "triggers", ",", "callable", "$", "callable", ",", "$", "key", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "triggers", ")", ")", "$", "triggers", "=", "[", "$", "triggers", "]", ";", "if",...
Adds Hook @param string|array $triggers @param callable $callable @param string $name
[ "Adds", "Hook" ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Hooks/HookDispatcher.php#L37-L53
PenoaksDev/Milky-Framework
src/Milky/Hooks/HookDispatcher.php
HookDispatcher.removeHooks
public function removeHooks( $key ) { if ( array_key_exists( $key, $this->hooks ) ) { unset( $this->hooks[$key] ); $this->bakeTriggers(); } }
php
public function removeHooks( $key ) { if ( array_key_exists( $key, $this->hooks ) ) { unset( $this->hooks[$key] ); $this->bakeTriggers(); } }
[ "public", "function", "removeHooks", "(", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "hooks", ")", ")", "{", "unset", "(", "$", "this", "->", "hooks", "[", "$", "key", "]", ")", ";", "$", "this",...
Remove Hook @param $key
[ "Remove", "Hook" ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Hooks/HookDispatcher.php#L60-L67
PenoaksDev/Milky-Framework
src/Milky/Hooks/HookDispatcher.php
HookDispatcher.trigger
public function trigger( $trigger, $params = [], $halt = false ) { $keys = explode( '.', $trigger ); $current = $this->triggers; $results = []; foreach ( $keys as $key ) { $current = Arr::get( $current, $key ); if ( !is_null( $current ) ) // && array_key_exists( '__hook_', $current ) ) { foreach ( preg_grep_keys( "/__hook_[0-9]?/", $current ) as $hook ) { if ( array_key_exists( $hook, $this->hooks ) ) { $hook = $this->hooks[$hook]; $result = BindingBuilder::call( $hook['callable'], is_array( $params ) ? $params : ['payload' => $params] ); if ( !is_null( $result ) ) { if ( $halt ) return $result; else if ( is_array( $result ) ) $results = array_merge_recursive( $results, $result ); else $results[] = $result; } } } } } return $halt ? null : $results; }
php
public function trigger( $trigger, $params = [], $halt = false ) { $keys = explode( '.', $trigger ); $current = $this->triggers; $results = []; foreach ( $keys as $key ) { $current = Arr::get( $current, $key ); if ( !is_null( $current ) ) // && array_key_exists( '__hook_', $current ) ) { foreach ( preg_grep_keys( "/__hook_[0-9]?/", $current ) as $hook ) { if ( array_key_exists( $hook, $this->hooks ) ) { $hook = $this->hooks[$hook]; $result = BindingBuilder::call( $hook['callable'], is_array( $params ) ? $params : ['payload' => $params] ); if ( !is_null( $result ) ) { if ( $halt ) return $result; else if ( is_array( $result ) ) $results = array_merge_recursive( $results, $result ); else $results[] = $result; } } } } } return $halt ? null : $results; }
[ "public", "function", "trigger", "(", "$", "trigger", ",", "$", "params", "=", "[", "]", ",", "$", "halt", "=", "false", ")", "{", "$", "keys", "=", "explode", "(", "'.'", ",", "$", "trigger", ")", ";", "$", "current", "=", "$", "this", "->", "...
Triggers Hooks @param string $trigger
[ "Triggers", "Hooks" ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Hooks/HookDispatcher.php#L86-L118
libreworks/caridea-session
src/CsrfPlugin.php
CsrfPlugin.onStart
public function onStart(Session $session): void { $this->values = $session->getValues(__CLASS__); if (!$this->values->get('value')) { $this->regenerate(); } }
php
public function onStart(Session $session): void { $this->values = $session->getValues(__CLASS__); if (!$this->values->get('value')) { $this->regenerate(); } }
[ "public", "function", "onStart", "(", "Session", "$", "session", ")", ":", "void", "{", "$", "this", "->", "values", "=", "$", "session", "->", "getValues", "(", "__CLASS__", ")", ";", "if", "(", "!", "$", "this", "->", "values", "->", "get", "(", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/libreworks/caridea-session/blob/cb2a7c0cdcd172edbf267e5c69b396708b425f47/src/CsrfPlugin.php#L84-L90
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php
SmartTemplateParser.SmartTemplateParser
function SmartTemplateParser ( $template_filename ) { // Load Template if ($hd = @fopen($template_filename, "r")) { if (filesize($template_filename)) { $this->template = fread($hd, filesize($template_filename)); } else { $this->template = "SmartTemplate Parser Error: File size is zero byte: '$template_filename'"; } fclose($hd); // Extract the name of the template directory $this->template_dir = dirname($template_filename); } else { $this->template = "SmartTemplate Parser Error: File not found: '$template_filename'"; } }
php
function SmartTemplateParser ( $template_filename ) { // Load Template if ($hd = @fopen($template_filename, "r")) { if (filesize($template_filename)) { $this->template = fread($hd, filesize($template_filename)); } else { $this->template = "SmartTemplate Parser Error: File size is zero byte: '$template_filename'"; } fclose($hd); // Extract the name of the template directory $this->template_dir = dirname($template_filename); } else { $this->template = "SmartTemplate Parser Error: File not found: '$template_filename'"; } }
[ "function", "SmartTemplateParser", "(", "$", "template_filename", ")", "{", "// Load Template", "if", "(", "$", "hd", "=", "@", "fopen", "(", "$", "template_filename", ",", "\"r\"", ")", ")", "{", "if", "(", "filesize", "(", "$", "template_filename", ")", ...
SmartTemplateParser Constructor @param string $template_filename HTML Template Filename
[ "SmartTemplateParser", "Constructor" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php#L48-L69
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php
SmartTemplateParser.compile
function compile( $compiled_template_filename = '' ) { if (empty($this->template)) { return; } /* Quick hack to allow subtemplates */ if(eregi("<!-- INCLUDE", $this->template)) { while ($this->count_subtemplates() > 0) { preg_match_all('/<!-- INCLUDE ([a-zA-Z0-9_.]+) -->/', $this->template, $tvar); foreach($tvar[1] as $subfile) { if(file_exists($this->template_dir . "/$subfile")) { $subst = implode('',file($this->template_dir . "/$subfile")); } else { $subst = 'SmartTemplate Parser Error: Subtemplate not found: \''.$subfile.'\''; } $this->template = str_replace("<!-- INCLUDE $subfile -->", $subst, $this->template); } } } // END, ELSE Blocks $page = preg_replace("/<!-- ENDIF.+?-->/", "<?php\n}\n?>", $this->template); $page = preg_replace("/<!-- END[ a-zA-Z0-9_.]* -->/", "<?php\n}\n\$_obj=\$_stack[--\$_stack_cnt];}\n?>", $page); $page = str_replace("<!-- ELSE -->", "<?php\n} else {\n?>", $page); // 'BEGIN - END' Blocks if (preg_match_all('/<!-- BEGIN ([a-zA-Z0-9_.]+) -->/', $page, $var)) { foreach ($var[1] as $tag) { list($parent, $block) = $this->var_name($tag); $code = "<?php\n" . "if (!empty(\$$parent"."['$block'])){\n" . "if (!is_array(\$$parent"."['$block']))\n" . "\$$parent"."['$block']=array(array('$block'=>\$$parent"."['$block']));\n" . "\$_tmp_arr_keys=array_keys(\$$parent"."['$block']);\n" . "if (\$_tmp_arr_keys[0]!='0')\n" . "\$$parent"."['$block']=array(0=>\$$parent"."['$block']);\n" . "\$_stack[\$_stack_cnt++]=\$_obj;\n" . "foreach (\$$parent"."['$block'] as \$rowcnt=>\$$block) {\n" . "\$$block"."['ROWCNT']=\$rowcnt;\n" . "\$$block"."['ALTROW']=\$rowcnt%2;\n" . "\$$block"."['ROWBIT']=\$rowcnt%2;\n" . "\$_obj=&\$$block;\n?>"; $page = str_replace("<!-- BEGIN $tag -->", $code, $page); } } // 'IF nnn=mmm' Blocks if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+)[ ]*([!=<>]+)[ ]*(["]?[^"]*["]?) -->/', $page, $var)) { foreach ($var[2] as $cnt => $tag) { list($parent, $block) = $this->var_name($tag); $cmp = $var[3][$cnt]; $val = $var[4][$cnt]; $else = ($var[1][$cnt] == 'ELSE') ? '} else' : ''; if ($cmp == '=') { $cmp = '=='; } if (preg_match('/"([^"]*)"/',$val,$matches)) { $code = "<?php\n$else"."if (\$$parent"."['$block'] $cmp \"".$matches[1]."\"){\n?>"; } elseif (preg_match('/([^"]*)/',$val,$matches)) { list($parent_right, $block_right) = $this->var_name($matches[1]); $code = "<?php\n$else"."if (\$$parent"."['$block'] $cmp \$$parent_right"."['$block_right']){\n?>"; } $page = str_replace($var[0][$cnt], $code, $page); } } // 'IF nnn' Blocks if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+) -->/', $page, $var)) { foreach ($var[2] as $cnt => $tag) { $else = ($var[1][$cnt] == 'ELSE') ? '} else' : ''; list($parent, $block) = $this->var_name($tag); $code = "<?php\n$else"."if (!empty(\$$parent"."['$block'])){\n?>"; $page = str_replace($var[0][$cnt], $code, $page); } } // Replace Scalars if (preg_match_all('/{([a-zA-Z0-9_. >]+)}/', $page, $var)) { foreach ($var[1] as $fulltag) { // Determin Command (echo / $obj[n]=) list($cmd, $tag) = $this->cmd_name($fulltag); list($block, $skalar) = $this->var_name($tag); $code = "<?php\n$cmd \$$block"."['$skalar'];\n?>\n"; $page = str_replace('{'.$fulltag.'}', $code, $page); } } // ROSI Special: Replace Translations if (preg_match_all('/<"([a-zA-Z0-9_.]+)">/', $page, $var)) { foreach ($var[1] as $tag) { list($block, $skalar) = $this->var_name($tag); $code = "<?php\necho gettext('$skalar');\n?>\n"; $page = str_replace('<"'.$tag.'">', $code, $page); } } // Include Extensions $header = ''; if (preg_match_all('/{([a-zA-Z0-9_]+):([^}]*)}/', $page, $var)) { foreach ($var[2] as $cnt => $tag) { // Determin Command (echo / $obj[n]=) list($cmd, $tag) = $this->cmd_name($tag); $extension = $var[1][$cnt]; if (!isset($this->extension_tagged[$extension])) { $header .= "include_once \"smarttemplate_extensions/smarttemplate_extension_$extension.php\";\n"; $this->extension_tagged[$extension] = true; } if (!strlen($tag)) { $code = "<?php\n$cmd smarttemplate_extension_$extension();\n?>\n"; } elseif (substr($tag, 0, 1) == '"') { $code = "<?php\n$cmd smarttemplate_extension_$extension($tag);\n?>\n"; } elseif (strpos($tag, ',')) { list($tag, $addparam) = explode(',', $tag, 2); list($block, $skalar) = $this->var_name($tag); if (preg_match('/^([a-zA-Z_]+)/', $addparam, $match)) { $nexttag = $match[1]; list($nextblock, $nextskalar) = $this->var_name($nexttag); $addparam = substr($addparam, strlen($nexttag)); $code = "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],\$$nextblock"."['$nextskalar']"."$addparam);\n?>\n"; } else { $code = "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],$addparam);\n?>\n"; } } else { list($block, $skalar) = $this->var_name($tag); $code = "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar']);\n?>\n"; } $page = str_replace($var[0][$cnt], $code, $page); } } // Add Include Header if (isset($header) && !empty($header)) { $page = "<?php\n$header\n?>$page"; } // Store Code to Temp Dir if (strlen($compiled_template_filename)) { if ($hd = fopen($compiled_template_filename, "w")) { fwrite($hd, $page); fclose($hd); return true; } else { $this->error = "Could not write compiled file."; return false; } } else { return $page; } }
php
function compile( $compiled_template_filename = '' ) { if (empty($this->template)) { return; } /* Quick hack to allow subtemplates */ if(eregi("<!-- INCLUDE", $this->template)) { while ($this->count_subtemplates() > 0) { preg_match_all('/<!-- INCLUDE ([a-zA-Z0-9_.]+) -->/', $this->template, $tvar); foreach($tvar[1] as $subfile) { if(file_exists($this->template_dir . "/$subfile")) { $subst = implode('',file($this->template_dir . "/$subfile")); } else { $subst = 'SmartTemplate Parser Error: Subtemplate not found: \''.$subfile.'\''; } $this->template = str_replace("<!-- INCLUDE $subfile -->", $subst, $this->template); } } } // END, ELSE Blocks $page = preg_replace("/<!-- ENDIF.+?-->/", "<?php\n}\n?>", $this->template); $page = preg_replace("/<!-- END[ a-zA-Z0-9_.]* -->/", "<?php\n}\n\$_obj=\$_stack[--\$_stack_cnt];}\n?>", $page); $page = str_replace("<!-- ELSE -->", "<?php\n} else {\n?>", $page); // 'BEGIN - END' Blocks if (preg_match_all('/<!-- BEGIN ([a-zA-Z0-9_.]+) -->/', $page, $var)) { foreach ($var[1] as $tag) { list($parent, $block) = $this->var_name($tag); $code = "<?php\n" . "if (!empty(\$$parent"."['$block'])){\n" . "if (!is_array(\$$parent"."['$block']))\n" . "\$$parent"."['$block']=array(array('$block'=>\$$parent"."['$block']));\n" . "\$_tmp_arr_keys=array_keys(\$$parent"."['$block']);\n" . "if (\$_tmp_arr_keys[0]!='0')\n" . "\$$parent"."['$block']=array(0=>\$$parent"."['$block']);\n" . "\$_stack[\$_stack_cnt++]=\$_obj;\n" . "foreach (\$$parent"."['$block'] as \$rowcnt=>\$$block) {\n" . "\$$block"."['ROWCNT']=\$rowcnt;\n" . "\$$block"."['ALTROW']=\$rowcnt%2;\n" . "\$$block"."['ROWBIT']=\$rowcnt%2;\n" . "\$_obj=&\$$block;\n?>"; $page = str_replace("<!-- BEGIN $tag -->", $code, $page); } } // 'IF nnn=mmm' Blocks if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+)[ ]*([!=<>]+)[ ]*(["]?[^"]*["]?) -->/', $page, $var)) { foreach ($var[2] as $cnt => $tag) { list($parent, $block) = $this->var_name($tag); $cmp = $var[3][$cnt]; $val = $var[4][$cnt]; $else = ($var[1][$cnt] == 'ELSE') ? '} else' : ''; if ($cmp == '=') { $cmp = '=='; } if (preg_match('/"([^"]*)"/',$val,$matches)) { $code = "<?php\n$else"."if (\$$parent"."['$block'] $cmp \"".$matches[1]."\"){\n?>"; } elseif (preg_match('/([^"]*)/',$val,$matches)) { list($parent_right, $block_right) = $this->var_name($matches[1]); $code = "<?php\n$else"."if (\$$parent"."['$block'] $cmp \$$parent_right"."['$block_right']){\n?>"; } $page = str_replace($var[0][$cnt], $code, $page); } } // 'IF nnn' Blocks if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+) -->/', $page, $var)) { foreach ($var[2] as $cnt => $tag) { $else = ($var[1][$cnt] == 'ELSE') ? '} else' : ''; list($parent, $block) = $this->var_name($tag); $code = "<?php\n$else"."if (!empty(\$$parent"."['$block'])){\n?>"; $page = str_replace($var[0][$cnt], $code, $page); } } // Replace Scalars if (preg_match_all('/{([a-zA-Z0-9_. >]+)}/', $page, $var)) { foreach ($var[1] as $fulltag) { // Determin Command (echo / $obj[n]=) list($cmd, $tag) = $this->cmd_name($fulltag); list($block, $skalar) = $this->var_name($tag); $code = "<?php\n$cmd \$$block"."['$skalar'];\n?>\n"; $page = str_replace('{'.$fulltag.'}', $code, $page); } } // ROSI Special: Replace Translations if (preg_match_all('/<"([a-zA-Z0-9_.]+)">/', $page, $var)) { foreach ($var[1] as $tag) { list($block, $skalar) = $this->var_name($tag); $code = "<?php\necho gettext('$skalar');\n?>\n"; $page = str_replace('<"'.$tag.'">', $code, $page); } } // Include Extensions $header = ''; if (preg_match_all('/{([a-zA-Z0-9_]+):([^}]*)}/', $page, $var)) { foreach ($var[2] as $cnt => $tag) { // Determin Command (echo / $obj[n]=) list($cmd, $tag) = $this->cmd_name($tag); $extension = $var[1][$cnt]; if (!isset($this->extension_tagged[$extension])) { $header .= "include_once \"smarttemplate_extensions/smarttemplate_extension_$extension.php\";\n"; $this->extension_tagged[$extension] = true; } if (!strlen($tag)) { $code = "<?php\n$cmd smarttemplate_extension_$extension();\n?>\n"; } elseif (substr($tag, 0, 1) == '"') { $code = "<?php\n$cmd smarttemplate_extension_$extension($tag);\n?>\n"; } elseif (strpos($tag, ',')) { list($tag, $addparam) = explode(',', $tag, 2); list($block, $skalar) = $this->var_name($tag); if (preg_match('/^([a-zA-Z_]+)/', $addparam, $match)) { $nexttag = $match[1]; list($nextblock, $nextskalar) = $this->var_name($nexttag); $addparam = substr($addparam, strlen($nexttag)); $code = "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],\$$nextblock"."['$nextskalar']"."$addparam);\n?>\n"; } else { $code = "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],$addparam);\n?>\n"; } } else { list($block, $skalar) = $this->var_name($tag); $code = "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar']);\n?>\n"; } $page = str_replace($var[0][$cnt], $code, $page); } } // Add Include Header if (isset($header) && !empty($header)) { $page = "<?php\n$header\n?>$page"; } // Store Code to Temp Dir if (strlen($compiled_template_filename)) { if ($hd = fopen($compiled_template_filename, "w")) { fwrite($hd, $page); fclose($hd); return true; } else { $this->error = "Could not write compiled file."; return false; } } else { return $page; } }
[ "function", "compile", "(", "$", "compiled_template_filename", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "template", ")", ")", "{", "return", ";", "}", "/* Quick hack to allow subtemplates */", "if", "(", "eregi", "(", "\"<!-- INCLUDE\""...
Main Template Parser @param string $compiled_template_filename Compiled Template Filename @desc Creates Compiled PHP Template
[ "Main", "Template", "Parser" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php#L77-L271
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php
SmartTemplateParser.var_name
function var_name($tag) { $parent_level = 0; while (substr($tag, 0, 7) == 'parent.') { $tag = substr($tag, 7); $parent_level++; } if (substr($tag, 0, 4) == 'top.') { $obj = '_stack[0]'; $tag = substr($tag,4); } elseif ($parent_level) { $obj = '_stack[$_stack_cnt-'.$parent_level.']'; } else { $obj = '_obj'; } while (is_int(strpos($tag, '.'))) { list($parent, $tag) = explode('.', $tag, 2); if (is_numeric($parent)) { $obj .= "[" . $parent . "]"; } else { $obj .= "['" . $parent . "']"; } } $ret = array($obj, $tag); return $ret; }
php
function var_name($tag) { $parent_level = 0; while (substr($tag, 0, 7) == 'parent.') { $tag = substr($tag, 7); $parent_level++; } if (substr($tag, 0, 4) == 'top.') { $obj = '_stack[0]'; $tag = substr($tag,4); } elseif ($parent_level) { $obj = '_stack[$_stack_cnt-'.$parent_level.']'; } else { $obj = '_obj'; } while (is_int(strpos($tag, '.'))) { list($parent, $tag) = explode('.', $tag, 2); if (is_numeric($parent)) { $obj .= "[" . $parent . "]"; } else { $obj .= "['" . $parent . "']"; } } $ret = array($obj, $tag); return $ret; }
[ "function", "var_name", "(", "$", "tag", ")", "{", "$", "parent_level", "=", "0", ";", "while", "(", "substr", "(", "$", "tag", ",", "0", ",", "7", ")", "==", "'parent.'", ")", "{", "$", "tag", "=", "substr", "(", "$", "tag", ",", "7", ")", "...
Splits Template-Style Variable Names into an Array-Name/Key-Name Components {example} : array( "_obj", "example" ) -> $_obj['example'] {example.value} : array( "_obj['example']", "value" ) -> $_obj['example']['value'] {example.0.value} : array( "_obj['example'][0]", "value" ) -> $_obj['example'][0]['value'] {top.example} : array( "_stack[0]", "example" ) -> $_stack[0]['example'] {parent.example} : array( "_stack[$_stack_cnt-1]", "example" ) -> $_stack[$_stack_cnt-1]['example'] {parent.parent.example} : array( "_stack[$_stack_cnt-2]", "example" ) -> $_stack[$_stack_cnt-2]['example'] @param string $tag Variale Name used in Template @return array Array Name, Key Name @access private @desc Splits Template-Style Variable Names into an Array-Name/Key-Name Components
[ "Splits", "Template", "-", "Style", "Variable", "Names", "into", "an", "Array", "-", "Name", "/", "Key", "-", "Name", "Components", "{", "example", "}", ":", "array", "(", "_obj", "example", ")", "-", ">", "$_obj", "[", "example", "]", "{", "example", ...
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php#L288-L323
KDF5000/EasyThink
src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php
SmartTemplateParser.cmd_name
function cmd_name($tag) { if (preg_match('/^(.+) > ([a-zA-Z0-9_.]+)$/', $tag, $tagvar)) { $tag = $tagvar[1]; list($newblock, $newskalar) = $this->var_name($tagvar[2]); $cmd = "\$$newblock"."['$newskalar']="; } else { $cmd = "echo"; } $ret = array($cmd, $tag); return $ret; }
php
function cmd_name($tag) { if (preg_match('/^(.+) > ([a-zA-Z0-9_.]+)$/', $tag, $tagvar)) { $tag = $tagvar[1]; list($newblock, $newskalar) = $this->var_name($tagvar[2]); $cmd = "\$$newblock"."['$newskalar']="; } else { $cmd = "echo"; } $ret = array($cmd, $tag); return $ret; }
[ "function", "cmd_name", "(", "$", "tag", ")", "{", "if", "(", "preg_match", "(", "'/^(.+) > ([a-zA-Z0-9_.]+)$/'", ",", "$", "tag", ",", "$", "tagvar", ")", ")", "{", "$", "tag", "=", "$", "tagvar", "[", "1", "]", ";", "list", "(", "$", "newblock", ...
Determine Template Command from Variable Name {variable} : array( "echo", "variable" ) -> echo $_obj['variable'] {variable > new_name} : array( "_obj['new_name']=", "variable" ) -> $_obj['new_name']= $_obj['variable'] @param string $tag Variale Name used in Template @return array Array Command, Variable @access private @desc Determine Template Command from Variable Name
[ "Determine", "Template", "Command", "from", "Variable", "Name", "{", "variable", "}", ":", "array", "(", "echo", "variable", ")", "-", ">", "echo", "$_obj", "[", "variable", "]", "{", "variable", ">", "new_name", "}", ":", "array", "(", "_obj", "[", "n...
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/SmartTemplate/class.smarttemplateparser.php#L336-L350
rafrsr/lib-array2object
src/Parser/FloatParser.php
FloatParser.toObjectValue
public function toObjectValue($value, $type, \ReflectionProperty $property, $object) { if ($type === 'float' || $type === 'double') { return (float) $value; } return $value; }
php
public function toObjectValue($value, $type, \ReflectionProperty $property, $object) { if ($type === 'float' || $type === 'double') { return (float) $value; } return $value; }
[ "public", "function", "toObjectValue", "(", "$", "value", ",", "$", "type", ",", "\\", "ReflectionProperty", "$", "property", ",", "$", "object", ")", "{", "if", "(", "$", "type", "===", "'float'", "||", "$", "type", "===", "'double'", ")", "{", "retur...
{@inheritdoc}
[ "{" ]
train
https://github.com/rafrsr/lib-array2object/blob/d15db63b5f5740dbc7c2213373320445785856ef/src/Parser/FloatParser.php#L28-L35
internetofvoice/vsms-core
src/Controller/AbstractLinkController.php
AbstractLinkController.validateRequestParameters
public function validateRequestParameters($request, $amz_client_id) { $errors = array(); $state = $request->getParam('state', false); $redirect_uri = $request->getParam('redirect_uri', false); $client_id = $request->getParam('client_id', false); $scope = $request->getParam('scope', false); $response_type = $request->getParam('response_type', false); if($state === false) { $errors[] = 'state'; } if($redirect_uri === false) { $errors[] = 'redirect_uri'; } if($client_id != $amz_client_id) { $errors[] = 'client_id'; } if($response_type != 'token') { $errors[] = 'response_type'; } if(count($errors)) { throw new InvalidArgumentException('Missing or incorrect parameters: ' . implode(', ', $errors)); } else { return [ 'state' => $state, 'redirect_uri' => $redirect_uri, 'client_id' => $client_id, 'scope' => $scope, 'response_type' => $response_type, ]; } }
php
public function validateRequestParameters($request, $amz_client_id) { $errors = array(); $state = $request->getParam('state', false); $redirect_uri = $request->getParam('redirect_uri', false); $client_id = $request->getParam('client_id', false); $scope = $request->getParam('scope', false); $response_type = $request->getParam('response_type', false); if($state === false) { $errors[] = 'state'; } if($redirect_uri === false) { $errors[] = 'redirect_uri'; } if($client_id != $amz_client_id) { $errors[] = 'client_id'; } if($response_type != 'token') { $errors[] = 'response_type'; } if(count($errors)) { throw new InvalidArgumentException('Missing or incorrect parameters: ' . implode(', ', $errors)); } else { return [ 'state' => $state, 'redirect_uri' => $redirect_uri, 'client_id' => $client_id, 'scope' => $scope, 'response_type' => $response_type, ]; } }
[ "public", "function", "validateRequestParameters", "(", "$", "request", ",", "$", "amz_client_id", ")", "{", "$", "errors", "=", "array", "(", ")", ";", "$", "state", "=", "$", "request", "->", "getParam", "(", "'state'", ",", "false", ")", ";", "$", "...
Validate request parameters @param \Slim\Http\Request $request Slim request @param string $amz_client_id Client ID as configured in Amazon Developer Console @return array @throws \InvalidArgumentException @access public @author a.schmidt@internet-of-voice.de
[ "Validate", "request", "parameters" ]
train
https://github.com/internetofvoice/vsms-core/blob/bd1eb6ca90a55f4928c35b9f0742a5cc922298ef/src/Controller/AbstractLinkController.php#L24-L59
internetofvoice/vsms-core
src/Controller/AbstractLinkController.php
AbstractLinkController.getRedirectLocation
public function getRedirectLocation($parameters, $access_token) { $location = array(); array_push($location, $parameters['redirect_uri'] . '#state=' . $parameters['state']); array_push($location, 'access_token=' . $access_token); array_push($location, 'token_type=Bearer'); return implode('&', $location); }
php
public function getRedirectLocation($parameters, $access_token) { $location = array(); array_push($location, $parameters['redirect_uri'] . '#state=' . $parameters['state']); array_push($location, 'access_token=' . $access_token); array_push($location, 'token_type=Bearer'); return implode('&', $location); }
[ "public", "function", "getRedirectLocation", "(", "$", "parameters", ",", "$", "access_token", ")", "{", "$", "location", "=", "array", "(", ")", ";", "array_push", "(", "$", "location", ",", "$", "parameters", "[", "'redirect_uri'", "]", ".", "'#state='", ...
Get redirect location @param array $parameters Amazon parameters (see validateRequestParameters()) @param string $access_token Generated access token @return string @access public @author a.schmidt@internet-of-voice.de
[ "Get", "redirect", "location" ]
train
https://github.com/internetofvoice/vsms-core/blob/bd1eb6ca90a55f4928c35b9f0742a5cc922298ef/src/Controller/AbstractLinkController.php#L70-L77
jabernardo/lollipop-php
Library/HTTP/Router.php
Router.serve
static public function serve(array $route) { if (!isset($route['path']) || !isset($route['callback']) || (isset($route['method']) && is_string($route['method']))) { throw new \Lollipop\Exception\HTTP\Router('Invalid route'); } // Default path to '/' $path = Utils::fuse($route['path'], ''); $path = trim($path, '/'); if (!isset($route['method'])) { $route['method'] = []; } if (!isset($route['middlewares'])) { $route['middlewares'] = []; } if (!isset($route['arguments'])) { $route['arguments'] = []; } // Report duplicated path // if (isset(self::$_stored_routes[$path])) { // throw new \Lollipop\Exception\HTTP\Router("Duplicate path: $path"); // } // if (isset($route['name']) && isset(self::$_stored_names[$route['name']])) { // throw new \Lollipop\Exception\HTTP\Router('Duplicate name: ' . $route['name']); // } // Store route foreach ($route['method'] as $method) { self::$_stored_routes[$method][$path] = $route; } if (isset($route['name'])) { self::$_stored_names[$route['name']] = $path; } // Register dispatcher once this function was called self::_registerDispatch(); }
php
static public function serve(array $route) { if (!isset($route['path']) || !isset($route['callback']) || (isset($route['method']) && is_string($route['method']))) { throw new \Lollipop\Exception\HTTP\Router('Invalid route'); } // Default path to '/' $path = Utils::fuse($route['path'], ''); $path = trim($path, '/'); if (!isset($route['method'])) { $route['method'] = []; } if (!isset($route['middlewares'])) { $route['middlewares'] = []; } if (!isset($route['arguments'])) { $route['arguments'] = []; } // Report duplicated path // if (isset(self::$_stored_routes[$path])) { // throw new \Lollipop\Exception\HTTP\Router("Duplicate path: $path"); // } // if (isset($route['name']) && isset(self::$_stored_names[$route['name']])) { // throw new \Lollipop\Exception\HTTP\Router('Duplicate name: ' . $route['name']); // } // Store route foreach ($route['method'] as $method) { self::$_stored_routes[$method][$path] = $route; } if (isset($route['name'])) { self::$_stored_names[$route['name']] = $path; } // Register dispatcher once this function was called self::_registerDispatch(); }
[ "static", "public", "function", "serve", "(", "array", "$", "route", ")", "{", "if", "(", "!", "isset", "(", "$", "route", "[", "'path'", "]", ")", "||", "!", "isset", "(", "$", "route", "[", "'callback'", "]", ")", "||", "(", "isset", "(", "$", ...
Serve route @param array $route Route settings @example [ 'path' => '/', 'callback' => 'MyController.index', 'method' => ['GET', 'POST'], ] @throws \Lollipop\Exception\HTTP\Router @return void
[ "Serve", "route" ]
train
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Router.php#L186-L228
jabernardo/lollipop-php
Library/HTTP/Router.php
Router.getRoute
static public function getRoute($name) { $route_by_name = isset(self::$_stored_names[$name]) ? self::$_stored_names[$name] : null; if (!is_null($route_by_name) && isset(self::$_stored_routes[$route_by_name])) { return self::$_stored_routes[$route_by_name]; } return null; }
php
static public function getRoute($name) { $route_by_name = isset(self::$_stored_names[$name]) ? self::$_stored_names[$name] : null; if (!is_null($route_by_name) && isset(self::$_stored_routes[$route_by_name])) { return self::$_stored_routes[$route_by_name]; } return null; }
[ "static", "public", "function", "getRoute", "(", "$", "name", ")", "{", "$", "route_by_name", "=", "isset", "(", "self", "::", "$", "_stored_names", "[", "$", "name", "]", ")", "?", "self", "::", "$", "_stored_names", "[", "$", "name", "]", ":", "nul...
Get route by name @access public @param string $name Route name @return route
[ "Get", "route", "by", "name" ]
train
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Router.php#L250-L260
jabernardo/lollipop-php
Library/HTTP/Router.php
Router.dispatch
static public function dispatch($render = true, \Lollipop\HTTP\Request $response = null, \Lollipop\HTTP\Response $request = null) { if (is_null($response)) { // Create a new response $response = new Response(); } if (is_null($request)) { // New request object $request = new Request(); } // Get URL Path property only $url = trim($request->url(PHP_URL_PATH), '/'); // Create an instance of URL parser for checking if current // path matches any route $parser = new \Lollipop\HTTP\URL\Pretty($url); // Get 404 Page Not Found // Check if `404` route was declared self::$_active_route = isset(self::$_stored_routes[$request->method()]['404']) ? self::$_stored_routes[$request->method()]['404'] : self::_getDefaultPageNotFound(); foreach (self::$_stored_routes[$request->method()] as $path => $route) { if ($parser->test($path)) { // Set the route arguments based from the matches from the url $route['arguments'] = $parser->getMatches();; // Set route as active self::$_active_route = $route; } } // Stack specific route level middleware if (isset(self::$_active_route['middlewares']) && is_array(self::$_active_route['middlewares'])) { foreach (self::$_active_route['middlewares'] as $mw) { self::_stackMiddleware($mw); } } // Stack route level middleware if (isset(self::$_middlewares) && is_array(self::$_middlewares)) { foreach (self::$_middlewares as $mw) { self::_stackMiddleware($mw); } } // Now call the main callback $response = self::_process($request, $response); // Render output from our application if (!($response instanceof Response)) { $response = new Response($response); } // Is gzip compression enabled in config if (Config::get('output.compression')) { $response->compress(); } if ($render) { // `->render()` will set cookies, header and document // content $response->render(); } return $response; }
php
static public function dispatch($render = true, \Lollipop\HTTP\Request $response = null, \Lollipop\HTTP\Response $request = null) { if (is_null($response)) { // Create a new response $response = new Response(); } if (is_null($request)) { // New request object $request = new Request(); } // Get URL Path property only $url = trim($request->url(PHP_URL_PATH), '/'); // Create an instance of URL parser for checking if current // path matches any route $parser = new \Lollipop\HTTP\URL\Pretty($url); // Get 404 Page Not Found // Check if `404` route was declared self::$_active_route = isset(self::$_stored_routes[$request->method()]['404']) ? self::$_stored_routes[$request->method()]['404'] : self::_getDefaultPageNotFound(); foreach (self::$_stored_routes[$request->method()] as $path => $route) { if ($parser->test($path)) { // Set the route arguments based from the matches from the url $route['arguments'] = $parser->getMatches();; // Set route as active self::$_active_route = $route; } } // Stack specific route level middleware if (isset(self::$_active_route['middlewares']) && is_array(self::$_active_route['middlewares'])) { foreach (self::$_active_route['middlewares'] as $mw) { self::_stackMiddleware($mw); } } // Stack route level middleware if (isset(self::$_middlewares) && is_array(self::$_middlewares)) { foreach (self::$_middlewares as $mw) { self::_stackMiddleware($mw); } } // Now call the main callback $response = self::_process($request, $response); // Render output from our application if (!($response instanceof Response)) { $response = new Response($response); } // Is gzip compression enabled in config if (Config::get('output.compression')) { $response->compress(); } if ($render) { // `->render()` will set cookies, header and document // content $response->render(); } return $response; }
[ "static", "public", "function", "dispatch", "(", "$", "render", "=", "true", ",", "\\", "Lollipop", "\\", "HTTP", "\\", "Request", "$", "response", "=", "null", ",", "\\", "Lollipop", "\\", "HTTP", "\\", "Response", "$", "request", "=", "null", ")", "{...
Dispath function @access public @param boolean $render Render response (true) @param \Lollipop\HTTP\Request $req Request object (null default) @param \Lollipop\HTTP\Response $res Response object (null default) @return void
[ "Dispath", "function" ]
train
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Router.php#L295-L363
jabernardo/lollipop-php
Library/HTTP/Router.php
Router._registerDispatch
static private function _registerDispatch() { // Register dispatch function $auto_dispatch = !is_null(Config::get('router.auto_dispatch')) ? Config::get('router.auto_dispatch') : true; if (!self::$_dispatch_registered && $auto_dispatch) { // Make sure things ends here... register_shutdown_function(function() { // Get response data from Dispatcher $response = self::dispatch(); }); // Mark as dispatched self::$_dispatch_registered = true; } }
php
static private function _registerDispatch() { // Register dispatch function $auto_dispatch = !is_null(Config::get('router.auto_dispatch')) ? Config::get('router.auto_dispatch') : true; if (!self::$_dispatch_registered && $auto_dispatch) { // Make sure things ends here... register_shutdown_function(function() { // Get response data from Dispatcher $response = self::dispatch(); }); // Mark as dispatched self::$_dispatch_registered = true; } }
[ "static", "private", "function", "_registerDispatch", "(", ")", "{", "// Register dispatch function", "$", "auto_dispatch", "=", "!", "is_null", "(", "Config", "::", "get", "(", "'router.auto_dispatch'", ")", ")", "?", "Config", "::", "get", "(", "'router.auto_dis...
Register dispatch function on shutdown @access private @return void
[ "Register", "dispatch", "function", "on", "shutdown" ]
train
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Router.php#L372-L388
jabernardo/lollipop-php
Library/HTTP/Router.php
Router._process
static private function _process(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) { if (is_null(self::$_kernel)) { $active = self::$_active_route; $top = function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) use ($active) { return Route::resolve($active['callback'], $req, $res, $active['arguments']); }; self::$_kernel = $top; } // Create a new address for the top callable $start = self::$_kernel; // Start dequeue self::$_busy = true; $new_response = $start($req, $res); self::$_busy = false; // Just want to make sure that processed response from middlewares // are instance of \Calf\HTTP\Response if ($new_response instanceof \Lollipop\HTTP\Response) { $res = $new_response; } else { $res->set($new_response); } return $res; }
php
static private function _process(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) { if (is_null(self::$_kernel)) { $active = self::$_active_route; $top = function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) use ($active) { return Route::resolve($active['callback'], $req, $res, $active['arguments']); }; self::$_kernel = $top; } // Create a new address for the top callable $start = self::$_kernel; // Start dequeue self::$_busy = true; $new_response = $start($req, $res); self::$_busy = false; // Just want to make sure that processed response from middlewares // are instance of \Calf\HTTP\Response if ($new_response instanceof \Lollipop\HTTP\Response) { $res = $new_response; } else { $res->set($new_response); } return $res; }
[ "static", "private", "function", "_process", "(", "\\", "Lollipop", "\\", "HTTP", "\\", "Request", "$", "req", ",", "\\", "Lollipop", "\\", "HTTP", "\\", "Response", "$", "res", ")", "{", "if", "(", "is_null", "(", "self", "::", "$", "_kernel", ")", ...
Process middleware stack @access private @param \Lollipop\HTTP\Request $req Request Object @param \Lollipop\HTTP\Response $res Response Object @return \Lollipop\HTTP\Response Response object
[ "Process", "middleware", "stack" ]
train
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Router.php#L399-L425
jabernardo/lollipop-php
Library/HTTP/Router.php
Router._stackMiddleware
static private function _stackMiddleware(Callable $callback) { if (self::$_busy) { // Make sure it's not busy before adding something. throw new \Lollipop\Exception\HTTP\Router('Cannot add new middleware while dequeue in progress'); } if (is_null(self::$_kernel)) { $active = self::$_active_route; $top = function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) use ($active) { return Route::resolve($active['callback'], $req, $res, $active['arguments']); }; self::$_kernel = $top; } $next = self::$_kernel; // The update the top function self::$_kernel = function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) use ($callback, $next) { // Pass the last function $new_response = call_user_func($callback, $req, $res, $next); if ($new_response instanceof \Lollipop\HTTP\Response) { $res = $new_response; } else { $res->set($new_response); } // Return the new result return $res; }; }
php
static private function _stackMiddleware(Callable $callback) { if (self::$_busy) { // Make sure it's not busy before adding something. throw new \Lollipop\Exception\HTTP\Router('Cannot add new middleware while dequeue in progress'); } if (is_null(self::$_kernel)) { $active = self::$_active_route; $top = function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) use ($active) { return Route::resolve($active['callback'], $req, $res, $active['arguments']); }; self::$_kernel = $top; } $next = self::$_kernel; // The update the top function self::$_kernel = function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res) use ($callback, $next) { // Pass the last function $new_response = call_user_func($callback, $req, $res, $next); if ($new_response instanceof \Lollipop\HTTP\Response) { $res = $new_response; } else { $res->set($new_response); } // Return the new result return $res; }; }
[ "static", "private", "function", "_stackMiddleware", "(", "Callable", "$", "callback", ")", "{", "if", "(", "self", "::", "$", "_busy", ")", "{", "// Make sure it's not busy before adding something.", "throw", "new", "\\", "Lollipop", "\\", "Exception", "\\", "HTT...
Stack middleware @access private @param Callable $callback Middleware callable @throws \Lollipop\Exception\HTTP\Router @return void
[ "Stack", "middleware" ]
train
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Router.php#L436-L466
jabernardo/lollipop-php
Library/HTTP/Router.php
Router._getDefaultPageNotFound
static private function _getDefaultPageNotFound() { return [ 'path' => '404', 'callback' => function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res, $args = []) { // Create a default 404 page $pagenotfound = '<!DOCTYPE html>' . '<!-- Lollipop for PHP by John Aldrich Bernardo -->' . '<html>' . '<head><title>404 Not Found</title></head>' . '<meta name="viewport" content="width=device-width, initial-scale=1">' . '<body>' . '<h1>404 Not Found</h1>' . '<p>The page that you have requested could not be found.</p>' . '</body>' . '</html>'; // Create a new 404 Page Not Found Response $response = new Response($pagenotfound); // Set header for 404 $response->header('HTTP/1.0 404 Not Found'); // Execute return $response; }, 'arguments' => [] ]; }
php
static private function _getDefaultPageNotFound() { return [ 'path' => '404', 'callback' => function(\Lollipop\HTTP\Request $req, \Lollipop\HTTP\Response $res, $args = []) { // Create a default 404 page $pagenotfound = '<!DOCTYPE html>' . '<!-- Lollipop for PHP by John Aldrich Bernardo -->' . '<html>' . '<head><title>404 Not Found</title></head>' . '<meta name="viewport" content="width=device-width, initial-scale=1">' . '<body>' . '<h1>404 Not Found</h1>' . '<p>The page that you have requested could not be found.</p>' . '</body>' . '</html>'; // Create a new 404 Page Not Found Response $response = new Response($pagenotfound); // Set header for 404 $response->header('HTTP/1.0 404 Not Found'); // Execute return $response; }, 'arguments' => [] ]; }
[ "static", "private", "function", "_getDefaultPageNotFound", "(", ")", "{", "return", "[", "'path'", "=>", "'404'", ",", "'callback'", "=>", "function", "(", "\\", "Lollipop", "\\", "HTTP", "\\", "Request", "$", "req", ",", "\\", "Lollipop", "\\", "HTTP", "...
Check if any of routes doesn't match @access private @return \Lollipop\HTTP\Response
[ "Check", "if", "any", "of", "routes", "doesn", "t", "match" ]
train
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/HTTP/Router.php#L475-L501
ARCANESOFT/SEO
src/Providers/RouteServiceProvider.php
RouteServiceProvider.registerRouteBindings
protected function registerRouteBindings() { Routes\Admin\PagesRoutes::bindings(); Routes\Admin\FootersRoutes::bindings(); Routes\Admin\MetasRoutes::bindings(); Routes\Admin\RedirectsRoutes::bindings(); }
php
protected function registerRouteBindings() { Routes\Admin\PagesRoutes::bindings(); Routes\Admin\FootersRoutes::bindings(); Routes\Admin\MetasRoutes::bindings(); Routes\Admin\RedirectsRoutes::bindings(); }
[ "protected", "function", "registerRouteBindings", "(", ")", "{", "Routes", "\\", "Admin", "\\", "PagesRoutes", "::", "bindings", "(", ")", ";", "Routes", "\\", "Admin", "\\", "FootersRoutes", "::", "bindings", "(", ")", ";", "Routes", "\\", "Admin", "\\", ...
Register the route bindings.
[ "Register", "the", "route", "bindings", "." ]
train
https://github.com/ARCANESOFT/SEO/blob/ce6d6135d55e8b2fd43cf7923839b4791b7c7ad2/src/Providers/RouteServiceProvider.php#L51-L57
ARCANESOFT/SEO
src/Providers/RouteServiceProvider.php
RouteServiceProvider.mapAdminRoutes
protected function mapAdminRoutes() { $this->name('seo.') ->prefix($this->config()->get('arcanesoft.seo.route.prefix', 'seo')) ->group(function () { Routes\Admin\DashboardRoutes::register(); Routes\Admin\PagesRoutes::register(); Routes\Admin\FootersRoutes::register(); Routes\Admin\MetasRoutes::register(); Routes\Admin\RedirectsRoutes::register(); Routes\Admin\SpammersRoutes::register(); Routes\Admin\SettingsRoutes::register(); }); }
php
protected function mapAdminRoutes() { $this->name('seo.') ->prefix($this->config()->get('arcanesoft.seo.route.prefix', 'seo')) ->group(function () { Routes\Admin\DashboardRoutes::register(); Routes\Admin\PagesRoutes::register(); Routes\Admin\FootersRoutes::register(); Routes\Admin\MetasRoutes::register(); Routes\Admin\RedirectsRoutes::register(); Routes\Admin\SpammersRoutes::register(); Routes\Admin\SettingsRoutes::register(); }); }
[ "protected", "function", "mapAdminRoutes", "(", ")", "{", "$", "this", "->", "name", "(", "'seo.'", ")", "->", "prefix", "(", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'arcanesoft.seo.route.prefix'", ",", "'seo'", ")", ")", "->", "group",...
Map the admin routes.
[ "Map", "the", "admin", "routes", "." ]
train
https://github.com/ARCANESOFT/SEO/blob/ce6d6135d55e8b2fd43cf7923839b4791b7c7ad2/src/Providers/RouteServiceProvider.php#L62-L75
MindyPHP/SitemapBundle
Command/BuildCommand.php
BuildCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $sitemaps = $this->builder->build(); foreach ($sitemaps as $sitemap) { $output->writeln($sitemap); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $sitemaps = $this->builder->build(); foreach ($sitemaps as $sitemap) { $output->writeln($sitemap); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "sitemaps", "=", "$", "this", "->", "builder", "->", "build", "(", ")", ";", "foreach", "(", "$", "sitemaps", "as", "$", "sitem...
@param InputInterface $input @param OutputInterface $output @throws \Exception @return int|null|void
[ "@param", "InputInterface", "$input", "@param", "OutputInterface", "$output" ]
train
https://github.com/MindyPHP/SitemapBundle/blob/fccd6154697da0703c8703c378b9e959ef9ac3b2/Command/BuildCommand.php#L54-L60
cinnamonlab/framework
src/Framework/Input.php
Input.get
public static function get($key, $default = "", $validator = null) { $me = self::getInstance(); if (isset($me->parameters[$key]) ) { $value = $me->parameters[$key]; } else if ( isset($_REQUEST[$key]) ) { $value = $_REQUEST[$key]; } else { $value = $me->processDefaultValue($default); } if ($validator instanceof Validator) { if ( $validator->execute($value) ) { return $value; } else { return $me->processDefaultValue($default); } } else if (is_callable($validator)) { try { if ($validator($value) ) { return $value; } else { return $me->processDefaultValue($default); } } catch (Exception $e) { throw FrameworkException::internalError("Validator error"); } } return $value; }
php
public static function get($key, $default = "", $validator = null) { $me = self::getInstance(); if (isset($me->parameters[$key]) ) { $value = $me->parameters[$key]; } else if ( isset($_REQUEST[$key]) ) { $value = $_REQUEST[$key]; } else { $value = $me->processDefaultValue($default); } if ($validator instanceof Validator) { if ( $validator->execute($value) ) { return $value; } else { return $me->processDefaultValue($default); } } else if (is_callable($validator)) { try { if ($validator($value) ) { return $value; } else { return $me->processDefaultValue($default); } } catch (Exception $e) { throw FrameworkException::internalError("Validator error"); } } return $value; }
[ "public", "static", "function", "get", "(", "$", "key", ",", "$", "default", "=", "\"\"", ",", "$", "validator", "=", "null", ")", "{", "$", "me", "=", "self", "::", "getInstance", "(", ")", ";", "if", "(", "isset", "(", "$", "me", "->", "paramet...
Get Value @param $key @param string $default @param null $validator @return mixed @throws Exception\FrameworkException
[ "Get", "Value" ]
train
https://github.com/cinnamonlab/framework/blob/958ba3e60d3f927adc40a543ec6d4f08d38cfd2c/src/Framework/Input.php#L21-L52
cinnamonlab/framework
src/Framework/Input.php
Input.file
static function file( $key, $default = null, $validator = null) { if ( ! isset($_FILES[$key]) || $_FILES[$key]['error'] != UPLOAD_ERR_OK) return self::processError($default); $file = new InputFile($_FILES[$key]['tmp_name']); $file->setContentType($_FILES[$key]['type']); $file->setOriginalName($_FILES[$key]['name']); if ($validator instanceof Validator) { if ( $validator->execute( $file ) ) { return $file; } else { return self::processError($default); } } else if (is_callable($validator)) { try { if ($validator($file) ) { return $file; } else { return self::processError($default); } } catch (Exception $e) { throw FrameworkException::internalError("Validator error"); } } return $file; }
php
static function file( $key, $default = null, $validator = null) { if ( ! isset($_FILES[$key]) || $_FILES[$key]['error'] != UPLOAD_ERR_OK) return self::processError($default); $file = new InputFile($_FILES[$key]['tmp_name']); $file->setContentType($_FILES[$key]['type']); $file->setOriginalName($_FILES[$key]['name']); if ($validator instanceof Validator) { if ( $validator->execute( $file ) ) { return $file; } else { return self::processError($default); } } else if (is_callable($validator)) { try { if ($validator($file) ) { return $file; } else { return self::processError($default); } } catch (Exception $e) { throw FrameworkException::internalError("Validator error"); } } return $file; }
[ "static", "function", "file", "(", "$", "key", ",", "$", "default", "=", "null", ",", "$", "validator", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "_FILES", "[", "$", "key", "]", ")", "||", "$", "_FILES", "[", "$", "key", "]", ...
Get Uploaded File @param $key @param null $default @param null $validator @return InputFile
[ "Get", "Uploaded", "File" ]
train
https://github.com/cinnamonlab/framework/blob/958ba3e60d3f927adc40a543ec6d4f08d38cfd2c/src/Framework/Input.php#L76-L105
cinnamonlab/framework
src/Framework/Input.php
Input.set
static function set( $key, $value ) { $me = self::getInstance(); $me->parameters[$key] = $value; }
php
static function set( $key, $value ) { $me = self::getInstance(); $me->parameters[$key] = $value; }
[ "static", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "$", "me", "=", "self", "::", "getInstance", "(", ")", ";", "$", "me", "->", "parameters", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Set Value Manually @param $key @param $value
[ "Set", "Value", "Manually" ]
train
https://github.com/cinnamonlab/framework/blob/958ba3e60d3f927adc40a543ec6d4f08d38cfd2c/src/Framework/Input.php#L112-L115
SahilDude89ss/PyntaxFramework
src/Pyntax/DAO/Bean/Bean.php
Bean.find
public function find($searchCriteria = false, $returnArray = false) { $result = array(); if (is_int($searchCriteria)) { $primaryKeyValueForSearch = intval($searchCriteria); $result = $this->_db_adapter->getOneResult($this->_table_name, array($this->_primary_key => $primaryKeyValueForSearch)); } else if (is_array($searchCriteria) && !empty($searchCriteria)) { $limit = isset($searchCriteria['limit']) ? $searchCriteria['limit'] : 0; unset($searchCriteria['limit']); $result = $this->_db_adapter->Select($this->_table_name, $searchCriteria, $limit); } else if(empty($searchCriteria) || !$searchCriteria) { $result = $this->_db_adapter->Select($this->_table_name); } if($returnArray) { return $result; } return $this->convertSearchResultIntoBean($result); }
php
public function find($searchCriteria = false, $returnArray = false) { $result = array(); if (is_int($searchCriteria)) { $primaryKeyValueForSearch = intval($searchCriteria); $result = $this->_db_adapter->getOneResult($this->_table_name, array($this->_primary_key => $primaryKeyValueForSearch)); } else if (is_array($searchCriteria) && !empty($searchCriteria)) { $limit = isset($searchCriteria['limit']) ? $searchCriteria['limit'] : 0; unset($searchCriteria['limit']); $result = $this->_db_adapter->Select($this->_table_name, $searchCriteria, $limit); } else if(empty($searchCriteria) || !$searchCriteria) { $result = $this->_db_adapter->Select($this->_table_name); } if($returnArray) { return $result; } return $this->convertSearchResultIntoBean($result); }
[ "public", "function", "find", "(", "$", "searchCriteria", "=", "false", ",", "$", "returnArray", "=", "false", ")", "{", "$", "result", "=", "array", "(", ")", ";", "if", "(", "is_int", "(", "$", "searchCriteria", ")", ")", "{", "$", "primaryKeyValueFo...
@ToDo: Load any related fields as beans. This function is used to find data from the database. @param bool|false $searchCriteria @param bool|true $returnArray @return Bean
[ "@ToDo", ":", "Load", "any", "related", "fields", "as", "beans", ".", "This", "function", "is", "used", "to", "find", "data", "from", "the", "database", "." ]
train
https://github.com/SahilDude89ss/PyntaxFramework/blob/045cca87d24eb2b6405734966c64344e00224c7b/src/Pyntax/DAO/Bean/Bean.php#L84-L104
kambalabs/KmbServers
src/KmbServers/Service/NodeCollectorFactory.php
NodeCollectorFactory.createService
public function createService(ServiceLocatorInterface $serviceLocator) { $service = new NodeCollector(); /** @var Service\Node $nodeService */ $nodeService = $serviceLocator->get('KmbPuppetDb\Service\Node'); $service->setNodeService($nodeService); /** @var QueryBuilderInterface $nodesEnvironmentsQueryBuilder */ $nodesEnvironmentsQueryBuilder = $serviceLocator->get('KmbPuppetDb\Query\NodesEnvironmentsQueryBuilder'); $service->setNodesEnvironmentsQueryBuilder($nodesEnvironmentsQueryBuilder); /** @var EnvironmentInterface $permissionEnvironmentService */ $permissionEnvironmentService = $serviceLocator->get('KmbPermission\Service\Environment'); $service->setPermissionEnvironmentService($permissionEnvironmentService); return $service; }
php
public function createService(ServiceLocatorInterface $serviceLocator) { $service = new NodeCollector(); /** @var Service\Node $nodeService */ $nodeService = $serviceLocator->get('KmbPuppetDb\Service\Node'); $service->setNodeService($nodeService); /** @var QueryBuilderInterface $nodesEnvironmentsQueryBuilder */ $nodesEnvironmentsQueryBuilder = $serviceLocator->get('KmbPuppetDb\Query\NodesEnvironmentsQueryBuilder'); $service->setNodesEnvironmentsQueryBuilder($nodesEnvironmentsQueryBuilder); /** @var EnvironmentInterface $permissionEnvironmentService */ $permissionEnvironmentService = $serviceLocator->get('KmbPermission\Service\Environment'); $service->setPermissionEnvironmentService($permissionEnvironmentService); return $service; }
[ "public", "function", "createService", "(", "ServiceLocatorInterface", "$", "serviceLocator", ")", "{", "$", "service", "=", "new", "NodeCollector", "(", ")", ";", "/** @var Service\\Node $nodeService */", "$", "nodeService", "=", "$", "serviceLocator", "->", "get", ...
Create service @param ServiceLocatorInterface $serviceLocator @return mixed
[ "Create", "service" ]
train
https://github.com/kambalabs/KmbServers/blob/0d70fd83366af312374be5c28cf73b287418b9e5/src/KmbServers/Service/NodeCollectorFactory.php#L37-L54
ekyna/PaymentBundle
Form/Type/MethodType.php
MethodType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('gatewayName', 'text', array( 'label' => 'ekyna_core.field.name', )) ->add('factoryName', 'payum_gateway_factories_choice', array( 'label' => 'ekyna_payment.method.field.factory_name', 'disabled' => true, )) ->add('media', 'ekyna_media_choice', array( 'label' => 'ekyna_core.field.image', 'types' => MediaTypes::IMAGE, )) ->add('description', 'tinymce', array( 'label' => 'ekyna_core.field.description', )) ->add('messages', 'ekyna_payment_messages') ->add('enabled', 'checkbox', array( 'label' => 'ekyna_core.field.enabled', 'required' => false, 'attr' => array( 'align_with_widget' => true, ), )) ->add('available', 'checkbox', array( 'label' => 'ekyna_payment.method.field.available', 'required' => false, 'attr' => array( 'align_with_widget' => true, ), )) ; $builder->addEventSubscriber(new BuildConfigSubscriber($this->registry)); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('gatewayName', 'text', array( 'label' => 'ekyna_core.field.name', )) ->add('factoryName', 'payum_gateway_factories_choice', array( 'label' => 'ekyna_payment.method.field.factory_name', 'disabled' => true, )) ->add('media', 'ekyna_media_choice', array( 'label' => 'ekyna_core.field.image', 'types' => MediaTypes::IMAGE, )) ->add('description', 'tinymce', array( 'label' => 'ekyna_core.field.description', )) ->add('messages', 'ekyna_payment_messages') ->add('enabled', 'checkbox', array( 'label' => 'ekyna_core.field.enabled', 'required' => false, 'attr' => array( 'align_with_widget' => true, ), )) ->add('available', 'checkbox', array( 'label' => 'ekyna_payment.method.field.available', 'required' => false, 'attr' => array( 'align_with_widget' => true, ), )) ; $builder->addEventSubscriber(new BuildConfigSubscriber($this->registry)); }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", "{", "$", "builder", "->", "add", "(", "'gatewayName'", ",", "'text'", ",", "array", "(", "'label'", "=>", "'ekyna_core.field.name'", ",", ")", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Form/Type/MethodType.php#L39-L74
koolkode/view-express
src/Tree/HelperNode.php
HelperNode.compile
public function compile(ExpressCompiler $compiler, $flags = 0) { try { $helper = $this->getHelper($compiler); $field = $compiler->nextField('h'); $compiler->write("\t\t" . 'if(' . $field . ' === NULL) {' . "\n"); $compiler->write("\t\ttry {\n"); $compiler->write("\t\t" . $field . ' = $this->renderer->getHelper('); $compiler->write(var_export($this->namespace, true) . ', ' . var_export($this->name, true)); $compiler->write(");\n"); $compiler->write("\t\t" . $field . "->bindContext(\$this->context);\n"); $bound = []; // Setup helper arguments: foreach($this->attributes as $attr) { $name = preg_replace_callback("'-([a-z0-9])'", function(array $m) { return strtoupper($m[1]); }, $attr->getName()); if(false !== strpos($name, ':')) { continue; } $dynamic = $attr->isExpressionCallback() || $attr->isDynamic(); $pass = $helper->isPassthroughAttribute($name); $bound[$name] = true; if($pass) { // Dealing with passthrough attributes. if($dynamic) { // Dynamic value passthrough attribute, use ArrayAccess to set compiled closure. $compiler->write("\t\t" . $field . "[" . var_export($attr->getName(), true)); $compiler->write("] = function() {\n\t\t\ttry {\n\t\t\treturn "); $exp = ''; foreach($attr as $i => $sub) { if($i != 0) { $compiler->write(' . '); } $compiler->write($sub->compile($compiler, self::FLAG_RAW)); if($sub instanceof ExpressionNode) { $exp .= $sub->getExpression(); } elseif($sub instanceof TextNode) { $exp .= $sub->getText(); } } $compiler->write(";\n\t\t\t} catch(\ExpressViewException \$ex) {\n"); $compiler->write("\t\t\t\tthrow \$ex;\n"); $compiler->write("\t\t\t} catch(\Exception \$ex) {\n"); $compiler->write("\t\t\t\tthrow new ExpressViewException("); $compiler->write(var_export(sprintf('Unable to evaluate attribute "%s" in view helper "%s" using expression "%s"', $name, $this->namespace . ':' . $this->name, $exp), true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t\t}\n\t\t};\n"); } else { // Static passthrough attribute. $sub = $compiler->createCompiler(); $attr->compile($sub); $compiler->write("\t\t" . $field . "[" . var_export($attr->getName(), true)); $compiler->write("] = " . var_export($sub->getOutputBuffer(), true) . ";\n"); } } else { if($dynamic) { // Dynamic and expression attributes are assembled into a string and returned: $compiler->write("\t\t" . $field . '->setAttr(' . var_export($name, true)); $compiler->write(", function(\$inspect = false) {\n\t\t\ttry {\n\t\t\treturn "); $childNodes = iterator_to_array($attr->getIterator()); $inspectable = false; $exp = ''; if(count($childNodes) == 1) { if($childNodes[0] instanceof ExpressionNode) { $chain = $childNodes[0]->getExpression()->getNode(); if($chain instanceof AccessorChain) { $inspectable = true; } } } if($inspectable) { $compiler->write('$inspect ? '); $compiler->write($chain->compile($compiler->getExpressionContextFactory(), '$this->exp', 'inspectValue')); $compiler->write(' : '); $compiler->write($chain->compile($compiler->getExpressionContextFactory(), '$this->exp')); $exp .= $childNodes[0]->getExpression(); } else { foreach($childNodes as $i => $sub) { if($i != 0) { $compiler->write(' . '); } $compiler->write($sub->compile($compiler, self::FLAG_RAW)); if($sub instanceof ExpressionNode) { $exp .= $sub->getExpression(); } elseif($sub instanceof TextNode) { $exp .= $sub->getText(); } } } $compiler->write(";\n\t\t\t} catch(\ExpressViewException \$ex) {\n"); $compiler->write("\t\t\t\tthrow \$ex;\n"); $compiler->write("\t\t\t} catch(\Exception \$ex) {\n"); $compiler->write("\t\t\t\tthrow new ExpressViewException("); $compiler->write(var_export(sprintf('Unable to evaluate attribute "%s" in view helper "%s" using expression "%s"', $name, $this->namespace . ':' . $this->name, $exp), true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t\t}\n\t\t});\n"); } else { // Static attributes are set as property values: $sub = $compiler->createCompiler(); $attr->compile($sub); $compiler->write("\t\t" . $field . '->' . $name . ' = '); $compiler->write(var_export($sub->getOutputBuffer(), true) . ";\n"); } } } $compiler->write("\t\t" . $field . "->bindAttr(["); foreach(array_keys($bound) as $i => $key) { if($i != 0) { $compiler->write(', '); } $compiler->write(var_export($key, true) . ' => true'); } $compiler->write("]);\n"); if(!empty($this->childNodes)) { if($helper instanceof CompositeViewHelperInterface) { $helpers = []; foreach($this->childNodes as $node) { if(!$node instanceof HelperNode) { continue; } $helpers[] = $node->compile($compiler, self::FLAG_NO_OUTPUT); } $compiler->write("\t\t" . $field . '->setNestedNodes([' . "\n"); $compiler->write("\t\t" . implode(', ', $helpers) . "\n"); $compiler->write("\t\t]);\n"); } else { $compiler->write("\t\t" . $field . '->setNestedNodes([function(OutputBuffer $out) {' . "\n"); foreach($this->childNodes as $node) { $node->compile($compiler); } $compiler->write("\n\t\t}]);\n"); } } $compiler->write("\t\t} catch(ExpressViewException \$ex) {\n"); $compiler->write("\t\t\tthrow \$ex;\n"); $compiler->write("\t\t} catch(\\Exception \$ex) {\n"); $compiler->write("\t\t\tthrow new ExpressViewException("); $compiler->write(var_export('Unable to instantiate view helper "' . $this->namespace . ':' . $this->name . '"', true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t}\n"); $compiler->write("\t\t}\n"); if(!($flags & self::FLAG_NO_OUTPUT)) { $compiler->write("\t\ttry {\n"); $compiler->write("\t\t" . $field . '->__invoke($out);' . "\n"); $compiler->write("\t\t} catch(ExpressViewException \$ex) {\n"); $compiler->write("\t\t\tthrow \$ex;\n"); $compiler->write("\t\t} catch(\\Exception \$ex) {\n"); $compiler->write("\t\t\tthrow new ExpressViewException("); $compiler->write(var_export('Unable to invoke view helper "' . $this->namespace . ':' . $this->name . '"', true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t}\n"); } return $field; } catch(ExpressViewException $e) { throw $e; } catch(\Exception $e) { throw new ExpressViewException(sprintf('Unable to compile view helper "%s" in namespace "%s"', $this->name, $this->namespace), $compiler->getResource(), $this->line, $e); } }
php
public function compile(ExpressCompiler $compiler, $flags = 0) { try { $helper = $this->getHelper($compiler); $field = $compiler->nextField('h'); $compiler->write("\t\t" . 'if(' . $field . ' === NULL) {' . "\n"); $compiler->write("\t\ttry {\n"); $compiler->write("\t\t" . $field . ' = $this->renderer->getHelper('); $compiler->write(var_export($this->namespace, true) . ', ' . var_export($this->name, true)); $compiler->write(");\n"); $compiler->write("\t\t" . $field . "->bindContext(\$this->context);\n"); $bound = []; // Setup helper arguments: foreach($this->attributes as $attr) { $name = preg_replace_callback("'-([a-z0-9])'", function(array $m) { return strtoupper($m[1]); }, $attr->getName()); if(false !== strpos($name, ':')) { continue; } $dynamic = $attr->isExpressionCallback() || $attr->isDynamic(); $pass = $helper->isPassthroughAttribute($name); $bound[$name] = true; if($pass) { // Dealing with passthrough attributes. if($dynamic) { // Dynamic value passthrough attribute, use ArrayAccess to set compiled closure. $compiler->write("\t\t" . $field . "[" . var_export($attr->getName(), true)); $compiler->write("] = function() {\n\t\t\ttry {\n\t\t\treturn "); $exp = ''; foreach($attr as $i => $sub) { if($i != 0) { $compiler->write(' . '); } $compiler->write($sub->compile($compiler, self::FLAG_RAW)); if($sub instanceof ExpressionNode) { $exp .= $sub->getExpression(); } elseif($sub instanceof TextNode) { $exp .= $sub->getText(); } } $compiler->write(";\n\t\t\t} catch(\ExpressViewException \$ex) {\n"); $compiler->write("\t\t\t\tthrow \$ex;\n"); $compiler->write("\t\t\t} catch(\Exception \$ex) {\n"); $compiler->write("\t\t\t\tthrow new ExpressViewException("); $compiler->write(var_export(sprintf('Unable to evaluate attribute "%s" in view helper "%s" using expression "%s"', $name, $this->namespace . ':' . $this->name, $exp), true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t\t}\n\t\t};\n"); } else { // Static passthrough attribute. $sub = $compiler->createCompiler(); $attr->compile($sub); $compiler->write("\t\t" . $field . "[" . var_export($attr->getName(), true)); $compiler->write("] = " . var_export($sub->getOutputBuffer(), true) . ";\n"); } } else { if($dynamic) { // Dynamic and expression attributes are assembled into a string and returned: $compiler->write("\t\t" . $field . '->setAttr(' . var_export($name, true)); $compiler->write(", function(\$inspect = false) {\n\t\t\ttry {\n\t\t\treturn "); $childNodes = iterator_to_array($attr->getIterator()); $inspectable = false; $exp = ''; if(count($childNodes) == 1) { if($childNodes[0] instanceof ExpressionNode) { $chain = $childNodes[0]->getExpression()->getNode(); if($chain instanceof AccessorChain) { $inspectable = true; } } } if($inspectable) { $compiler->write('$inspect ? '); $compiler->write($chain->compile($compiler->getExpressionContextFactory(), '$this->exp', 'inspectValue')); $compiler->write(' : '); $compiler->write($chain->compile($compiler->getExpressionContextFactory(), '$this->exp')); $exp .= $childNodes[0]->getExpression(); } else { foreach($childNodes as $i => $sub) { if($i != 0) { $compiler->write(' . '); } $compiler->write($sub->compile($compiler, self::FLAG_RAW)); if($sub instanceof ExpressionNode) { $exp .= $sub->getExpression(); } elseif($sub instanceof TextNode) { $exp .= $sub->getText(); } } } $compiler->write(";\n\t\t\t} catch(\ExpressViewException \$ex) {\n"); $compiler->write("\t\t\t\tthrow \$ex;\n"); $compiler->write("\t\t\t} catch(\Exception \$ex) {\n"); $compiler->write("\t\t\t\tthrow new ExpressViewException("); $compiler->write(var_export(sprintf('Unable to evaluate attribute "%s" in view helper "%s" using expression "%s"', $name, $this->namespace . ':' . $this->name, $exp), true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t\t}\n\t\t});\n"); } else { // Static attributes are set as property values: $sub = $compiler->createCompiler(); $attr->compile($sub); $compiler->write("\t\t" . $field . '->' . $name . ' = '); $compiler->write(var_export($sub->getOutputBuffer(), true) . ";\n"); } } } $compiler->write("\t\t" . $field . "->bindAttr(["); foreach(array_keys($bound) as $i => $key) { if($i != 0) { $compiler->write(', '); } $compiler->write(var_export($key, true) . ' => true'); } $compiler->write("]);\n"); if(!empty($this->childNodes)) { if($helper instanceof CompositeViewHelperInterface) { $helpers = []; foreach($this->childNodes as $node) { if(!$node instanceof HelperNode) { continue; } $helpers[] = $node->compile($compiler, self::FLAG_NO_OUTPUT); } $compiler->write("\t\t" . $field . '->setNestedNodes([' . "\n"); $compiler->write("\t\t" . implode(', ', $helpers) . "\n"); $compiler->write("\t\t]);\n"); } else { $compiler->write("\t\t" . $field . '->setNestedNodes([function(OutputBuffer $out) {' . "\n"); foreach($this->childNodes as $node) { $node->compile($compiler); } $compiler->write("\n\t\t}]);\n"); } } $compiler->write("\t\t} catch(ExpressViewException \$ex) {\n"); $compiler->write("\t\t\tthrow \$ex;\n"); $compiler->write("\t\t} catch(\\Exception \$ex) {\n"); $compiler->write("\t\t\tthrow new ExpressViewException("); $compiler->write(var_export('Unable to instantiate view helper "' . $this->namespace . ':' . $this->name . '"', true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t}\n"); $compiler->write("\t\t}\n"); if(!($flags & self::FLAG_NO_OUTPUT)) { $compiler->write("\t\ttry {\n"); $compiler->write("\t\t" . $field . '->__invoke($out);' . "\n"); $compiler->write("\t\t} catch(ExpressViewException \$ex) {\n"); $compiler->write("\t\t\tthrow \$ex;\n"); $compiler->write("\t\t} catch(\\Exception \$ex) {\n"); $compiler->write("\t\t\tthrow new ExpressViewException("); $compiler->write(var_export('Unable to invoke view helper "' . $this->namespace . ':' . $this->name . '"', true)); $compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n"); $compiler->write("\t\t}\n"); } return $field; } catch(ExpressViewException $e) { throw $e; } catch(\Exception $e) { throw new ExpressViewException(sprintf('Unable to compile view helper "%s" in namespace "%s"', $this->name, $this->namespace), $compiler->getResource(), $this->line, $e); } }
[ "public", "function", "compile", "(", "ExpressCompiler", "$", "compiler", ",", "$", "flags", "=", "0", ")", "{", "try", "{", "$", "helper", "=", "$", "this", "->", "getHelper", "(", "$", "compiler", ")", ";", "$", "field", "=", "$", "compiler", "->",...
Compile an express helper into PHP code. @param ExpressCompiler $compiler @param integer $flags Direct ouput of helper? Not needed for child nodes of composite helpers. @return string Returns the variable field accessor of this helper ($this->helper).
[ "Compile", "an", "express", "helper", "into", "PHP", "code", "." ]
train
https://github.com/koolkode/view-express/blob/a8ebe6f373b6bfe8b8818d6264535e8fe063a596/src/Tree/HelperNode.php#L108-L352
MichaelJ2324/PHP-REST-Client
src/Auth/Abstracts/AbstractAuthController.php
AbstractAuthController.configureEndpoint
protected function configureEndpoint(EndpointInterface $Endpoint, $action) { switch ($action) { case self::ACTION_AUTH: $Endpoint = $this->configureAuthenticationEndpoint($Endpoint); break; case self::ACTION_LOGOUT: $Endpoint = $this->configureLogoutEndpoint($Endpoint); break; } return $Endpoint; }
php
protected function configureEndpoint(EndpointInterface $Endpoint, $action) { switch ($action) { case self::ACTION_AUTH: $Endpoint = $this->configureAuthenticationEndpoint($Endpoint); break; case self::ACTION_LOGOUT: $Endpoint = $this->configureLogoutEndpoint($Endpoint); break; } return $Endpoint; }
[ "protected", "function", "configureEndpoint", "(", "EndpointInterface", "$", "Endpoint", ",", "$", "action", ")", "{", "switch", "(", "$", "action", ")", "{", "case", "self", "::", "ACTION_AUTH", ":", "$", "Endpoint", "=", "$", "this", "->", "configureAuthen...
Configure an actions Endpoint Object @param EndpointInterface $Endpoint @param string $action @return EndpointInterface
[ "Configure", "an", "actions", "Endpoint", "Object" ]
train
https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Auth/Abstracts/AbstractAuthController.php#L249-L260
eliasis-framework/complement
src/Complement.php
Complement.__callstatic
public static function __callstatic($index, $params = false) { $type = self::getType(); $appID = App::getCurrentID(); if (! array_key_exists($index, self::$instances[$appID][$type])) { $msg = self::getType('ucfirst', false) . ' or method not found'; throw new ComplementException($msg . ': ' . $index); } self::$id = $index; $that = self::getInstance(); if (! $params) { return $that; } $method = (isset($params[0])) ? $params[0] : ''; $args = (isset($params[1])) ? $params[1] : 0; if (method_exists($that, $method)) { return call_user_func_array([$that, $method], [$args]); } }
php
public static function __callstatic($index, $params = false) { $type = self::getType(); $appID = App::getCurrentID(); if (! array_key_exists($index, self::$instances[$appID][$type])) { $msg = self::getType('ucfirst', false) . ' or method not found'; throw new ComplementException($msg . ': ' . $index); } self::$id = $index; $that = self::getInstance(); if (! $params) { return $that; } $method = (isset($params[0])) ? $params[0] : ''; $args = (isset($params[1])) ? $params[1] : 0; if (method_exists($that, $method)) { return call_user_func_array([$that, $method], [$args]); } }
[ "public", "static", "function", "__callstatic", "(", "$", "index", ",", "$", "params", "=", "false", ")", "{", "$", "type", "=", "self", "::", "getType", "(", ")", ";", "$", "appID", "=", "App", "::", "getCurrentID", "(", ")", ";", "if", "(", "!", ...
Receives the name of the complement to execute: Complement::Name(). @param string $index → complement name @param array $params → params @uses \Eliasis\Framework\App::getCurrentID() @uses \Eliasis\Complement\ComplementHandler::getType() @throws ComplementException → complement not found @return object
[ "Receives", "the", "name", "of", "the", "complement", "to", "execute", ":", "Complement", "::", "Name", "()", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L79-L103
eliasis-framework/complement
src/Complement.php
Complement.run
public static function run() { if (! session_id()) { session_start(); } $complementType = self::getType('strtoupper'); $path = App::$complementType(); if ($paths = File::getFilesFromDir($path)) { foreach ($paths as $path) { if (! $path->isDot() && $path->isDir()) { $_path = Url::addBackSlash($path->getPath()); $slug = $path->getBasename(); $file = $_path . $slug . '/' . $slug . '.json'; if (! File::exists($file)) { continue; } self::load($file); } } } self::requestHandler(self::getType('strtolower', false)); }
php
public static function run() { if (! session_id()) { session_start(); } $complementType = self::getType('strtoupper'); $path = App::$complementType(); if ($paths = File::getFilesFromDir($path)) { foreach ($paths as $path) { if (! $path->isDot() && $path->isDir()) { $_path = Url::addBackSlash($path->getPath()); $slug = $path->getBasename(); $file = $_path . $slug . '/' . $slug . '.json'; if (! File::exists($file)) { continue; } self::load($file); } } } self::requestHandler(self::getType('strtolower', false)); }
[ "public", "static", "function", "run", "(", ")", "{", "if", "(", "!", "session_id", "(", ")", ")", "{", "session_start", "(", ")", ";", "}", "$", "complementType", "=", "self", "::", "getType", "(", "'strtoupper'", ")", ";", "$", "path", "=", "App", ...
Load all complements found in the directory. @uses \Eliasis\Complement\ComplementRequest::requestHandler() @uses \Eliasis\Complement\ComplementHandler::getType()
[ "Load", "all", "complements", "found", "in", "the", "directory", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L111-L136
eliasis-framework/complement
src/Complement.php
Complement.load
public static function load($file) { $complement = Json::fileToArray($file); $complement['config-file'] = $file; self::$id = isset($complement['id']) ? $complement['id'] : 'Default'; $that = self::getInstance(); return $that->setComplement($complement); }
php
public static function load($file) { $complement = Json::fileToArray($file); $complement['config-file'] = $file; self::$id = isset($complement['id']) ? $complement['id'] : 'Default'; $that = self::getInstance(); return $that->setComplement($complement); }
[ "public", "static", "function", "load", "(", "$", "file", ")", "{", "$", "complement", "=", "Json", "::", "fileToArray", "(", "$", "file", ")", ";", "$", "complement", "[", "'config-file'", "]", "=", "$", "file", ";", "self", "::", "$", "id", "=", ...
Load complement configuration from json file and set settings. @param string $file → path or url to the complement configuration file @uses \Josantonius\Json\Json::fileToArray() @uses \Eliasis\Complement\ComplementHandler->setComplement() @return bool true
[ "Load", "complement", "configuration", "from", "json", "file", "and", "set", "settings", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L148-L156
eliasis-framework/complement
src/Complement.php
Complement.getList
public static function getList($filter = 'all', $sort = 'asort') { $data = []; $type = self::getType(); $complementID = self::getCurrentID(); $appID = App::getCurrentID(); $complements = array_keys(self::$instances[$appID][$type]); foreach ($complements as $id) { self::setCurrentID($id); $that = self::getInstance(); $complement = $that->complement; if (! isset($complement['category'])) { continue; } $skip = ($filter != 'all' && $complement['category'] != $filter); if ($skip || $id == 'Default' || ! $complement) { continue; } if ($that->hasNewVersion() && $complement['state'] === 'active') { $complement['state'] = 'outdated'; $that->setState('outdated'); } $data[$complement['id']] = [ 'id' => $complement['id'], 'name' => $complement['name'], 'version' => $complement['version'], 'description' => $complement['description'], 'state' => $complement['state'], 'category' => $complement['category'], 'path' => $complement['path']['root'], 'url' => $complement['url'], 'author' => $complement['author'], 'author-url' => $complement['author-url'], 'license' => $complement['license'], 'state' => $complement['state'], 'slug' => $complement['slug'], 'image' => $complement['image'], 'hooks-controller' => $complement['hooks-controller'], 'url-import' => $complement['url-import'], 'extra' => $complement['extra'] ]; } self::setCurrentID($complementID); self::getInstance(); $sorting = '|asort|arsort|krsort|ksort|rsort|shuffle|sort|'; strpos($sorting, $sort) ? $sort($data) : asort($data); return $data; }
php
public static function getList($filter = 'all', $sort = 'asort') { $data = []; $type = self::getType(); $complementID = self::getCurrentID(); $appID = App::getCurrentID(); $complements = array_keys(self::$instances[$appID][$type]); foreach ($complements as $id) { self::setCurrentID($id); $that = self::getInstance(); $complement = $that->complement; if (! isset($complement['category'])) { continue; } $skip = ($filter != 'all' && $complement['category'] != $filter); if ($skip || $id == 'Default' || ! $complement) { continue; } if ($that->hasNewVersion() && $complement['state'] === 'active') { $complement['state'] = 'outdated'; $that->setState('outdated'); } $data[$complement['id']] = [ 'id' => $complement['id'], 'name' => $complement['name'], 'version' => $complement['version'], 'description' => $complement['description'], 'state' => $complement['state'], 'category' => $complement['category'], 'path' => $complement['path']['root'], 'url' => $complement['url'], 'author' => $complement['author'], 'author-url' => $complement['author-url'], 'license' => $complement['license'], 'state' => $complement['state'], 'slug' => $complement['slug'], 'image' => $complement['image'], 'hooks-controller' => $complement['hooks-controller'], 'url-import' => $complement['url-import'], 'extra' => $complement['extra'] ]; } self::setCurrentID($complementID); self::getInstance(); $sorting = '|asort|arsort|krsort|ksort|rsort|shuffle|sort|'; strpos($sorting, $sort) ? $sort($data) : asort($data); return $data; }
[ "public", "static", "function", "getList", "(", "$", "filter", "=", "'all'", ",", "$", "sort", "=", "'asort'", ")", "{", "$", "data", "=", "[", "]", ";", "$", "type", "=", "self", "::", "getType", "(", ")", ";", "$", "complementID", "=", "self", ...
Get components/plugins/modules/templates list. @param string $filter → complement category filter @param string $sort → PHP sorting function to complements sort @uses \Eliasis\Complement\ComplementHandler::getType() @uses \Eliasis\Framework\App::getCurrentID() @return array $data → complements list
[ "Get", "components", "/", "plugins", "/", "modules", "/", "templates", "list", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L169-L227
eliasis-framework/complement
src/Complement.php
Complement.setCurrentID
public static function setCurrentID($id) { $type = self::getType(); $appID = App::getCurrentID(); if (array_key_exists($id, self::$instances[$appID][$type])) { self::$id = $id; return true; } return false; }
php
public static function setCurrentID($id) { $type = self::getType(); $appID = App::getCurrentID(); if (array_key_exists($id, self::$instances[$appID][$type])) { self::$id = $id; return true; } return false; }
[ "public", "static", "function", "setCurrentID", "(", "$", "id", ")", "{", "$", "type", "=", "self", "::", "getType", "(", ")", ";", "$", "appID", "=", "App", "::", "getCurrentID", "(", ")", ";", "if", "(", "array_key_exists", "(", "$", "id", ",", "...
Define the current complement ID. @since 1.1.0 @param string $id → complement ID @return bool
[ "Define", "the", "current", "complement", "ID", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L250-L261
eliasis-framework/complement
src/Complement.php
Complement.script
public static function script($pathUrl = null, $vue = true, $vueResource = true) { $that = self::getInstance(); $file = $vue ? 'vue+' : ''; $file .= $vueResource ? 'vue-resource+' : ''; return $that->setFile($file . 'eliasis-complement.min', 'script', $pathUrl); }
php
public static function script($pathUrl = null, $vue = true, $vueResource = true) { $that = self::getInstance(); $file = $vue ? 'vue+' : ''; $file .= $vueResource ? 'vue-resource+' : ''; return $that->setFile($file . 'eliasis-complement.min', 'script', $pathUrl); }
[ "public", "static", "function", "script", "(", "$", "pathUrl", "=", "null", ",", "$", "vue", "=", "true", ",", "$", "vueResource", "=", "true", ")", "{", "$", "that", "=", "self", "::", "getInstance", "(", ")", ";", "$", "file", "=", "$", "vue", ...
Set and get script url. @param string $pathUrl → url where JS files will be created & loaded @param bool $vue → include Vue.js in the script @param bool $vueResource → include vue-resource in the script @uses \Eliasis\Complement\ComplementView::setFile() @return string → script url
[ "Set", "and", "get", "script", "url", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L274-L282
eliasis-framework/complement
src/Complement.php
Complement.exists
public static function exists($complementID) { $type = self::getType(); return array_key_exists( $complementID, self::$instances[App::getCurrentID()][$type] ); }
php
public static function exists($complementID) { $type = self::getType(); return array_key_exists( $complementID, self::$instances[App::getCurrentID()][$type] ); }
[ "public", "static", "function", "exists", "(", "$", "complementID", ")", "{", "$", "type", "=", "self", "::", "getType", "(", ")", ";", "return", "array_key_exists", "(", "$", "complementID", ",", "self", "::", "$", "instances", "[", "App", "::", "getCur...
Check if complement exists. @param string $complementID → complement id @uses \Eliasis\Framework\App::getCurrentID() @uses \Eliasis\Complement\ComplementHandler::getType() @return bool
[ "Check", "if", "complement", "exists", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L310-L318
eliasis-framework/complement
src/Complement.php
Complement.getLibraryVersion
public static function getLibraryVersion() { $path = self::getLibraryPath(); $composer = Json::fileToArray($path . 'composer.json'); return isset($composer['version']) ? $composer['version'] : '1.1.1'; }
php
public static function getLibraryVersion() { $path = self::getLibraryPath(); $composer = Json::fileToArray($path . 'composer.json'); return isset($composer['version']) ? $composer['version'] : '1.1.1'; }
[ "public", "static", "function", "getLibraryVersion", "(", ")", "{", "$", "path", "=", "self", "::", "getLibraryPath", "(", ")", ";", "$", "composer", "=", "Json", "::", "fileToArray", "(", "$", "path", ".", "'composer.json'", ")", ";", "return", "isset", ...
Get library version. @uses \Josantonius\Json\Json::fileToArray() @return string
[ "Get", "library", "version", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L337-L343
eliasis-framework/complement
src/Complement.php
Complement.render
public static function render($filter = 'all', $remote = null, $sort = 'asort', $translations = null) { $that = self::getInstance(); $translations = $translations ?: [ 'active' => 'active', 'activate' => 'activate', 'install' => 'install', 'update' => 'update', 'uninstall' => 'uninstall' ]; return $that->renderizate($filter, $remote, $sort, $translations); }
php
public static function render($filter = 'all', $remote = null, $sort = 'asort', $translations = null) { $that = self::getInstance(); $translations = $translations ?: [ 'active' => 'active', 'activate' => 'activate', 'install' => 'install', 'update' => 'update', 'uninstall' => 'uninstall' ]; return $that->renderizate($filter, $remote, $sort, $translations); }
[ "public", "static", "function", "render", "(", "$", "filter", "=", "'all'", ",", "$", "remote", "=", "null", ",", "$", "sort", "=", "'asort'", ",", "$", "translations", "=", "null", ")", "{", "$", "that", "=", "self", "::", "getInstance", "(", ")", ...
Get complements view. @param string $filter → complements category to display @param array $remote → urls of the remote optional complements @param string $sort → PHP sorting function to complements sort @param array $translations → translations for button texts @uses \Eliasis\Complement\ComplementView::renderizate() @return bool true
[ "Get", "complements", "view", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L357-L370
eliasis-framework/complement
src/Complement.php
Complement.getInstance
protected static function getInstance() { $type = self::getType(); $appID = App::getCurrentID(); $complementID = self::getCurrentID(); $complement = get_called_class(); if (! isset(self::$instances[$appID][$type][$complementID])) { self::$instances[$appID][$type][$complementID] = new $complement(); } return self::$instances[$appID][$type][$complementID]; }
php
protected static function getInstance() { $type = self::getType(); $appID = App::getCurrentID(); $complementID = self::getCurrentID(); $complement = get_called_class(); if (! isset(self::$instances[$appID][$type][$complementID])) { self::$instances[$appID][$type][$complementID] = new $complement(); } return self::$instances[$appID][$type][$complementID]; }
[ "protected", "static", "function", "getInstance", "(", ")", "{", "$", "type", "=", "self", "::", "getType", "(", ")", ";", "$", "appID", "=", "App", "::", "getCurrentID", "(", ")", ";", "$", "complementID", "=", "self", "::", "getCurrentID", "(", ")", ...
Get complement instance. @uses \Eliasis\Framework\App::getCurrentID() @uses \Eliasis\Complement\ComplementHandler::getType() @return object → complement instance
[ "Get", "complement", "instance", "." ]
train
https://github.com/eliasis-framework/complement/blob/d50e92cf01600ff4573bf1761c312069044748c3/src/Complement.php#L380-L391
cubicmushroom/valueobjects
src/Geography/Address.php
Address.fromNative
public static function fromNative() { $args = \func_get_args(); if (\count($args) != 8) { throw new \BadMethodCallException('You must provide exactly 8 arguments: 1) addressee name, 2) street name, 3) street number, 4) district, 5) city, 6) region, 7) postal code, 8) country code.'); } $name = new StringLiteral($args[0]); $street = new Street(new StringLiteral($args[1]), new StringLiteral($args[2])); $district = new StringLiteral($args[3]); $city = new StringLiteral($args[4]); $region = new StringLiteral($args[5]); $postalCode = new StringLiteral($args[6]); $country = Country::fromNative($args[7]); return new self($name, $street, $district, $city, $region, $postalCode, $country); }
php
public static function fromNative() { $args = \func_get_args(); if (\count($args) != 8) { throw new \BadMethodCallException('You must provide exactly 8 arguments: 1) addressee name, 2) street name, 3) street number, 4) district, 5) city, 6) region, 7) postal code, 8) country code.'); } $name = new StringLiteral($args[0]); $street = new Street(new StringLiteral($args[1]), new StringLiteral($args[2])); $district = new StringLiteral($args[3]); $city = new StringLiteral($args[4]); $region = new StringLiteral($args[5]); $postalCode = new StringLiteral($args[6]); $country = Country::fromNative($args[7]); return new self($name, $street, $district, $city, $region, $postalCode, $country); }
[ "public", "static", "function", "fromNative", "(", ")", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "if", "(", "\\", "count", "(", "$", "args", ")", "!=", "8", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "'You must p...
Returns a new Address from native PHP arguments @param string $name @param string $street_name @param string $street_number @param string $district @param string $city @param string $region @param string $postal_code @param string $country_code @return self @throws \BadMethodCallException
[ "Returns", "a", "new", "Address", "from", "native", "PHP", "arguments" ]
train
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/Geography/Address.php#L61-L78
cubicmushroom/valueobjects
src/Geography/Address.php
Address.sameValueAs
public function sameValueAs(ValueObjectInterface $address) { if (false === Util::classEquals($this, $address)) { return false; } return $this->getName()->sameValueAs($address->getName()) && $this->getStreet()->sameValueAs($address->getStreet()) && $this->getDistrict()->sameValueAs($address->getDistrict()) && $this->getCity()->sameValueAs($address->getCity()) && $this->getRegion()->sameValueAs($address->getRegion()) && $this->getPostalCode()->sameValueAs($address->getPostalCode()) && $this->getCountry()->sameValueAs($address->getCountry()) ; }
php
public function sameValueAs(ValueObjectInterface $address) { if (false === Util::classEquals($this, $address)) { return false; } return $this->getName()->sameValueAs($address->getName()) && $this->getStreet()->sameValueAs($address->getStreet()) && $this->getDistrict()->sameValueAs($address->getDistrict()) && $this->getCity()->sameValueAs($address->getCity()) && $this->getRegion()->sameValueAs($address->getRegion()) && $this->getPostalCode()->sameValueAs($address->getPostalCode()) && $this->getCountry()->sameValueAs($address->getCountry()) ; }
[ "public", "function", "sameValueAs", "(", "ValueObjectInterface", "$", "address", ")", "{", "if", "(", "false", "===", "Util", "::", "classEquals", "(", "$", "this", ",", "$", "address", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", ...
Tells whether two Address are equal @param ValueObjectInterface $address @return bool
[ "Tells", "whether", "two", "Address", "are", "equal" ]
train
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/Geography/Address.php#L108-L122
agniukaitis/CInformer
src/cinformer/CInformer.php
CInformer.setMessage
public function setMessage($data) { // initialize a flash session variable if(!isset($_SESSION['flash'])) { $_SESSION['flash'] = array(); } // check for valid message template. Set to default if not valid if(!in_array($data['type'], $this->valid)) { $data['type'] = $this->valid[0]; } $_SESSION['flash']['type'] = $data['type']; $_SESSION['flash']['message'] = $data['message']; return true; }
php
public function setMessage($data) { // initialize a flash session variable if(!isset($_SESSION['flash'])) { $_SESSION['flash'] = array(); } // check for valid message template. Set to default if not valid if(!in_array($data['type'], $this->valid)) { $data['type'] = $this->valid[0]; } $_SESSION['flash']['type'] = $data['type']; $_SESSION['flash']['message'] = $data['message']; return true; }
[ "public", "function", "setMessage", "(", "$", "data", ")", "{", "// initialize a flash session variable", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "'flash'", "]", ")", ")", "{", "$", "_SESSION", "[", "'flash'", "]", "=", "array", "(", ")", ";"...
Set the message into session variable @return boolean
[ "Set", "the", "message", "into", "session", "variable" ]
train
https://github.com/agniukaitis/CInformer/blob/bfaed9d9f624174efe3ac0a6654d49d2fdba628b/src/cinformer/CInformer.php#L31-L47
benjamindulau/AnoDataGrid
src/Ano/DataGrid/View.php
View.get
public function get($name, $default = null) { if (false === $this->has($name)) { return $default; } return $this->vars[$name]; }
php
public function get($name, $default = null) { if (false === $this->has($name)) { return $default; } return $this->vars[$name]; }
[ "public", "function", "get", "(", "$", "name", ",", "$", "default", "=", "null", ")", "{", "if", "(", "false", "===", "$", "this", "->", "has", "(", "$", "name", ")", ")", "{", "return", "$", "default", ";", "}", "return", "$", "this", "->", "v...
@param $name @param $default @return mixed
[ "@param", "$name", "@param", "$default" ]
train
https://github.com/benjamindulau/AnoDataGrid/blob/69b31803929b04e9d6e807bb2213b9b3477d0367/src/Ano/DataGrid/View.php#L42-L49
bseddon/XPath20
NameBinder.php
NameBinder.PushVar
public function PushVar( $name ) { $id = $this->NewReference(); $this->_slots[] = new NameSlot( $id, $name ); return $id; }
php
public function PushVar( $name ) { $id = $this->NewReference(); $this->_slots[] = new NameSlot( $id, $name ); return $id; }
[ "public", "function", "PushVar", "(", "$", "name", ")", "{", "$", "id", "=", "$", "this", "->", "NewReference", "(", ")", ";", "$", "this", "->", "_slots", "[", "]", "=", "new", "NameSlot", "(", "$", "id", ",", "$", "name", ")", ";", "return", ...
PushVar @param QName $name @return ReferenceLink
[ "PushVar" ]
train
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/NameBinder.php#L69-L74
bseddon/XPath20
NameBinder.php
NameBinder.VarIndexByName
public function VarIndexByName( $name ) { foreach ( array_reverse( $this->_slots, true ) as $k => /** @var NameSlot $nameSlot */ $nameSlot ) { // if ( $nameSlot->name == $name->__toString() ) if ( (string)$nameSlot->name == (string)$name ) { return $nameSlot->id; } } throw XPath2Exception::withErrorCodeAndParam( "XPST0008", Resources::XPST0008, $name->__toString() ); // for ( $k = count( $this->_slots ) - 1; $k >= 0; $k-- ) // { // /** @var NameSlot $nameSlot */ // $nameSlot = $this->_slots[ $k ]; // if ( $nameSlot->name == $name->__toString() ) // { // return $nameSlot->id; // } // } // throw XPath2Exception::withErrorCodeAndParam( "XPST0008", Resources::XPST0008, $name->__toString() ); }
php
public function VarIndexByName( $name ) { foreach ( array_reverse( $this->_slots, true ) as $k => /** @var NameSlot $nameSlot */ $nameSlot ) { // if ( $nameSlot->name == $name->__toString() ) if ( (string)$nameSlot->name == (string)$name ) { return $nameSlot->id; } } throw XPath2Exception::withErrorCodeAndParam( "XPST0008", Resources::XPST0008, $name->__toString() ); // for ( $k = count( $this->_slots ) - 1; $k >= 0; $k-- ) // { // /** @var NameSlot $nameSlot */ // $nameSlot = $this->_slots[ $k ]; // if ( $nameSlot->name == $name->__toString() ) // { // return $nameSlot->id; // } // } // throw XPath2Exception::withErrorCodeAndParam( "XPST0008", Resources::XPST0008, $name->__toString() ); }
[ "public", "function", "VarIndexByName", "(", "$", "name", ")", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "_slots", ",", "true", ")", "as", "$", "k", "=>", "/** @var NameSlot $nameSlot */", "$", "nameSlot", ")", "{", "// if ( $nameSlot->name...
VarIndexByName @param QName $name @return ReferenceLink
[ "VarIndexByName" ]
train
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/NameBinder.php#L90-L112
sabinus52/OlixDatatablesBootstrapBundle
Twig/DatatableTwigExtension.php
DatatableTwigExtension.getOptions
private function getOptions(AbstractDatatableView $datatable) { $options = array(); $options['view_actions'] = $datatable->getTopActions(); $options['view_features'] = $datatable->getFeatures(); $options['view_options'] = $datatable->getOptions(); $options['view_callbacks'] = $datatable->getCallbacks(); $options['view_events'] = $datatable->getEvents(); $options['view_columns'] = $datatable->getColumnBuilder()->getColumns(); if ('' === $datatable->getAjax()->getUrl()) { throw new Exception('getOptions(): Specify an ajax url.'); } $options['view_ajax'] = $datatable->getAjax(); $options['view_multiselect'] = $datatable->getColumnBuilder()->isMultiselect(); $options['view_multiselect_column'] = $datatable->getColumnBuilder()->getMultiselectColumn(); $options['view_table_id'] = $datatable->getName(); $options['datatable'] = $datatable; return $options; }
php
private function getOptions(AbstractDatatableView $datatable) { $options = array(); $options['view_actions'] = $datatable->getTopActions(); $options['view_features'] = $datatable->getFeatures(); $options['view_options'] = $datatable->getOptions(); $options['view_callbacks'] = $datatable->getCallbacks(); $options['view_events'] = $datatable->getEvents(); $options['view_columns'] = $datatable->getColumnBuilder()->getColumns(); if ('' === $datatable->getAjax()->getUrl()) { throw new Exception('getOptions(): Specify an ajax url.'); } $options['view_ajax'] = $datatable->getAjax(); $options['view_multiselect'] = $datatable->getColumnBuilder()->isMultiselect(); $options['view_multiselect_column'] = $datatable->getColumnBuilder()->getMultiselectColumn(); $options['view_table_id'] = $datatable->getName(); $options['datatable'] = $datatable; return $options; }
[ "private", "function", "getOptions", "(", "AbstractDatatableView", "$", "datatable", ")", "{", "$", "options", "=", "array", "(", ")", ";", "$", "options", "[", "'view_actions'", "]", "=", "$", "datatable", "->", "getTopActions", "(", ")", ";", "$", "optio...
Get options. @param AbstractDatatableView $datatable @return array @throws Exception
[ "Get", "options", "." ]
train
https://github.com/sabinus52/OlixDatatablesBootstrapBundle/blob/9b5d6dfb72b7aeecef43545378f50e7a6adc1b12/Twig/DatatableTwigExtension.php#L86-L111
sabinus52/OlixDatatablesBootstrapBundle
Twig/DatatableTwigExtension.php
DatatableTwigExtension.datatableRender
public function datatableRender(Twig_Environment $twig, AbstractDatatableView $datatable) { return $twig->render('SgDatatablesBundle:Datatable:datatable.html.twig', $this->getOptions($datatable)); }
php
public function datatableRender(Twig_Environment $twig, AbstractDatatableView $datatable) { return $twig->render('SgDatatablesBundle:Datatable:datatable.html.twig', $this->getOptions($datatable)); }
[ "public", "function", "datatableRender", "(", "Twig_Environment", "$", "twig", ",", "AbstractDatatableView", "$", "datatable", ")", "{", "return", "$", "twig", "->", "render", "(", "'SgDatatablesBundle:Datatable:datatable.html.twig'", ",", "$", "this", "->", "getOptio...
Renders the template. @param Twig_Environment $twig @param AbstractDatatableView $datatable @return mixed|string @throws Exception
[ "Renders", "the", "template", "." ]
train
https://github.com/sabinus52/OlixDatatablesBootstrapBundle/blob/9b5d6dfb72b7aeecef43545378f50e7a6adc1b12/Twig/DatatableTwigExtension.php#L122-L125
sabinus52/OlixDatatablesBootstrapBundle
Twig/DatatableTwigExtension.php
DatatableTwigExtension.datatableRenderHtml
public function datatableRenderHtml(Twig_Environment $twig, AbstractDatatableView $datatable) { //return $twig->render('OlixDatatablesBootstrapBundle::datatable_html.html.twig', $this->getOptions($datatable)); return $twig->render('SgDatatablesBundle:Datatable:datatable_html.html.twig', $this->getOptions($datatable)); }
php
public function datatableRenderHtml(Twig_Environment $twig, AbstractDatatableView $datatable) { //return $twig->render('OlixDatatablesBootstrapBundle::datatable_html.html.twig', $this->getOptions($datatable)); return $twig->render('SgDatatablesBundle:Datatable:datatable_html.html.twig', $this->getOptions($datatable)); }
[ "public", "function", "datatableRenderHtml", "(", "Twig_Environment", "$", "twig", ",", "AbstractDatatableView", "$", "datatable", ")", "{", "//return $twig->render('OlixDatatablesBootstrapBundle::datatable_html.html.twig', $this->getOptions($datatable));", "return", "$", "twig", "...
Renders the html template. @param Twig_Environment $twig @param AbstractDatatableView $datatable @return mixed|string @throws Exception
[ "Renders", "the", "html", "template", "." ]
train
https://github.com/sabinus52/OlixDatatablesBootstrapBundle/blob/9b5d6dfb72b7aeecef43545378f50e7a6adc1b12/Twig/DatatableTwigExtension.php#L136-L140
sabinus52/OlixDatatablesBootstrapBundle
Twig/DatatableTwigExtension.php
DatatableTwigExtension.datatableRenderJs
public function datatableRenderJs(Twig_Environment $twig, AbstractDatatableView $datatable) { return $twig->render('SgDatatablesBundle:Datatable:datatable_js.html.twig', $this->getOptions($datatable)); }
php
public function datatableRenderJs(Twig_Environment $twig, AbstractDatatableView $datatable) { return $twig->render('SgDatatablesBundle:Datatable:datatable_js.html.twig', $this->getOptions($datatable)); }
[ "public", "function", "datatableRenderJs", "(", "Twig_Environment", "$", "twig", ",", "AbstractDatatableView", "$", "datatable", ")", "{", "return", "$", "twig", "->", "render", "(", "'SgDatatablesBundle:Datatable:datatable_js.html.twig'", ",", "$", "this", "->", "get...
Renders the js template. @param Twig_Environment $twig @param AbstractDatatableView $datatable @return mixed|string @throws Exception
[ "Renders", "the", "js", "template", "." ]
train
https://github.com/sabinus52/OlixDatatablesBootstrapBundle/blob/9b5d6dfb72b7aeecef43545378f50e7a6adc1b12/Twig/DatatableTwigExtension.php#L151-L154
sabinus52/OlixDatatablesBootstrapBundle
Twig/DatatableTwigExtension.php
DatatableTwigExtension.datatableFilterRender
public function datatableFilterRender(Twig_Environment $twig, AbstractDatatableView $datatable, AbstractColumn $column, $loopIndex) { if ($filterProperty = $column->getFilter()->getProperty()) { $filterColumnId = $datatable->getColumnIdByColumnName($filterProperty); } else { $filterColumnId = $loopIndex; } return $twig->render($column->getFilter()->getTemplate(), array( 'column' => $column, 'filterColumnId' => $filterColumnId, 'selectorId' => $loopIndex, 'tableId' => $datatable->getName() ) ); }
php
public function datatableFilterRender(Twig_Environment $twig, AbstractDatatableView $datatable, AbstractColumn $column, $loopIndex) { if ($filterProperty = $column->getFilter()->getProperty()) { $filterColumnId = $datatable->getColumnIdByColumnName($filterProperty); } else { $filterColumnId = $loopIndex; } return $twig->render($column->getFilter()->getTemplate(), array( 'column' => $column, 'filterColumnId' => $filterColumnId, 'selectorId' => $loopIndex, 'tableId' => $datatable->getName() ) ); }
[ "public", "function", "datatableFilterRender", "(", "Twig_Environment", "$", "twig", ",", "AbstractDatatableView", "$", "datatable", ",", "AbstractColumn", "$", "column", ",", "$", "loopIndex", ")", "{", "if", "(", "$", "filterProperty", "=", "$", "column", "->"...
Renders the custom datatable filter. @param Twig_Environment $twig @param AbstractDatatableView $datatable @param AbstractColumn $column @param integer $loopIndex @return mixed|string|void
[ "Renders", "the", "custom", "datatable", "filter", "." ]
train
https://github.com/sabinus52/OlixDatatablesBootstrapBundle/blob/9b5d6dfb72b7aeecef43545378f50e7a6adc1b12/Twig/DatatableTwigExtension.php#L166-L181
sabinus52/OlixDatatablesBootstrapBundle
Twig/DatatableTwigExtension.php
DatatableTwigExtension.datatableIcon
public function datatableIcon(Twig_Environment $twig, $icon, $label = '') { if ($icon) return $twig->render('SgDatatablesBundle:Action:icon.html.twig', array('icon' => $icon, 'label' => $label)); else return $label; }
php
public function datatableIcon(Twig_Environment $twig, $icon, $label = '') { if ($icon) return $twig->render('SgDatatablesBundle:Action:icon.html.twig', array('icon' => $icon, 'label' => $label)); else return $label; }
[ "public", "function", "datatableIcon", "(", "Twig_Environment", "$", "twig", ",", "$", "icon", ",", "$", "label", "=", "''", ")", "{", "if", "(", "$", "icon", ")", "return", "$", "twig", "->", "render", "(", "'SgDatatablesBundle:Action:icon.html.twig'", ",",...
Renders icon && label. @param Twig_Environment $twig @param string $icon @param string $label @return string
[ "Renders", "icon", "&&", "label", "." ]
train
https://github.com/sabinus52/OlixDatatablesBootstrapBundle/blob/9b5d6dfb72b7aeecef43545378f50e7a6adc1b12/Twig/DatatableTwigExtension.php#L192-L198
LpFactory/NestedSetRoutingBundle
Satinizer/UrlSatinizerChain.php
UrlSatinizerChain.clean
public function clean($url) { /** @var UrlSatinizerInterface $satinizer */ foreach ($this->satinizers as $satinizer) { $url = $satinizer->clean($url); } return $url; }
php
public function clean($url) { /** @var UrlSatinizerInterface $satinizer */ foreach ($this->satinizers as $satinizer) { $url = $satinizer->clean($url); } return $url; }
[ "public", "function", "clean", "(", "$", "url", ")", "{", "/** @var UrlSatinizerInterface $satinizer */", "foreach", "(", "$", "this", "->", "satinizers", "as", "$", "satinizer", ")", "{", "$", "url", "=", "$", "satinizer", "->", "clean", "(", "$", "url", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/LpFactory/NestedSetRoutingBundle/blob/dc07227a6764e657b7b321827a18127ec18ba214/Satinizer/UrlSatinizerChain.php#L36-L44
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Storage/Driver/Sae.php
Sae.read
public function read($filename,$type=''){ switch(strtolower($type)){ case 'f': $kv = $this->getKv(); if(!isset($this->kvs[$filename])){ $this->kvs[$filename]=$kv->get($filename); } return $this->kvs[$filename]; default: return $this->get($filename,'content',$type); } }
php
public function read($filename,$type=''){ switch(strtolower($type)){ case 'f': $kv = $this->getKv(); if(!isset($this->kvs[$filename])){ $this->kvs[$filename]=$kv->get($filename); } return $this->kvs[$filename]; default: return $this->get($filename,'content',$type); } }
[ "public", "function", "read", "(", "$", "filename", ",", "$", "type", "=", "''", ")", "{", "switch", "(", "strtolower", "(", "$", "type", ")", ")", "{", "case", "'f'", ":", "$", "kv", "=", "$", "this", "->", "getKv", "(", ")", ";", "if", "(", ...
文件内容读取 @access public @param string $filename 文件名 @return string
[ "文件内容读取" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Storage/Driver/Sae.php#L56-L67
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Storage/Driver/Sae.php
Sae.put
public function put($filename,$content,$type=''){ switch(strtolower($type)){ case 'f': $kv = $this->getKv(); $this->kvs[$filename] = $content; return $kv->set($filename,$content); case 'html': $kv = $this->getKv(); $content = time().$content; $this->htmls[$filename] = $content; return $kv->set($filename,$content); default: $content = time().$content; if(!$this->mc->set($filename,$content,MEMCACHE_COMPRESSED,0)){ E(L('_STORAGE_WRITE_ERROR_').':'.$filename); }else{ $this->contents[$filename] = $content; return true; } } }
php
public function put($filename,$content,$type=''){ switch(strtolower($type)){ case 'f': $kv = $this->getKv(); $this->kvs[$filename] = $content; return $kv->set($filename,$content); case 'html': $kv = $this->getKv(); $content = time().$content; $this->htmls[$filename] = $content; return $kv->set($filename,$content); default: $content = time().$content; if(!$this->mc->set($filename,$content,MEMCACHE_COMPRESSED,0)){ E(L('_STORAGE_WRITE_ERROR_').':'.$filename); }else{ $this->contents[$filename] = $content; return true; } } }
[ "public", "function", "put", "(", "$", "filename", ",", "$", "content", ",", "$", "type", "=", "''", ")", "{", "switch", "(", "strtolower", "(", "$", "type", ")", ")", "{", "case", "'f'", ":", "$", "kv", "=", "$", "this", "->", "getKv", "(", ")...
文件写入 @access public @param string $filename 文件名 @param string $content 文件内容 @return boolean
[ "文件写入" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Storage/Driver/Sae.php#L76-L96
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Storage/Driver/Sae.php
Sae.append
public function append($filename,$content,$type=''){ if($old_content = $this->read($filename,$type)){ $content = $old_content.$content; } return $this->put($filename,$content,$type); }
php
public function append($filename,$content,$type=''){ if($old_content = $this->read($filename,$type)){ $content = $old_content.$content; } return $this->put($filename,$content,$type); }
[ "public", "function", "append", "(", "$", "filename", ",", "$", "content", ",", "$", "type", "=", "''", ")", "{", "if", "(", "$", "old_content", "=", "$", "this", "->", "read", "(", "$", "filename", ",", "$", "type", ")", ")", "{", "$", "content"...
文件追加写入 @access public @param string $filename 文件名 @param string $content 追加的文件内容 @return boolean
[ "文件追加写入" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Storage/Driver/Sae.php#L105-L110
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Storage/Driver/Sae.php
Sae.load
public function load($_filename,$vars=null){ if(!is_null($vars)) extract($vars, EXTR_OVERWRITE); eval('?>'.$this->read($_filename)); }
php
public function load($_filename,$vars=null){ if(!is_null($vars)) extract($vars, EXTR_OVERWRITE); eval('?>'.$this->read($_filename)); }
[ "public", "function", "load", "(", "$", "_filename", ",", "$", "vars", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "vars", ")", ")", "extract", "(", "$", "vars", ",", "EXTR_OVERWRITE", ")", ";", "eval", "(", "'?>'", ".", "$", "thi...
加载文件 @access public @param string $_filename 文件名 @param array $vars 传入变量 @return void
[ "加载文件" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Storage/Driver/Sae.php#L119-L123
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Storage/Driver/Sae.php
Sae.unlink
public function unlink($filename,$type=''){ switch(strtolower($type)){ case 'f': $kv = $this->getKv(); unset($this->kvs[$filename]); return $kv->delete($filename); case 'html': $kv = $this->getKv(); unset($this->htmls[$filename]); return $kv->delete($filename); default: unset($this->contents[$filename]); return $this->mc->delete($filename); } }
php
public function unlink($filename,$type=''){ switch(strtolower($type)){ case 'f': $kv = $this->getKv(); unset($this->kvs[$filename]); return $kv->delete($filename); case 'html': $kv = $this->getKv(); unset($this->htmls[$filename]); return $kv->delete($filename); default: unset($this->contents[$filename]); return $this->mc->delete($filename); } }
[ "public", "function", "unlink", "(", "$", "filename", ",", "$", "type", "=", "''", ")", "{", "switch", "(", "strtolower", "(", "$", "type", ")", ")", "{", "case", "'f'", ":", "$", "kv", "=", "$", "this", "->", "getKv", "(", ")", ";", "unset", "...
文件删除 @access public @param string $filename 文件名 @return boolean
[ "文件删除" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Storage/Driver/Sae.php#L145-L159
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Storage/Driver/Sae.php
Sae.get
public function get($filename,$name,$type=''){ switch(strtolower($type)){ case 'html': if(!isset($this->htmls[$filename])){ $kv = $this->getKv(); $this->htmls[$filename] = $kv->get($filename); } $content = $this->htmls[$filename]; break; default: if(!isset($this->contents[$filename])){ $this->contents[$filename] = $this->mc->get($filename); } $content = $this->contents[$filename]; } if(false===$content){ return false; } $info = array( 'mtime' => substr($content,0,10), 'content' => substr($content,10) ); return $info[$name]; }
php
public function get($filename,$name,$type=''){ switch(strtolower($type)){ case 'html': if(!isset($this->htmls[$filename])){ $kv = $this->getKv(); $this->htmls[$filename] = $kv->get($filename); } $content = $this->htmls[$filename]; break; default: if(!isset($this->contents[$filename])){ $this->contents[$filename] = $this->mc->get($filename); } $content = $this->contents[$filename]; } if(false===$content){ return false; } $info = array( 'mtime' => substr($content,0,10), 'content' => substr($content,10) ); return $info[$name]; }
[ "public", "function", "get", "(", "$", "filename", ",", "$", "name", ",", "$", "type", "=", "''", ")", "{", "switch", "(", "strtolower", "(", "$", "type", ")", ")", "{", "case", "'html'", ":", "if", "(", "!", "isset", "(", "$", "this", "->", "h...
读取文件信息 @access public @param string $filename 文件名 @param string $name 信息名 mtime或者content @return boolean
[ "读取文件信息" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Storage/Driver/Sae.php#L168-L191
vatson/isolated-callback
src/Vatson/Callback/IsolatedCallback.php
IsolatedCallback.registerChildShutdown
protected function registerChildShutdown() { $ipc = $this->ipc; register_shutdown_function(function () use ($ipc) { $error = error_get_last(); if ($error && isset($error['type']) && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR))) { $ipc->put(new ExceptionDataHolder( new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']) )); } }); register_shutdown_function(function () { posix_kill(getmypid(), SIGKILL); }); }
php
protected function registerChildShutdown() { $ipc = $this->ipc; register_shutdown_function(function () use ($ipc) { $error = error_get_last(); if ($error && isset($error['type']) && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR))) { $ipc->put(new ExceptionDataHolder( new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']) )); } }); register_shutdown_function(function () { posix_kill(getmypid(), SIGKILL); }); }
[ "protected", "function", "registerChildShutdown", "(", ")", "{", "$", "ipc", "=", "$", "this", "->", "ipc", ";", "register_shutdown_function", "(", "function", "(", ")", "use", "(", "$", "ipc", ")", "{", "$", "error", "=", "error_get_last", "(", ")", ";"...
Avoids the closing of resources in child process
[ "Avoids", "the", "closing", "of", "resources", "in", "child", "process" ]
train
https://github.com/vatson/isolated-callback/blob/c048f4cc830c246c0aa8c45da91af9e8c5a86ca4/src/Vatson/Callback/IsolatedCallback.php#L70-L86
vatson/isolated-callback
src/Vatson/Callback/IsolatedCallback.php
IsolatedCallback.handleParentProcess
protected function handleParentProcess() { pcntl_wait($status); $result = $this->ipc->get(); if ($result instanceof ExceptionDataHolder) { throw new IsolatedCallbackExecutionException($result); } return $result; }
php
protected function handleParentProcess() { pcntl_wait($status); $result = $this->ipc->get(); if ($result instanceof ExceptionDataHolder) { throw new IsolatedCallbackExecutionException($result); } return $result; }
[ "protected", "function", "handleParentProcess", "(", ")", "{", "pcntl_wait", "(", "$", "status", ")", ";", "$", "result", "=", "$", "this", "->", "ipc", "->", "get", "(", ")", ";", "if", "(", "$", "result", "instanceof", "ExceptionDataHolder", ")", "{", ...
@throws \Exception when child process ends with an Exception @return mixed
[ "@throws", "\\", "Exception", "when", "child", "process", "ends", "with", "an", "Exception" ]
train
https://github.com/vatson/isolated-callback/blob/c048f4cc830c246c0aa8c45da91af9e8c5a86ca4/src/Vatson/Callback/IsolatedCallback.php#L93-L103
FuzeWorks/Core
src/FuzeWorks/Events.php
Events.addListener
public static function addListener($callback, $eventName, $priority = EventPriority::NORMAL) { // Perform multiple checks if (EventPriority::getPriority($priority) == false) { throw new EventException('Can not add listener: Unknown priority '.$priority, 1); } if (!is_callable($callback)) { throw new EventException("Can not add listener: Callback is not callable", 1); } if (empty($eventName)) { throw new EventException("Can not add listener: No eventname provided", 1); } if (!isset(self::$listeners[$eventName])) { self::$listeners[$eventName] = array(); } if (!isset(self::$listeners[$eventName][$priority])) { self::$listeners[$eventName][$priority] = array(); } if (func_num_args() > 3) { $args = array_slice(func_get_args(), 3); } else { $args = array(); } self::$listeners[$eventName][$priority][] = array($callback, $args); }
php
public static function addListener($callback, $eventName, $priority = EventPriority::NORMAL) { // Perform multiple checks if (EventPriority::getPriority($priority) == false) { throw new EventException('Can not add listener: Unknown priority '.$priority, 1); } if (!is_callable($callback)) { throw new EventException("Can not add listener: Callback is not callable", 1); } if (empty($eventName)) { throw new EventException("Can not add listener: No eventname provided", 1); } if (!isset(self::$listeners[$eventName])) { self::$listeners[$eventName] = array(); } if (!isset(self::$listeners[$eventName][$priority])) { self::$listeners[$eventName][$priority] = array(); } if (func_num_args() > 3) { $args = array_slice(func_get_args(), 3); } else { $args = array(); } self::$listeners[$eventName][$priority][] = array($callback, $args); }
[ "public", "static", "function", "addListener", "(", "$", "callback", ",", "$", "eventName", ",", "$", "priority", "=", "EventPriority", "::", "NORMAL", ")", "{", "// Perform multiple checks", "if", "(", "EventPriority", "::", "getPriority", "(", "$", "priority",...
Adds a function as listener. @param mixed $callback The callback when the events get fired, see {@link http://php.net/manual/en/language.types.callable.php PHP.net} @param string $eventName The name of the event @param int $priority The priority, even though integers are valid, please use EventPriority (for example EventPriority::Lowest) @param mixed $parameters,... Parameters for the listener @see EventPriority @throws EventException
[ "Adds", "a", "function", "as", "listener", "." ]
train
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Events.php#L85-L119
FuzeWorks/Core
src/FuzeWorks/Events.php
Events.removeListener
public static function removeListener($callback, $eventName, $priority = EventPriority::NORMAL) { if (EventPriority::getPriority($priority) == false) { throw new EventException('Unknown priority '.$priority); } if (!isset(self::$listeners[$eventName]) || !isset(self::$listeners[$eventName][$priority])) { return; } foreach (self::$listeners[$eventName][$priority] as $i => $_callback) { if ($_callback[0] == $callback) { unset(self::$listeners[$eventName][$priority][$i]); return; } } }
php
public static function removeListener($callback, $eventName, $priority = EventPriority::NORMAL) { if (EventPriority::getPriority($priority) == false) { throw new EventException('Unknown priority '.$priority); } if (!isset(self::$listeners[$eventName]) || !isset(self::$listeners[$eventName][$priority])) { return; } foreach (self::$listeners[$eventName][$priority] as $i => $_callback) { if ($_callback[0] == $callback) { unset(self::$listeners[$eventName][$priority][$i]); return; } } }
[ "public", "static", "function", "removeListener", "(", "$", "callback", ",", "$", "eventName", ",", "$", "priority", "=", "EventPriority", "::", "NORMAL", ")", "{", "if", "(", "EventPriority", "::", "getPriority", "(", "$", "priority", ")", "==", "false", ...
Removes a function as listener. @param mixed callback The callback when the events get fired, see {@link http://php.net/manual/en/language.types.callable.php PHP.net} @param string $eventName The name of the event @param int $priority The priority, even though integers are valid, please use EventPriority (for example EventPriority::Lowest) @see EventPriority @throws EventException
[ "Removes", "a", "function", "as", "listener", "." ]
train
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Events.php#L132-L149
FuzeWorks/Core
src/FuzeWorks/Events.php
Events.fireEvent
public static function fireEvent($input): Event { // First try and see if the object is an Event if (is_object($input)) { $eventName = get_class($input); $eventName = explode('\\', $eventName); $eventName = end($eventName); $event = $input; } // Otherwise try to load an event based on the input string elseif (is_string($input)) { $eventClass = ucfirst($input); $eventName = $input; // Try a direct class if (class_exists($eventClass, true)) { $event = new $eventClass(); } // Try a core event elseif (class_exists("\FuzeWorks\Event\\".$eventClass, true)) { $class = "\FuzeWorks\Event\\".$eventClass; $event = new $class(); } // Try a notifier event elseif (func_num_args() == 1) { $class = "\FuzeWorks\Event\NotifierEvent"; $event = new $class(); } // Or throw an exception on failure else { throw new EventException('Event '.$eventName.' could not be found!', 1); } } else { throw new EventException('Event could not be loaded. Invalid variable provided.', 1); } if (self::$enabled) { Logger::newLevel("Firing Event: '".$eventName."'"); } if (func_num_args() > 1) { call_user_func_array(array($event, 'init'), array_slice(func_get_args(), 1)); } // Do not run if the event system is disabled if (!self::$enabled) { return $event; } Logger::log('Checking for Listeners'); //There are listeners for this event if (isset(self::$listeners[$eventName])) { //Loop from the highest priority to the lowest for ($priority = EventPriority::getHighestPriority(); $priority <= EventPriority::getLowestPriority(); ++$priority) { //Check for listeners in this priority if (isset(self::$listeners[$eventName][$priority])) { $listeners = self::$listeners[$eventName][$priority]; Logger::newLevel('Found listeners with priority '.EventPriority::getPriority($priority)); //Fire the event to each listener foreach ($listeners as $callbackArray) { // @codeCoverageIgnoreStart $callback = $callbackArray[0]; if (is_callable($callback)) { Logger::newLevel('Firing function'); } elseif (!is_string($callback[0])) { Logger::newLevel('Firing '.get_class($callback[0]).'->'.$callback[1]); } else { Logger::newLevel('Firing '.implode('->', $callback)); } // @codeCoverageIgnoreEnd $args = array_merge(array($event), $callbackArray[1]); call_user_func_array($callback, $args); Logger::stopLevel(); } Logger::stopLevel(); } } } Logger::stopLevel(); return $event; }
php
public static function fireEvent($input): Event { // First try and see if the object is an Event if (is_object($input)) { $eventName = get_class($input); $eventName = explode('\\', $eventName); $eventName = end($eventName); $event = $input; } // Otherwise try to load an event based on the input string elseif (is_string($input)) { $eventClass = ucfirst($input); $eventName = $input; // Try a direct class if (class_exists($eventClass, true)) { $event = new $eventClass(); } // Try a core event elseif (class_exists("\FuzeWorks\Event\\".$eventClass, true)) { $class = "\FuzeWorks\Event\\".$eventClass; $event = new $class(); } // Try a notifier event elseif (func_num_args() == 1) { $class = "\FuzeWorks\Event\NotifierEvent"; $event = new $class(); } // Or throw an exception on failure else { throw new EventException('Event '.$eventName.' could not be found!', 1); } } else { throw new EventException('Event could not be loaded. Invalid variable provided.', 1); } if (self::$enabled) { Logger::newLevel("Firing Event: '".$eventName."'"); } if (func_num_args() > 1) { call_user_func_array(array($event, 'init'), array_slice(func_get_args(), 1)); } // Do not run if the event system is disabled if (!self::$enabled) { return $event; } Logger::log('Checking for Listeners'); //There are listeners for this event if (isset(self::$listeners[$eventName])) { //Loop from the highest priority to the lowest for ($priority = EventPriority::getHighestPriority(); $priority <= EventPriority::getLowestPriority(); ++$priority) { //Check for listeners in this priority if (isset(self::$listeners[$eventName][$priority])) { $listeners = self::$listeners[$eventName][$priority]; Logger::newLevel('Found listeners with priority '.EventPriority::getPriority($priority)); //Fire the event to each listener foreach ($listeners as $callbackArray) { // @codeCoverageIgnoreStart $callback = $callbackArray[0]; if (is_callable($callback)) { Logger::newLevel('Firing function'); } elseif (!is_string($callback[0])) { Logger::newLevel('Firing '.get_class($callback[0]).'->'.$callback[1]); } else { Logger::newLevel('Firing '.implode('->', $callback)); } // @codeCoverageIgnoreEnd $args = array_merge(array($event), $callbackArray[1]); call_user_func_array($callback, $args); Logger::stopLevel(); } Logger::stopLevel(); } } } Logger::stopLevel(); return $event; }
[ "public", "static", "function", "fireEvent", "(", "$", "input", ")", ":", "Event", "{", "// First try and see if the object is an Event", "if", "(", "is_object", "(", "$", "input", ")", ")", "{", "$", "eventName", "=", "get_class", "(", "$", "input", ")", ";...
Fires an Event. The Event gets created, passed around and then returned to the issuer. @param mixed $input Object for direct event, string for system event or notifierEvent @param mixed $parameters,... Parameters for the event @todo Implement Application Events @todo Implement Directory input for Events from other locations (like Modules) @return Event The Event
[ "Fires", "an", "Event", "." ]
train
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/Events.php#L163-L260
CampaignChain/report-analytics-metrics-per-activity
Util/Data.php
Data.getMetrics
public function getMetrics(Campaign $campaign, Activity $activity){ $qb = $this->em->createQueryBuilder(); $qb->select('r') ->from('CampaignChain\CoreBundle\Entity\ReportAnalyticsActivityFact', 'r') ->where('r.activity = :activityId') ->andWhere('r.campaign = :campaignId') ->groupBy('r.metric') ->setParameter('activityId', $activity->getId()) ->setParameter('campaignId', $campaign->getId()); $query = $qb->getQuery(); $this->dimensions = $query->getResult(); return $this->dimensions; }
php
public function getMetrics(Campaign $campaign, Activity $activity){ $qb = $this->em->createQueryBuilder(); $qb->select('r') ->from('CampaignChain\CoreBundle\Entity\ReportAnalyticsActivityFact', 'r') ->where('r.activity = :activityId') ->andWhere('r.campaign = :campaignId') ->groupBy('r.metric') ->setParameter('activityId', $activity->getId()) ->setParameter('campaignId', $campaign->getId()); $query = $qb->getQuery(); $this->dimensions = $query->getResult(); return $this->dimensions; }
[ "public", "function", "getMetrics", "(", "Campaign", "$", "campaign", ",", "Activity", "$", "activity", ")", "{", "$", "qb", "=", "$", "this", "->", "em", "->", "createQueryBuilder", "(", ")", ";", "$", "qb", "->", "select", "(", "'r'", ")", "->", "f...
Get the report data per activity. @param Campaign $campaign @param Activity $activity @return ReportAnalyticsActivityFact[]
[ "Get", "the", "report", "data", "per", "activity", ".", "@param", "Campaign", "$campaign", "@param", "Activity", "$activity" ]
train
https://github.com/CampaignChain/report-analytics-metrics-per-activity/blob/ce12845f7a8938893d2c3d33ed05579b08425cf4/Util/Data.php#L208-L220
CampaignChain/report-analytics-metrics-per-activity
Util/Data.php
Data.getFacts
public function getFacts(Campaign $campaign, Activity $activity, $percent = false){ $qb = $this->em->createQueryBuilder(); $qb->select('r.time, r.value, IDENTITY(r.metric) as metric') ->from('CampaignChain\CoreBundle\Entity\ReportAnalyticsActivityFact', 'r') ->where('r.activity = :activityId') ->andWhere('r.campaign = :campaignId') ->orderBy('r.time', 'ASC') ->setParameter('activityId', $activity->getId()) ->setParameter('campaignId', $campaign->getId()); $query = $qb->getQuery(); $facts = $query->getArrayResult(); $factsData = []; $tmp = []; foreach ($facts as $fact) { $tmp[$fact['metric']][] = [ $fact['time']->getTimestamp() * 1000, $fact['value'], ]; } foreach (array_keys($tmp) as $k) { $factsData[$k]['data'] = $this->serializer->serialize($tmp[$k], 'json'); $factsData[$k]['id'] = $k; if ($percent) { $factsData[$k]['percent'] = $this->getDimensionPercent($campaign, $activity, $k); } } return $factsData; }
php
public function getFacts(Campaign $campaign, Activity $activity, $percent = false){ $qb = $this->em->createQueryBuilder(); $qb->select('r.time, r.value, IDENTITY(r.metric) as metric') ->from('CampaignChain\CoreBundle\Entity\ReportAnalyticsActivityFact', 'r') ->where('r.activity = :activityId') ->andWhere('r.campaign = :campaignId') ->orderBy('r.time', 'ASC') ->setParameter('activityId', $activity->getId()) ->setParameter('campaignId', $campaign->getId()); $query = $qb->getQuery(); $facts = $query->getArrayResult(); $factsData = []; $tmp = []; foreach ($facts as $fact) { $tmp[$fact['metric']][] = [ $fact['time']->getTimestamp() * 1000, $fact['value'], ]; } foreach (array_keys($tmp) as $k) { $factsData[$k]['data'] = $this->serializer->serialize($tmp[$k], 'json'); $factsData[$k]['id'] = $k; if ($percent) { $factsData[$k]['percent'] = $this->getDimensionPercent($campaign, $activity, $k); } } return $factsData; }
[ "public", "function", "getFacts", "(", "Campaign", "$", "campaign", ",", "Activity", "$", "activity", ",", "$", "percent", "=", "false", ")", "{", "$", "qb", "=", "$", "this", "->", "em", "->", "createQueryBuilder", "(", ")", ";", "$", "qb", "->", "s...
Get facts data per dimension. @param Campaign $campaign @param Activity $activity @param boolean $percent @return array
[ "Get", "facts", "data", "per", "dimension", "." ]
train
https://github.com/CampaignChain/report-analytics-metrics-per-activity/blob/ce12845f7a8938893d2c3d33ed05579b08425cf4/Util/Data.php#L231-L262
miaoxing/wechat
src/Service/WechatTemplate.php
WechatTemplate.to
public function to(User $user) { $this->user = $user; $this->request['touser'] = $user['wechatOpenId']; return $this; }
php
public function to(User $user) { $this->user = $user; $this->request['touser'] = $user['wechatOpenId']; return $this; }
[ "public", "function", "to", "(", "User", "$", "user", ")", "{", "$", "this", "->", "user", "=", "$", "user", ";", "$", "this", "->", "request", "[", "'touser'", "]", "=", "$", "user", "[", "'wechatOpenId'", "]", ";", "return", "$", "this", ";", "...
设置接受的用户 @param User $user @return $this
[ "设置接受的用户" ]
train
https://github.com/miaoxing/wechat/blob/8620f7788cd0b6b9d20d436cede1f9f2fd24925f/src/Service/WechatTemplate.php#L64-L70
miaoxing/wechat
src/Service/WechatTemplate.php
WechatTemplate.url
public function url($url) { if (parse_url($url, PHP_URL_SCHEME) == '') { $url = wei()->request->getUrlFor($url); } $this->request['url'] = $url; return $this; }
php
public function url($url) { if (parse_url($url, PHP_URL_SCHEME) == '') { $url = wei()->request->getUrlFor($url); } $this->request['url'] = $url; return $this; }
[ "public", "function", "url", "(", "$", "url", ")", "{", "if", "(", "parse_url", "(", "$", "url", ",", "PHP_URL_SCHEME", ")", "==", "''", ")", "{", "$", "url", "=", "wei", "(", ")", "->", "request", "->", "getUrlFor", "(", "$", "url", ")", ";", ...
设置模板跳转链接 @param string $url @return $this
[ "设置模板跳转链接" ]
train
https://github.com/miaoxing/wechat/blob/8620f7788cd0b6b9d20d436cede1f9f2fd24925f/src/Service/WechatTemplate.php#L78-L87
miaoxing/wechat
src/Service/WechatTemplate.php
WechatTemplate.data
public function data(array $data) { foreach ($data as $name => $rows) { // 允许直接传入文案,不传颜色,如 ['first' => '恭喜你购买成功!'] if (!is_array($rows)) { $data[$name] = ['value' => $rows]; } // 空值则显示默认值 if ($name !== 'remark' && !$this->wei->isPresent($data[$name]['value'])) { $data[$name]['value'] = '-'; } } $this->request['data'] = $data; return $this; }
php
public function data(array $data) { foreach ($data as $name => $rows) { // 允许直接传入文案,不传颜色,如 ['first' => '恭喜你购买成功!'] if (!is_array($rows)) { $data[$name] = ['value' => $rows]; } // 空值则显示默认值 if ($name !== 'remark' && !$this->wei->isPresent($data[$name]['value'])) { $data[$name]['value'] = '-'; } } $this->request['data'] = $data; return $this; }
[ "public", "function", "data", "(", "array", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "name", "=>", "$", "rows", ")", "{", "// 允许直接传入文案,不传颜色,如 ['first' => '恭喜你购买成功!']", "if", "(", "!", "is_array", "(", "$", "rows", ")", ")", "{", "...
设置模板数据 @param array $data @return WechatTemplate
[ "设置模板数据" ]
train
https://github.com/miaoxing/wechat/blob/8620f7788cd0b6b9d20d436cede1f9f2fd24925f/src/Service/WechatTemplate.php#L115-L132
miaoxing/wechat
src/Service/WechatTemplate.php
WechatTemplate.send
public function send() { $this->logger->debug('Send template message', $this->request); if (!$this->request['template_id']) { return $this->err('缺少模板编号', -2); } if (!$this->request['touser']) { return $this->err('缺少用户OpenID', -3); } $account = wei()->wechatAccount->getCurrentAccount(); $api = $account->createApiService(); if ($account->isService()) { return $this->sendServiceTemplate($account, $api); } else { return $this->sendWxaTemplate($account, $api); } }
php
public function send() { $this->logger->debug('Send template message', $this->request); if (!$this->request['template_id']) { return $this->err('缺少模板编号', -2); } if (!$this->request['touser']) { return $this->err('缺少用户OpenID', -3); } $account = wei()->wechatAccount->getCurrentAccount(); $api = $account->createApiService(); if ($account->isService()) { return $this->sendServiceTemplate($account, $api); } else { return $this->sendWxaTemplate($account, $api); } }
[ "public", "function", "send", "(", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'Send template message'", ",", "$", "this", "->", "request", ")", ";", "if", "(", "!", "$", "this", "->", "request", "[", "'template_id'", "]", ")", "{", "...
发送模板消息 @return array
[ "发送模板消息" ]
train
https://github.com/miaoxing/wechat/blob/8620f7788cd0b6b9d20d436cede1f9f2fd24925f/src/Service/WechatTemplate.php#L159-L178
shampeak/GraceServer
src/View/View.php
View.fetch
public function fetch($tplFile, $data) { foreach ($data as $key => $value) { $this->_data[$key] = $value; } $Controller = $this->router['controller'] ?: 'Home'; $Mothed = $this->router['mothed'] ?: "Index"; $tplFile = $tplFile ? ucfirst($tplFile) : ucfirst($Mothed); $this->_viewPath = $this->_tplDir . ucfirst($Controller) . '/' . $tplFile . '.php'; unset($tplFile); extract($this->_data); ob_start(); //开启缓冲区 include $this->_viewPath; $html = ob_get_contents(); ob_end_clean(); return $html; }
php
public function fetch($tplFile, $data) { foreach ($data as $key => $value) { $this->_data[$key] = $value; } $Controller = $this->router['controller'] ?: 'Home'; $Mothed = $this->router['mothed'] ?: "Index"; $tplFile = $tplFile ? ucfirst($tplFile) : ucfirst($Mothed); $this->_viewPath = $this->_tplDir . ucfirst($Controller) . '/' . $tplFile . '.php'; unset($tplFile); extract($this->_data); ob_start(); //开启缓冲区 include $this->_viewPath; $html = ob_get_contents(); ob_end_clean(); return $html; }
[ "public", "function", "fetch", "(", "$", "tplFile", ",", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "_data", "[", "$", "key", "]", "=", "$", "value", ";", "}", "$", "...
@param $tplFile @param $data @return mixed
[ "@param", "$tplFile", "@param", "$data" ]
train
https://github.com/shampeak/GraceServer/blob/e69891de3daae7d228c803c06213eb248fc88594/src/View/View.php#L92-L112
shampeak/GraceServer
src/View/View.php
View.display
public function display($tplFile, $data) { foreach ($data as $key => $value) { $this->_data[$key] = $value; } $Controller = $this->router['controller'] ?: 'Home'; $Mothed = $this->router['mothed'] ?: "Index"; $tplFile = $tplFile ? ucfirst($tplFile) : ucfirst($Mothed); $this->_viewPath = $this->_tplDir . ucfirst($Controller) . '/' . $tplFile . '.php'; unset($tplFile); extract($this->_data); include $this->_viewPath; }
php
public function display($tplFile, $data) { foreach ($data as $key => $value) { $this->_data[$key] = $value; } $Controller = $this->router['controller'] ?: 'Home'; $Mothed = $this->router['mothed'] ?: "Index"; $tplFile = $tplFile ? ucfirst($tplFile) : ucfirst($Mothed); $this->_viewPath = $this->_tplDir . ucfirst($Controller) . '/' . $tplFile . '.php'; unset($tplFile); extract($this->_data); include $this->_viewPath; }
[ "public", "function", "display", "(", "$", "tplFile", ",", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "_data", "[", "$", "key", "]", "=", "$", "value", ";", "}", "$", ...
渲染模板并输出 $tplFile 模板文件路径,相对于App/View/文件的相对路径,不包含后缀名,例如index/index @param $tplFile @param $data
[ "渲染模板并输出", "$tplFile", "模板文件路径,相对于App", "/", "View", "/", "文件的相对路径,不包含后缀名,例如index", "/", "index" ]
train
https://github.com/shampeak/GraceServer/blob/e69891de3daae7d228c803c06213eb248fc88594/src/View/View.php#L120-L134
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php
DataTransferObjectFactory.getDataTransferObjectName
public function getDataTransferObjectName($object) { $objectName = TypeHandling::getTypeForValue($object); if (!array_key_exists($objectName, $this->classMappingConfiguration)) { foreach (array_reverse($this->classNameToDtoClassNameReplaceFragments, TRUE) as $dtoClassNameFragment => $classNameFragment) { $dtoClassName = str_replace($classNameFragment, $dtoClassNameFragment, $objectName); if (class_exists($dtoClassName)) { $this->classMappingConfiguration[$objectName] = $dtoClassName; break; } } } if (!isset($this->classMappingConfiguration[$objectName])) { throw new InvalidTargetException(sprintf('There is no DTO class name for "%s" objects.', $objectName), 1407499486); } return $this->classMappingConfiguration[$objectName]; }
php
public function getDataTransferObjectName($object) { $objectName = TypeHandling::getTypeForValue($object); if (!array_key_exists($objectName, $this->classMappingConfiguration)) { foreach (array_reverse($this->classNameToDtoClassNameReplaceFragments, TRUE) as $dtoClassNameFragment => $classNameFragment) { $dtoClassName = str_replace($classNameFragment, $dtoClassNameFragment, $objectName); if (class_exists($dtoClassName)) { $this->classMappingConfiguration[$objectName] = $dtoClassName; break; } } } if (!isset($this->classMappingConfiguration[$objectName])) { throw new InvalidTargetException(sprintf('There is no DTO class name for "%s" objects.', $objectName), 1407499486); } return $this->classMappingConfiguration[$objectName]; }
[ "public", "function", "getDataTransferObjectName", "(", "$", "object", ")", "{", "$", "objectName", "=", "TypeHandling", "::", "getTypeForValue", "(", "$", "object", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "objectName", ",", "$", "this", "->"...
Returns the class name of the given DataTransferObject. @param $object @return string @throws InvalidTargetException
[ "Returns", "the", "class", "name", "of", "the", "given", "DataTransferObject", "." ]
train
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php#L82-L100
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php
DataTransferObjectFactory.getDataTransferObject
public function getDataTransferObject($object) { if ($object === NULL) { return NULL; } $identifier = $this->persistenceManager->getIdentifierByObject($object); $dto = $this->propertyMapper->convert($identifier, $this->getDataTransferObjectName($object)); return $dto; }
php
public function getDataTransferObject($object) { if ($object === NULL) { return NULL; } $identifier = $this->persistenceManager->getIdentifierByObject($object); $dto = $this->propertyMapper->convert($identifier, $this->getDataTransferObjectName($object)); return $dto; }
[ "public", "function", "getDataTransferObject", "(", "$", "object", ")", "{", "if", "(", "$", "object", "===", "NULL", ")", "{", "return", "NULL", ";", "}", "$", "identifier", "=", "$", "this", "->", "persistenceManager", "->", "getIdentifierByObject", "(", ...
Returns a DataTransferObject for the given object name. @param mixed $object @return \Netlogix\Crud\Domain\Model\DataTransfer\AbstractDataTransferObject
[ "Returns", "a", "DataTransferObject", "for", "the", "given", "object", "name", "." ]
train
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php#L108-L115
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php
DataTransferObjectFactory.pushClassNameToDtoClassNameReplaceFragments
public function pushClassNameToDtoClassNameReplaceFragments(array $classNameToDtoClassNameReplaceFragments, $mergeWithExistingFragments = TRUE) { array_push($this->classNameToDtoClassNameReplaceFragmentsStack, $this->classNameToDtoClassNameReplaceFragments); array_push($this->classMappingConfigurationStack, $this->classMappingConfiguration); $this->classNameToDtoClassNameReplaceFragments = \Netlogix\Crud\Utility\ArrayUtility::arrayMergeRecursiveOverrule( $mergeWithExistingFragments ? $this->classNameToDtoClassNameReplaceFragments : array(), $classNameToDtoClassNameReplaceFragments ); }
php
public function pushClassNameToDtoClassNameReplaceFragments(array $classNameToDtoClassNameReplaceFragments, $mergeWithExistingFragments = TRUE) { array_push($this->classNameToDtoClassNameReplaceFragmentsStack, $this->classNameToDtoClassNameReplaceFragments); array_push($this->classMappingConfigurationStack, $this->classMappingConfiguration); $this->classNameToDtoClassNameReplaceFragments = \Netlogix\Crud\Utility\ArrayUtility::arrayMergeRecursiveOverrule( $mergeWithExistingFragments ? $this->classNameToDtoClassNameReplaceFragments : array(), $classNameToDtoClassNameReplaceFragments ); }
[ "public", "function", "pushClassNameToDtoClassNameReplaceFragments", "(", "array", "$", "classNameToDtoClassNameReplaceFragments", ",", "$", "mergeWithExistingFragments", "=", "TRUE", ")", "{", "array_push", "(", "$", "this", "->", "classNameToDtoClassNameReplaceFragmentsStack"...
Register new class name fragments @param array $classNameToDtoClassNameReplaceFragments @param bool $mergeWithExistingFragments
[ "Register", "new", "class", "name", "fragments" ]
train
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php#L135-L142
netlogix/Netlogix.Crud
Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php
DataTransferObjectFactory.popClassNameToDtoClassNameReplaceFragments
public function popClassNameToDtoClassNameReplaceFragments() { $this->classMappingConfiguration = array_pop($this->classMappingConfigurationStack); $this->classNameToDtoClassNameReplaceFragments = array_pop($this->classNameToDtoClassNameReplaceFragmentsStack); }
php
public function popClassNameToDtoClassNameReplaceFragments() { $this->classMappingConfiguration = array_pop($this->classMappingConfigurationStack); $this->classNameToDtoClassNameReplaceFragments = array_pop($this->classNameToDtoClassNameReplaceFragmentsStack); }
[ "public", "function", "popClassNameToDtoClassNameReplaceFragments", "(", ")", "{", "$", "this", "->", "classMappingConfiguration", "=", "array_pop", "(", "$", "this", "->", "classMappingConfigurationStack", ")", ";", "$", "this", "->", "classNameToDtoClassNameReplaceFragm...
Restore old class name fragment settings
[ "Restore", "old", "class", "name", "fragment", "settings" ]
train
https://github.com/netlogix/Netlogix.Crud/blob/61438827ba6b0a7a63cd2f08a294967ed5928144/Classes/Netlogix/Crud/Domain/Service/DataTransferObjectFactory.php#L147-L150
MindyPHP/Sitemap
AbstractSitemapProvider.php
AbstractSitemapProvider.generateLoc
protected function generateLoc($hostWithScheme, $route, $parameters = []) { if (null === $this->router) { throw new \RuntimeException('UrlGenerator interface is missing'); } list($scheme, $host) = explode('://', $hostWithScheme); $this->router ->getContext() ->setHost($host) ->setScheme($scheme); return $this->router->generate($route, $parameters, UrlGeneratorInterface::ABSOLUTE_URL); }
php
protected function generateLoc($hostWithScheme, $route, $parameters = []) { if (null === $this->router) { throw new \RuntimeException('UrlGenerator interface is missing'); } list($scheme, $host) = explode('://', $hostWithScheme); $this->router ->getContext() ->setHost($host) ->setScheme($scheme); return $this->router->generate($route, $parameters, UrlGeneratorInterface::ABSOLUTE_URL); }
[ "protected", "function", "generateLoc", "(", "$", "hostWithScheme", ",", "$", "route", ",", "$", "parameters", "=", "[", "]", ")", "{", "if", "(", "null", "===", "$", "this", "->", "router", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Ur...
@param string $hostWithScheme @param $route @param array $parameters @return string
[ "@param", "string", "$hostWithScheme", "@param", "$route", "@param", "array", "$parameters" ]
train
https://github.com/MindyPHP/Sitemap/blob/0f0594b522e11f096d327dcb27cbbd998677d52c/AbstractSitemapProvider.php#L43-L57
RudyMas/Emvc_Login
src/Login.php
Login.translateData
private function translateData(): void { foreach ($this->db->data as $key => $value) { $this->data[$key] = $value; } }
php
private function translateData(): void { foreach ($this->db->data as $key => $value) { $this->data[$key] = $value; } }
[ "private", "function", "translateData", "(", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "db", "->", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "data", "[", "$", "key", "]", "=", "$", "value", ";", ...
Transform clean SQL data to normal data
[ "Transform", "clean", "SQL", "data", "to", "normal", "data" ]
train
https://github.com/RudyMas/Emvc_Login/blob/9bcb50b08836d0639338ca2bc173182bc6b4bce3/src/Login.php#L358-L363
RudyMas/Emvc_Login
src/Login.php
Login.setData
public function setData(string $key, $value): bool { if ($key !== 'password' || $key !== 'salt' || $key !== 'remember_md') { $this->data[$key] = $value; return true; } else { return false; } }
php
public function setData(string $key, $value): bool { if ($key !== 'password' || $key !== 'salt' || $key !== 'remember_md') { $this->data[$key] = $value; return true; } else { return false; } }
[ "public", "function", "setData", "(", "string", "$", "key", ",", "$", "value", ")", ":", "bool", "{", "if", "(", "$", "key", "!==", "'password'", "||", "$", "key", "!==", "'salt'", "||", "$", "key", "!==", "'remember_md'", ")", "{", "$", "this", "-...
Set any other field from the table @param string $key @param mixed $value @return bool
[ "Set", "any", "other", "field", "from", "the", "table" ]
train
https://github.com/RudyMas/Emvc_Login/blob/9bcb50b08836d0639338ca2bc173182bc6b4bce3/src/Login.php#L460-L468
RudyMas/Emvc_Login
src/Login.php
Login.getData
public function getData(string $key) { return ($key !== 'password' || $key !== 'salt' || $key !== 'remember_me') ? $this->data[$key] : false; }
php
public function getData(string $key) { return ($key !== 'password' || $key !== 'salt' || $key !== 'remember_me') ? $this->data[$key] : false; }
[ "public", "function", "getData", "(", "string", "$", "key", ")", "{", "return", "(", "$", "key", "!==", "'password'", "||", "$", "key", "!==", "'salt'", "||", "$", "key", "!==", "'remember_me'", ")", "?", "$", "this", "->", "data", "[", "$", "key", ...
Get any other field from the table Will return 'false' is key 'password', 'salt' or 'remember_me' is accessed @param string $key @return bool|mixed
[ "Get", "any", "other", "field", "from", "the", "table", "Will", "return", "false", "is", "key", "password", "salt", "or", "remember_me", "is", "accessed" ]
train
https://github.com/RudyMas/Emvc_Login/blob/9bcb50b08836d0639338ca2bc173182bc6b4bce3/src/Login.php#L477-L480
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/plugins/PluginDAO.php
PluginDAO.postCacheTranslateObject
public function postCacheTranslateObject(ModelObject $obj) { if(strpos($obj->Path, $this->rootPath) === FALSE) $obj->setPath($this->rootPath.DIRECTORY_SEPARATOR.$obj->Path); return $obj; }
php
public function postCacheTranslateObject(ModelObject $obj) { if(strpos($obj->Path, $this->rootPath) === FALSE) $obj->setPath($this->rootPath.DIRECTORY_SEPARATOR.$obj->Path); return $obj; }
[ "public", "function", "postCacheTranslateObject", "(", "ModelObject", "$", "obj", ")", "{", "if", "(", "strpos", "(", "$", "obj", "->", "Path", ",", "$", "this", "->", "rootPath", ")", "===", "FALSE", ")", "$", "obj", "->", "setPath", "(", "$", "this",...
Sets the path and returns the object @param ModelObject $obj The plugin @return ModelObject
[ "Sets", "the", "path", "and", "returns", "the", "object" ]
train
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/plugins/PluginDAO.php#L62-L67
koolkode/http
src/UriBuilder.php
UriBuilder.param
public function param($name, $value) { if(is_integer($name)) { if(array_key_exists($name, $this->pathParamNames)) { $this->path[$this->pathParamNames[$name]] = $value; return $this; } throw new \OutOfBoundsException(sprintf('No path param at position %u', $name)); } if(in_array($name, $this->pathParamNames, true)) { $this->path[(string)$name] = $value; return $this; } $this->query[(string)$name] = $value; return $this; }
php
public function param($name, $value) { if(is_integer($name)) { if(array_key_exists($name, $this->pathParamNames)) { $this->path[$this->pathParamNames[$name]] = $value; return $this; } throw new \OutOfBoundsException(sprintf('No path param at position %u', $name)); } if(in_array($name, $this->pathParamNames, true)) { $this->path[(string)$name] = $value; return $this; } $this->query[(string)$name] = $value; return $this; }
[ "public", "function", "param", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "is_integer", "(", "$", "name", ")", ")", "{", "if", "(", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "pathParamNames", ")", ")", "{", "$", ...
Assign a value to a path or query param depending on the URI pattern checking the name of the param. @param string $name @param string $value @return UriBuilder
[ "Assign", "a", "value", "to", "a", "path", "or", "query", "param", "depending", "on", "the", "URI", "pattern", "checking", "the", "name", "of", "the", "param", "." ]
train
https://github.com/koolkode/http/blob/3c1626d409d5ce5d71d26f0e8f31ae3683a2a966/src/UriBuilder.php#L167-L191
koolkode/http
src/UriBuilder.php
UriBuilder.pathParam
public function pathParam($name, $value) { if(is_integer($name)) { if(array_key_exists($name, $this->pathParamNames)) { $this->path[$this->pathParamNames[$name]] = $value; return $this; } throw new \OutOfBoundsException(sprintf('Path param %u not found in pattern "%s"', $name, $this->uri)); } if(in_array($name, $this->pathParamNames, true)) { $this->path[(string)$name] = $value; return $this; } throw new \OutOfBoundsException(sprintf('Path param "%s" not found in pattern "%s"', $name, $this->uri)); }
php
public function pathParam($name, $value) { if(is_integer($name)) { if(array_key_exists($name, $this->pathParamNames)) { $this->path[$this->pathParamNames[$name]] = $value; return $this; } throw new \OutOfBoundsException(sprintf('Path param %u not found in pattern "%s"', $name, $this->uri)); } if(in_array($name, $this->pathParamNames, true)) { $this->path[(string)$name] = $value; return $this; } throw new \OutOfBoundsException(sprintf('Path param "%s" not found in pattern "%s"', $name, $this->uri)); }
[ "public", "function", "pathParam", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "is_integer", "(", "$", "name", ")", ")", "{", "if", "(", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "pathParamNames", ")", ")", "{", "$...
Assign a value to a path param. @param string $name @param string $value @return UriBuilder @throws \OutOfBoundsException When no such param (name or index) exists.
[ "Assign", "a", "value", "to", "a", "path", "param", "." ]
train
https://github.com/koolkode/http/blob/3c1626d409d5ce5d71d26f0e8f31ae3683a2a966/src/UriBuilder.php#L212-L234
koolkode/http
src/UriBuilder.php
UriBuilder.queryParam
public function queryParam($name, $value) { if($value === NULL) { unset($this->query[(string)$name]); } else { $this->query[(string)$name] = $value; } return $this; }
php
public function queryParam($name, $value) { if($value === NULL) { unset($this->query[(string)$name]); } else { $this->query[(string)$name] = $value; } return $this; }
[ "public", "function", "queryParam", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "$", "value", "===", "NULL", ")", "{", "unset", "(", "$", "this", "->", "query", "[", "(", "string", ")", "$", "name", "]", ")", ";", "}", "else", "{"...
Assign a value to a query param, assigning a NULL value will remove the query param. @param string $name @param mixed $value @return UriBuilder
[ "Assign", "a", "value", "to", "a", "query", "param", "assigning", "a", "NULL", "value", "will", "remove", "the", "query", "param", "." ]
train
https://github.com/koolkode/http/blob/3c1626d409d5ce5d71d26f0e8f31ae3683a2a966/src/UriBuilder.php#L243-L255
koolkode/http
src/UriBuilder.php
UriBuilder.queryParams
public function queryParams(array $query) { $this->query = Arrays::mergeDeep($this->query, $query); return $this; }
php
public function queryParams(array $query) { $this->query = Arrays::mergeDeep($this->query, $query); return $this; }
[ "public", "function", "queryParams", "(", "array", "$", "query", ")", "{", "$", "this", "->", "query", "=", "Arrays", "::", "mergeDeep", "(", "$", "this", "->", "query", ",", "$", "query", ")", ";", "return", "$", "this", ";", "}" ]
Merges query params recursively. @param array<string, mixed> $query @return UriBuilder
[ "Merges", "query", "params", "recursively", "." ]
train
https://github.com/koolkode/http/blob/3c1626d409d5ce5d71d26f0e8f31ae3683a2a966/src/UriBuilder.php#L263-L268
koolkode/http
src/UriBuilder.php
UriBuilder.setParams
public function setParams(array $params) { $this->path = []; $this->query = []; foreach($params as $k => $v) { if(is_integer($k)) { if(array_key_exists($k, $this->pathParamNames)) { $this->path[$this->pathParamNames[$k]] = $v; continue; } throw new \OutOfBoundsException(sprintf('No path param at position %u', $k)); } if(in_array($k, $this->pathParamNames, true)) { $this->path[$k] = $v; continue; } $this->query[$k] = $v; } return $this; }
php
public function setParams(array $params) { $this->path = []; $this->query = []; foreach($params as $k => $v) { if(is_integer($k)) { if(array_key_exists($k, $this->pathParamNames)) { $this->path[$this->pathParamNames[$k]] = $v; continue; } throw new \OutOfBoundsException(sprintf('No path param at position %u', $k)); } if(in_array($k, $this->pathParamNames, true)) { $this->path[$k] = $v; continue; } $this->query[$k] = $v; } return $this; }
[ "public", "function", "setParams", "(", "array", "$", "params", ")", "{", "$", "this", "->", "path", "=", "[", "]", ";", "$", "this", "->", "query", "=", "[", "]", ";", "foreach", "(", "$", "params", "as", "$", "k", "=>", "$", "v", ")", "{", ...
Removes all param values from path and query and re-populates using the given values. @param array<string, mixed> $params Path and query params to be set. @return UriBuilder
[ "Removes", "all", "param", "values", "from", "path", "and", "query", "and", "re", "-", "populates", "using", "the", "given", "values", "." ]
train
https://github.com/koolkode/http/blob/3c1626d409d5ce5d71d26f0e8f31ae3683a2a966/src/UriBuilder.php#L288-L318
koolkode/http
src/UriBuilder.php
UriBuilder.fragment
public function fragment($fragment) { $this->fragment = ($fragment === NULL || $fragment == '') ? NULL : (string)$fragment; return $this; }
php
public function fragment($fragment) { $this->fragment = ($fragment === NULL || $fragment == '') ? NULL : (string)$fragment; return $this; }
[ "public", "function", "fragment", "(", "$", "fragment", ")", "{", "$", "this", "->", "fragment", "=", "(", "$", "fragment", "===", "NULL", "||", "$", "fragment", "==", "''", ")", "?", "NULL", ":", "(", "string", ")", "$", "fragment", ";", "return", ...
Set or remove the fragment part of this URI. @param string $fragment @return UriBuilder
[ "Set", "or", "remove", "the", "fragment", "part", "of", "this", "URI", "." ]
train
https://github.com/koolkode/http/blob/3c1626d409d5ce5d71d26f0e8f31ae3683a2a966/src/UriBuilder.php#L326-L331
koolkode/http
src/UriBuilder.php
UriBuilder.build
public function build($trailingSlash = false) { $result = ''; foreach(preg_split("'(\\{(?:(?>[^\\{\\}]+)|(?R))+\\})'S", $this->uri, -1, PREG_SPLIT_DELIM_CAPTURE) as $part) { if(substr($part, 0, 1) == '{') { $result .= Uri::encode($this->path[substr($part, 1, -1)]); } else { $result .= $part; } } $result = $this->replaceParams($this->uri, $this->path); if($trailingSlash && substr($result, -1) != '/') { $uri = new Uri($result . '/'); } else { $uri = new Uri($result); } if(!empty($this->query)) { $uri = $uri->setQuery($this->query); } if($this->fragment !== NULL) { if(false === strpos($this->fragment, '{')) { $uri = $uri->setFragment($this->fragment); } else { $uri = $uri->setFragment($this->replaceParams($this->fragment, $this->path)); } } return $uri; }
php
public function build($trailingSlash = false) { $result = ''; foreach(preg_split("'(\\{(?:(?>[^\\{\\}]+)|(?R))+\\})'S", $this->uri, -1, PREG_SPLIT_DELIM_CAPTURE) as $part) { if(substr($part, 0, 1) == '{') { $result .= Uri::encode($this->path[substr($part, 1, -1)]); } else { $result .= $part; } } $result = $this->replaceParams($this->uri, $this->path); if($trailingSlash && substr($result, -1) != '/') { $uri = new Uri($result . '/'); } else { $uri = new Uri($result); } if(!empty($this->query)) { $uri = $uri->setQuery($this->query); } if($this->fragment !== NULL) { if(false === strpos($this->fragment, '{')) { $uri = $uri->setFragment($this->fragment); } else { $uri = $uri->setFragment($this->replaceParams($this->fragment, $this->path)); } } return $uri; }
[ "public", "function", "build", "(", "$", "trailingSlash", "=", "false", ")", "{", "$", "result", "=", "''", ";", "foreach", "(", "preg_split", "(", "\"'(\\\\{(?:(?>[^\\\\{\\\\}]+)|(?R))+\\\\})'S\"", ",", "$", "this", "->", "uri", ",", "-", "1", ",", "PREG_SP...
Build a URI from template and assigned parameters. @param boolean $trailingSlash @return Uri @throws \OutOfBoundsException When at least one path parameter value is missing.
[ "Build", "a", "URI", "from", "template", "and", "assigned", "parameters", "." ]
train
https://github.com/koolkode/http/blob/3c1626d409d5ce5d71d26f0e8f31ae3683a2a966/src/UriBuilder.php#L341-L386
kambalabs/KmbPuppet
src/KmbPuppet/Service/GroupFactory.php
GroupFactory.createService
public function createService(ServiceLocatorInterface $serviceLocator) { $service = new Group(); /** @var Environment $environmentService */ $environmentService = $serviceLocator->get('KmbPuppet\Service\Environment'); $service->setEnvironmentService($environmentService); return $service; }
php
public function createService(ServiceLocatorInterface $serviceLocator) { $service = new Group(); /** @var Environment $environmentService */ $environmentService = $serviceLocator->get('KmbPuppet\Service\Environment'); $service->setEnvironmentService($environmentService); return $service; }
[ "public", "function", "createService", "(", "ServiceLocatorInterface", "$", "serviceLocator", ")", "{", "$", "service", "=", "new", "Group", "(", ")", ";", "/** @var Environment $environmentService */", "$", "environmentService", "=", "$", "serviceLocator", "->", "get...
Create service @param ServiceLocatorInterface $serviceLocator @return mixed
[ "Create", "service" ]
train
https://github.com/kambalabs/KmbPuppet/blob/b97a0d2077085df4933c6b3cda9e41468bf7ffca/src/KmbPuppet/Service/GroupFactory.php#L34-L43
phpffcms/ffcms-core
src/Helper/Type/Integer.php
Integer.random
public static function random(int $sequence): ?int { $start = pow(10, $sequence - 1); $end = pow(10, $sequence); return mt_rand($start, $end); }
php
public static function random(int $sequence): ?int { $start = pow(10, $sequence - 1); $end = pow(10, $sequence); return mt_rand($start, $end); }
[ "public", "static", "function", "random", "(", "int", "$", "sequence", ")", ":", "?", "int", "{", "$", "start", "=", "pow", "(", "10", ",", "$", "sequence", "-", "1", ")", ";", "$", "end", "=", "pow", "(", "10", ",", "$", "sequence", ")", ";", ...
Random Integer with $sequence. Ex: randomInt(2) = 1..9 * 10 ^ 2 @param int $sequence - sequence of random calculation @return int
[ "Random", "Integer", "with", "$sequence", ".", "Ex", ":", "randomInt", "(", "2", ")", "=", "1", "..", "9", "*", "10", "^", "2" ]
train
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/Type/Integer.php#L18-L23
shgysk8zer0/core_api
traits/console.php
Console._formatLocation
final protected function _formatLocation($file, $line, $format = self::LOG_FORMAT) { return sprintf($format, $file, $line); }
php
final protected function _formatLocation($file, $line, $format = self::LOG_FORMAT) { return sprintf($format, $file, $line); }
[ "final", "protected", "function", "_formatLocation", "(", "$", "file", ",", "$", "line", ",", "$", "format", "=", "self", "::", "LOG_FORMAT", ")", "{", "return", "sprintf", "(", "$", "format", ",", "$", "file", ",", "$", "line", ")", ";", "}" ]
formats the location from backtrace using sprintf @param string $file the file the log was created in @param int $line the line the log was created on @param string $format output format @return string location formatted according to $format
[ "formats", "the", "location", "from", "backtrace", "using", "sprintf" ]
train
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/console.php#L154-L157
shgysk8zer0/core_api
traits/console.php
Console._log
final protected function _log($type, array $args) { // nothing passed in, don't do anything if (count($args) === 0 && $type !== self::GROUP_END) { return; } $this->_processed = array(); $logs = array_map([$this, '_convert'], $args); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 4); $backtrace_message = 'unknown'; $backtrace = end($backtrace); if (isset($backtrace['file'], $backtrace['line'])) { $backtrace_message = $this->_formatLocation( $backtrace['file'], $backtrace['line'] ); } $this->_addRow($logs, $backtrace_message, $type); }
php
final protected function _log($type, array $args) { // nothing passed in, don't do anything if (count($args) === 0 && $type !== self::GROUP_END) { return; } $this->_processed = array(); $logs = array_map([$this, '_convert'], $args); $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 4); $backtrace_message = 'unknown'; $backtrace = end($backtrace); if (isset($backtrace['file'], $backtrace['line'])) { $backtrace_message = $this->_formatLocation( $backtrace['file'], $backtrace['line'] ); } $this->_addRow($logs, $backtrace_message, $type); }
[ "final", "protected", "function", "_log", "(", "$", "type", ",", "array", "$", "args", ")", "{", "// nothing passed in, don't do anything", "if", "(", "count", "(", "$", "args", ")", "===", "0", "&&", "$", "type", "!==", "self", "::", "GROUP_END", ")", "...
internal logging call @param string $type @return void
[ "internal", "logging", "call" ]
train
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/console.php#L165-L184
shgysk8zer0/core_api
traits/console.php
Console._convert
final protected function _convert($object) { // if this isn't an object then just return it if (!is_object($object)) { return $object; } //Mark this object as processed so we don't convert it twice and it //Also avoid recursion when objects refer to each other $this->_processed[] = $object; $object_as_array = array(); // first add the class name $object_as_array['___class_name'] = get_class($object); // loop through object vars $object_vars = get_object_vars($object); foreach ($object_vars as $key => $value) { // same instance as parent object if ($value === $object || in_array($value, $this->_processed, true)) { $value = 'recursion - parent object [' . get_class($value) . ']'; } $object_as_array[$key] = $this->_convert($value); } $reflection = new \ReflectionClass($object); // loop through the properties and add those foreach ($reflection->getProperties() as $property) { // if one of these properties was already added above then ignore it if (array_key_exists($property->getName(), $object_vars)) { continue; } $type = $this->_getPropertyKey($property); if ($this->_php_version >= 5.3) { $property->setAccessible(true); } try { $value = $property->getValue($object); } catch (\ReflectionException $e) { $value = 'only PHP 5.3 can access private/protected properties'; } // same instance as parent object if ($value === $object || in_array($value, $this->_processed, true)) { $value = 'recursion - parent object [' . get_class($value) . ']'; } $object_as_array[$type] = $this->_convert($value); } return $object_as_array; }
php
final protected function _convert($object) { // if this isn't an object then just return it if (!is_object($object)) { return $object; } //Mark this object as processed so we don't convert it twice and it //Also avoid recursion when objects refer to each other $this->_processed[] = $object; $object_as_array = array(); // first add the class name $object_as_array['___class_name'] = get_class($object); // loop through object vars $object_vars = get_object_vars($object); foreach ($object_vars as $key => $value) { // same instance as parent object if ($value === $object || in_array($value, $this->_processed, true)) { $value = 'recursion - parent object [' . get_class($value) . ']'; } $object_as_array[$key] = $this->_convert($value); } $reflection = new \ReflectionClass($object); // loop through the properties and add those foreach ($reflection->getProperties() as $property) { // if one of these properties was already added above then ignore it if (array_key_exists($property->getName(), $object_vars)) { continue; } $type = $this->_getPropertyKey($property); if ($this->_php_version >= 5.3) { $property->setAccessible(true); } try { $value = $property->getValue($object); } catch (\ReflectionException $e) { $value = 'only PHP 5.3 can access private/protected properties'; } // same instance as parent object if ($value === $object || in_array($value, $this->_processed, true)) { $value = 'recursion - parent object [' . get_class($value) . ']'; } $object_as_array[$type] = $this->_convert($value); } return $object_as_array; }
[ "final", "protected", "function", "_convert", "(", "$", "object", ")", "{", "// if this isn't an object then just return it", "if", "(", "!", "is_object", "(", "$", "object", ")", ")", "{", "return", "$", "object", ";", "}", "//Mark this object as processed so we do...
converts an object to a better format for logging @param Object @return array
[ "converts", "an", "object", "to", "a", "better", "format", "for", "logging" ]
train
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/console.php#L192-L236
shgysk8zer0/core_api
traits/console.php
Console._getPropertyKey
final protected function _getPropertyKey(\ReflectionProperty $property) { $static = $property->isStatic() ? ' static' : ''; if ($property->isPublic()) { return 'public' . $static . ' ' . $property->getName(); } if ($property->isProtected()) { return 'protected' . $static . ' ' . $property->getName(); } if ($property->isPrivate()) { return 'private' . $static . ' ' . $property->getName(); } }
php
final protected function _getPropertyKey(\ReflectionProperty $property) { $static = $property->isStatic() ? ' static' : ''; if ($property->isPublic()) { return 'public' . $static . ' ' . $property->getName(); } if ($property->isProtected()) { return 'protected' . $static . ' ' . $property->getName(); } if ($property->isPrivate()) { return 'private' . $static . ' ' . $property->getName(); } }
[ "final", "protected", "function", "_getPropertyKey", "(", "\\", "ReflectionProperty", "$", "property", ")", "{", "$", "static", "=", "$", "property", "->", "isStatic", "(", ")", "?", "' static'", ":", "''", ";", "if", "(", "$", "property", "->", "isPublic"...
takes a reflection property and returns a nicely formatted key of the property name @param ReflectionProperty @return string
[ "takes", "a", "reflection", "property", "and", "returns", "a", "nicely", "formatted", "key", "of", "the", "property", "name" ]
train
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/console.php#L244-L256
shgysk8zer0/core_api
traits/console.php
Console._addRow
final protected function _addRow(array $logs, $backtrace, $type) { // if this is logged on the same line for example in a loop, set it to null to save space if (in_array($backtrace, $this->_backtraces)) { $backtrace = null; } // for group, groupEnd, and groupCollapsed // take out the backtrace since it is not useful if ($type === self::GROUP || $type === self::GROUP_END || $type === self::GROUP_COLLAPSED) { $backtrace = null; } if (isset($backtrace)) { $this->_backtraces[] = $backtrace; } array_push($this->_json['rows'], array($logs, $backtrace, $type)); }
php
final protected function _addRow(array $logs, $backtrace, $type) { // if this is logged on the same line for example in a loop, set it to null to save space if (in_array($backtrace, $this->_backtraces)) { $backtrace = null; } // for group, groupEnd, and groupCollapsed // take out the backtrace since it is not useful if ($type === self::GROUP || $type === self::GROUP_END || $type === self::GROUP_COLLAPSED) { $backtrace = null; } if (isset($backtrace)) { $this->_backtraces[] = $backtrace; } array_push($this->_json['rows'], array($logs, $backtrace, $type)); }
[ "final", "protected", "function", "_addRow", "(", "array", "$", "logs", ",", "$", "backtrace", ",", "$", "type", ")", "{", "// if this is logged on the same line for example in a loop, set it to null to save space", "if", "(", "in_array", "(", "$", "backtrace", ",", "...
adds a value to the data array @var mixed @return void
[ "adds", "a", "value", "to", "the", "data", "array" ]
train
https://github.com/shgysk8zer0/core_api/blob/9e9b8baf761af874b95256ad2462e55fbb2b2e58/traits/console.php#L264-L279
OxfordInfoLabs/kinikit-core
src/Util/Caching/CachingHeaders.php
CachingHeaders.addCachingHeaders
public function addCachingHeaders($numberOfMinutes = 60, $mustRevalidate = true) { // Add cache control header if revalidate $numberOfSeconds = $numberOfMinutes * 60; $header = "Cache-Control: public, max-age=" . ($numberOfSeconds); if ($mustRevalidate) $header .= ", must-revalidate"; header($header); // Add the Expires header. $expStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $numberOfSeconds) . " GMT"; header($expStr); // Add the last modified header. $lastModified = "Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT"; header($lastModified); header_remove("Pragma"); $etag = '"' . filemtime(__FILE__) . '.' . date("U") . '"'; header("ETag: $etag"); }
php
public function addCachingHeaders($numberOfMinutes = 60, $mustRevalidate = true) { // Add cache control header if revalidate $numberOfSeconds = $numberOfMinutes * 60; $header = "Cache-Control: public, max-age=" . ($numberOfSeconds); if ($mustRevalidate) $header .= ", must-revalidate"; header($header); // Add the Expires header. $expStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $numberOfSeconds) . " GMT"; header($expStr); // Add the last modified header. $lastModified = "Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT"; header($lastModified); header_remove("Pragma"); $etag = '"' . filemtime(__FILE__) . '.' . date("U") . '"'; header("ETag: $etag"); }
[ "public", "function", "addCachingHeaders", "(", "$", "numberOfMinutes", "=", "60", ",", "$", "mustRevalidate", "=", "true", ")", "{", "// Add cache control header if revalidate", "$", "numberOfSeconds", "=", "$", "numberOfMinutes", "*", "60", ";", "$", "header", "...
Add caching headers to the current request.
[ "Add", "caching", "headers", "to", "the", "current", "request", "." ]
train
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/Caching/CachingHeaders.php#L43-L67
Kris-Kuiper/sFire-Framework
src/Validator/Form/Rules/Equals.php
Equals.check
private function check($value, $params) { return true === ($this -> strict === true ? ($value === $params[0]) : ($value == $params[0])); }
php
private function check($value, $params) { return true === ($this -> strict === true ? ($value === $params[0]) : ($value == $params[0])); }
[ "private", "function", "check", "(", "$", "value", ",", "$", "params", ")", "{", "return", "true", "===", "(", "$", "this", "->", "strict", "===", "true", "?", "(", "$", "value", "===", "$", "params", "[", "0", "]", ")", ":", "(", "$", "value", ...
Check if rule passes @param mixed $value @param array $params @return boolean
[ "Check", "if", "rule", "passes" ]
train
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Validator/Form/Rules/Equals.php#L75-L77
freialib/freia.autoloader
src/SymbolEnvironment.php
SymbolEnvironment.loadModules
function loadModules($searchPaths, $maxdepth) { $modules = []; // Final all modules // ================= $idx = 0; // module order index $knownSegments = []; foreach ($searchPaths as $path) { $loadpath = $this->syspath.'/'.$path; $files = $this->find_file('composer.json', $loadpath, $maxdepth); foreach ($files as $file) { $composerjson = \json_decode($this->file_get_contents($file->getRealPath()), true); if ($this->composer_has_cfsinfo($composerjson)) { $moduleName = $composerjson['name']; // backwards compatibility $moduleName = \str_replace('.', '/', $moduleName); $this->state['modules'][$moduleName] = [ 'idx' => null, 'enabled' => true, 'path' => realpath($file->getPath()), 'namespace' => \str_replace('/', '\\', $moduleName).'\\', 'rules' => [ 'identity' => [], 'matches-before' => [] ] ]; $slashPos = \strpos($moduleName, '/'); if ($slashPos === false || $slashPos == 0) { throw new \Exception('Invalid freia module name ['.$moduleName.']. The module name must have at least two segments seperated by a slash'); } $mainsegment = \substr($moduleName, 0, $slashPos); if ( ! \in_array($mainsegment, $knownSegments)) { $knownSegments[] = $mainsegment; } // create entry in ordering index for rules reference $modules[$moduleName] = $idx += 1; if (isset($composerjson['extra'], $composerjson['extra']['freia'], $composerjson['extra']['freia']['rules'])) { $this->state['modules'][$moduleName]['rules'] = array_merge($this->state['modules'][$moduleName]['rules'], $composerjson['extra']['freia']['rules']); if ( ! $this->debugMode) { if (in_array('debug', $this->state['modules'][$moduleName]['rules']['identity'])) { $this->state['modules'][$moduleName]['enabled'] = false; } } } } } } $this->state['known-segments'] = $knownSegments; // Apply Stacking Rules // ==================== $iteration = 0; do { // Sanity Check // ------------ # it's entirely poissible for recursive rules to be applied, so we # need to have a stop mechanism; the system will try to function # even if recursion is detected; but a warning will be shown $iteration += 1; if ($iteration == $this->maxRulesIterations()) { $this->error_log("Exceeded maximum rule iteration count; potentially recursive module ruleset"); throw new \Exception("Exceeded maximum iterations count while trying to apply module rules; potential module recursive rules"); } // Sorter // ------ $ordered = true; $ordered_modules = $modules; foreach ($this->state['modules'] as $moduleName => $module) { foreach ($module['rules']['matches-before'] as $target) { # matches-before: this module recieves idx of top # matching target -1 and all other modules aside from # this module who have idx < target idx recieve -1, # all entries with idx > old module idx recieve -1; if # target is not found in the modules or if the idx is # already smaller then the entire operation is skipped # and everyting retains their current idx $targetmodulename = static::firstMatchingModule(\array_keys($ordered_modules), $target); if ($targetmodulename !== null) { $target_idx = $ordered_modules[$targetmodulename]; if ($target_idx < $ordered_modules[$module]) { $updated_modules = $ordered_modules; $old_module_idx = $updated_modules[$module]; $updated_modules[$module] = $updated_modules[$targetmodulename] - 1; foreach ($ordered_modules as $k => $idx) { if ($idx < $target_idx && $k != $module) { $updated_modules[$k] = $idx - 1; } else if ($idx > $old_module_idx) { $updated_modules[$k] = $idx - 1; } } asort($updated_modules); $ordered_modules = $updated_modules; $ordered = false; } } } } $modules = $ordered_modules; } while ( ! $ordered); // Integrate Updated Order // ======================= $updatedModules = []; foreach ($modules as $moduleName => $idx) { $updatedModules[$moduleName] = $this->state['modules'][$moduleName]; $updatedModules[$moduleName]['idx'] = $idx; } $this->state['modules'] = $updatedModules; }
php
function loadModules($searchPaths, $maxdepth) { $modules = []; // Final all modules // ================= $idx = 0; // module order index $knownSegments = []; foreach ($searchPaths as $path) { $loadpath = $this->syspath.'/'.$path; $files = $this->find_file('composer.json', $loadpath, $maxdepth); foreach ($files as $file) { $composerjson = \json_decode($this->file_get_contents($file->getRealPath()), true); if ($this->composer_has_cfsinfo($composerjson)) { $moduleName = $composerjson['name']; // backwards compatibility $moduleName = \str_replace('.', '/', $moduleName); $this->state['modules'][$moduleName] = [ 'idx' => null, 'enabled' => true, 'path' => realpath($file->getPath()), 'namespace' => \str_replace('/', '\\', $moduleName).'\\', 'rules' => [ 'identity' => [], 'matches-before' => [] ] ]; $slashPos = \strpos($moduleName, '/'); if ($slashPos === false || $slashPos == 0) { throw new \Exception('Invalid freia module name ['.$moduleName.']. The module name must have at least two segments seperated by a slash'); } $mainsegment = \substr($moduleName, 0, $slashPos); if ( ! \in_array($mainsegment, $knownSegments)) { $knownSegments[] = $mainsegment; } // create entry in ordering index for rules reference $modules[$moduleName] = $idx += 1; if (isset($composerjson['extra'], $composerjson['extra']['freia'], $composerjson['extra']['freia']['rules'])) { $this->state['modules'][$moduleName]['rules'] = array_merge($this->state['modules'][$moduleName]['rules'], $composerjson['extra']['freia']['rules']); if ( ! $this->debugMode) { if (in_array('debug', $this->state['modules'][$moduleName]['rules']['identity'])) { $this->state['modules'][$moduleName]['enabled'] = false; } } } } } } $this->state['known-segments'] = $knownSegments; // Apply Stacking Rules // ==================== $iteration = 0; do { // Sanity Check // ------------ # it's entirely poissible for recursive rules to be applied, so we # need to have a stop mechanism; the system will try to function # even if recursion is detected; but a warning will be shown $iteration += 1; if ($iteration == $this->maxRulesIterations()) { $this->error_log("Exceeded maximum rule iteration count; potentially recursive module ruleset"); throw new \Exception("Exceeded maximum iterations count while trying to apply module rules; potential module recursive rules"); } // Sorter // ------ $ordered = true; $ordered_modules = $modules; foreach ($this->state['modules'] as $moduleName => $module) { foreach ($module['rules']['matches-before'] as $target) { # matches-before: this module recieves idx of top # matching target -1 and all other modules aside from # this module who have idx < target idx recieve -1, # all entries with idx > old module idx recieve -1; if # target is not found in the modules or if the idx is # already smaller then the entire operation is skipped # and everyting retains their current idx $targetmodulename = static::firstMatchingModule(\array_keys($ordered_modules), $target); if ($targetmodulename !== null) { $target_idx = $ordered_modules[$targetmodulename]; if ($target_idx < $ordered_modules[$module]) { $updated_modules = $ordered_modules; $old_module_idx = $updated_modules[$module]; $updated_modules[$module] = $updated_modules[$targetmodulename] - 1; foreach ($ordered_modules as $k => $idx) { if ($idx < $target_idx && $k != $module) { $updated_modules[$k] = $idx - 1; } else if ($idx > $old_module_idx) { $updated_modules[$k] = $idx - 1; } } asort($updated_modules); $ordered_modules = $updated_modules; $ordered = false; } } } } $modules = $ordered_modules; } while ( ! $ordered); // Integrate Updated Order // ======================= $updatedModules = []; foreach ($modules as $moduleName => $idx) { $updatedModules[$moduleName] = $this->state['modules'][$moduleName]; $updatedModules[$moduleName]['idx'] = $idx; } $this->state['modules'] = $updatedModules; }
[ "function", "loadModules", "(", "$", "searchPaths", ",", "$", "maxdepth", ")", "{", "$", "modules", "=", "[", "]", ";", "// Final all modules", "// =================", "$", "idx", "=", "0", ";", "// module order index", "$", "knownSegments", "=", "[", "]", "...
Search given paths and load modules into the current state
[ "Search", "given", "paths", "and", "load", "modules", "into", "the", "current", "state" ]
train
https://github.com/freialib/freia.autoloader/blob/45e0dfcd56d55cf533f12255db647e8a05fcd494/src/SymbolEnvironment.php#L147-L287
freialib/freia.autoloader
src/SymbolEnvironment.php
SymbolEnvironment.firstMatchingModule
protected static function firstMatchingModule($module_names, $target) { foreach ($module_names as $module) { if (stripos($module, $target) !== false) { return $module; } } }
php
protected static function firstMatchingModule($module_names, $target) { foreach ($module_names as $module) { if (stripos($module, $target) !== false) { return $module; } } }
[ "protected", "static", "function", "firstMatchingModule", "(", "$", "module_names", ",", "$", "target", ")", "{", "foreach", "(", "$", "module_names", "as", "$", "module", ")", "{", "if", "(", "stripos", "(", "$", "module", ",", "$", "target", ")", "!=="...
[matches-before] rule helper function @return string name
[ "[", "matches", "-", "before", "]", "rule", "helper", "function" ]
train
https://github.com/freialib/freia.autoloader/blob/45e0dfcd56d55cf533f12255db647e8a05fcd494/src/SymbolEnvironment.php#L294-L300