repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
expectation-php/expect
src/matcher/ToContain.php
ToContain.reportFailed
public function reportFailed(FailedMessage $message) { $unmatchResults = $this->matchResult->getUnmatchResults(); $message->appendText('Expected ') ->appendText($this->type) ->appendText(' to contain ') ->appendValues($unmatchResults); }
php
public function reportFailed(FailedMessage $message) { $unmatchResults = $this->matchResult->getUnmatchResults(); $message->appendText('Expected ') ->appendText($this->type) ->appendText(' to contain ') ->appendValues($unmatchResults); }
[ "public", "function", "reportFailed", "(", "FailedMessage", "$", "message", ")", "{", "$", "unmatchResults", "=", "$", "this", "->", "matchResult", "->", "getUnmatchResults", "(", ")", ";", "$", "message", "->", "appendText", "(", "'Expected '", ")", "->", "appendText", "(", "$", "this", "->", "type", ")", "->", "appendText", "(", "' to contain '", ")", "->", "appendValues", "(", "$", "unmatchResults", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/expectation-php/expect/blob/1a32c5af37f3dc8dabe4e8eedeeb21aea16ce139/src/matcher/ToContain.php#L81-L89
expectation-php/expect
src/matcher/ToContain.php
ToContain.reportNegativeFailed
public function reportNegativeFailed(FailedMessage $message) { $matchResults = $this->matchResult->getMatchResults(); $message->appendText('Expected ') ->appendText($this->type) ->appendText(' not to contain ') ->appendValues($matchResults); }
php
public function reportNegativeFailed(FailedMessage $message) { $matchResults = $this->matchResult->getMatchResults(); $message->appendText('Expected ') ->appendText($this->type) ->appendText(' not to contain ') ->appendValues($matchResults); }
[ "public", "function", "reportNegativeFailed", "(", "FailedMessage", "$", "message", ")", "{", "$", "matchResults", "=", "$", "this", "->", "matchResult", "->", "getMatchResults", "(", ")", ";", "$", "message", "->", "appendText", "(", "'Expected '", ")", "->", "appendText", "(", "$", "this", "->", "type", ")", "->", "appendText", "(", "' not to contain '", ")", "->", "appendValues", "(", "$", "matchResults", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/expectation-php/expect/blob/1a32c5af37f3dc8dabe4e8eedeeb21aea16ce139/src/matcher/ToContain.php#L94-L102
CalderaWP/metaplate-core
src/render.php
render.render_metaplate
public function render_metaplate( $content, $meta_stack = null, $template_data = null, $placement = null ) { if ( is_null( $meta_stack ) ) { $meta_stack = data::get_active_metaplates(); } // clear out <!--metaplate--> $content = str_replace( '<p><!--metaplate--></p>', '', $content ); // in case the wpautop didnt detect the tag. $content = str_replace( '<!--metaplate-->', '', $content ); if( empty( $meta_stack ) ){ return $content; } if ( is_null( $template_data ) ) { global $post; if( caldera_metaplate_pods_mode() ) { $instance_id = $template_data[ 'ID' ]; }else{ $instance_id = $post->ID; $template_data = data::get_custom_field_data( $post->ID ); } }else{ $instance_id = md5( json_encode( (array) $template_data ) ); } // setup the instance record if( !isset( $this->rendered_posts[ $instance_id ] ) ){ $this->rendered_posts[ $instance_id ] = array(); } if( ! $template_data || empty( $template_data ) ){ return $content; } // unserilize if needed. if ( true != caldera_metaplate_pods_mode() ) { foreach ( $template_data as &$meta_item ) { $meta_item = maybe_unserialize( $meta_item ); } } // add filter. $magic = new filter\magictag(); $content = $magic->do_magic_tag( trim( $content ) ); $style_data = null; $script_data = null; $engine = new Handlebars; $engine = $this->helpers( $engine ); foreach( $meta_stack as $metaplate ){ if( ! isset( $metaplate[ 'id' ] ) ) { $metaplate[ 'id' ] = md5( json_encode( (array) $template_data ) ); } // add metaplate_id to rendered plates for this post if( isset( $this->rendered_posts[ $instance_id ] ) ){ if( ! empty( $this->rendered_posts[ $instance_id ][ $metaplate['id'] ] ) ){ continue; } $this->rendered_posts[ $instance_id ][ $metaplate['id'] ] = true; } // apply filter to data for this metaplate $template_data = apply_filters( 'metaplate_data', $template_data, $metaplate ); // check CSS if ( isset( $metaplate[ 'css' ][ 'code' ] ) ) { $style_data .= $engine->render( $metaplate['css']['code'], $template_data ); } else { $style_data = ''; } if ( isset( $metaplate['js']['code'] ) ) { // check JS $script_data .= $engine->render( $metaplate['js']['code'], $template_data ); } else { $script_data = ''; } if ( ! is_null( $placement ) ) { $metaplate[ 'placement' ] = $placement; } if ( ! isset( $metaplate['placement'] ) || ! in_array( $metaplate['placement'], array( 'prepend', 'append', 'replace' ) ) ) { $metaplate['placement'] = false; } $template = $metaplate[ 'html' ][ 'code' ]; switch ( $metaplate['placement'] ){ case 'prepend': $content = $engine->render( $template, $template_data ) . $content; break; case 'append': $content .= $engine->render( $template, $template_data ); break; case 'replace': $content = $engine->render( str_replace( '{{content}}', $content, $template ), $template_data ); break; default : $content = $engine->render( str_replace( '{{content}}', $content, $template ), $template_data ); } } // insert CSS if( ! empty( $style_data ) ){ $content = '<style>' . $style_data . '</style>' . $content; } // insert JS if( ! empty( $script_data ) ){ $content .= '<script type="text/javascript">' . $script_data . '</script>'; } // add magic filter. $magic = new filter\magictag(); $content = $magic->do_magic_tag( $content ); return $content; }
php
public function render_metaplate( $content, $meta_stack = null, $template_data = null, $placement = null ) { if ( is_null( $meta_stack ) ) { $meta_stack = data::get_active_metaplates(); } // clear out <!--metaplate--> $content = str_replace( '<p><!--metaplate--></p>', '', $content ); // in case the wpautop didnt detect the tag. $content = str_replace( '<!--metaplate-->', '', $content ); if( empty( $meta_stack ) ){ return $content; } if ( is_null( $template_data ) ) { global $post; if( caldera_metaplate_pods_mode() ) { $instance_id = $template_data[ 'ID' ]; }else{ $instance_id = $post->ID; $template_data = data::get_custom_field_data( $post->ID ); } }else{ $instance_id = md5( json_encode( (array) $template_data ) ); } // setup the instance record if( !isset( $this->rendered_posts[ $instance_id ] ) ){ $this->rendered_posts[ $instance_id ] = array(); } if( ! $template_data || empty( $template_data ) ){ return $content; } // unserilize if needed. if ( true != caldera_metaplate_pods_mode() ) { foreach ( $template_data as &$meta_item ) { $meta_item = maybe_unserialize( $meta_item ); } } // add filter. $magic = new filter\magictag(); $content = $magic->do_magic_tag( trim( $content ) ); $style_data = null; $script_data = null; $engine = new Handlebars; $engine = $this->helpers( $engine ); foreach( $meta_stack as $metaplate ){ if( ! isset( $metaplate[ 'id' ] ) ) { $metaplate[ 'id' ] = md5( json_encode( (array) $template_data ) ); } // add metaplate_id to rendered plates for this post if( isset( $this->rendered_posts[ $instance_id ] ) ){ if( ! empty( $this->rendered_posts[ $instance_id ][ $metaplate['id'] ] ) ){ continue; } $this->rendered_posts[ $instance_id ][ $metaplate['id'] ] = true; } // apply filter to data for this metaplate $template_data = apply_filters( 'metaplate_data', $template_data, $metaplate ); // check CSS if ( isset( $metaplate[ 'css' ][ 'code' ] ) ) { $style_data .= $engine->render( $metaplate['css']['code'], $template_data ); } else { $style_data = ''; } if ( isset( $metaplate['js']['code'] ) ) { // check JS $script_data .= $engine->render( $metaplate['js']['code'], $template_data ); } else { $script_data = ''; } if ( ! is_null( $placement ) ) { $metaplate[ 'placement' ] = $placement; } if ( ! isset( $metaplate['placement'] ) || ! in_array( $metaplate['placement'], array( 'prepend', 'append', 'replace' ) ) ) { $metaplate['placement'] = false; } $template = $metaplate[ 'html' ][ 'code' ]; switch ( $metaplate['placement'] ){ case 'prepend': $content = $engine->render( $template, $template_data ) . $content; break; case 'append': $content .= $engine->render( $template, $template_data ); break; case 'replace': $content = $engine->render( str_replace( '{{content}}', $content, $template ), $template_data ); break; default : $content = $engine->render( str_replace( '{{content}}', $content, $template ), $template_data ); } } // insert CSS if( ! empty( $style_data ) ){ $content = '<style>' . $style_data . '</style>' . $content; } // insert JS if( ! empty( $script_data ) ){ $content .= '<script type="text/javascript">' . $script_data . '</script>'; } // add magic filter. $magic = new filter\magictag(); $content = $magic->do_magic_tag( $content ); return $content; }
[ "public", "function", "render_metaplate", "(", "$", "content", ",", "$", "meta_stack", "=", "null", ",", "$", "template_data", "=", "null", ",", "$", "placement", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "meta_stack", ")", ")", "{", "$", "meta_stack", "=", "data", "::", "get_active_metaplates", "(", ")", ";", "}", "// clear out <!--metaplate-->", "$", "content", "=", "str_replace", "(", "'<p><!--metaplate--></p>'", ",", "''", ",", "$", "content", ")", ";", "// in case the wpautop didnt detect the tag.", "$", "content", "=", "str_replace", "(", "'<!--metaplate-->'", ",", "''", ",", "$", "content", ")", ";", "if", "(", "empty", "(", "$", "meta_stack", ")", ")", "{", "return", "$", "content", ";", "}", "if", "(", "is_null", "(", "$", "template_data", ")", ")", "{", "global", "$", "post", ";", "if", "(", "caldera_metaplate_pods_mode", "(", ")", ")", "{", "$", "instance_id", "=", "$", "template_data", "[", "'ID'", "]", ";", "}", "else", "{", "$", "instance_id", "=", "$", "post", "->", "ID", ";", "$", "template_data", "=", "data", "::", "get_custom_field_data", "(", "$", "post", "->", "ID", ")", ";", "}", "}", "else", "{", "$", "instance_id", "=", "md5", "(", "json_encode", "(", "(", "array", ")", "$", "template_data", ")", ")", ";", "}", "// setup the instance record", "if", "(", "!", "isset", "(", "$", "this", "->", "rendered_posts", "[", "$", "instance_id", "]", ")", ")", "{", "$", "this", "->", "rendered_posts", "[", "$", "instance_id", "]", "=", "array", "(", ")", ";", "}", "if", "(", "!", "$", "template_data", "||", "empty", "(", "$", "template_data", ")", ")", "{", "return", "$", "content", ";", "}", "// unserilize if needed.", "if", "(", "true", "!=", "caldera_metaplate_pods_mode", "(", ")", ")", "{", "foreach", "(", "$", "template_data", "as", "&", "$", "meta_item", ")", "{", "$", "meta_item", "=", "maybe_unserialize", "(", "$", "meta_item", ")", ";", "}", "}", "// add filter.", "$", "magic", "=", "new", "filter", "\\", "magictag", "(", ")", ";", "$", "content", "=", "$", "magic", "->", "do_magic_tag", "(", "trim", "(", "$", "content", ")", ")", ";", "$", "style_data", "=", "null", ";", "$", "script_data", "=", "null", ";", "$", "engine", "=", "new", "Handlebars", ";", "$", "engine", "=", "$", "this", "->", "helpers", "(", "$", "engine", ")", ";", "foreach", "(", "$", "meta_stack", "as", "$", "metaplate", ")", "{", "if", "(", "!", "isset", "(", "$", "metaplate", "[", "'id'", "]", ")", ")", "{", "$", "metaplate", "[", "'id'", "]", "=", "md5", "(", "json_encode", "(", "(", "array", ")", "$", "template_data", ")", ")", ";", "}", "// add metaplate_id to rendered plates for this post", "if", "(", "isset", "(", "$", "this", "->", "rendered_posts", "[", "$", "instance_id", "]", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "rendered_posts", "[", "$", "instance_id", "]", "[", "$", "metaplate", "[", "'id'", "]", "]", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "rendered_posts", "[", "$", "instance_id", "]", "[", "$", "metaplate", "[", "'id'", "]", "]", "=", "true", ";", "}", "// apply filter to data for this metaplate", "$", "template_data", "=", "apply_filters", "(", "'metaplate_data'", ",", "$", "template_data", ",", "$", "metaplate", ")", ";", "// check CSS", "if", "(", "isset", "(", "$", "metaplate", "[", "'css'", "]", "[", "'code'", "]", ")", ")", "{", "$", "style_data", ".=", "$", "engine", "->", "render", "(", "$", "metaplate", "[", "'css'", "]", "[", "'code'", "]", ",", "$", "template_data", ")", ";", "}", "else", "{", "$", "style_data", "=", "''", ";", "}", "if", "(", "isset", "(", "$", "metaplate", "[", "'js'", "]", "[", "'code'", "]", ")", ")", "{", "// check JS", "$", "script_data", ".=", "$", "engine", "->", "render", "(", "$", "metaplate", "[", "'js'", "]", "[", "'code'", "]", ",", "$", "template_data", ")", ";", "}", "else", "{", "$", "script_data", "=", "''", ";", "}", "if", "(", "!", "is_null", "(", "$", "placement", ")", ")", "{", "$", "metaplate", "[", "'placement'", "]", "=", "$", "placement", ";", "}", "if", "(", "!", "isset", "(", "$", "metaplate", "[", "'placement'", "]", ")", "||", "!", "in_array", "(", "$", "metaplate", "[", "'placement'", "]", ",", "array", "(", "'prepend'", ",", "'append'", ",", "'replace'", ")", ")", ")", "{", "$", "metaplate", "[", "'placement'", "]", "=", "false", ";", "}", "$", "template", "=", "$", "metaplate", "[", "'html'", "]", "[", "'code'", "]", ";", "switch", "(", "$", "metaplate", "[", "'placement'", "]", ")", "{", "case", "'prepend'", ":", "$", "content", "=", "$", "engine", "->", "render", "(", "$", "template", ",", "$", "template_data", ")", ".", "$", "content", ";", "break", ";", "case", "'append'", ":", "$", "content", ".=", "$", "engine", "->", "render", "(", "$", "template", ",", "$", "template_data", ")", ";", "break", ";", "case", "'replace'", ":", "$", "content", "=", "$", "engine", "->", "render", "(", "str_replace", "(", "'{{content}}'", ",", "$", "content", ",", "$", "template", ")", ",", "$", "template_data", ")", ";", "break", ";", "default", ":", "$", "content", "=", "$", "engine", "->", "render", "(", "str_replace", "(", "'{{content}}'", ",", "$", "content", ",", "$", "template", ")", ",", "$", "template_data", ")", ";", "}", "}", "// insert CSS", "if", "(", "!", "empty", "(", "$", "style_data", ")", ")", "{", "$", "content", "=", "'<style>'", ".", "$", "style_data", ".", "'</style>'", ".", "$", "content", ";", "}", "// insert JS", "if", "(", "!", "empty", "(", "$", "script_data", ")", ")", "{", "$", "content", ".=", "'<script type=\"text/javascript\">'", ".", "$", "script_data", ".", "'</script>'", ";", "}", "// add magic filter.", "$", "magic", "=", "new", "filter", "\\", "magictag", "(", ")", ";", "$", "content", "=", "$", "magic", "->", "do_magic_tag", "(", "$", "content", ")", ";", "return", "$", "content", ";", "}" ]
Return the content with metaplate applied. @uses "the_content" filter @param string $content Post content @param array|null $meta_stalk Optional. The metaplate to use to render the data. If is null, the default, one will be load, if possible, based on current global $post object. @param array|null $template_data Optional. Prepared field data to render metaplate with. If is null, the default, meta stalk will be retrieved, if possible, based on current global $post object. @param string|null $placement Optional. Where to put the template output, before, after or in place of $content. If is null, option from metaplate is used. Default is--funcitonally speaking--replace. Options: prepend|append|replace|null. @return string Rendered HTML with templates applied--if templates and data were provided.
[ "Return", "the", "content", "with", "metaplate", "applied", "." ]
train
https://github.com/CalderaWP/metaplate-core/blob/15ede9c4250ab23112a32f8e45d5393f8278bbb8/src/render.php#L38-L172
CalderaWP/metaplate-core
src/render.php
render.helpers
private function helpers( $handlebars ) { $helpers = $this->default_helpers(); /** * * @param array $helpers { * Name, class & callback for the helper. * * @type string $name Name of helper to use in Handlebars. * @type string $class Class containing callback function. * @type string $callback. Optional. The name of the callback function. If not set, "helper" will be used. * } * @param obj|\Handlebars\Handlebars $handlebars Handlebars.php class instance * */ $helpers = apply_filters( 'caldera_metaplate_handlebars_helpers', $helpers, $handlebars ); $handlebars = new helper_loader( $handlebars, $helpers ); if ( isset( $handlebars->handlebars ) ) { $handlebars = $handlebars->handlebars; } return $handlebars; }
php
private function helpers( $handlebars ) { $helpers = $this->default_helpers(); /** * * @param array $helpers { * Name, class & callback for the helper. * * @type string $name Name of helper to use in Handlebars. * @type string $class Class containing callback function. * @type string $callback. Optional. The name of the callback function. If not set, "helper" will be used. * } * @param obj|\Handlebars\Handlebars $handlebars Handlebars.php class instance * */ $helpers = apply_filters( 'caldera_metaplate_handlebars_helpers', $helpers, $handlebars ); $handlebars = new helper_loader( $handlebars, $helpers ); if ( isset( $handlebars->handlebars ) ) { $handlebars = $handlebars->handlebars; } return $handlebars; }
[ "private", "function", "helpers", "(", "$", "handlebars", ")", "{", "$", "helpers", "=", "$", "this", "->", "default_helpers", "(", ")", ";", "/**\n\t\t *\n\t\t * @param array $helpers {\n\t\t * Name, class & callback for the helper.\n\t\t *\n\t\t * @type string $name Name of helper to use in Handlebars.\n\t\t * @type string $class Class containing callback function.\n\t\t * @type string $callback. Optional. The name of the callback function. If not set, \"helper\" will be used.\n\t\t * }\n\t\t * @param obj|\\Handlebars\\Handlebars $handlebars Handlebars.php class instance\n\t\t *\n\t\t */", "$", "helpers", "=", "apply_filters", "(", "'caldera_metaplate_handlebars_helpers'", ",", "$", "helpers", ",", "$", "handlebars", ")", ";", "$", "handlebars", "=", "new", "helper_loader", "(", "$", "handlebars", ",", "$", "helpers", ")", ";", "if", "(", "isset", "(", "$", "handlebars", "->", "handlebars", ")", ")", "{", "$", "handlebars", "=", "$", "handlebars", "->", "handlebars", ";", "}", "return", "$", "handlebars", ";", "}" ]
Register helpers. Adds the default helpers, plus any set on "caldera_metaplate_handlebars_helpers" filter. @param obj|\Handlebars\Handlebars $handlebars Current instance of Handlebars. @return \Handlebars\Handlebars Current instance of Handlebars with the additional helpers added on.
[ "Register", "helpers", "." ]
train
https://github.com/CalderaWP/metaplate-core/blob/15ede9c4250ab23112a32f8e45d5393f8278bbb8/src/render.php#L183-L207
KodiComponents/Support
src/HtmlAttributes.php
HtmlAttributes.setHtmlAttribute
public function setHtmlAttribute($key, $attribute) { $attribute = $this->prepareHtmlAttributeValue($attribute); if ($key == 'class') { $this->htmlAttributes[$key][] = $attribute; } else { $this->htmlAttributes[$key] = $attribute; } return $this; }
php
public function setHtmlAttribute($key, $attribute) { $attribute = $this->prepareHtmlAttributeValue($attribute); if ($key == 'class') { $this->htmlAttributes[$key][] = $attribute; } else { $this->htmlAttributes[$key] = $attribute; } return $this; }
[ "public", "function", "setHtmlAttribute", "(", "$", "key", ",", "$", "attribute", ")", "{", "$", "attribute", "=", "$", "this", "->", "prepareHtmlAttributeValue", "(", "$", "attribute", ")", ";", "if", "(", "$", "key", "==", "'class'", ")", "{", "$", "this", "->", "htmlAttributes", "[", "$", "key", "]", "[", "]", "=", "$", "attribute", ";", "}", "else", "{", "$", "this", "->", "htmlAttributes", "[", "$", "key", "]", "=", "$", "attribute", ";", "}", "return", "$", "this", ";", "}" ]
@param string $key @param string|array $attribute @return $this
[ "@param", "string", "$key", "@param", "string|array", "$attribute" ]
train
https://github.com/KodiComponents/Support/blob/9090543605a2354c7454d707650a0abdb815b60a/src/HtmlAttributes.php#L42-L53
KodiComponents/Support
src/HtmlAttributes.php
HtmlAttributes.setHtmlAttributes
public function setHtmlAttributes(array $attributes) { foreach ($attributes as $key => $attribute) { if (is_numeric($key)) { $key = $attribute; } $this->setHtmlAttribute($key, $attribute); } return $this; }
php
public function setHtmlAttributes(array $attributes) { foreach ($attributes as $key => $attribute) { if (is_numeric($key)) { $key = $attribute; } $this->setHtmlAttribute($key, $attribute); } return $this; }
[ "public", "function", "setHtmlAttributes", "(", "array", "$", "attributes", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "key", "=>", "$", "attribute", ")", "{", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "{", "$", "key", "=", "$", "attribute", ";", "}", "$", "this", "->", "setHtmlAttribute", "(", "$", "key", ",", "$", "attribute", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param array $attributes @return $this
[ "@param", "array", "$attributes" ]
train
https://github.com/KodiComponents/Support/blob/9090543605a2354c7454d707650a0abdb815b60a/src/HtmlAttributes.php#L60-L71
KodiComponents/Support
src/HtmlAttributes.php
HtmlAttributes.replaceHtmlAttribute
public function replaceHtmlAttribute($key, $attribute) { $attribute = $this->prepareHtmlAttributeValue($attribute); $this->htmlAttributes[$key] = $attribute; return $this; }
php
public function replaceHtmlAttribute($key, $attribute) { $attribute = $this->prepareHtmlAttributeValue($attribute); $this->htmlAttributes[$key] = $attribute; return $this; }
[ "public", "function", "replaceHtmlAttribute", "(", "$", "key", ",", "$", "attribute", ")", "{", "$", "attribute", "=", "$", "this", "->", "prepareHtmlAttributeValue", "(", "$", "attribute", ")", ";", "$", "this", "->", "htmlAttributes", "[", "$", "key", "]", "=", "$", "attribute", ";", "return", "$", "this", ";", "}" ]
@param string $key @param string|array $attribute @return $this
[ "@param", "string", "$key", "@param", "string|array", "$attribute" ]
train
https://github.com/KodiComponents/Support/blob/9090543605a2354c7454d707650a0abdb815b60a/src/HtmlAttributes.php#L79-L85
KodiComponents/Support
src/HtmlAttributes.php
HtmlAttributes.hasClassProperty
public function hasClassProperty($class) { if (! is_array($class)) { $class = func_get_args(); } if (isset($this->htmlAttributes['class']) && is_array($this->htmlAttributes['class'])) { foreach ($this->htmlAttributes['class'] as $i => $string) { foreach ($class as $className) { if (strpos($string, $className) !== false) { return true; } } } } return false; }
php
public function hasClassProperty($class) { if (! is_array($class)) { $class = func_get_args(); } if (isset($this->htmlAttributes['class']) && is_array($this->htmlAttributes['class'])) { foreach ($this->htmlAttributes['class'] as $i => $string) { foreach ($class as $className) { if (strpos($string, $className) !== false) { return true; } } } } return false; }
[ "public", "function", "hasClassProperty", "(", "$", "class", ")", "{", "if", "(", "!", "is_array", "(", "$", "class", ")", ")", "{", "$", "class", "=", "func_get_args", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "htmlAttributes", "[", "'class'", "]", ")", "&&", "is_array", "(", "$", "this", "->", "htmlAttributes", "[", "'class'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "htmlAttributes", "[", "'class'", "]", "as", "$", "i", "=>", "$", "string", ")", "{", "foreach", "(", "$", "class", "as", "$", "className", ")", "{", "if", "(", "strpos", "(", "$", "string", ",", "$", "className", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
@param string $class @return bool
[ "@param", "string", "$class" ]
train
https://github.com/KodiComponents/Support/blob/9090543605a2354c7454d707650a0abdb815b60a/src/HtmlAttributes.php#L92-L109
ShaoZeMing/laravel-merchant
src/Middleware/Permission.php
Permission.handle
public function handle(Request $request, \Closure $next) { if (!Merchant::user()) { return $next($request); } if (!Merchant::user()->allPermissions()->first(function ($permission) use ($request) { return $permission->shouldPassThrough($request); })) { \ShaoZeMing\Merchant\Auth\Permission::error(); } return $next($request); }
php
public function handle(Request $request, \Closure $next) { if (!Merchant::user()) { return $next($request); } if (!Merchant::user()->allPermissions()->first(function ($permission) use ($request) { return $permission->shouldPassThrough($request); })) { \ShaoZeMing\Merchant\Auth\Permission::error(); } return $next($request); }
[ "public", "function", "handle", "(", "Request", "$", "request", ",", "\\", "Closure", "$", "next", ")", "{", "if", "(", "!", "Merchant", "::", "user", "(", ")", ")", "{", "return", "$", "next", "(", "$", "request", ")", ";", "}", "if", "(", "!", "Merchant", "::", "user", "(", ")", "->", "allPermissions", "(", ")", "->", "first", "(", "function", "(", "$", "permission", ")", "use", "(", "$", "request", ")", "{", "return", "$", "permission", "->", "shouldPassThrough", "(", "$", "request", ")", ";", "}", ")", ")", "{", "\\", "ShaoZeMing", "\\", "Merchant", "\\", "Auth", "\\", "Permission", "::", "error", "(", ")", ";", "}", "return", "$", "next", "(", "$", "request", ")", ";", "}" ]
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/ShaoZeMing/laravel-merchant/blob/20801b1735e7832a6e58b37c2c391328f8d626fa/src/Middleware/Permission.php#L18-L31
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.getTypeExtensions
public function getTypeExtensions($name) { if (null === $this->typeExtensions) { $this->initTypeExtensions(); } return !empty($this->typeExtensions[$name]) ? $this->typeExtensions[$name] : []; }
php
public function getTypeExtensions($name) { if (null === $this->typeExtensions) { $this->initTypeExtensions(); } return !empty($this->typeExtensions[$name]) ? $this->typeExtensions[$name] : []; }
[ "public", "function", "getTypeExtensions", "(", "$", "name", ")", "{", "if", "(", "null", "===", "$", "this", "->", "typeExtensions", ")", "{", "$", "this", "->", "initTypeExtensions", "(", ")", ";", "}", "return", "!", "empty", "(", "$", "this", "->", "typeExtensions", "[", "$", "name", "]", ")", "?", "$", "this", "->", "typeExtensions", "[", "$", "name", "]", ":", "[", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L101-L110
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.hasTypeExtensions
public function hasTypeExtensions($name) { if (null === $this->typeExtensions) { $this->initTypeExtensions(); } return !empty($this->typeExtensions[$name]); }
php
public function hasTypeExtensions($name) { if (null === $this->typeExtensions) { $this->initTypeExtensions(); } return !empty($this->typeExtensions[$name]); }
[ "public", "function", "hasTypeExtensions", "(", "$", "name", ")", "{", "if", "(", "null", "===", "$", "this", "->", "typeExtensions", ")", "{", "$", "this", "->", "initTypeExtensions", "(", ")", ";", "}", "return", "!", "empty", "(", "$", "this", "->", "typeExtensions", "[", "$", "name", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L115-L122
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.getLayoutUpdates
public function getLayoutUpdates(LayoutItemInterface $item) { $idOrAlias = $item->getAlias() ? : $item->getId(); if (null === $this->layoutUpdates) { $this->initLayoutUpdates($item->getContext()); } return !empty($this->layoutUpdates[$idOrAlias]) ? $this->layoutUpdates[$idOrAlias] : []; }
php
public function getLayoutUpdates(LayoutItemInterface $item) { $idOrAlias = $item->getAlias() ? : $item->getId(); if (null === $this->layoutUpdates) { $this->initLayoutUpdates($item->getContext()); } return !empty($this->layoutUpdates[$idOrAlias]) ? $this->layoutUpdates[$idOrAlias] : []; }
[ "public", "function", "getLayoutUpdates", "(", "LayoutItemInterface", "$", "item", ")", "{", "$", "idOrAlias", "=", "$", "item", "->", "getAlias", "(", ")", "?", ":", "$", "item", "->", "getId", "(", ")", ";", "if", "(", "null", "===", "$", "this", "->", "layoutUpdates", ")", "{", "$", "this", "->", "initLayoutUpdates", "(", "$", "item", "->", "getContext", "(", ")", ")", ";", "}", "return", "!", "empty", "(", "$", "this", "->", "layoutUpdates", "[", "$", "idOrAlias", "]", ")", "?", "$", "this", "->", "layoutUpdates", "[", "$", "idOrAlias", "]", ":", "[", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L127-L138
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.hasDataProvider
public function hasDataProvider($name) { if (null === $this->dataProviders) { $this->initDataProviders(); } return isset($this->dataProviders[$name]); }
php
public function hasDataProvider($name) { if (null === $this->dataProviders) { $this->initDataProviders(); } return isset($this->dataProviders[$name]); }
[ "public", "function", "hasDataProvider", "(", "$", "name", ")", "{", "if", "(", "null", "===", "$", "this", "->", "dataProviders", ")", "{", "$", "this", "->", "initDataProviders", "(", ")", ";", "}", "return", "isset", "(", "$", "this", "->", "dataProviders", "[", "$", "name", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L199-L206
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.initTypes
private function initTypes() { $this->types = []; foreach ($this->loadTypes() as $type) { if (!$type instanceof BlockTypeInterface) { throw new Exception\UnexpectedTypeException( $type, 'Oro\Component\Layout\BlockTypeInterface' ); } $this->types[$type->getName()] = $type; } }
php
private function initTypes() { $this->types = []; foreach ($this->loadTypes() as $type) { if (!$type instanceof BlockTypeInterface) { throw new Exception\UnexpectedTypeException( $type, 'Oro\Component\Layout\BlockTypeInterface' ); } $this->types[$type->getName()] = $type; } }
[ "private", "function", "initTypes", "(", ")", "{", "$", "this", "->", "types", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "loadTypes", "(", ")", "as", "$", "type", ")", "{", "if", "(", "!", "$", "type", "instanceof", "BlockTypeInterface", ")", "{", "throw", "new", "Exception", "\\", "UnexpectedTypeException", "(", "$", "type", ",", "'Oro\\Component\\Layout\\BlockTypeInterface'", ")", ";", "}", "$", "this", "->", "types", "[", "$", "type", "->", "getName", "(", ")", "]", "=", "$", "type", ";", "}", "}" ]
Initializes block types. @throws Exception\UnexpectedTypeException if any registered block type is not an instance of BlockTypeInterface
[ "Initializes", "block", "types", "." ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L278-L292
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.initTypeExtensions
private function initTypeExtensions() { $this->typeExtensions = []; foreach ($this->loadTypeExtensions() as $extension) { if (!$extension instanceof BlockTypeExtensionInterface) { throw new Exception\UnexpectedTypeException( $extension, 'Oro\Component\Layout\BlockTypeExtensionInterface' ); } $type = $extension->getExtendedType(); $this->typeExtensions[$type][] = $extension; } }
php
private function initTypeExtensions() { $this->typeExtensions = []; foreach ($this->loadTypeExtensions() as $extension) { if (!$extension instanceof BlockTypeExtensionInterface) { throw new Exception\UnexpectedTypeException( $extension, 'Oro\Component\Layout\BlockTypeExtensionInterface' ); } $type = $extension->getExtendedType(); $this->typeExtensions[$type][] = $extension; } }
[ "private", "function", "initTypeExtensions", "(", ")", "{", "$", "this", "->", "typeExtensions", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "loadTypeExtensions", "(", ")", "as", "$", "extension", ")", "{", "if", "(", "!", "$", "extension", "instanceof", "BlockTypeExtensionInterface", ")", "{", "throw", "new", "Exception", "\\", "UnexpectedTypeException", "(", "$", "extension", ",", "'Oro\\Component\\Layout\\BlockTypeExtensionInterface'", ")", ";", "}", "$", "type", "=", "$", "extension", "->", "getExtendedType", "(", ")", ";", "$", "this", "->", "typeExtensions", "[", "$", "type", "]", "[", "]", "=", "$", "extension", ";", "}", "}" ]
Initializes block type extensions. @throws Exception\UnexpectedTypeException if any registered block type extension is not an instance of BlockTypeExtensionInterface
[ "Initializes", "block", "type", "extensions", "." ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L300-L316
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.initLayoutUpdates
private function initLayoutUpdates(ContextInterface $context) { $loadedLayoutUpdates = $this->loadLayoutUpdates($context); foreach ($loadedLayoutUpdates as $id => $layoutUpdates) { if (!is_string($id)) { throw new Exception\UnexpectedTypeException( $id, 'string', 'layout item id' ); } if (!is_array($layoutUpdates)) { throw new Exception\UnexpectedTypeException( $layoutUpdates, 'array', sprintf('layout updates for item "%s"', $id) ); } foreach ($layoutUpdates as $layoutUpdate) { if (!$layoutUpdate instanceof LayoutUpdateInterface) { throw new Exception\UnexpectedTypeException( $layoutUpdate, 'Oro\Component\Layout\LayoutUpdateInterface' ); } } } $this->layoutUpdates = $loadedLayoutUpdates; }
php
private function initLayoutUpdates(ContextInterface $context) { $loadedLayoutUpdates = $this->loadLayoutUpdates($context); foreach ($loadedLayoutUpdates as $id => $layoutUpdates) { if (!is_string($id)) { throw new Exception\UnexpectedTypeException( $id, 'string', 'layout item id' ); } if (!is_array($layoutUpdates)) { throw new Exception\UnexpectedTypeException( $layoutUpdates, 'array', sprintf('layout updates for item "%s"', $id) ); } foreach ($layoutUpdates as $layoutUpdate) { if (!$layoutUpdate instanceof LayoutUpdateInterface) { throw new Exception\UnexpectedTypeException( $layoutUpdate, 'Oro\Component\Layout\LayoutUpdateInterface' ); } } } $this->layoutUpdates = $loadedLayoutUpdates; }
[ "private", "function", "initLayoutUpdates", "(", "ContextInterface", "$", "context", ")", "{", "$", "loadedLayoutUpdates", "=", "$", "this", "->", "loadLayoutUpdates", "(", "$", "context", ")", ";", "foreach", "(", "$", "loadedLayoutUpdates", "as", "$", "id", "=>", "$", "layoutUpdates", ")", "{", "if", "(", "!", "is_string", "(", "$", "id", ")", ")", "{", "throw", "new", "Exception", "\\", "UnexpectedTypeException", "(", "$", "id", ",", "'string'", ",", "'layout item id'", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "layoutUpdates", ")", ")", "{", "throw", "new", "Exception", "\\", "UnexpectedTypeException", "(", "$", "layoutUpdates", ",", "'array'", ",", "sprintf", "(", "'layout updates for item \"%s\"'", ",", "$", "id", ")", ")", ";", "}", "foreach", "(", "$", "layoutUpdates", "as", "$", "layoutUpdate", ")", "{", "if", "(", "!", "$", "layoutUpdate", "instanceof", "LayoutUpdateInterface", ")", "{", "throw", "new", "Exception", "\\", "UnexpectedTypeException", "(", "$", "layoutUpdate", ",", "'Oro\\Component\\Layout\\LayoutUpdateInterface'", ")", ";", "}", "}", "}", "$", "this", "->", "layoutUpdates", "=", "$", "loadedLayoutUpdates", ";", "}" ]
Initializes layout updates. @param ContextInterface $context @throws Exception\UnexpectedTypeException if any registered layout update is not an instance of LayoutUpdateInterface or layout item id is not a string
[ "Initializes", "layout", "updates", "." ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L327-L355
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.initContextConfigurators
private function initContextConfigurators() { $this->contextConfigurators = []; foreach ($this->loadContextConfigurators() as $configurator) { if (!$configurator instanceof ContextConfiguratorInterface) { throw new Exception\UnexpectedTypeException( $configurator, 'Oro\Component\Layout\ContextConfiguratorInterface' ); } $this->contextConfigurators[] = $configurator; } }
php
private function initContextConfigurators() { $this->contextConfigurators = []; foreach ($this->loadContextConfigurators() as $configurator) { if (!$configurator instanceof ContextConfiguratorInterface) { throw new Exception\UnexpectedTypeException( $configurator, 'Oro\Component\Layout\ContextConfiguratorInterface' ); } $this->contextConfigurators[] = $configurator; } }
[ "private", "function", "initContextConfigurators", "(", ")", "{", "$", "this", "->", "contextConfigurators", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "loadContextConfigurators", "(", ")", "as", "$", "configurator", ")", "{", "if", "(", "!", "$", "configurator", "instanceof", "ContextConfiguratorInterface", ")", "{", "throw", "new", "Exception", "\\", "UnexpectedTypeException", "(", "$", "configurator", ",", "'Oro\\Component\\Layout\\ContextConfiguratorInterface'", ")", ";", "}", "$", "this", "->", "contextConfigurators", "[", "]", "=", "$", "configurator", ";", "}", "}" ]
Initializes layout context configurators. @throws Exception\UnexpectedTypeException if any registered context configurators is not an instance of ContextConfiguratorInterface
[ "Initializes", "layout", "context", "configurators", "." ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L363-L377
oroinc/OroLayoutComponent
Extension/AbstractExtension.php
AbstractExtension.initDataProviders
private function initDataProviders() { $this->dataProviders = []; foreach ($this->loadDataProviders() as $name => $dataProvider) { $this->dataProviders[$name] = $dataProvider; } }
php
private function initDataProviders() { $this->dataProviders = []; foreach ($this->loadDataProviders() as $name => $dataProvider) { $this->dataProviders[$name] = $dataProvider; } }
[ "private", "function", "initDataProviders", "(", ")", "{", "$", "this", "->", "dataProviders", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "loadDataProviders", "(", ")", "as", "$", "name", "=>", "$", "dataProvider", ")", "{", "$", "this", "->", "dataProviders", "[", "$", "name", "]", "=", "$", "dataProvider", ";", "}", "}" ]
Initializes data providers.
[ "Initializes", "data", "providers", "." ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/AbstractExtension.php#L382-L389
php-lug/lug
src/Bundle/GridBundle/Form/Type/Batch/GridBatchAllType.php
GridBatchAllType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'label' => function (Options $options) { return 'lug.'.$options['grid']->getDefinition()->getResource()->getName().'.batch.all'; }, 'label_translation_arguments' => function (Options $options) { return ['%count%' => count($options['grid']->getDataSource())]; }, ]) ->setRequired('grid') ->setAllowedTypes('grid', GridViewInterface::class); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'label' => function (Options $options) { return 'lug.'.$options['grid']->getDefinition()->getResource()->getName().'.batch.all'; }, 'label_translation_arguments' => function (Options $options) { return ['%count%' => count($options['grid']->getDataSource())]; }, ]) ->setRequired('grid') ->setAllowedTypes('grid', GridViewInterface::class); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "$", "resolver", "->", "setDefaults", "(", "[", "'label'", "=>", "function", "(", "Options", "$", "options", ")", "{", "return", "'lug.'", ".", "$", "options", "[", "'grid'", "]", "->", "getDefinition", "(", ")", "->", "getResource", "(", ")", "->", "getName", "(", ")", ".", "'.batch.all'", ";", "}", ",", "'label_translation_arguments'", "=>", "function", "(", "Options", "$", "options", ")", "{", "return", "[", "'%count%'", "=>", "count", "(", "$", "options", "[", "'grid'", "]", "->", "getDataSource", "(", ")", ")", "]", ";", "}", ",", "]", ")", "->", "setRequired", "(", "'grid'", ")", "->", "setAllowedTypes", "(", "'grid'", ",", "GridViewInterface", "::", "class", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Form/Type/Batch/GridBatchAllType.php#L28-L41
rem42/scraper
HttpClient/HttpClient.php
HttpClient.get
public function get($path, array $parameters = [], array $headers = []) { $this->setHeaders($headers); $this->setQuery($parameters); return $this->client->request('GET', $path, $this->headers); }
php
public function get($path, array $parameters = [], array $headers = []) { $this->setHeaders($headers); $this->setQuery($parameters); return $this->client->request('GET', $path, $this->headers); }
[ "public", "function", "get", "(", "$", "path", ",", "array", "$", "parameters", "=", "[", "]", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "$", "this", "->", "setHeaders", "(", "$", "headers", ")", ";", "$", "this", "->", "setQuery", "(", "$", "parameters", ")", ";", "return", "$", "this", "->", "client", "->", "request", "(", "'GET'", ",", "$", "path", ",", "$", "this", "->", "headers", ")", ";", "}" ]
@param string $path @param array $parameters @param array $headers @return Response|mixed|\Psr\Http\Message\ResponseInterface @throws \GuzzleHttp\Exception\GuzzleException
[ "@param", "string", "$path", "@param", "array", "$parameters", "@param", "array", "$headers" ]
train
https://github.com/rem42/scraper/blob/7c4ec23ce61b8187f2d8cfebdd233525359adb83/HttpClient/HttpClient.php#L62-L67
rem42/scraper
HttpClient/HttpClient.php
HttpClient.post
public function post($path, array $parameters = [], array $headers = [], $body = null) { $this->setQuery($parameters); $this->setHeaders($headers); if ($body instanceof BodyMultipart) { $this->setMultipart($body); } elseif (is_array($body)) { $this->setFormParams($body); } return $this->client->request('POST', $path, $this->headers); }
php
public function post($path, array $parameters = [], array $headers = [], $body = null) { $this->setQuery($parameters); $this->setHeaders($headers); if ($body instanceof BodyMultipart) { $this->setMultipart($body); } elseif (is_array($body)) { $this->setFormParams($body); } return $this->client->request('POST', $path, $this->headers); }
[ "public", "function", "post", "(", "$", "path", ",", "array", "$", "parameters", "=", "[", "]", ",", "array", "$", "headers", "=", "[", "]", ",", "$", "body", "=", "null", ")", "{", "$", "this", "->", "setQuery", "(", "$", "parameters", ")", ";", "$", "this", "->", "setHeaders", "(", "$", "headers", ")", ";", "if", "(", "$", "body", "instanceof", "BodyMultipart", ")", "{", "$", "this", "->", "setMultipart", "(", "$", "body", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "body", ")", ")", "{", "$", "this", "->", "setFormParams", "(", "$", "body", ")", ";", "}", "return", "$", "this", "->", "client", "->", "request", "(", "'POST'", ",", "$", "path", ",", "$", "this", "->", "headers", ")", ";", "}" ]
@param string $path @param array $parameters @param array $headers @param null $body @return Response|mixed|\Psr\Http\Message\ResponseInterface @throws \GuzzleHttp\Exception\GuzzleException
[ "@param", "string", "$path", "@param", "array", "$parameters", "@param", "array", "$headers", "@param", "null", "$body" ]
train
https://github.com/rem42/scraper/blob/7c4ec23ce61b8187f2d8cfebdd233525359adb83/HttpClient/HttpClient.php#L78-L89
rem42/scraper
HttpClient/HttpClient.php
HttpClient.request
public function request($path, $body, $httpMethod = 'GET', array $headers = [], array $options = []) { $request = $this->createRequest($httpMethod, $path, $body, $headers); try { $response = $this->client->send($request, $options); } catch (\LogicException $e) { throw new \ErrorException($e->getMessage(), $e->getCode(), $e); } catch (\RuntimeException $e) { throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $this->lastRequest = $request; $this->lastResponse = $response; return $response; }
php
public function request($path, $body, $httpMethod = 'GET', array $headers = [], array $options = []) { $request = $this->createRequest($httpMethod, $path, $body, $headers); try { $response = $this->client->send($request, $options); } catch (\LogicException $e) { throw new \ErrorException($e->getMessage(), $e->getCode(), $e); } catch (\RuntimeException $e) { throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } $this->lastRequest = $request; $this->lastResponse = $response; return $response; }
[ "public", "function", "request", "(", "$", "path", ",", "$", "body", ",", "$", "httpMethod", "=", "'GET'", ",", "array", "$", "headers", "=", "[", "]", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "request", "=", "$", "this", "->", "createRequest", "(", "$", "httpMethod", ",", "$", "path", ",", "$", "body", ",", "$", "headers", ")", ";", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "send", "(", "$", "request", ",", "$", "options", ")", ";", "}", "catch", "(", "\\", "LogicException", "$", "e", ")", "{", "throw", "new", "\\", "ErrorException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "catch", "(", "\\", "RuntimeException", "$", "e", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "$", "this", "->", "lastRequest", "=", "$", "request", ";", "$", "this", "->", "lastResponse", "=", "$", "response", ";", "return", "$", "response", ";", "}" ]
@param string $path @param mixed $body @param string $httpMethod @param array $headers @param array $options @return Response|mixed|\Psr\Http\Message\ResponseInterface @throws \ErrorException @throws \GuzzleHttp\Exception\GuzzleException
[ "@param", "string", "$path", "@param", "mixed", "$body", "@param", "string", "$httpMethod", "@param", "array", "$headers", "@param", "array", "$options" ]
train
https://github.com/rem42/scraper/blob/7c4ec23ce61b8187f2d8cfebdd233525359adb83/HttpClient/HttpClient.php#L102-L118
rem42/scraper
HttpClient/HttpClient.php
HttpClient.createRequest
public function createRequest($httpMethod, $path, $body = null, array $headers = []) { return new Request( $httpMethod, $path, array_merge($this->headers, $headers), $body ); }
php
public function createRequest($httpMethod, $path, $body = null, array $headers = []) { return new Request( $httpMethod, $path, array_merge($this->headers, $headers), $body ); }
[ "public", "function", "createRequest", "(", "$", "httpMethod", ",", "$", "path", ",", "$", "body", "=", "null", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "return", "new", "Request", "(", "$", "httpMethod", ",", "$", "path", ",", "array_merge", "(", "$", "this", "->", "headers", ",", "$", "headers", ")", ",", "$", "body", ")", ";", "}" ]
@param $httpMethod @param $path @param null $body @param array $headers @return Request
[ "@param", "$httpMethod", "@param", "$path", "@param", "null", "$body", "@param", "array", "$headers" ]
train
https://github.com/rem42/scraper/blob/7c4ec23ce61b8187f2d8cfebdd233525359adb83/HttpClient/HttpClient.php#L167-L175
alevilar/ristorantino-vendor
Compras/Controller/RubrosController.php
RubrosController.add
public function add() { if ($this->request->is('post')) { $this->Rubro->create(); if ($this->Rubro->save($this->request->data)) { $this->Session->setFlash(__('The rubro has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The rubro could not be saved. Please, try again.')); } } $proveedores = $this->Rubro->Proveedor->find('list'); $this->set(compact('proveedores')); }
php
public function add() { if ($this->request->is('post')) { $this->Rubro->create(); if ($this->Rubro->save($this->request->data)) { $this->Session->setFlash(__('The rubro has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The rubro could not be saved. Please, try again.')); } } $proveedores = $this->Rubro->Proveedor->find('list'); $this->set(compact('proveedores')); }
[ "public", "function", "add", "(", ")", "{", "if", "(", "$", "this", "->", "request", "->", "is", "(", "'post'", ")", ")", "{", "$", "this", "->", "Rubro", "->", "create", "(", ")", ";", "if", "(", "$", "this", "->", "Rubro", "->", "save", "(", "$", "this", "->", "request", "->", "data", ")", ")", "{", "$", "this", "->", "Session", "->", "setFlash", "(", "__", "(", "'The rubro has been saved.'", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "array", "(", "'action'", "=>", "'index'", ")", ")", ";", "}", "else", "{", "$", "this", "->", "Session", "->", "setFlash", "(", "__", "(", "'The rubro could not be saved. Please, try again.'", ")", ")", ";", "}", "}", "$", "proveedores", "=", "$", "this", "->", "Rubro", "->", "Proveedor", "->", "find", "(", "'list'", ")", ";", "$", "this", "->", "set", "(", "compact", "(", "'proveedores'", ")", ")", ";", "}" ]
add method @return void
[ "add", "method" ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Compras/Controller/RubrosController.php#L43-L55
alevilar/ristorantino-vendor
Compras/Controller/RubrosController.php
RubrosController.edit
public function edit($id = null) { if (!$this->Rubro->exists($id)) { throw new NotFoundException(__('Invalid rubro')); } if ($this->request->is(array('post', 'put'))) { if ($this->Rubro->save($this->request->data)) { $this->Flash->success(__('The rubro has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Flash->error(__('The rubro could not be saved. Please, try again.')); } } else { $options = array('conditions' => array('Rubro.' . $this->Rubro->primaryKey => $id)); $this->request->data = $this->Rubro->find('first', $options); } $proveedores = $this->Rubro->Proveedor->find('list'); $this->set(compact('proveedores')); }
php
public function edit($id = null) { if (!$this->Rubro->exists($id)) { throw new NotFoundException(__('Invalid rubro')); } if ($this->request->is(array('post', 'put'))) { if ($this->Rubro->save($this->request->data)) { $this->Flash->success(__('The rubro has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Flash->error(__('The rubro could not be saved. Please, try again.')); } } else { $options = array('conditions' => array('Rubro.' . $this->Rubro->primaryKey => $id)); $this->request->data = $this->Rubro->find('first', $options); } $proveedores = $this->Rubro->Proveedor->find('list'); $this->set(compact('proveedores')); }
[ "public", "function", "edit", "(", "$", "id", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "Rubro", "->", "exists", "(", "$", "id", ")", ")", "{", "throw", "new", "NotFoundException", "(", "__", "(", "'Invalid rubro'", ")", ")", ";", "}", "if", "(", "$", "this", "->", "request", "->", "is", "(", "array", "(", "'post'", ",", "'put'", ")", ")", ")", "{", "if", "(", "$", "this", "->", "Rubro", "->", "save", "(", "$", "this", "->", "request", "->", "data", ")", ")", "{", "$", "this", "->", "Flash", "->", "success", "(", "__", "(", "'The rubro has been saved.'", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "array", "(", "'action'", "=>", "'index'", ")", ")", ";", "}", "else", "{", "$", "this", "->", "Flash", "->", "error", "(", "__", "(", "'The rubro could not be saved. Please, try again.'", ")", ")", ";", "}", "}", "else", "{", "$", "options", "=", "array", "(", "'conditions'", "=>", "array", "(", "'Rubro.'", ".", "$", "this", "->", "Rubro", "->", "primaryKey", "=>", "$", "id", ")", ")", ";", "$", "this", "->", "request", "->", "data", "=", "$", "this", "->", "Rubro", "->", "find", "(", "'first'", ",", "$", "options", ")", ";", "}", "$", "proveedores", "=", "$", "this", "->", "Rubro", "->", "Proveedor", "->", "find", "(", "'list'", ")", ";", "$", "this", "->", "set", "(", "compact", "(", "'proveedores'", ")", ")", ";", "}" ]
edit method @throws NotFoundException @param string $id @return void
[ "edit", "method" ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Compras/Controller/RubrosController.php#L64-L81
josh-taylor/migrations-generator
src/SchemaArgumentBuilder.php
SchemaArgumentBuilder.create
public function create($schema) { $types = array_map(function ($column) { return $column['name'] . ':' . $column['type']; }, $schema); return implode(', ', $types); }
php
public function create($schema) { $types = array_map(function ($column) { return $column['name'] . ':' . $column['type']; }, $schema); return implode(', ', $types); }
[ "public", "function", "create", "(", "$", "schema", ")", "{", "$", "types", "=", "array_map", "(", "function", "(", "$", "column", ")", "{", "return", "$", "column", "[", "'name'", "]", ".", "':'", ".", "$", "column", "[", "'type'", "]", ";", "}", ",", "$", "schema", ")", ";", "return", "implode", "(", "', '", ",", "$", "types", ")", ";", "}" ]
Return the argument string to use for the migration command. @param $schema @return string
[ "Return", "the", "argument", "string", "to", "use", "for", "the", "migration", "command", "." ]
train
https://github.com/josh-taylor/migrations-generator/blob/bb6edc78773d11491881f12265a658bf058cb218/src/SchemaArgumentBuilder.php#L13-L20
nabab/bbn
src/bbn/mvc/router.php
router.find_controller
private function find_controller($path, $mode){ /** @var string $root Where the files will be searched for by default */ $root = $this->get_root($mode); /** @var boolean|string $file Once found, full path and filename */ $file = false; /** @var string $tmp Will contain the different states of the path along searching for the file */ $tmp = $path ? $path : '.'; /** @var array $args Each element of the URL outside the file path */ $args = []; /** @var boolean|string $plugin Name of the controller's plugin if it's inside one */ $plugin = false; /** @var string $real_path The application path */ $real_path = null; // We go through the path, removing a bit each time until we find the corresponding file while ( \strlen($tmp) > 0){ // We might already know it! if ($this->is_known($tmp, $mode)){ return $this->get_known($tmp, $mode); } // if $tmp is a plugin root index setting $this->alt_root and rerouting to reprocess the path if ( isset($this->routes['root'][$tmp]) && ($this->alt_root !== $tmp) ){ $this->set_alt_root($tmp); return $this->route($path, $mode, $this->get_alt_root($mode)); } // navigation (we are in dom and dom is default or we are not in dom, i.e. public) if ( (($mode === 'dom') && (BBN_DEFAULT_MODE === 'dom')) || ($mode !== 'dom') ){ // Checking first if the specific route exists (through $routes['alias']) if ( $this->has_route($tmp) ){ $real_path = $this->get_route($tmp); if ( is_file($root.$real_path.'.php') ){ $file = $root.$real_path.'.php'; } } // Then looks for a corresponding file in the regular MVC else if (file_exists($root.$tmp.'.php')){ $real_path = $tmp; $file = $root.$tmp.'.php'; } // Then looks for a home.php file in the corresponding directory else if ( is_dir($root.$tmp) && is_file($root.$tmp.'/home.php') ){ $real_path = $tmp.'/home'; $file = $root.$tmp.'/home.php'; } // If an alternative root exists (plugin), we look into it for the same else if ( $this->alt_root && (strpos($tmp, $this->alt_root) === 0) ){ $name = substr($tmp, \strlen($this->alt_root)+1); // Corresponding file if ( file_exists($this->get_alt_root($mode).$name.'.php') ){ $plugin = $this->alt_root; $real_path = $tmp; $file = $this->get_alt_root($mode).$name.'.php'; $root = $this->get_alt_root($mode); } // home.php in corresponding dir else if ( is_dir($this->get_alt_root($mode).$name) && is_file($this->get_alt_root($mode).$name.'/home.php') ){ $plugin = $this->alt_root; $real_path = $tmp.'/home'; $file = $this->get_alt_root($mode).$name.'/home.php'; $root = $this->get_alt_root($mode); } } } // Full DOM requested if ( !$file && ($mode === 'dom') ){ if ( $this->has_route($tmp) ){ return $this->find_controller($this->get_route($tmp), $mode); } // Root index file (if $tmp is at the root level) else if ( ($tmp === '.') && !$this->alt_root ){ // If file exists if ( file_exists($root.'index.php') ){ $real_path = '.'; $file = $root.'index.php'; } // Otherwise $file will remain undefined else{ /** @todo throw an alert as there is no default index */ die('Impossible to find a route'); break; } } // There is an index file in a subfolder else if ( file_exists($root.$tmp.'/index.php') ){ $real_path = $tmp; $file = $root.$tmp.'/index.php'; } // An alternative root exists, we look into it else if ( $this->alt_root && (strpos($tmp, $this->alt_root) === 0) ){ if ( $tmp === $this->alt_root ){ $name = ''; } else{ $name = substr($tmp, \strlen($this->alt_root)+1); } // Corresponding file if ( file_exists($this->get_alt_root($mode).$name.'/index.php') ){ $plugin = $this->alt_root; $real_path = $tmp; $file = $this->get_alt_root($mode).$name.'/index.php'; $root = $this->get_alt_root($mode); } // home.php in corresponding dir } } if ( $file ){ break; } array_unshift($args, basename($tmp)); $tmp = strpos($tmp, '/') === false ? '' : substr($tmp, 0, strrpos($tmp, '/')); if ( empty($tmp) && ($mode === 'dom') ){ $tmp = '.'; } else if ( $tmp === '.' ){ $tmp = ''; } } /* // Not found, sending the default controllers if ( !$file && is_file($root.'404.php') ){ $real_path = '404'; $file = $root.'404.php'; } */ if ( $file ){ if ( $plugin ){ $this->apply_locale($plugin); } return $this->set_known([ 'file' => $file, 'path' => $real_path, 'root' => \dirname($root, 2).'/', 'request' => $path, 'mode' => $mode, 'plugin' => $plugin, 'args' => $args, ]); } // Aaaargh! //die(bbn\x::dump("No default file defined for mode $mode $tmp (and no 404 file either)")); }
php
private function find_controller($path, $mode){ /** @var string $root Where the files will be searched for by default */ $root = $this->get_root($mode); /** @var boolean|string $file Once found, full path and filename */ $file = false; /** @var string $tmp Will contain the different states of the path along searching for the file */ $tmp = $path ? $path : '.'; /** @var array $args Each element of the URL outside the file path */ $args = []; /** @var boolean|string $plugin Name of the controller's plugin if it's inside one */ $plugin = false; /** @var string $real_path The application path */ $real_path = null; // We go through the path, removing a bit each time until we find the corresponding file while ( \strlen($tmp) > 0){ // We might already know it! if ($this->is_known($tmp, $mode)){ return $this->get_known($tmp, $mode); } // if $tmp is a plugin root index setting $this->alt_root and rerouting to reprocess the path if ( isset($this->routes['root'][$tmp]) && ($this->alt_root !== $tmp) ){ $this->set_alt_root($tmp); return $this->route($path, $mode, $this->get_alt_root($mode)); } // navigation (we are in dom and dom is default or we are not in dom, i.e. public) if ( (($mode === 'dom') && (BBN_DEFAULT_MODE === 'dom')) || ($mode !== 'dom') ){ // Checking first if the specific route exists (through $routes['alias']) if ( $this->has_route($tmp) ){ $real_path = $this->get_route($tmp); if ( is_file($root.$real_path.'.php') ){ $file = $root.$real_path.'.php'; } } // Then looks for a corresponding file in the regular MVC else if (file_exists($root.$tmp.'.php')){ $real_path = $tmp; $file = $root.$tmp.'.php'; } // Then looks for a home.php file in the corresponding directory else if ( is_dir($root.$tmp) && is_file($root.$tmp.'/home.php') ){ $real_path = $tmp.'/home'; $file = $root.$tmp.'/home.php'; } // If an alternative root exists (plugin), we look into it for the same else if ( $this->alt_root && (strpos($tmp, $this->alt_root) === 0) ){ $name = substr($tmp, \strlen($this->alt_root)+1); // Corresponding file if ( file_exists($this->get_alt_root($mode).$name.'.php') ){ $plugin = $this->alt_root; $real_path = $tmp; $file = $this->get_alt_root($mode).$name.'.php'; $root = $this->get_alt_root($mode); } // home.php in corresponding dir else if ( is_dir($this->get_alt_root($mode).$name) && is_file($this->get_alt_root($mode).$name.'/home.php') ){ $plugin = $this->alt_root; $real_path = $tmp.'/home'; $file = $this->get_alt_root($mode).$name.'/home.php'; $root = $this->get_alt_root($mode); } } } // Full DOM requested if ( !$file && ($mode === 'dom') ){ if ( $this->has_route($tmp) ){ return $this->find_controller($this->get_route($tmp), $mode); } // Root index file (if $tmp is at the root level) else if ( ($tmp === '.') && !$this->alt_root ){ // If file exists if ( file_exists($root.'index.php') ){ $real_path = '.'; $file = $root.'index.php'; } // Otherwise $file will remain undefined else{ /** @todo throw an alert as there is no default index */ die('Impossible to find a route'); break; } } // There is an index file in a subfolder else if ( file_exists($root.$tmp.'/index.php') ){ $real_path = $tmp; $file = $root.$tmp.'/index.php'; } // An alternative root exists, we look into it else if ( $this->alt_root && (strpos($tmp, $this->alt_root) === 0) ){ if ( $tmp === $this->alt_root ){ $name = ''; } else{ $name = substr($tmp, \strlen($this->alt_root)+1); } // Corresponding file if ( file_exists($this->get_alt_root($mode).$name.'/index.php') ){ $plugin = $this->alt_root; $real_path = $tmp; $file = $this->get_alt_root($mode).$name.'/index.php'; $root = $this->get_alt_root($mode); } // home.php in corresponding dir } } if ( $file ){ break; } array_unshift($args, basename($tmp)); $tmp = strpos($tmp, '/') === false ? '' : substr($tmp, 0, strrpos($tmp, '/')); if ( empty($tmp) && ($mode === 'dom') ){ $tmp = '.'; } else if ( $tmp === '.' ){ $tmp = ''; } } /* // Not found, sending the default controllers if ( !$file && is_file($root.'404.php') ){ $real_path = '404'; $file = $root.'404.php'; } */ if ( $file ){ if ( $plugin ){ $this->apply_locale($plugin); } return $this->set_known([ 'file' => $file, 'path' => $real_path, 'root' => \dirname($root, 2).'/', 'request' => $path, 'mode' => $mode, 'plugin' => $plugin, 'args' => $args, ]); } // Aaaargh! //die(bbn\x::dump("No default file defined for mode $mode $tmp (and no 404 file either)")); }
[ "private", "function", "find_controller", "(", "$", "path", ",", "$", "mode", ")", "{", "/** @var string $root Where the files will be searched for by default */", "$", "root", "=", "$", "this", "->", "get_root", "(", "$", "mode", ")", ";", "/** @var boolean|string $file Once found, full path and filename */", "$", "file", "=", "false", ";", "/** @var string $tmp Will contain the different states of the path along searching for the file */", "$", "tmp", "=", "$", "path", "?", "$", "path", ":", "'.'", ";", "/** @var array $args Each element of the URL outside the file path */", "$", "args", "=", "[", "]", ";", "/** @var boolean|string $plugin Name of the controller's plugin if it's inside one */", "$", "plugin", "=", "false", ";", "/** @var string $real_path The application path */", "$", "real_path", "=", "null", ";", "// We go through the path, removing a bit each time until we find the corresponding file", "while", "(", "\\", "strlen", "(", "$", "tmp", ")", ">", "0", ")", "{", "// We might already know it!", "if", "(", "$", "this", "->", "is_known", "(", "$", "tmp", ",", "$", "mode", ")", ")", "{", "return", "$", "this", "->", "get_known", "(", "$", "tmp", ",", "$", "mode", ")", ";", "}", "// if $tmp is a plugin root index setting $this->alt_root and rerouting to reprocess the path", "if", "(", "isset", "(", "$", "this", "->", "routes", "[", "'root'", "]", "[", "$", "tmp", "]", ")", "&&", "(", "$", "this", "->", "alt_root", "!==", "$", "tmp", ")", ")", "{", "$", "this", "->", "set_alt_root", "(", "$", "tmp", ")", ";", "return", "$", "this", "->", "route", "(", "$", "path", ",", "$", "mode", ",", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ")", ";", "}", "// navigation (we are in dom and dom is default or we are not in dom, i.e. public)", "if", "(", "(", "(", "$", "mode", "===", "'dom'", ")", "&&", "(", "BBN_DEFAULT_MODE", "===", "'dom'", ")", ")", "||", "(", "$", "mode", "!==", "'dom'", ")", ")", "{", "// Checking first if the specific route exists (through $routes['alias'])", "if", "(", "$", "this", "->", "has_route", "(", "$", "tmp", ")", ")", "{", "$", "real_path", "=", "$", "this", "->", "get_route", "(", "$", "tmp", ")", ";", "if", "(", "is_file", "(", "$", "root", ".", "$", "real_path", ".", "'.php'", ")", ")", "{", "$", "file", "=", "$", "root", ".", "$", "real_path", ".", "'.php'", ";", "}", "}", "// Then looks for a corresponding file in the regular MVC", "else", "if", "(", "file_exists", "(", "$", "root", ".", "$", "tmp", ".", "'.php'", ")", ")", "{", "$", "real_path", "=", "$", "tmp", ";", "$", "file", "=", "$", "root", ".", "$", "tmp", ".", "'.php'", ";", "}", "// Then looks for a home.php file in the corresponding directory", "else", "if", "(", "is_dir", "(", "$", "root", ".", "$", "tmp", ")", "&&", "is_file", "(", "$", "root", ".", "$", "tmp", ".", "'/home.php'", ")", ")", "{", "$", "real_path", "=", "$", "tmp", ".", "'/home'", ";", "$", "file", "=", "$", "root", ".", "$", "tmp", ".", "'/home.php'", ";", "}", "// If an alternative root exists (plugin), we look into it for the same", "else", "if", "(", "$", "this", "->", "alt_root", "&&", "(", "strpos", "(", "$", "tmp", ",", "$", "this", "->", "alt_root", ")", "===", "0", ")", ")", "{", "$", "name", "=", "substr", "(", "$", "tmp", ",", "\\", "strlen", "(", "$", "this", "->", "alt_root", ")", "+", "1", ")", ";", "// Corresponding file", "if", "(", "file_exists", "(", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ".", "$", "name", ".", "'.php'", ")", ")", "{", "$", "plugin", "=", "$", "this", "->", "alt_root", ";", "$", "real_path", "=", "$", "tmp", ";", "$", "file", "=", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ".", "$", "name", ".", "'.php'", ";", "$", "root", "=", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ";", "}", "// home.php in corresponding dir", "else", "if", "(", "is_dir", "(", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ".", "$", "name", ")", "&&", "is_file", "(", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ".", "$", "name", ".", "'/home.php'", ")", ")", "{", "$", "plugin", "=", "$", "this", "->", "alt_root", ";", "$", "real_path", "=", "$", "tmp", ".", "'/home'", ";", "$", "file", "=", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ".", "$", "name", ".", "'/home.php'", ";", "$", "root", "=", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ";", "}", "}", "}", "// Full DOM requested", "if", "(", "!", "$", "file", "&&", "(", "$", "mode", "===", "'dom'", ")", ")", "{", "if", "(", "$", "this", "->", "has_route", "(", "$", "tmp", ")", ")", "{", "return", "$", "this", "->", "find_controller", "(", "$", "this", "->", "get_route", "(", "$", "tmp", ")", ",", "$", "mode", ")", ";", "}", "// Root index file (if $tmp is at the root level)", "else", "if", "(", "(", "$", "tmp", "===", "'.'", ")", "&&", "!", "$", "this", "->", "alt_root", ")", "{", "// If file exists", "if", "(", "file_exists", "(", "$", "root", ".", "'index.php'", ")", ")", "{", "$", "real_path", "=", "'.'", ";", "$", "file", "=", "$", "root", ".", "'index.php'", ";", "}", "// Otherwise $file will remain undefined", "else", "{", "/** @todo throw an alert as there is no default index */", "die", "(", "'Impossible to find a route'", ")", ";", "break", ";", "}", "}", "// There is an index file in a subfolder", "else", "if", "(", "file_exists", "(", "$", "root", ".", "$", "tmp", ".", "'/index.php'", ")", ")", "{", "$", "real_path", "=", "$", "tmp", ";", "$", "file", "=", "$", "root", ".", "$", "tmp", ".", "'/index.php'", ";", "}", "// An alternative root exists, we look into it", "else", "if", "(", "$", "this", "->", "alt_root", "&&", "(", "strpos", "(", "$", "tmp", ",", "$", "this", "->", "alt_root", ")", "===", "0", ")", ")", "{", "if", "(", "$", "tmp", "===", "$", "this", "->", "alt_root", ")", "{", "$", "name", "=", "''", ";", "}", "else", "{", "$", "name", "=", "substr", "(", "$", "tmp", ",", "\\", "strlen", "(", "$", "this", "->", "alt_root", ")", "+", "1", ")", ";", "}", "// Corresponding file", "if", "(", "file_exists", "(", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ".", "$", "name", ".", "'/index.php'", ")", ")", "{", "$", "plugin", "=", "$", "this", "->", "alt_root", ";", "$", "real_path", "=", "$", "tmp", ";", "$", "file", "=", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ".", "$", "name", ".", "'/index.php'", ";", "$", "root", "=", "$", "this", "->", "get_alt_root", "(", "$", "mode", ")", ";", "}", "// home.php in corresponding dir", "}", "}", "if", "(", "$", "file", ")", "{", "break", ";", "}", "array_unshift", "(", "$", "args", ",", "basename", "(", "$", "tmp", ")", ")", ";", "$", "tmp", "=", "strpos", "(", "$", "tmp", ",", "'/'", ")", "===", "false", "?", "''", ":", "substr", "(", "$", "tmp", ",", "0", ",", "strrpos", "(", "$", "tmp", ",", "'/'", ")", ")", ";", "if", "(", "empty", "(", "$", "tmp", ")", "&&", "(", "$", "mode", "===", "'dom'", ")", ")", "{", "$", "tmp", "=", "'.'", ";", "}", "else", "if", "(", "$", "tmp", "===", "'.'", ")", "{", "$", "tmp", "=", "''", ";", "}", "}", "/*\n // Not found, sending the default controllers\n if ( !$file && is_file($root.'404.php') ){\n $real_path = '404';\n $file = $root.'404.php';\n }\n */", "if", "(", "$", "file", ")", "{", "if", "(", "$", "plugin", ")", "{", "$", "this", "->", "apply_locale", "(", "$", "plugin", ")", ";", "}", "return", "$", "this", "->", "set_known", "(", "[", "'file'", "=>", "$", "file", ",", "'path'", "=>", "$", "real_path", ",", "'root'", "=>", "\\", "dirname", "(", "$", "root", ",", "2", ")", ".", "'/'", ",", "'request'", "=>", "$", "path", ",", "'mode'", "=>", "$", "mode", ",", "'plugin'", "=>", "$", "plugin", ",", "'args'", "=>", "$", "args", ",", "]", ")", ";", "}", "// Aaaargh!", "//die(bbn\\x::dump(\"No default file defined for mode $mode $tmp (and no 404 file either)\"));", "}" ]
Return the actual controller file corresponding to a gievn path @param string $path @param string $mode @return mixed
[ "Return", "the", "actual", "controller", "file", "corresponding", "to", "a", "gievn", "path" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc/router.php#L264-L405
PHPPowertools/HTML5
src/PowerTools/HTML5/Parser/Scanner.php
HTML5_Parser_Scanner.next
public function next() { $this->is->next(); if ($this->is->valid()) { if ($this->debug) fprintf(STDOUT, "> %s\n", $this->is->current()); return $this->is->current(); } return false; }
php
public function next() { $this->is->next(); if ($this->is->valid()) { if ($this->debug) fprintf(STDOUT, "> %s\n", $this->is->current()); return $this->is->current(); } return false; }
[ "public", "function", "next", "(", ")", "{", "$", "this", "->", "is", "->", "next", "(", ")", ";", "if", "(", "$", "this", "->", "is", "->", "valid", "(", ")", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "fprintf", "(", "STDOUT", ",", "\"> %s\\n\"", ",", "$", "this", "->", "is", "->", "current", "(", ")", ")", ";", "return", "$", "this", "->", "is", "->", "current", "(", ")", ";", "}", "return", "false", ";", "}" ]
Get the next character. Note: This advances the pointer. @return string The next character.
[ "Get", "the", "next", "character", "." ]
train
https://github.com/PHPPowertools/HTML5/blob/4ea8caf5b2618a82ca5061dcbb7421b31065c1c7/src/PowerTools/HTML5/Parser/Scanner.php#L138-L147
i-lateral/silverstripe-users
code/control/Users_Account_Controller.php
Users_Account_Controller.init
public function init() { parent::init(); // Check we are logged in as a user who can access front end management if (!Permission::check("USERS_MANAGE_ACCOUNT")) { Security::permissionFailure(); } // Set our member object $member = Member::currentUser(); if ($member instanceof Member) { $this->member = $member; } }
php
public function init() { parent::init(); // Check we are logged in as a user who can access front end management if (!Permission::check("USERS_MANAGE_ACCOUNT")) { Security::permissionFailure(); } // Set our member object $member = Member::currentUser(); if ($member instanceof Member) { $this->member = $member; } }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "// Check we are logged in as a user who can access front end management", "if", "(", "!", "Permission", "::", "check", "(", "\"USERS_MANAGE_ACCOUNT\"", ")", ")", "{", "Security", "::", "permissionFailure", "(", ")", ";", "}", "// Set our member object", "$", "member", "=", "Member", "::", "currentUser", "(", ")", ";", "if", "(", "$", "member", "instanceof", "Member", ")", "{", "$", "this", "->", "member", "=", "$", "member", ";", "}", "}" ]
Perorm setup when this controller is initialised @return void
[ "Perorm", "setup", "when", "this", "controller", "is", "initialised" ]
train
https://github.com/i-lateral/silverstripe-users/blob/27ddc38890fa2709ac419eccf854ab6b439f0d9a/code/control/Users_Account_Controller.php#L83-L98
i-lateral/silverstripe-users
code/control/Users_Account_Controller.php
Users_Account_Controller.index
public function index() { // Setup default profile summary sections $sections = ArrayList::create(); $sections->push( ArrayData::create( array( "Title" => "", "Content" => $this->renderWith( "UsersProfileSummary", array("CurrentUser" => Member::currentUser()) ) ) ) ); // Allow users to add extra content sections to the // summary $this->extend("updateIndexSections", $sections); $this->customise( array( "Title" => _t('Users.ProfileSummary', 'Profile Summary'), "MetaTitle" => _t('Users.ProfileSummary', 'Profile Summary'), "Content" => $this->renderWith( "UsersAccountSections", array("Sections" => $sections) ) ) ); $this->extend("onBeforeIndex"); return $this->renderWith( array( "UserAccount", "Page" ) ); }
php
public function index() { // Setup default profile summary sections $sections = ArrayList::create(); $sections->push( ArrayData::create( array( "Title" => "", "Content" => $this->renderWith( "UsersProfileSummary", array("CurrentUser" => Member::currentUser()) ) ) ) ); // Allow users to add extra content sections to the // summary $this->extend("updateIndexSections", $sections); $this->customise( array( "Title" => _t('Users.ProfileSummary', 'Profile Summary'), "MetaTitle" => _t('Users.ProfileSummary', 'Profile Summary'), "Content" => $this->renderWith( "UsersAccountSections", array("Sections" => $sections) ) ) ); $this->extend("onBeforeIndex"); return $this->renderWith( array( "UserAccount", "Page" ) ); }
[ "public", "function", "index", "(", ")", "{", "// Setup default profile summary sections", "$", "sections", "=", "ArrayList", "::", "create", "(", ")", ";", "$", "sections", "->", "push", "(", "ArrayData", "::", "create", "(", "array", "(", "\"Title\"", "=>", "\"\"", ",", "\"Content\"", "=>", "$", "this", "->", "renderWith", "(", "\"UsersProfileSummary\"", ",", "array", "(", "\"CurrentUser\"", "=>", "Member", "::", "currentUser", "(", ")", ")", ")", ")", ")", ")", ";", "// Allow users to add extra content sections to the", "// summary", "$", "this", "->", "extend", "(", "\"updateIndexSections\"", ",", "$", "sections", ")", ";", "$", "this", "->", "customise", "(", "array", "(", "\"Title\"", "=>", "_t", "(", "'Users.ProfileSummary'", ",", "'Profile Summary'", ")", ",", "\"MetaTitle\"", "=>", "_t", "(", "'Users.ProfileSummary'", ",", "'Profile Summary'", ")", ",", "\"Content\"", "=>", "$", "this", "->", "renderWith", "(", "\"UsersAccountSections\"", ",", "array", "(", "\"Sections\"", "=>", "$", "sections", ")", ")", ")", ")", ";", "$", "this", "->", "extend", "(", "\"onBeforeIndex\"", ")", ";", "return", "$", "this", "->", "renderWith", "(", "array", "(", "\"UserAccount\"", ",", "\"Page\"", ")", ")", ";", "}" ]
Display the currently outstanding orders for the current user @return HTMLText
[ "Display", "the", "currently", "outstanding", "orders", "for", "the", "current", "user" ]
train
https://github.com/i-lateral/silverstripe-users/blob/27ddc38890fa2709ac419eccf854ab6b439f0d9a/code/control/Users_Account_Controller.php#L174-L214
i-lateral/silverstripe-users
code/control/Users_Account_Controller.php
Users_Account_Controller.ChangePasswordForm
public function ChangePasswordForm() { $form = ChangePasswordForm::create($this, "ChangePasswordForm"); $form ->Actions() ->find("name", "action_doChangePassword") ->addExtraClass("btn") ->addExtraClass("btn-green"); $cancel_btn = LiteralField::create( "CancelLink", '<a href="' . $this->Link() . '" class="btn btn-red">'. _t("Users.CANCEL", "Cancel") .'</a>' ); $form ->Actions() ->insertBefore($cancel_btn, "action_doChangePassword"); $this->extend("updateChangePasswordForm", $form); return $form; }
php
public function ChangePasswordForm() { $form = ChangePasswordForm::create($this, "ChangePasswordForm"); $form ->Actions() ->find("name", "action_doChangePassword") ->addExtraClass("btn") ->addExtraClass("btn-green"); $cancel_btn = LiteralField::create( "CancelLink", '<a href="' . $this->Link() . '" class="btn btn-red">'. _t("Users.CANCEL", "Cancel") .'</a>' ); $form ->Actions() ->insertBefore($cancel_btn, "action_doChangePassword"); $this->extend("updateChangePasswordForm", $form); return $form; }
[ "public", "function", "ChangePasswordForm", "(", ")", "{", "$", "form", "=", "ChangePasswordForm", "::", "create", "(", "$", "this", ",", "\"ChangePasswordForm\"", ")", ";", "$", "form", "->", "Actions", "(", ")", "->", "find", "(", "\"name\"", ",", "\"action_doChangePassword\"", ")", "->", "addExtraClass", "(", "\"btn\"", ")", "->", "addExtraClass", "(", "\"btn-green\"", ")", ";", "$", "cancel_btn", "=", "LiteralField", "::", "create", "(", "\"CancelLink\"", ",", "'<a href=\"'", ".", "$", "this", "->", "Link", "(", ")", ".", "'\" class=\"btn btn-red\">'", ".", "_t", "(", "\"Users.CANCEL\"", ",", "\"Cancel\"", ")", ".", "'</a>'", ")", ";", "$", "form", "->", "Actions", "(", ")", "->", "insertBefore", "(", "$", "cancel_btn", ",", "\"action_doChangePassword\"", ")", ";", "$", "this", "->", "extend", "(", "\"updateChangePasswordForm\"", ",", "$", "form", ")", ";", "return", "$", "form", ";", "}" ]
Factory for generating a change password form. The form can be expanded using an extension class and calling the updateChangePasswordForm method. @return Form
[ "Factory", "for", "generating", "a", "change", "password", "form", ".", "The", "form", "can", "be", "expanded", "using", "an", "extension", "class", "and", "calling", "the", "updateChangePasswordForm", "method", "." ]
train
https://github.com/i-lateral/silverstripe-users/blob/27ddc38890fa2709ac419eccf854ab6b439f0d9a/code/control/Users_Account_Controller.php#L305-L327
i-lateral/silverstripe-users
code/control/Users_Account_Controller.php
Users_Account_Controller.getAccountMenu
public function getAccountMenu() { $menu = ArrayList::create(); $curr_action = $this->request->param("Action"); $menu->add( ArrayData::create( array( "ID" => 0, "Title" => _t('Users.PROFILESUMMARY', "Profile Summary"), "Link" => $this->Link(), "LinkingMode" => (!$curr_action) ? "current" : "link" ) ) ); $menu->add( ArrayData::create( array( "ID" => 10, "Title" => _t('Users.EDITDETAILS', "Edit account details"), "Link" => $this->Link("edit"), "LinkingMode" => ($curr_action == "edit") ? "current" : "link" ) ) ); $menu->add( ArrayData::create( array( "ID" => 30, "Title" => _t('Users.CHANGEPASSWORD', "Change password"), "Link" => $this->Link("changepassword"), "LinkingMode" => ($curr_action == "changepassword") ? "current" : "link" ) ) ); $this->extend("updateAccountMenu", $menu); return $menu->sort("ID", "ASC"); }
php
public function getAccountMenu() { $menu = ArrayList::create(); $curr_action = $this->request->param("Action"); $menu->add( ArrayData::create( array( "ID" => 0, "Title" => _t('Users.PROFILESUMMARY', "Profile Summary"), "Link" => $this->Link(), "LinkingMode" => (!$curr_action) ? "current" : "link" ) ) ); $menu->add( ArrayData::create( array( "ID" => 10, "Title" => _t('Users.EDITDETAILS', "Edit account details"), "Link" => $this->Link("edit"), "LinkingMode" => ($curr_action == "edit") ? "current" : "link" ) ) ); $menu->add( ArrayData::create( array( "ID" => 30, "Title" => _t('Users.CHANGEPASSWORD', "Change password"), "Link" => $this->Link("changepassword"), "LinkingMode" => ($curr_action == "changepassword") ? "current" : "link" ) ) ); $this->extend("updateAccountMenu", $menu); return $menu->sort("ID", "ASC"); }
[ "public", "function", "getAccountMenu", "(", ")", "{", "$", "menu", "=", "ArrayList", "::", "create", "(", ")", ";", "$", "curr_action", "=", "$", "this", "->", "request", "->", "param", "(", "\"Action\"", ")", ";", "$", "menu", "->", "add", "(", "ArrayData", "::", "create", "(", "array", "(", "\"ID\"", "=>", "0", ",", "\"Title\"", "=>", "_t", "(", "'Users.PROFILESUMMARY'", ",", "\"Profile Summary\"", ")", ",", "\"Link\"", "=>", "$", "this", "->", "Link", "(", ")", ",", "\"LinkingMode\"", "=>", "(", "!", "$", "curr_action", ")", "?", "\"current\"", ":", "\"link\"", ")", ")", ")", ";", "$", "menu", "->", "add", "(", "ArrayData", "::", "create", "(", "array", "(", "\"ID\"", "=>", "10", ",", "\"Title\"", "=>", "_t", "(", "'Users.EDITDETAILS'", ",", "\"Edit account details\"", ")", ",", "\"Link\"", "=>", "$", "this", "->", "Link", "(", "\"edit\"", ")", ",", "\"LinkingMode\"", "=>", "(", "$", "curr_action", "==", "\"edit\"", ")", "?", "\"current\"", ":", "\"link\"", ")", ")", ")", ";", "$", "menu", "->", "add", "(", "ArrayData", "::", "create", "(", "array", "(", "\"ID\"", "=>", "30", ",", "\"Title\"", "=>", "_t", "(", "'Users.CHANGEPASSWORD'", ",", "\"Change password\"", ")", ",", "\"Link\"", "=>", "$", "this", "->", "Link", "(", "\"changepassword\"", ")", ",", "\"LinkingMode\"", "=>", "(", "$", "curr_action", "==", "\"changepassword\"", ")", "?", "\"current\"", ":", "\"link\"", ")", ")", ")", ";", "$", "this", "->", "extend", "(", "\"updateAccountMenu\"", ",", "$", "menu", ")", ";", "return", "$", "menu", "->", "sort", "(", "\"ID\"", ",", "\"ASC\"", ")", ";", "}" ]
Return a list of nav items for managing a users profile. You can add new items to this menu using the "updateAccountMenu" extension @return ArrayList
[ "Return", "a", "list", "of", "nav", "items", "for", "managing", "a", "users", "profile", ".", "You", "can", "add", "new", "items", "to", "this", "menu", "using", "the", "updateAccountMenu", "extension" ]
train
https://github.com/i-lateral/silverstripe-users/blob/27ddc38890fa2709ac419eccf854ab6b439f0d9a/code/control/Users_Account_Controller.php#L335-L377
songshenzong/log
src/TokenMiddleware.php
TokenMiddleware.handle
public function handle($request, Closure $next) { if (isset($request->token)) { $tokens = config('songshenzong-log.token', ['songshenzong']); if (in_array($request->token, $tokens, true)) { return $next($request); } return $this->songshenzong->json(403, $request->token . ' is Invalid Token !'); } return $this->songshenzong->json(403, 'No Token !'); }
php
public function handle($request, Closure $next) { if (isset($request->token)) { $tokens = config('songshenzong-log.token', ['songshenzong']); if (in_array($request->token, $tokens, true)) { return $next($request); } return $this->songshenzong->json(403, $request->token . ' is Invalid Token !'); } return $this->songshenzong->json(403, 'No Token !'); }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ")", "{", "if", "(", "isset", "(", "$", "request", "->", "token", ")", ")", "{", "$", "tokens", "=", "config", "(", "'songshenzong-log.token'", ",", "[", "'songshenzong'", "]", ")", ";", "if", "(", "in_array", "(", "$", "request", "->", "token", ",", "$", "tokens", ",", "true", ")", ")", "{", "return", "$", "next", "(", "$", "request", ")", ";", "}", "return", "$", "this", "->", "songshenzong", "->", "json", "(", "403", ",", "$", "request", "->", "token", ".", "' is Invalid Token !'", ")", ";", "}", "return", "$", "this", "->", "songshenzong", "->", "json", "(", "403", ",", "'No Token !'", ")", ";", "}" ]
Handle an incoming request. @param Request $request @param Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/TokenMiddleware.php#L54-L64
arndtteunissen/column-layout
Classes/Hook/ColumnConfigurationGridsystemFlexFormHook.php
ColumnConfigurationGridsystemFlexFormHook.getDataStructureIdentifierPreProcess
public function getDataStructureIdentifierPreProcess(array $fieldTca, string $tableName, string $fieldName, array $row): array { if ($tableName != 'tt_content' || $fieldName != 'tx_column_layout_column_config') { return []; } return [ 'type' => 'tca', 'tableName' => $tableName, 'fieldName' => $fieldName, 'dataStructureKey' => ColumnLayoutUtility::getColumnLayoutSettings($row['_tx_column_layout_orig_pid'] ?? $row['pid'])['flexFormKey'] ]; }
php
public function getDataStructureIdentifierPreProcess(array $fieldTca, string $tableName, string $fieldName, array $row): array { if ($tableName != 'tt_content' || $fieldName != 'tx_column_layout_column_config') { return []; } return [ 'type' => 'tca', 'tableName' => $tableName, 'fieldName' => $fieldName, 'dataStructureKey' => ColumnLayoutUtility::getColumnLayoutSettings($row['_tx_column_layout_orig_pid'] ?? $row['pid'])['flexFormKey'] ]; }
[ "public", "function", "getDataStructureIdentifierPreProcess", "(", "array", "$", "fieldTca", ",", "string", "$", "tableName", ",", "string", "$", "fieldName", ",", "array", "$", "row", ")", ":", "array", "{", "if", "(", "$", "tableName", "!=", "'tt_content'", "||", "$", "fieldName", "!=", "'tx_column_layout_column_config'", ")", "{", "return", "[", "]", ";", "}", "return", "[", "'type'", "=>", "'tca'", ",", "'tableName'", "=>", "$", "tableName", ",", "'fieldName'", "=>", "$", "fieldName", ",", "'dataStructureKey'", "=>", "ColumnLayoutUtility", "::", "getColumnLayoutSettings", "(", "$", "row", "[", "'_tx_column_layout_orig_pid'", "]", "??", "$", "row", "[", "'pid'", "]", ")", "[", "'flexFormKey'", "]", "]", ";", "}" ]
Generates a DataStructureIdentifier for the flexform in column configuration field @param array $fieldTca @param string $tableName @param string $fieldName @param array $row @return array @throws \TYPO3\CMS\Core\Exception
[ "Generates", "a", "DataStructureIdentifier", "for", "the", "flexform", "in", "column", "configuration", "field" ]
train
https://github.com/arndtteunissen/column-layout/blob/ad737068eef3b084d4d0e3a48e6a3d8277af9560/Classes/Hook/ColumnConfigurationGridsystemFlexFormHook.php#L32-L44
ShaoZeMing/laravel-merchant
src/Controllers/UserController.php
UserController.grid
protected function grid() { return Administrator::grid(function (Grid $grid) { $grid->model()->where('merchant_id', auth('merchant')->user()->merchant_id); $grid->mobile(trans('merchant.mobile')); $grid->name(trans('merchant.name')); $grid->roles(trans('merchant.roles'))->pluck('name')->label(); $grid->created_at(trans('merchant.created_at')); $grid->updated_at(trans('merchant.updated_at')); $grid->actions(function (Grid\Displayers\Actions $actions)use($grid) { if (Administrator::find($actions->getKey())->user_type) { $actions->disableDelete();} }); $grid->tools(function (Grid\Tools $tools) { $tools->batch(function (Grid\Tools\BatchActions $actions) { $actions->disableDelete(); }); }); }); }
php
protected function grid() { return Administrator::grid(function (Grid $grid) { $grid->model()->where('merchant_id', auth('merchant')->user()->merchant_id); $grid->mobile(trans('merchant.mobile')); $grid->name(trans('merchant.name')); $grid->roles(trans('merchant.roles'))->pluck('name')->label(); $grid->created_at(trans('merchant.created_at')); $grid->updated_at(trans('merchant.updated_at')); $grid->actions(function (Grid\Displayers\Actions $actions)use($grid) { if (Administrator::find($actions->getKey())->user_type) { $actions->disableDelete();} }); $grid->tools(function (Grid\Tools $tools) { $tools->batch(function (Grid\Tools\BatchActions $actions) { $actions->disableDelete(); }); }); }); }
[ "protected", "function", "grid", "(", ")", "{", "return", "Administrator", "::", "grid", "(", "function", "(", "Grid", "$", "grid", ")", "{", "$", "grid", "->", "model", "(", ")", "->", "where", "(", "'merchant_id'", ",", "auth", "(", "'merchant'", ")", "->", "user", "(", ")", "->", "merchant_id", ")", ";", "$", "grid", "->", "mobile", "(", "trans", "(", "'merchant.mobile'", ")", ")", ";", "$", "grid", "->", "name", "(", "trans", "(", "'merchant.name'", ")", ")", ";", "$", "grid", "->", "roles", "(", "trans", "(", "'merchant.roles'", ")", ")", "->", "pluck", "(", "'name'", ")", "->", "label", "(", ")", ";", "$", "grid", "->", "created_at", "(", "trans", "(", "'merchant.created_at'", ")", ")", ";", "$", "grid", "->", "updated_at", "(", "trans", "(", "'merchant.updated_at'", ")", ")", ";", "$", "grid", "->", "actions", "(", "function", "(", "Grid", "\\", "Displayers", "\\", "Actions", "$", "actions", ")", "use", "(", "$", "grid", ")", "{", "if", "(", "Administrator", "::", "find", "(", "$", "actions", "->", "getKey", "(", ")", ")", "->", "user_type", ")", "{", "$", "actions", "->", "disableDelete", "(", ")", ";", "}", "}", ")", ";", "$", "grid", "->", "tools", "(", "function", "(", "Grid", "\\", "Tools", "$", "tools", ")", "{", "$", "tools", "->", "batch", "(", "function", "(", "Grid", "\\", "Tools", "\\", "BatchActions", "$", "actions", ")", "{", "$", "actions", "->", "disableDelete", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Make a grid builder. @return Grid
[ "Make", "a", "grid", "builder", "." ]
train
https://github.com/ShaoZeMing/laravel-merchant/blob/20801b1735e7832a6e58b37c2c391328f8d626fa/src/Controllers/UserController.php#L67-L88
ShaoZeMing/laravel-merchant
src/Controllers/UserController.php
UserController.form
public function form() { return Administrator::form(function (Form $form) { $form->mobile('mobile', trans('merchant.mobile'))->rules('required'); $form->email('email', trans('merchant.email'))->default(''); $form->text('name', trans('merchant.name'))->rules('required'); $form->image('avatar', trans('merchant.avatar')); $form->password('password', trans('merchant.password'))->rules('required|confirmed'); $form->password('password_confirmation', trans('merchant.password_confirmation'))->rules('required') ->default(function ($form) { return $form->model()->password; }); $form->ignore(['password_confirmation']); $form->multipleSelect('roles', trans('merchant.roles'))->options(Role::all()->pluck('name', 'id')); $form->multipleSelect('permissions', trans('merchant.permissions'))->options(Permission::all()->pluck('name', 'id')); $form->display('created_at', trans('merchant.created_at')); $form->display('updated_at', trans('merchant.updated_at')); $form->hidden('merchant_id'); $form->saving(function (Form $form) { $form->merchant_id = auth('merchant')->user()->merchant_id; if ($form->password && $form->model()->password != $form->password) { $form->password = bcrypt($form->password); } }); }); }
php
public function form() { return Administrator::form(function (Form $form) { $form->mobile('mobile', trans('merchant.mobile'))->rules('required'); $form->email('email', trans('merchant.email'))->default(''); $form->text('name', trans('merchant.name'))->rules('required'); $form->image('avatar', trans('merchant.avatar')); $form->password('password', trans('merchant.password'))->rules('required|confirmed'); $form->password('password_confirmation', trans('merchant.password_confirmation'))->rules('required') ->default(function ($form) { return $form->model()->password; }); $form->ignore(['password_confirmation']); $form->multipleSelect('roles', trans('merchant.roles'))->options(Role::all()->pluck('name', 'id')); $form->multipleSelect('permissions', trans('merchant.permissions'))->options(Permission::all()->pluck('name', 'id')); $form->display('created_at', trans('merchant.created_at')); $form->display('updated_at', trans('merchant.updated_at')); $form->hidden('merchant_id'); $form->saving(function (Form $form) { $form->merchant_id = auth('merchant')->user()->merchant_id; if ($form->password && $form->model()->password != $form->password) { $form->password = bcrypt($form->password); } }); }); }
[ "public", "function", "form", "(", ")", "{", "return", "Administrator", "::", "form", "(", "function", "(", "Form", "$", "form", ")", "{", "$", "form", "->", "mobile", "(", "'mobile'", ",", "trans", "(", "'merchant.mobile'", ")", ")", "->", "rules", "(", "'required'", ")", ";", "$", "form", "->", "email", "(", "'email'", ",", "trans", "(", "'merchant.email'", ")", ")", "->", "default", "(", "''", ")", ";", "$", "form", "->", "text", "(", "'name'", ",", "trans", "(", "'merchant.name'", ")", ")", "->", "rules", "(", "'required'", ")", ";", "$", "form", "->", "image", "(", "'avatar'", ",", "trans", "(", "'merchant.avatar'", ")", ")", ";", "$", "form", "->", "password", "(", "'password'", ",", "trans", "(", "'merchant.password'", ")", ")", "->", "rules", "(", "'required|confirmed'", ")", ";", "$", "form", "->", "password", "(", "'password_confirmation'", ",", "trans", "(", "'merchant.password_confirmation'", ")", ")", "->", "rules", "(", "'required'", ")", "->", "default", "(", "function", "(", "$", "form", ")", "{", "return", "$", "form", "->", "model", "(", ")", "->", "password", ";", "}", ")", ";", "$", "form", "->", "ignore", "(", "[", "'password_confirmation'", "]", ")", ";", "$", "form", "->", "multipleSelect", "(", "'roles'", ",", "trans", "(", "'merchant.roles'", ")", ")", "->", "options", "(", "Role", "::", "all", "(", ")", "->", "pluck", "(", "'name'", ",", "'id'", ")", ")", ";", "$", "form", "->", "multipleSelect", "(", "'permissions'", ",", "trans", "(", "'merchant.permissions'", ")", ")", "->", "options", "(", "Permission", "::", "all", "(", ")", "->", "pluck", "(", "'name'", ",", "'id'", ")", ")", ";", "$", "form", "->", "display", "(", "'created_at'", ",", "trans", "(", "'merchant.created_at'", ")", ")", ";", "$", "form", "->", "display", "(", "'updated_at'", ",", "trans", "(", "'merchant.updated_at'", ")", ")", ";", "$", "form", "->", "hidden", "(", "'merchant_id'", ")", ";", "$", "form", "->", "saving", "(", "function", "(", "Form", "$", "form", ")", "{", "$", "form", "->", "merchant_id", "=", "auth", "(", "'merchant'", ")", "->", "user", "(", ")", "->", "merchant_id", ";", "if", "(", "$", "form", "->", "password", "&&", "$", "form", "->", "model", "(", ")", "->", "password", "!=", "$", "form", "->", "password", ")", "{", "$", "form", "->", "password", "=", "bcrypt", "(", "$", "form", "->", "password", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Make a form builder. @return Form
[ "Make", "a", "form", "builder", "." ]
train
https://github.com/ShaoZeMing/laravel-merchant/blob/20801b1735e7832a6e58b37c2c391328f8d626fa/src/Controllers/UserController.php#L95-L122
geosocio/slugger
src/Slugger.php
Slugger.slug
public function slug(string $text) : string { $slug = trim($text); $slug = mb_strtolower($slug); $slug = str_replace(' ', '-', $slug); $slug = str_replace(['.', '(', ')'], '', $slug); $slug = preg_replace('/-{2,}/u', '-', $slug); $slug = trim($slug, '-'); return $slug; }
php
public function slug(string $text) : string { $slug = trim($text); $slug = mb_strtolower($slug); $slug = str_replace(' ', '-', $slug); $slug = str_replace(['.', '(', ')'], '', $slug); $slug = preg_replace('/-{2,}/u', '-', $slug); $slug = trim($slug, '-'); return $slug; }
[ "public", "function", "slug", "(", "string", "$", "text", ")", ":", "string", "{", "$", "slug", "=", "trim", "(", "$", "text", ")", ";", "$", "slug", "=", "mb_strtolower", "(", "$", "slug", ")", ";", "$", "slug", "=", "str_replace", "(", "' '", ",", "'-'", ",", "$", "slug", ")", ";", "$", "slug", "=", "str_replace", "(", "[", "'.'", ",", "'('", ",", "')'", "]", ",", "''", ",", "$", "slug", ")", ";", "$", "slug", "=", "preg_replace", "(", "'/-{2,}/u'", ",", "'-'", ",", "$", "slug", ")", ";", "$", "slug", "=", "trim", "(", "$", "slug", ",", "'-'", ")", ";", "return", "$", "slug", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/geosocio/slugger/blob/230b0564bd75a5c009ce68be88e1b1d828bac5c3/src/Slugger.php#L14-L24
blast-project/BaseEntitiesBundle
src/Entity/Repository/SortableRepository.php
SortableRepository.moveObjectAfter
public function moveObjectAfter($id, $after_rank) { $object = $this->find($id); if (!$object) { return false; } $old_rank = $object->getSortRank(); $qb = $this->_em->createQueryBuilder() ->select('MIN(n.sortRank)') ->from($this->_entityName, 'n') ->where('n.sortRank > :rank') ->setParameter('rank', $after_rank); $query = $qb->getQuery(); $res = $query->getResult(); $before_rank = empty($res[0][1]) ? $after_rank + 2048 : $res[0][1]; if ($old_rank > $after_rank && $old_rank < $before_rank) { return $old_rank; } $new_rank = $after_rank + ($before_rank - $after_rank) / 2; $object->setSortRank($new_rank); $this->_em->persist($object); $this->_em->flush(); return $new_rank; }
php
public function moveObjectAfter($id, $after_rank) { $object = $this->find($id); if (!$object) { return false; } $old_rank = $object->getSortRank(); $qb = $this->_em->createQueryBuilder() ->select('MIN(n.sortRank)') ->from($this->_entityName, 'n') ->where('n.sortRank > :rank') ->setParameter('rank', $after_rank); $query = $qb->getQuery(); $res = $query->getResult(); $before_rank = empty($res[0][1]) ? $after_rank + 2048 : $res[0][1]; if ($old_rank > $after_rank && $old_rank < $before_rank) { return $old_rank; } $new_rank = $after_rank + ($before_rank - $after_rank) / 2; $object->setSortRank($new_rank); $this->_em->persist($object); $this->_em->flush(); return $new_rank; }
[ "public", "function", "moveObjectAfter", "(", "$", "id", ",", "$", "after_rank", ")", "{", "$", "object", "=", "$", "this", "->", "find", "(", "$", "id", ")", ";", "if", "(", "!", "$", "object", ")", "{", "return", "false", ";", "}", "$", "old_rank", "=", "$", "object", "->", "getSortRank", "(", ")", ";", "$", "qb", "=", "$", "this", "->", "_em", "->", "createQueryBuilder", "(", ")", "->", "select", "(", "'MIN(n.sortRank)'", ")", "->", "from", "(", "$", "this", "->", "_entityName", ",", "'n'", ")", "->", "where", "(", "'n.sortRank > :rank'", ")", "->", "setParameter", "(", "'rank'", ",", "$", "after_rank", ")", ";", "$", "query", "=", "$", "qb", "->", "getQuery", "(", ")", ";", "$", "res", "=", "$", "query", "->", "getResult", "(", ")", ";", "$", "before_rank", "=", "empty", "(", "$", "res", "[", "0", "]", "[", "1", "]", ")", "?", "$", "after_rank", "+", "2048", ":", "$", "res", "[", "0", "]", "[", "1", "]", ";", "if", "(", "$", "old_rank", ">", "$", "after_rank", "&&", "$", "old_rank", "<", "$", "before_rank", ")", "{", "return", "$", "old_rank", ";", "}", "$", "new_rank", "=", "$", "after_rank", "+", "(", "$", "before_rank", "-", "$", "after_rank", ")", "/", "2", ";", "$", "object", "->", "setSortRank", "(", "$", "new_rank", ")", ";", "$", "this", "->", "_em", "->", "persist", "(", "$", "object", ")", ";", "$", "this", "->", "_em", "->", "flush", "(", ")", ";", "return", "$", "new_rank", ";", "}" ]
Move an object after a given sort rank (add 1024 to the rank if the object is moved beyond the highest existing rank). @param string $id Id of the object to move @param int $after_rank @return int | false the new rank or false if the object could not be moved
[ "Move", "an", "object", "after", "a", "given", "sort", "rank", "(", "add", "1024", "to", "the", "rank", "if", "the", "object", "is", "moved", "beyond", "the", "highest", "existing", "rank", ")", "." ]
train
https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/Entity/Repository/SortableRepository.php#L50-L79
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Writer/Xsl.php
Xsl.transform
public function transform(ProjectDescriptor $project, Transformation $transformation) { $structure = $this->loadAst($this->getAstPath($transformation)); $proc = $this->getXslProcessor($transformation); $proc->registerPHPFunctions(); $this->registerDefaultVariables($transformation, $proc, $structure); $this->setProcessorParameters($transformation, $proc); $artifact = $this->getArtifactPath($transformation); $this->checkForSpacesInPath($artifact); // if a query is given, then apply a transformation to the artifact // location by replacing ($<var>} with the sluggified node-value of the // search result if ($transformation->getQuery() !== '') { $xpath = new \DOMXPath($structure); /** @var \DOMNodeList $qry */ $qry = $xpath->query($transformation->getQuery()); $count = $qry->length; foreach ($qry as $key => $element) { Dispatcher::getInstance()->dispatch( 'transformer.writer.xsl.pre', PreXslWriterEvent::createInstance($this)->setElement($element)->setProgress(array($key+1, $count)) ); $proc->setParameter('', $element->nodeName, $element->nodeValue); $file_name = $transformation->getTransformer()->generateFilename( $element->nodeValue ); if (! $artifact) { $url = $this->generateUrlForXmlElement($project, $element); if ($url === false || $url[0] !== DIRECTORY_SEPARATOR) { continue; } $filename = $transformation->getTransformer()->getTarget() . str_replace('/', DIRECTORY_SEPARATOR, $url); } else { $filename = str_replace('{$' . $element->nodeName . '}', $file_name, $artifact); } $relativeFileName = substr($filename, strlen($transformation->getTransformer()->getTarget()) + 1); $proc->setParameter('', 'root', str_repeat('../', substr_count($relativeFileName, '/'))); $this->writeToFile($filename, $proc, $structure); } } else { if (substr($transformation->getArtifact(), 0, 1) == '$') { // not a file, it must become a variable! $variable_name = substr($transformation->getArtifact(), 1); $this->xsl_variables[$variable_name] = $proc->transformToXml($structure); } else { $relativeFileName = substr($artifact, strlen($transformation->getTransformer()->getTarget()) + 1); $proc->setParameter('', 'root', str_repeat('../', substr_count($relativeFileName, '/'))); $this->writeToFile($artifact, $proc, $structure); } } }
php
public function transform(ProjectDescriptor $project, Transformation $transformation) { $structure = $this->loadAst($this->getAstPath($transformation)); $proc = $this->getXslProcessor($transformation); $proc->registerPHPFunctions(); $this->registerDefaultVariables($transformation, $proc, $structure); $this->setProcessorParameters($transformation, $proc); $artifact = $this->getArtifactPath($transformation); $this->checkForSpacesInPath($artifact); // if a query is given, then apply a transformation to the artifact // location by replacing ($<var>} with the sluggified node-value of the // search result if ($transformation->getQuery() !== '') { $xpath = new \DOMXPath($structure); /** @var \DOMNodeList $qry */ $qry = $xpath->query($transformation->getQuery()); $count = $qry->length; foreach ($qry as $key => $element) { Dispatcher::getInstance()->dispatch( 'transformer.writer.xsl.pre', PreXslWriterEvent::createInstance($this)->setElement($element)->setProgress(array($key+1, $count)) ); $proc->setParameter('', $element->nodeName, $element->nodeValue); $file_name = $transformation->getTransformer()->generateFilename( $element->nodeValue ); if (! $artifact) { $url = $this->generateUrlForXmlElement($project, $element); if ($url === false || $url[0] !== DIRECTORY_SEPARATOR) { continue; } $filename = $transformation->getTransformer()->getTarget() . str_replace('/', DIRECTORY_SEPARATOR, $url); } else { $filename = str_replace('{$' . $element->nodeName . '}', $file_name, $artifact); } $relativeFileName = substr($filename, strlen($transformation->getTransformer()->getTarget()) + 1); $proc->setParameter('', 'root', str_repeat('../', substr_count($relativeFileName, '/'))); $this->writeToFile($filename, $proc, $structure); } } else { if (substr($transformation->getArtifact(), 0, 1) == '$') { // not a file, it must become a variable! $variable_name = substr($transformation->getArtifact(), 1); $this->xsl_variables[$variable_name] = $proc->transformToXml($structure); } else { $relativeFileName = substr($artifact, strlen($transformation->getTransformer()->getTarget()) + 1); $proc->setParameter('', 'root', str_repeat('../', substr_count($relativeFileName, '/'))); $this->writeToFile($artifact, $proc, $structure); } } }
[ "public", "function", "transform", "(", "ProjectDescriptor", "$", "project", ",", "Transformation", "$", "transformation", ")", "{", "$", "structure", "=", "$", "this", "->", "loadAst", "(", "$", "this", "->", "getAstPath", "(", "$", "transformation", ")", ")", ";", "$", "proc", "=", "$", "this", "->", "getXslProcessor", "(", "$", "transformation", ")", ";", "$", "proc", "->", "registerPHPFunctions", "(", ")", ";", "$", "this", "->", "registerDefaultVariables", "(", "$", "transformation", ",", "$", "proc", ",", "$", "structure", ")", ";", "$", "this", "->", "setProcessorParameters", "(", "$", "transformation", ",", "$", "proc", ")", ";", "$", "artifact", "=", "$", "this", "->", "getArtifactPath", "(", "$", "transformation", ")", ";", "$", "this", "->", "checkForSpacesInPath", "(", "$", "artifact", ")", ";", "// if a query is given, then apply a transformation to the artifact", "// location by replacing ($<var>} with the sluggified node-value of the", "// search result", "if", "(", "$", "transformation", "->", "getQuery", "(", ")", "!==", "''", ")", "{", "$", "xpath", "=", "new", "\\", "DOMXPath", "(", "$", "structure", ")", ";", "/** @var \\DOMNodeList $qry */", "$", "qry", "=", "$", "xpath", "->", "query", "(", "$", "transformation", "->", "getQuery", "(", ")", ")", ";", "$", "count", "=", "$", "qry", "->", "length", ";", "foreach", "(", "$", "qry", "as", "$", "key", "=>", "$", "element", ")", "{", "Dispatcher", "::", "getInstance", "(", ")", "->", "dispatch", "(", "'transformer.writer.xsl.pre'", ",", "PreXslWriterEvent", "::", "createInstance", "(", "$", "this", ")", "->", "setElement", "(", "$", "element", ")", "->", "setProgress", "(", "array", "(", "$", "key", "+", "1", ",", "$", "count", ")", ")", ")", ";", "$", "proc", "->", "setParameter", "(", "''", ",", "$", "element", "->", "nodeName", ",", "$", "element", "->", "nodeValue", ")", ";", "$", "file_name", "=", "$", "transformation", "->", "getTransformer", "(", ")", "->", "generateFilename", "(", "$", "element", "->", "nodeValue", ")", ";", "if", "(", "!", "$", "artifact", ")", "{", "$", "url", "=", "$", "this", "->", "generateUrlForXmlElement", "(", "$", "project", ",", "$", "element", ")", ";", "if", "(", "$", "url", "===", "false", "||", "$", "url", "[", "0", "]", "!==", "DIRECTORY_SEPARATOR", ")", "{", "continue", ";", "}", "$", "filename", "=", "$", "transformation", "->", "getTransformer", "(", ")", "->", "getTarget", "(", ")", ".", "str_replace", "(", "'/'", ",", "DIRECTORY_SEPARATOR", ",", "$", "url", ")", ";", "}", "else", "{", "$", "filename", "=", "str_replace", "(", "'{$'", ".", "$", "element", "->", "nodeName", ".", "'}'", ",", "$", "file_name", ",", "$", "artifact", ")", ";", "}", "$", "relativeFileName", "=", "substr", "(", "$", "filename", ",", "strlen", "(", "$", "transformation", "->", "getTransformer", "(", ")", "->", "getTarget", "(", ")", ")", "+", "1", ")", ";", "$", "proc", "->", "setParameter", "(", "''", ",", "'root'", ",", "str_repeat", "(", "'../'", ",", "substr_count", "(", "$", "relativeFileName", ",", "'/'", ")", ")", ")", ";", "$", "this", "->", "writeToFile", "(", "$", "filename", ",", "$", "proc", ",", "$", "structure", ")", ";", "}", "}", "else", "{", "if", "(", "substr", "(", "$", "transformation", "->", "getArtifact", "(", ")", ",", "0", ",", "1", ")", "==", "'$'", ")", "{", "// not a file, it must become a variable!", "$", "variable_name", "=", "substr", "(", "$", "transformation", "->", "getArtifact", "(", ")", ",", "1", ")", ";", "$", "this", "->", "xsl_variables", "[", "$", "variable_name", "]", "=", "$", "proc", "->", "transformToXml", "(", "$", "structure", ")", ";", "}", "else", "{", "$", "relativeFileName", "=", "substr", "(", "$", "artifact", ",", "strlen", "(", "$", "transformation", "->", "getTransformer", "(", ")", "->", "getTarget", "(", ")", ")", "+", "1", ")", ";", "$", "proc", "->", "setParameter", "(", "''", ",", "'root'", ",", "str_repeat", "(", "'../'", ",", "substr_count", "(", "$", "relativeFileName", ",", "'/'", ")", ")", ")", ";", "$", "this", "->", "writeToFile", "(", "$", "artifact", ",", "$", "proc", ",", "$", "structure", ")", ";", "}", "}", "}" ]
This method combines the structure.xml and the given target template and creates a static html page at the artifact location. @param ProjectDescriptor $project Document containing the structure. @param Transformation $transformation Transformation to execute. @throws \RuntimeException if the structure.xml file could not be found. @throws Exception if the structure.xml file's documentRoot could not be read because of encoding issues or because it was absent. @return void
[ "This", "method", "combines", "the", "structure", ".", "xml", "and", "the", "given", "target", "template", "and", "creates", "a", "static", "html", "page", "at", "the", "artifact", "location", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/Xsl.php#L96-L158
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Writer/Xsl.php
Xsl.getXsltUriFromFilename
protected function getXsltUriFromFilename($filename) { // Windows requires an additional / after the scheme. If not provided then errno 22 (I/O Error: Invalid // Argument) will be raised. Thanks to @FnTmLV for finding the cause. See issue #284 for more information. // An exception to the above is when running from a Phar file; in this case the stream is handled as if on // linux; see issue #713 for more information on this exception. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && ! \Phar::running()) { $filename = '/' . $filename; } return 'file://' . $filename; }
php
protected function getXsltUriFromFilename($filename) { // Windows requires an additional / after the scheme. If not provided then errno 22 (I/O Error: Invalid // Argument) will be raised. Thanks to @FnTmLV for finding the cause. See issue #284 for more information. // An exception to the above is when running from a Phar file; in this case the stream is handled as if on // linux; see issue #713 for more information on this exception. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && ! \Phar::running()) { $filename = '/' . $filename; } return 'file://' . $filename; }
[ "protected", "function", "getXsltUriFromFilename", "(", "$", "filename", ")", "{", "// Windows requires an additional / after the scheme. If not provided then errno 22 (I/O Error: Invalid", "// Argument) will be raised. Thanks to @FnTmLV for finding the cause. See issue #284 for more information.", "// An exception to the above is when running from a Phar file; in this case the stream is handled as if on", "// linux; see issue #713 for more information on this exception.", "if", "(", "strtoupper", "(", "substr", "(", "PHP_OS", ",", "0", ",", "3", ")", ")", "==", "'WIN'", "&&", "!", "\\", "Phar", "::", "running", "(", ")", ")", "{", "$", "filename", "=", "'/'", ".", "$", "filename", ";", "}", "return", "'file://'", ".", "$", "filename", ";", "}" ]
Takes the filename and converts it into a correct URI for XSLTProcessor. @param string $filename @return string
[ "Takes", "the", "filename", "and", "converts", "it", "into", "a", "correct", "URI", "for", "XSLTProcessor", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/Xsl.php#L167-L178
php-lug/lug
src/Bundle/GridBundle/Form/DataTransformer/Filter/BooleanFilterTransformer.php
BooleanFilterTransformer.transform
public function transform($value) { if ($value === null) { return; } if ($value === true) { return 'true'; } if ($value === false) { return 'false'; } throw new TransformationFailedException(sprintf( 'The boolean model data should be a boolean or null, got "%s".', is_object($value) ? get_class($value) : gettype($value) )); }
php
public function transform($value) { if ($value === null) { return; } if ($value === true) { return 'true'; } if ($value === false) { return 'false'; } throw new TransformationFailedException(sprintf( 'The boolean model data should be a boolean or null, got "%s".', is_object($value) ? get_class($value) : gettype($value) )); }
[ "public", "function", "transform", "(", "$", "value", ")", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", ";", "}", "if", "(", "$", "value", "===", "true", ")", "{", "return", "'true'", ";", "}", "if", "(", "$", "value", "===", "false", ")", "{", "return", "'false'", ";", "}", "throw", "new", "TransformationFailedException", "(", "sprintf", "(", "'The boolean model data should be a boolean or null, got \"%s\".'", ",", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "gettype", "(", "$", "value", ")", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Form/DataTransformer/Filter/BooleanFilterTransformer.php#L25-L43
php-lug/lug
src/Bundle/GridBundle/Form/DataTransformer/Filter/BooleanFilterTransformer.php
BooleanFilterTransformer.reverseTransform
public function reverseTransform($value) { if ($value === null) { return; } if ($value === 'true') { return true; } if ($value === 'false') { return false; } throw new TransformationFailedException(sprintf( 'The boolean view data should be "true" or "false", got "%s".', is_object($value) ? get_class($value) : (is_string($value) ? $value : gettype($value)) )); }
php
public function reverseTransform($value) { if ($value === null) { return; } if ($value === 'true') { return true; } if ($value === 'false') { return false; } throw new TransformationFailedException(sprintf( 'The boolean view data should be "true" or "false", got "%s".', is_object($value) ? get_class($value) : (is_string($value) ? $value : gettype($value)) )); }
[ "public", "function", "reverseTransform", "(", "$", "value", ")", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", ";", "}", "if", "(", "$", "value", "===", "'true'", ")", "{", "return", "true", ";", "}", "if", "(", "$", "value", "===", "'false'", ")", "{", "return", "false", ";", "}", "throw", "new", "TransformationFailedException", "(", "sprintf", "(", "'The boolean view data should be \"true\" or \"false\", got \"%s\".'", ",", "is_object", "(", "$", "value", ")", "?", "get_class", "(", "$", "value", ")", ":", "(", "is_string", "(", "$", "value", ")", "?", "$", "value", ":", "gettype", "(", "$", "value", ")", ")", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Form/DataTransformer/Filter/BooleanFilterTransformer.php#L48-L66
david-mk/mail-map
src/MailMap/ConnectionFactory.php
ConnectionFactory.create
public function create($inbox = 'INBOX') { $stream = imap_open($this->connectionString($inbox), $this->user, $this->password); return new Connection($stream); }
php
public function create($inbox = 'INBOX') { $stream = imap_open($this->connectionString($inbox), $this->user, $this->password); return new Connection($stream); }
[ "public", "function", "create", "(", "$", "inbox", "=", "'INBOX'", ")", "{", "$", "stream", "=", "imap_open", "(", "$", "this", "->", "connectionString", "(", "$", "inbox", ")", ",", "$", "this", "->", "user", ",", "$", "this", "->", "password", ")", ";", "return", "new", "Connection", "(", "$", "stream", ")", ";", "}" ]
Create new IMAP connection @param string $inbox @return \MailMap\Contracts\ConnectionContract
[ "Create", "new", "IMAP", "connection" ]
train
https://github.com/david-mk/mail-map/blob/4eea346ece9fa35c0d309b5a909f657ad83e1e6a/src/MailMap/ConnectionFactory.php#L88-L93
david-mk/mail-map
src/MailMap/ConnectionFactory.php
ConnectionFactory.mailboxes
public function mailboxes($mailboxSearch = '*', $withConnection = false) { $connectionString = $this->connectionString(); $stream = imap_open($connectionString, $this->user, $this->password); $mailboxes = imap_list($stream, $connectionString, $mailboxSearch); if ($withConnection) { return $mailboxes; } return array_map(function ($mailbox) use ($connectionString) { return str_replace($connectionString, '', $mailbox); }, $mailboxes); }
php
public function mailboxes($mailboxSearch = '*', $withConnection = false) { $connectionString = $this->connectionString(); $stream = imap_open($connectionString, $this->user, $this->password); $mailboxes = imap_list($stream, $connectionString, $mailboxSearch); if ($withConnection) { return $mailboxes; } return array_map(function ($mailbox) use ($connectionString) { return str_replace($connectionString, '', $mailbox); }, $mailboxes); }
[ "public", "function", "mailboxes", "(", "$", "mailboxSearch", "=", "'*'", ",", "$", "withConnection", "=", "false", ")", "{", "$", "connectionString", "=", "$", "this", "->", "connectionString", "(", ")", ";", "$", "stream", "=", "imap_open", "(", "$", "connectionString", ",", "$", "this", "->", "user", ",", "$", "this", "->", "password", ")", ";", "$", "mailboxes", "=", "imap_list", "(", "$", "stream", ",", "$", "connectionString", ",", "$", "mailboxSearch", ")", ";", "if", "(", "$", "withConnection", ")", "{", "return", "$", "mailboxes", ";", "}", "return", "array_map", "(", "function", "(", "$", "mailbox", ")", "use", "(", "$", "connectionString", ")", "{", "return", "str_replace", "(", "$", "connectionString", ",", "''", ",", "$", "mailbox", ")", ";", "}", ",", "$", "mailboxes", ")", ";", "}" ]
Get a list of mailboxes on the mail server. @param string $mailboxSearch Pattern from http://php.net/manual/en/function.imap-list.php @param bool $withConnection Will strip off connection string from mailboxes by default @return array List of mailboxes
[ "Get", "a", "list", "of", "mailboxes", "on", "the", "mail", "server", "." ]
train
https://github.com/david-mk/mail-map/blob/4eea346ece9fa35c0d309b5a909f657ad83e1e6a/src/MailMap/ConnectionFactory.php#L102-L115
david-mk/mail-map
src/MailMap/ConnectionFactory.php
ConnectionFactory.connectionString
protected function connectionString($inbox = '') { return sprintf(static::$connectionFormat, $this->host, $this->port, $this->service, $this->enc, $inbox); }
php
protected function connectionString($inbox = '') { return sprintf(static::$connectionFormat, $this->host, $this->port, $this->service, $this->enc, $inbox); }
[ "protected", "function", "connectionString", "(", "$", "inbox", "=", "''", ")", "{", "return", "sprintf", "(", "static", "::", "$", "connectionFormat", ",", "$", "this", "->", "host", ",", "$", "this", "->", "port", ",", "$", "this", "->", "service", ",", "$", "this", "->", "enc", ",", "$", "inbox", ")", ";", "}" ]
Make the IMAP connection string from configuration @param string $inbox @return string The connection string
[ "Make", "the", "IMAP", "connection", "string", "from", "configuration" ]
train
https://github.com/david-mk/mail-map/blob/4eea346ece9fa35c0d309b5a909f657ad83e1e6a/src/MailMap/ConnectionFactory.php#L123-L126
mridang/magazine
lib/magento/Archive/Helper/File.php
Mage_Archive_Helper_File.open
public function open($mode = 'w+', $chmod = 0666) { if ($this->_isWritableMode($mode)) { if (!is_writable($this->_fileLocation)) { throw new Mage_Exception('Permission denied to write to ' . $this->_fileLocation); } if (is_file($this->_filePath) && !is_writable($this->_filePath)) { throw new Mage_Exception("Can't open file " . $this->_fileName . " for writing. Permission denied."); } } if ($this->_isReadableMode($mode) && (!is_file($this->_filePath) || !is_readable($this->_filePath))) { if (!is_file($this->_filePath)) { throw new Mage_Exception('File ' . $this->_filePath . ' does not exist'); } if (!is_readable($this->_filePath)) { throw new Mage_Exception('Permission denied to read file ' . $this->_filePath); } } $this->_open($mode); $this->_chmod = $chmod; }
php
public function open($mode = 'w+', $chmod = 0666) { if ($this->_isWritableMode($mode)) { if (!is_writable($this->_fileLocation)) { throw new Mage_Exception('Permission denied to write to ' . $this->_fileLocation); } if (is_file($this->_filePath) && !is_writable($this->_filePath)) { throw new Mage_Exception("Can't open file " . $this->_fileName . " for writing. Permission denied."); } } if ($this->_isReadableMode($mode) && (!is_file($this->_filePath) || !is_readable($this->_filePath))) { if (!is_file($this->_filePath)) { throw new Mage_Exception('File ' . $this->_filePath . ' does not exist'); } if (!is_readable($this->_filePath)) { throw new Mage_Exception('Permission denied to read file ' . $this->_filePath); } } $this->_open($mode); $this->_chmod = $chmod; }
[ "public", "function", "open", "(", "$", "mode", "=", "'w+'", ",", "$", "chmod", "=", "0666", ")", "{", "if", "(", "$", "this", "->", "_isWritableMode", "(", "$", "mode", ")", ")", "{", "if", "(", "!", "is_writable", "(", "$", "this", "->", "_fileLocation", ")", ")", "{", "throw", "new", "Mage_Exception", "(", "'Permission denied to write to '", ".", "$", "this", "->", "_fileLocation", ")", ";", "}", "if", "(", "is_file", "(", "$", "this", "->", "_filePath", ")", "&&", "!", "is_writable", "(", "$", "this", "->", "_filePath", ")", ")", "{", "throw", "new", "Mage_Exception", "(", "\"Can't open file \"", ".", "$", "this", "->", "_fileName", ".", "\" for writing. Permission denied.\"", ")", ";", "}", "}", "if", "(", "$", "this", "->", "_isReadableMode", "(", "$", "mode", ")", "&&", "(", "!", "is_file", "(", "$", "this", "->", "_filePath", ")", "||", "!", "is_readable", "(", "$", "this", "->", "_filePath", ")", ")", ")", "{", "if", "(", "!", "is_file", "(", "$", "this", "->", "_filePath", ")", ")", "{", "throw", "new", "Mage_Exception", "(", "'File '", ".", "$", "this", "->", "_filePath", ".", "' does not exist'", ")", ";", "}", "if", "(", "!", "is_readable", "(", "$", "this", "->", "_filePath", ")", ")", "{", "throw", "new", "Mage_Exception", "(", "'Permission denied to read file '", ".", "$", "this", "->", "_filePath", ")", ";", "}", "}", "$", "this", "->", "_open", "(", "$", "mode", ")", ";", "$", "this", "->", "_chmod", "=", "$", "chmod", ";", "}" ]
Open file @param string $mode @param int $chmod @throws Mage_Exception
[ "Open", "file" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File.php#L102-L127
mridang/magazine
lib/magento/Archive/Helper/File.php
Mage_Archive_Helper_File.read
public function read($length = 4096) { $data = false; $this->_checkFileOpened(); if ($length > 0) { $data = $this->_read($length); } return $data; }
php
public function read($length = 4096) { $data = false; $this->_checkFileOpened(); if ($length > 0) { $data = $this->_read($length); } return $data; }
[ "public", "function", "read", "(", "$", "length", "=", "4096", ")", "{", "$", "data", "=", "false", ";", "$", "this", "->", "_checkFileOpened", "(", ")", ";", "if", "(", "$", "length", ">", "0", ")", "{", "$", "data", "=", "$", "this", "->", "_read", "(", "$", "length", ")", ";", "}", "return", "$", "data", ";", "}" ]
Read data from file @param int $length @return string|boolean
[ "Read", "data", "from", "file" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File.php#L146-L155
mridang/magazine
lib/magento/Archive/Helper/File.php
Mage_Archive_Helper_File.close
public function close() { $this->_checkFileOpened(); $this->_close(); $this->_fileHandler = false; @chmod($this->_filePath, $this->_chmod); }
php
public function close() { $this->_checkFileOpened(); $this->_close(); $this->_fileHandler = false; @chmod($this->_filePath, $this->_chmod); }
[ "public", "function", "close", "(", ")", "{", "$", "this", "->", "_checkFileOpened", "(", ")", ";", "$", "this", "->", "_close", "(", ")", ";", "$", "this", "->", "_fileHandler", "=", "false", ";", "@", "chmod", "(", "$", "this", "->", "_filePath", ",", "$", "this", "->", "_chmod", ")", ";", "}" ]
Close file
[ "Close", "file" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File.php#L171-L177
mridang/magazine
lib/magento/Archive/Helper/File.php
Mage_Archive_Helper_File._open
protected function _open($mode) { $this->_fileHandler = @fopen($this->_filePath, $mode); if (false === $this->_fileHandler) { throw new Mage_Exception('Failed to open file ' . $this->_filePath); } }
php
protected function _open($mode) { $this->_fileHandler = @fopen($this->_filePath, $mode); if (false === $this->_fileHandler) { throw new Mage_Exception('Failed to open file ' . $this->_filePath); } }
[ "protected", "function", "_open", "(", "$", "mode", ")", "{", "$", "this", "->", "_fileHandler", "=", "@", "fopen", "(", "$", "this", "->", "_filePath", ",", "$", "mode", ")", ";", "if", "(", "false", "===", "$", "this", "->", "_fileHandler", ")", "{", "throw", "new", "Mage_Exception", "(", "'Failed to open file '", ".", "$", "this", "->", "_filePath", ")", ";", "}", "}" ]
Implementation of file opening @param string $mode @throws Mage_Exception
[ "Implementation", "of", "file", "opening" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File.php#L185-L192
mridang/magazine
lib/magento/Archive/Helper/File.php
Mage_Archive_Helper_File._write
protected function _write($data) { $result = @fwrite($this->_fileHandler, $data); if (false === $result) { throw new Mage_Exception('Failed to write data to ' . $this->_filePath); } }
php
protected function _write($data) { $result = @fwrite($this->_fileHandler, $data); if (false === $result) { throw new Mage_Exception('Failed to write data to ' . $this->_filePath); } }
[ "protected", "function", "_write", "(", "$", "data", ")", "{", "$", "result", "=", "@", "fwrite", "(", "$", "this", "->", "_fileHandler", ",", "$", "data", ")", ";", "if", "(", "false", "===", "$", "result", ")", "{", "throw", "new", "Mage_Exception", "(", "'Failed to write data to '", ".", "$", "this", "->", "_filePath", ")", ";", "}", "}" ]
Implementation of writing data to file @param string $data @throws Mage_Exception
[ "Implementation", "of", "writing", "data", "to", "file" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File.php#L200-L207
mridang/magazine
lib/magento/Archive/Helper/File.php
Mage_Archive_Helper_File._read
protected function _read($length) { $result = fread($this->_fileHandler, $length); if (false === $result) { throw new Mage_Exception('Failed to read data from ' . $this->_filePath); } return $result; }
php
protected function _read($length) { $result = fread($this->_fileHandler, $length); if (false === $result) { throw new Mage_Exception('Failed to read data from ' . $this->_filePath); } return $result; }
[ "protected", "function", "_read", "(", "$", "length", ")", "{", "$", "result", "=", "fread", "(", "$", "this", "->", "_fileHandler", ",", "$", "length", ")", ";", "if", "(", "false", "===", "$", "result", ")", "{", "throw", "new", "Mage_Exception", "(", "'Failed to read data from '", ".", "$", "this", "->", "_filePath", ")", ";", "}", "return", "$", "result", ";", "}" ]
Implementation of file reading @param int $length @throws Mage_Exception
[ "Implementation", "of", "file", "reading" ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Archive/Helper/File.php#L215-L224
highday/glitter
src/Audit/Listeners/Product/LogSave.php
LogSave.handle
public function handle(ProductSaved $event) { if (is_null($event->actor)) { return; } $data = [ 'ip' => request()->ip(), 'ua' => request()->header('User-Agent'), 'product_id' => $event->product->getKey(), 'dirty' => $event->product->getDirty(), ]; $event->actor->log('product.save', $data); }
php
public function handle(ProductSaved $event) { if (is_null($event->actor)) { return; } $data = [ 'ip' => request()->ip(), 'ua' => request()->header('User-Agent'), 'product_id' => $event->product->getKey(), 'dirty' => $event->product->getDirty(), ]; $event->actor->log('product.save', $data); }
[ "public", "function", "handle", "(", "ProductSaved", "$", "event", ")", "{", "if", "(", "is_null", "(", "$", "event", "->", "actor", ")", ")", "{", "return", ";", "}", "$", "data", "=", "[", "'ip'", "=>", "request", "(", ")", "->", "ip", "(", ")", ",", "'ua'", "=>", "request", "(", ")", "->", "header", "(", "'User-Agent'", ")", ",", "'product_id'", "=>", "$", "event", "->", "product", "->", "getKey", "(", ")", ",", "'dirty'", "=>", "$", "event", "->", "product", "->", "getDirty", "(", ")", ",", "]", ";", "$", "event", "->", "actor", "->", "log", "(", "'product.save'", ",", "$", "data", ")", ";", "}" ]
Handle the event. @param ProductSaved $event @return void
[ "Handle", "the", "event", "." ]
train
https://github.com/highday/glitter/blob/d1c7a227fd2343806bd3ec0314e621ced57dfe66/src/Audit/Listeners/Product/LogSave.php#L26-L40
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/multipart.php
ezcMailMultipart.__isset
public function __isset( $name ) { switch ( $name ) { case 'boundary': case 'noMimeMessage': return isset( $this->properties[$name] ); default: return parent::__isset( $name ); } }
php
public function __isset( $name ) { switch ( $name ) { case 'boundary': case 'noMimeMessage': return isset( $this->properties[$name] ); default: return parent::__isset( $name ); } }
[ "public", "function", "__isset", "(", "$", "name", ")", "{", "switch", "(", "$", "name", ")", "{", "case", "'boundary'", ":", "case", "'noMimeMessage'", ":", "return", "isset", "(", "$", "this", "->", "properties", "[", "$", "name", "]", ")", ";", "default", ":", "return", "parent", "::", "__isset", "(", "$", "name", ")", ";", "}", "}" ]
Returns true if the property $name is set, otherwise false. @param string $name @return bool @ignore
[ "Returns", "true", "if", "the", "property", "$name", "is", "set", "otherwise", "false", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/multipart.php#L149-L160
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/multipart.php
ezcMailMultipart.generateBody
public function generateBody() { $data = $this->noMimeMessage . ezcMailTools::lineBreak(); foreach ( $this->parts as $part ) { $data .= ezcMailTools::lineBreak() . '--' . $this->boundary . ezcMailTools::lineBreak(); $data .= $part->generate(); } $data .= ezcMailTools::lineBreak() . '--' . $this->boundary . '--'; return $data; }
php
public function generateBody() { $data = $this->noMimeMessage . ezcMailTools::lineBreak(); foreach ( $this->parts as $part ) { $data .= ezcMailTools::lineBreak() . '--' . $this->boundary . ezcMailTools::lineBreak(); $data .= $part->generate(); } $data .= ezcMailTools::lineBreak() . '--' . $this->boundary . '--'; return $data; }
[ "public", "function", "generateBody", "(", ")", "{", "$", "data", "=", "$", "this", "->", "noMimeMessage", ".", "ezcMailTools", "::", "lineBreak", "(", ")", ";", "foreach", "(", "$", "this", "->", "parts", "as", "$", "part", ")", "{", "$", "data", ".=", "ezcMailTools", "::", "lineBreak", "(", ")", ".", "'--'", ".", "$", "this", "->", "boundary", ".", "ezcMailTools", "::", "lineBreak", "(", ")", ";", "$", "data", ".=", "$", "part", "->", "generate", "(", ")", ";", "}", "$", "data", ".=", "ezcMailTools", "::", "lineBreak", "(", ")", ".", "'--'", ".", "$", "this", "->", "boundary", ".", "'--'", ";", "return", "$", "data", ";", "}" ]
Returns the generated body for all multipart types. @return string
[ "Returns", "the", "generated", "body", "for", "all", "multipart", "types", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parts/multipart.php#L167-L177
flint/Antenna
src/Coder.php
Coder.decode
public function decode($encoded) { $defaults = [ 'sub' => null, 'iat' => null, 'exp' => null, ]; $payload = (array) JWT::decode($encoded, $this->secret, [$this->algoritm]) + $defaults; $claims = array_diff_key($payload, $defaults); $expireAt = new DateTimeImmutable('@'.$payload['exp']); $issuedAt = new DateTimeImmutable('@'.$payload['iat']); return new WebToken($payload['sub'], $issuedAt, $expireAt, $claims); }
php
public function decode($encoded) { $defaults = [ 'sub' => null, 'iat' => null, 'exp' => null, ]; $payload = (array) JWT::decode($encoded, $this->secret, [$this->algoritm]) + $defaults; $claims = array_diff_key($payload, $defaults); $expireAt = new DateTimeImmutable('@'.$payload['exp']); $issuedAt = new DateTimeImmutable('@'.$payload['iat']); return new WebToken($payload['sub'], $issuedAt, $expireAt, $claims); }
[ "public", "function", "decode", "(", "$", "encoded", ")", "{", "$", "defaults", "=", "[", "'sub'", "=>", "null", ",", "'iat'", "=>", "null", ",", "'exp'", "=>", "null", ",", "]", ";", "$", "payload", "=", "(", "array", ")", "JWT", "::", "decode", "(", "$", "encoded", ",", "$", "this", "->", "secret", ",", "[", "$", "this", "->", "algoritm", "]", ")", "+", "$", "defaults", ";", "$", "claims", "=", "array_diff_key", "(", "$", "payload", ",", "$", "defaults", ")", ";", "$", "expireAt", "=", "new", "DateTimeImmutable", "(", "'@'", ".", "$", "payload", "[", "'exp'", "]", ")", ";", "$", "issuedAt", "=", "new", "DateTimeImmutable", "(", "'@'", ".", "$", "payload", "[", "'iat'", "]", ")", ";", "return", "new", "WebToken", "(", "$", "payload", "[", "'sub'", "]", ",", "$", "issuedAt", ",", "$", "expireAt", ",", "$", "claims", ")", ";", "}" ]
@param string $encoded @return WebToken
[ "@param", "string", "$encoded" ]
train
https://github.com/flint/Antenna/blob/282bafa99bf75bade965b00ef43fc421674048a5/src/Coder.php#L44-L60
sauls/widget
src/View/StringView.php
StringView.render
public function render(string $viewFile, array $viewData = []): string { return strtr( $viewFile, array_combine( array_map( function ($key) { return '{'.$key.'}'; }, array_keys($viewData) ), array_values($viewData) ) ); }
php
public function render(string $viewFile, array $viewData = []): string { return strtr( $viewFile, array_combine( array_map( function ($key) { return '{'.$key.'}'; }, array_keys($viewData) ), array_values($viewData) ) ); }
[ "public", "function", "render", "(", "string", "$", "viewFile", ",", "array", "$", "viewData", "=", "[", "]", ")", ":", "string", "{", "return", "strtr", "(", "$", "viewFile", ",", "array_combine", "(", "array_map", "(", "function", "(", "$", "key", ")", "{", "return", "'{'", ".", "$", "key", ".", "'}'", ";", "}", ",", "array_keys", "(", "$", "viewData", ")", ")", ",", "array_values", "(", "$", "viewData", ")", ")", ")", ";", "}" ]
@param string $viewFile @param array $viewData @return string
[ "@param", "string", "$viewFile", "@param", "array", "$viewData" ]
train
https://github.com/sauls/widget/blob/552c8118e92565f3f54969779269855b6a1d076a/src/View/StringView.php#L25-L39
Laralum/Events
src/Models/Event.php
Event.hasResponsible
public function hasResponsible($user) { return $this->users()->where('user_id', $user->id)->first()->pivot->responsible; }
php
public function hasResponsible($user) { return $this->users()->where('user_id', $user->id)->first()->pivot->responsible; }
[ "public", "function", "hasResponsible", "(", "$", "user", ")", "{", "return", "$", "this", "->", "users", "(", ")", "->", "where", "(", "'user_id'", ",", "$", "user", "->", "id", ")", "->", "first", "(", ")", "->", "pivot", "->", "responsible", ";", "}" ]
Returns true if the event have the specified user as responsible. @param mixed $user
[ "Returns", "true", "if", "the", "event", "have", "the", "specified", "user", "as", "responsible", "." ]
train
https://github.com/Laralum/Events/blob/9dc36468f4253e7d040863a115ea94cded0e6aa5/src/Models/Event.php#L58-L61
Laralum/Events
src/Models/Event.php
Event.startDatetime
public function startDatetime() { $date = explode('-', $this->start_date); $time = explode(':', $this->start_time); $start_datetime = Carbon::create($date[0], $date[1], $date[2], $time[0], $time[1]); return $start_datetime; }
php
public function startDatetime() { $date = explode('-', $this->start_date); $time = explode(':', $this->start_time); $start_datetime = Carbon::create($date[0], $date[1], $date[2], $time[0], $time[1]); return $start_datetime; }
[ "public", "function", "startDatetime", "(", ")", "{", "$", "date", "=", "explode", "(", "'-'", ",", "$", "this", "->", "start_date", ")", ";", "$", "time", "=", "explode", "(", "':'", ",", "$", "this", "->", "start_time", ")", ";", "$", "start_datetime", "=", "Carbon", "::", "create", "(", "$", "date", "[", "0", "]", ",", "$", "date", "[", "1", "]", ",", "$", "date", "[", "2", "]", ",", "$", "time", "[", "0", "]", ",", "$", "time", "[", "1", "]", ")", ";", "return", "$", "start_datetime", ";", "}" ]
Get Carbon start datetime. @return \Carbon\Carbon
[ "Get", "Carbon", "start", "datetime", "." ]
train
https://github.com/Laralum/Events/blob/9dc36468f4253e7d040863a115ea94cded0e6aa5/src/Models/Event.php#L150-L157
Laralum/Events
src/Models/Event.php
Event.endDatetime
public function endDatetime() { $date = explode('-', $this->end_date); $time = explode(':', $this->end_time); $end_datetime = Carbon::create($date[0], $date[1], $date[2], $time[0], $time[1]); return $end_datetime; }
php
public function endDatetime() { $date = explode('-', $this->end_date); $time = explode(':', $this->end_time); $end_datetime = Carbon::create($date[0], $date[1], $date[2], $time[0], $time[1]); return $end_datetime; }
[ "public", "function", "endDatetime", "(", ")", "{", "$", "date", "=", "explode", "(", "'-'", ",", "$", "this", "->", "end_date", ")", ";", "$", "time", "=", "explode", "(", "':'", ",", "$", "this", "->", "end_time", ")", ";", "$", "end_datetime", "=", "Carbon", "::", "create", "(", "$", "date", "[", "0", "]", ",", "$", "date", "[", "1", "]", ",", "$", "date", "[", "2", "]", ",", "$", "time", "[", "0", "]", ",", "$", "time", "[", "1", "]", ")", ";", "return", "$", "end_datetime", ";", "}" ]
Get Carbon end datetime. @return \Carbon\Carbon
[ "Get", "Carbon", "end", "datetime", "." ]
train
https://github.com/Laralum/Events/blob/9dc36468f4253e7d040863a115ea94cded0e6aa5/src/Models/Event.php#L164-L171
xiewulong/yii2-fileupload
oss/libs/symfony/class-loader/Symfony/Component/ClassLoader/ApcClassLoader.php
ApcClassLoader.findFile
public function findFile($class) { if (false === $file = apc_fetch($this->prefix.$class)) { apc_store($this->prefix.$class, $file = $this->decorated->findFile($class)); } return $file; }
php
public function findFile($class) { if (false === $file = apc_fetch($this->prefix.$class)) { apc_store($this->prefix.$class, $file = $this->decorated->findFile($class)); } return $file; }
[ "public", "function", "findFile", "(", "$", "class", ")", "{", "if", "(", "false", "===", "$", "file", "=", "apc_fetch", "(", "$", "this", "->", "prefix", ".", "$", "class", ")", ")", "{", "apc_store", "(", "$", "this", "->", "prefix", ".", "$", "class", ",", "$", "file", "=", "$", "this", "->", "decorated", "->", "findFile", "(", "$", "class", ")", ")", ";", "}", "return", "$", "file", ";", "}" ]
Finds a file by class name while caching lookups to APC. @param string $class A class name to resolve to file @return string|null
[ "Finds", "a", "file", "by", "class", "name", "while", "caching", "lookups", "to", "APC", "." ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/symfony/class-loader/Symfony/Component/ClassLoader/ApcClassLoader.php#L120-L127
lukasz-adamski/teamspeak3-framework
src/TeamSpeak3/Adapter/ServerQuery.php
ServerQuery.syn
protected function syn() { $this->initTransport($this->options); $this->transport->setAdapter($this); Profiler::init(spl_object_hash($this)); $rdy = $this->getTransport()->readLine(); if(!$rdy->startsWith(TeamSpeak3::TS3_PROTO_IDENT) && !$rdy->startsWith(TeamSpeak3::TEA_PROTO_IDENT) && !(defined("CUSTOM_PROTO_IDENT") && $rdy->startsWith(CUSTOM_PROTO_IDENT))) { throw new AdapterException("invalid reply from the server (" . $rdy . ")"); } Signal::getInstance()->emit("serverqueryConnected", $this); }
php
protected function syn() { $this->initTransport($this->options); $this->transport->setAdapter($this); Profiler::init(spl_object_hash($this)); $rdy = $this->getTransport()->readLine(); if(!$rdy->startsWith(TeamSpeak3::TS3_PROTO_IDENT) && !$rdy->startsWith(TeamSpeak3::TEA_PROTO_IDENT) && !(defined("CUSTOM_PROTO_IDENT") && $rdy->startsWith(CUSTOM_PROTO_IDENT))) { throw new AdapterException("invalid reply from the server (" . $rdy . ")"); } Signal::getInstance()->emit("serverqueryConnected", $this); }
[ "protected", "function", "syn", "(", ")", "{", "$", "this", "->", "initTransport", "(", "$", "this", "->", "options", ")", ";", "$", "this", "->", "transport", "->", "setAdapter", "(", "$", "this", ")", ";", "Profiler", "::", "init", "(", "spl_object_hash", "(", "$", "this", ")", ")", ";", "$", "rdy", "=", "$", "this", "->", "getTransport", "(", ")", "->", "readLine", "(", ")", ";", "if", "(", "!", "$", "rdy", "->", "startsWith", "(", "TeamSpeak3", "::", "TS3_PROTO_IDENT", ")", "&&", "!", "$", "rdy", "->", "startsWith", "(", "TeamSpeak3", "::", "TEA_PROTO_IDENT", ")", "&&", "!", "(", "defined", "(", "\"CUSTOM_PROTO_IDENT\"", ")", "&&", "$", "rdy", "->", "startsWith", "(", "CUSTOM_PROTO_IDENT", ")", ")", ")", "{", "throw", "new", "AdapterException", "(", "\"invalid reply from the server (\"", ".", "$", "rdy", ".", "\")\"", ")", ";", "}", "Signal", "::", "getInstance", "(", ")", "->", "emit", "(", "\"serverqueryConnected\"", ",", "$", "this", ")", ";", "}" ]
Connects the Transport object and performs initial actions on the remote server. @throws AdapterException @return void
[ "Connects", "the", "Transport", "object", "and", "performs", "initial", "actions", "on", "the", "remote", "server", "." ]
train
https://github.com/lukasz-adamski/teamspeak3-framework/blob/39a56eca608da6b56b6aa386a7b5b31dc576c41a/src/TeamSpeak3/Adapter/ServerQuery.php#L81-L96
lukasz-adamski/teamspeak3-framework
src/TeamSpeak3/Adapter/ServerQuery.php
ServerQuery.wait
public function wait() { if($this->getTransport()->getConfig("blocking")) { throw new AdapterException("only available in non-blocking mode"); } do { $evt = $this->getTransport()->readLine(); } while($evt instanceof Str && !$evt->section(TeamSpeak3::SEPARATOR_CELL)->startsWith(TeamSpeak3::EVENT)); return new Event($evt, $this->getHost()); }
php
public function wait() { if($this->getTransport()->getConfig("blocking")) { throw new AdapterException("only available in non-blocking mode"); } do { $evt = $this->getTransport()->readLine(); } while($evt instanceof Str && !$evt->section(TeamSpeak3::SEPARATOR_CELL)->startsWith(TeamSpeak3::EVENT)); return new Event($evt, $this->getHost()); }
[ "public", "function", "wait", "(", ")", "{", "if", "(", "$", "this", "->", "getTransport", "(", ")", "->", "getConfig", "(", "\"blocking\"", ")", ")", "{", "throw", "new", "AdapterException", "(", "\"only available in non-blocking mode\"", ")", ";", "}", "do", "{", "$", "evt", "=", "$", "this", "->", "getTransport", "(", ")", "->", "readLine", "(", ")", ";", "}", "while", "(", "$", "evt", "instanceof", "Str", "&&", "!", "$", "evt", "->", "section", "(", "TeamSpeak3", "::", "SEPARATOR_CELL", ")", "->", "startsWith", "(", "TeamSpeak3", "::", "EVENT", ")", ")", ";", "return", "new", "Event", "(", "$", "evt", ",", "$", "this", "->", "getHost", "(", ")", ")", ";", "}" ]
Waits for the server to send a notification message and returns the result. @throws AdapterException @return Event
[ "Waits", "for", "the", "server", "to", "send", "a", "notification", "message", "and", "returns", "the", "result", "." ]
train
https://github.com/lukasz-adamski/teamspeak3-framework/blob/39a56eca608da6b56b6aa386a7b5b31dc576c41a/src/TeamSpeak3/Adapter/ServerQuery.php#L168-L180
lukasz-adamski/teamspeak3-framework
src/TeamSpeak3/Adapter/ServerQuery.php
ServerQuery.prepare
public function prepare($cmd, array $params = array()) { $args = array(); $cells = array(); foreach($params as $ident => $value) { $ident = is_numeric($ident) ? "" : strtolower($ident) . TeamSpeak3::SEPARATOR_PAIR; if(is_array($value)) { $value = array_values($value); for($i = 0; $i < count($value); $i++) { if($value[$i] === null) continue; elseif($value[$i] === FALSE) $value[$i] = 0x00; elseif($value[$i] === TRUE) $value[$i] = 0x01; elseif($value[$i] instanceof Node) $value[$i] = $value[$i]->getId(); $cells[$i][] = $ident . Str::factory($value[$i])->escape()->toUtf8(); } } else { if($value === null) continue; elseif($value === FALSE) $value = 0x00; elseif($value === TRUE) $value = 0x01; elseif($value instanceof Node) $value = $value->getId(); $args[] = $ident . Str::factory($value)->escape()->toUtf8(); } } foreach(array_keys($cells) as $ident) $cells[$ident] = implode(TeamSpeak3::SEPARATOR_CELL, $cells[$ident]); if(count($args)) $cmd .= " " . implode(TeamSpeak3::SEPARATOR_CELL, $args); if(count($cells)) $cmd .= " " . implode(TeamSpeak3::SEPARATOR_LIST, $cells); return trim($cmd); }
php
public function prepare($cmd, array $params = array()) { $args = array(); $cells = array(); foreach($params as $ident => $value) { $ident = is_numeric($ident) ? "" : strtolower($ident) . TeamSpeak3::SEPARATOR_PAIR; if(is_array($value)) { $value = array_values($value); for($i = 0; $i < count($value); $i++) { if($value[$i] === null) continue; elseif($value[$i] === FALSE) $value[$i] = 0x00; elseif($value[$i] === TRUE) $value[$i] = 0x01; elseif($value[$i] instanceof Node) $value[$i] = $value[$i]->getId(); $cells[$i][] = $ident . Str::factory($value[$i])->escape()->toUtf8(); } } else { if($value === null) continue; elseif($value === FALSE) $value = 0x00; elseif($value === TRUE) $value = 0x01; elseif($value instanceof Node) $value = $value->getId(); $args[] = $ident . Str::factory($value)->escape()->toUtf8(); } } foreach(array_keys($cells) as $ident) $cells[$ident] = implode(TeamSpeak3::SEPARATOR_CELL, $cells[$ident]); if(count($args)) $cmd .= " " . implode(TeamSpeak3::SEPARATOR_CELL, $args); if(count($cells)) $cmd .= " " . implode(TeamSpeak3::SEPARATOR_LIST, $cells); return trim($cmd); }
[ "public", "function", "prepare", "(", "$", "cmd", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "$", "args", "=", "array", "(", ")", ";", "$", "cells", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "ident", "=>", "$", "value", ")", "{", "$", "ident", "=", "is_numeric", "(", "$", "ident", ")", "?", "\"\"", ":", "strtolower", "(", "$", "ident", ")", ".", "TeamSpeak3", "::", "SEPARATOR_PAIR", ";", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "array_values", "(", "$", "value", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "value", ")", ";", "$", "i", "++", ")", "{", "if", "(", "$", "value", "[", "$", "i", "]", "===", "null", ")", "continue", ";", "elseif", "(", "$", "value", "[", "$", "i", "]", "===", "FALSE", ")", "$", "value", "[", "$", "i", "]", "=", "0x00", ";", "elseif", "(", "$", "value", "[", "$", "i", "]", "===", "TRUE", ")", "$", "value", "[", "$", "i", "]", "=", "0x01", ";", "elseif", "(", "$", "value", "[", "$", "i", "]", "instanceof", "Node", ")", "$", "value", "[", "$", "i", "]", "=", "$", "value", "[", "$", "i", "]", "->", "getId", "(", ")", ";", "$", "cells", "[", "$", "i", "]", "[", "]", "=", "$", "ident", ".", "Str", "::", "factory", "(", "$", "value", "[", "$", "i", "]", ")", "->", "escape", "(", ")", "->", "toUtf8", "(", ")", ";", "}", "}", "else", "{", "if", "(", "$", "value", "===", "null", ")", "continue", ";", "elseif", "(", "$", "value", "===", "FALSE", ")", "$", "value", "=", "0x00", ";", "elseif", "(", "$", "value", "===", "TRUE", ")", "$", "value", "=", "0x01", ";", "elseif", "(", "$", "value", "instanceof", "Node", ")", "$", "value", "=", "$", "value", "->", "getId", "(", ")", ";", "$", "args", "[", "]", "=", "$", "ident", ".", "Str", "::", "factory", "(", "$", "value", ")", "->", "escape", "(", ")", "->", "toUtf8", "(", ")", ";", "}", "}", "foreach", "(", "array_keys", "(", "$", "cells", ")", "as", "$", "ident", ")", "$", "cells", "[", "$", "ident", "]", "=", "implode", "(", "TeamSpeak3", "::", "SEPARATOR_CELL", ",", "$", "cells", "[", "$", "ident", "]", ")", ";", "if", "(", "count", "(", "$", "args", ")", ")", "$", "cmd", ".=", "\" \"", ".", "implode", "(", "TeamSpeak3", "::", "SEPARATOR_CELL", ",", "$", "args", ")", ";", "if", "(", "count", "(", "$", "cells", ")", ")", "$", "cmd", ".=", "\" \"", ".", "implode", "(", "TeamSpeak3", "::", "SEPARATOR_LIST", ",", "$", "cells", ")", ";", "return", "trim", "(", "$", "cmd", ")", ";", "}" ]
Uses given parameters and returns a prepared ServerQuery command. @param string $cmd @param array $params @return string
[ "Uses", "given", "parameters", "and", "returns", "a", "prepared", "ServerQuery", "command", "." ]
train
https://github.com/lukasz-adamski/teamspeak3-framework/blob/39a56eca608da6b56b6aa386a7b5b31dc576c41a/src/TeamSpeak3/Adapter/ServerQuery.php#L189-L229
ronaldborla/chikka
src/Borla/Chikka/Models/Cost.php
Cost.adjust
public function adjust(Carrier $carrier = null) { // If there's carrier if ($carrier !== null) { // Set carrier $this->carrier = $carrier; } // If there's no carrier if ( ! isset($this->carrier)) { // Throw error throw new MissingCarrier('Carrier is required to adjust cost'); } // Get costs $costs = $this->getPossibleCostsPerCarrier()[$this->carrier->network]; // Loop through costs per carrier foreach ($costs as $i=> $cost) { // If cost equals if ($this->amount == $cost) { // Quit break; } // If amount is less than cost if ($this->amount < $cost || ! isset($costs[$i + 1])) { // Use previous $this->amount = $cost; // Break break; } } // Return self return $this; }
php
public function adjust(Carrier $carrier = null) { // If there's carrier if ($carrier !== null) { // Set carrier $this->carrier = $carrier; } // If there's no carrier if ( ! isset($this->carrier)) { // Throw error throw new MissingCarrier('Carrier is required to adjust cost'); } // Get costs $costs = $this->getPossibleCostsPerCarrier()[$this->carrier->network]; // Loop through costs per carrier foreach ($costs as $i=> $cost) { // If cost equals if ($this->amount == $cost) { // Quit break; } // If amount is less than cost if ($this->amount < $cost || ! isset($costs[$i + 1])) { // Use previous $this->amount = $cost; // Break break; } } // Return self return $this; }
[ "public", "function", "adjust", "(", "Carrier", "$", "carrier", "=", "null", ")", "{", "// If there's carrier", "if", "(", "$", "carrier", "!==", "null", ")", "{", "// Set carrier", "$", "this", "->", "carrier", "=", "$", "carrier", ";", "}", "// If there's no carrier", "if", "(", "!", "isset", "(", "$", "this", "->", "carrier", ")", ")", "{", "// Throw error", "throw", "new", "MissingCarrier", "(", "'Carrier is required to adjust cost'", ")", ";", "}", "// Get costs", "$", "costs", "=", "$", "this", "->", "getPossibleCostsPerCarrier", "(", ")", "[", "$", "this", "->", "carrier", "->", "network", "]", ";", "// Loop through costs per carrier", "foreach", "(", "$", "costs", "as", "$", "i", "=>", "$", "cost", ")", "{", "// If cost equals", "if", "(", "$", "this", "->", "amount", "==", "$", "cost", ")", "{", "// Quit", "break", ";", "}", "// If amount is less than cost", "if", "(", "$", "this", "->", "amount", "<", "$", "cost", "||", "!", "isset", "(", "$", "costs", "[", "$", "i", "+", "1", "]", ")", ")", "{", "// Use previous", "$", "this", "->", "amount", "=", "$", "cost", ";", "// Break", "break", ";", "}", "}", "// Return self", "return", "$", "this", ";", "}" ]
Adjust cost amount for a given carrier
[ "Adjust", "cost", "amount", "for", "a", "given", "carrier" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Models/Cost.php#L79-L109
ronaldborla/chikka
src/Borla/Chikka/Models/Cost.php
Cost.fix
public function fix($mobileOrCarrier) { // If instance of carrier if ($mobileOrCarrier instanceof Carrier) { // Use $this->carrier = $mobileOrCarrier; } // If instance of mobile elseif ($mobileOrCarrier instanceof Mobile) { // Get carrier $this->carrier = $mobileOrCarrier->carrier; } // Else else { // Get carrier $this->carrier = Loader::mobile($mobileOrCarrier)->carrier; } // Adjust and return return $this->adjust(); }
php
public function fix($mobileOrCarrier) { // If instance of carrier if ($mobileOrCarrier instanceof Carrier) { // Use $this->carrier = $mobileOrCarrier; } // If instance of mobile elseif ($mobileOrCarrier instanceof Mobile) { // Get carrier $this->carrier = $mobileOrCarrier->carrier; } // Else else { // Get carrier $this->carrier = Loader::mobile($mobileOrCarrier)->carrier; } // Adjust and return return $this->adjust(); }
[ "public", "function", "fix", "(", "$", "mobileOrCarrier", ")", "{", "// If instance of carrier", "if", "(", "$", "mobileOrCarrier", "instanceof", "Carrier", ")", "{", "// Use", "$", "this", "->", "carrier", "=", "$", "mobileOrCarrier", ";", "}", "// If instance of mobile", "elseif", "(", "$", "mobileOrCarrier", "instanceof", "Mobile", ")", "{", "// Get carrier", "$", "this", "->", "carrier", "=", "$", "mobileOrCarrier", "->", "carrier", ";", "}", "// Else ", "else", "{", "// Get carrier", "$", "this", "->", "carrier", "=", "Loader", "::", "mobile", "(", "$", "mobileOrCarrier", ")", "->", "carrier", ";", "}", "// Adjust and return", "return", "$", "this", "->", "adjust", "(", ")", ";", "}" ]
Fix cost by mobile or carrier @param int|string|Mobile|Carrier $mobileOrCarrier Can be mobile number or instance of Mobile or Carrier
[ "Fix", "cost", "by", "mobile", "or", "carrier" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Models/Cost.php#L115-L133
railt/reflection
src/Type.php
Type.instanceOf
public function instanceOf(TypeInterface $type): bool { $needle = $type->getName(); return $this->is($needle) || \in_array($needle, $this->parent, true); }
php
public function instanceOf(TypeInterface $type): bool { $needle = $type->getName(); return $this->is($needle) || \in_array($needle, $this->parent, true); }
[ "public", "function", "instanceOf", "(", "TypeInterface", "$", "type", ")", ":", "bool", "{", "$", "needle", "=", "$", "type", "->", "getName", "(", ")", ";", "return", "$", "this", "->", "is", "(", "$", "needle", ")", "||", "\\", "in_array", "(", "$", "needle", ",", "$", "this", "->", "parent", ",", "true", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/railt/reflection/blob/3f86cd0cc5f0a0895eaca0def0cb3a3afd7ab377/src/Type.php#L144-L149
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/imap/imap_set.php
ezcMailImapSet.getNextLine
public function getNextLine() { if ( $this->currentMessage === null ) { // instead of calling $this->nextMail() in the constructor, it is called // here, to avoid sending commands to the server when creating the set, and // instead send the server commands when parsing the set (see ezcMailParser). $this->nextMail(); } if ( $this->hasMoreMailData ) { if ( $this->bytesToRead !== false && $this->bytesToRead >= 0 ) { $data = $this->connection->getLine(); $this->bytesToRead -= strlen( $data ); // modified for issue #13878 (Endless loop in ezcMailParser): // removed wrong checks (ending in ')' check and ending with tag check (e.g. 'A0002')) if ( $this->bytesToRead <= 0 ) { if ( $this->bytesToRead < 0 ) { $data = substr( $data, 0, strlen( $data ) + $this->bytesToRead ); //trim( $data, ")\r\n" ); } if ( $this->bytesToRead === 0 ) { // hack for Microsoft Exchange, which sometimes puts // FLAGS (\Seen)) at the end of a message instead of before (!) if ( strlen( trim( $data, ")\r\n" ) !== strlen( $data ) - 3 ) ) { // if the last line in a mail does not end with ")\r\n" // then read an extra line and discard it $extraData = $this->connection->getLine(); } } $this->hasMoreMailData = false; // remove the mail if required by the user. if ( $this->deleteFromServer === true ) { $tag = $this->getNextTag(); $this->connection->sendData( "{$tag} {$this->uid}STORE {$this->currentMessage} +FLAGS (\\Deleted)" ); // skip OK response ("{$tag} OK Store completed.") $response = $this->getResponse( $tag ); } return $data; } } return $data; } return null; }
php
public function getNextLine() { if ( $this->currentMessage === null ) { // instead of calling $this->nextMail() in the constructor, it is called // here, to avoid sending commands to the server when creating the set, and // instead send the server commands when parsing the set (see ezcMailParser). $this->nextMail(); } if ( $this->hasMoreMailData ) { if ( $this->bytesToRead !== false && $this->bytesToRead >= 0 ) { $data = $this->connection->getLine(); $this->bytesToRead -= strlen( $data ); // modified for issue #13878 (Endless loop in ezcMailParser): // removed wrong checks (ending in ')' check and ending with tag check (e.g. 'A0002')) if ( $this->bytesToRead <= 0 ) { if ( $this->bytesToRead < 0 ) { $data = substr( $data, 0, strlen( $data ) + $this->bytesToRead ); //trim( $data, ")\r\n" ); } if ( $this->bytesToRead === 0 ) { // hack for Microsoft Exchange, which sometimes puts // FLAGS (\Seen)) at the end of a message instead of before (!) if ( strlen( trim( $data, ")\r\n" ) !== strlen( $data ) - 3 ) ) { // if the last line in a mail does not end with ")\r\n" // then read an extra line and discard it $extraData = $this->connection->getLine(); } } $this->hasMoreMailData = false; // remove the mail if required by the user. if ( $this->deleteFromServer === true ) { $tag = $this->getNextTag(); $this->connection->sendData( "{$tag} {$this->uid}STORE {$this->currentMessage} +FLAGS (\\Deleted)" ); // skip OK response ("{$tag} OK Store completed.") $response = $this->getResponse( $tag ); } return $data; } } return $data; } return null; }
[ "public", "function", "getNextLine", "(", ")", "{", "if", "(", "$", "this", "->", "currentMessage", "===", "null", ")", "{", "// instead of calling $this->nextMail() in the constructor, it is called", "// here, to avoid sending commands to the server when creating the set, and", "// instead send the server commands when parsing the set (see ezcMailParser).", "$", "this", "->", "nextMail", "(", ")", ";", "}", "if", "(", "$", "this", "->", "hasMoreMailData", ")", "{", "if", "(", "$", "this", "->", "bytesToRead", "!==", "false", "&&", "$", "this", "->", "bytesToRead", ">=", "0", ")", "{", "$", "data", "=", "$", "this", "->", "connection", "->", "getLine", "(", ")", ";", "$", "this", "->", "bytesToRead", "-=", "strlen", "(", "$", "data", ")", ";", "// modified for issue #13878 (Endless loop in ezcMailParser):", "// removed wrong checks (ending in ')' check and ending with tag check (e.g. 'A0002'))", "if", "(", "$", "this", "->", "bytesToRead", "<=", "0", ")", "{", "if", "(", "$", "this", "->", "bytesToRead", "<", "0", ")", "{", "$", "data", "=", "substr", "(", "$", "data", ",", "0", ",", "strlen", "(", "$", "data", ")", "+", "$", "this", "->", "bytesToRead", ")", ";", "//trim( $data, \")\\r\\n\" );", "}", "if", "(", "$", "this", "->", "bytesToRead", "===", "0", ")", "{", "// hack for Microsoft Exchange, which sometimes puts", "// FLAGS (\\Seen)) at the end of a message instead of before (!)", "if", "(", "strlen", "(", "trim", "(", "$", "data", ",", "\")\\r\\n\"", ")", "!==", "strlen", "(", "$", "data", ")", "-", "3", ")", ")", "{", "// if the last line in a mail does not end with \")\\r\\n\"", "// then read an extra line and discard it", "$", "extraData", "=", "$", "this", "->", "connection", "->", "getLine", "(", ")", ";", "}", "}", "$", "this", "->", "hasMoreMailData", "=", "false", ";", "// remove the mail if required by the user.", "if", "(", "$", "this", "->", "deleteFromServer", "===", "true", ")", "{", "$", "tag", "=", "$", "this", "->", "getNextTag", "(", ")", ";", "$", "this", "->", "connection", "->", "sendData", "(", "\"{$tag} {$this->uid}STORE {$this->currentMessage} +FLAGS (\\\\Deleted)\"", ")", ";", "// skip OK response (\"{$tag} OK Store completed.\")", "$", "response", "=", "$", "this", "->", "getResponse", "(", "$", "tag", ")", ";", "}", "return", "$", "data", ";", "}", "}", "return", "$", "data", ";", "}", "return", "null", ";", "}" ]
Returns one line of data from the current mail in the set. Null is returned if there is no current mail in the set or the end of the mail is reached, @return string
[ "Returns", "one", "line", "of", "data", "from", "the", "current", "mail", "in", "the", "set", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/imap/imap_set.php#L160-L212
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/imap/imap_set.php
ezcMailImapSet.nextMail
public function nextMail() { if ( $this->currentMessage === null ) { $this->currentMessage = reset( $this->messages ); } else { $this->currentMessage = next( $this->messages ); } $this->nextData = null; $this->bytesToRead = false; if ( $this->currentMessage !== false ) { $tag = $this->getNextTag(); $this->connection->sendData( "{$tag} {$this->uid}FETCH {$this->currentMessage} RFC822" ); $response = $this->connection->getLine(); if ( strpos( $response, ' NO ' ) !== false || strpos( $response, ' BAD ') !== false ) { throw new ezcMailTransportException( "The IMAP server sent a negative reply when requesting mail." ); } else { $response = $this->getResponse( 'FETCH (', $response ); if ( strpos( $response, 'FETCH (' ) !== false ) { $this->hasMoreMailData = true; // retrieve the message size from $response, eg. if $response is: // * 2 FETCH (FLAGS (\Answered \Seen) RFC822 {377} // then $this->bytesToRead will be 377 preg_match( '/\{(.*)\}/', $response, $matches ); if ( count( $matches ) > 0 ) { $this->bytesToRead = (int) $matches[1]; } return true; } else { $response = $this->getResponse( $tag ); if ( strpos( $response, 'OK ' ) === false ) { throw new ezcMailTransportException( "The IMAP server sent a negative reply when requesting mail." ); } } } } return false; }
php
public function nextMail() { if ( $this->currentMessage === null ) { $this->currentMessage = reset( $this->messages ); } else { $this->currentMessage = next( $this->messages ); } $this->nextData = null; $this->bytesToRead = false; if ( $this->currentMessage !== false ) { $tag = $this->getNextTag(); $this->connection->sendData( "{$tag} {$this->uid}FETCH {$this->currentMessage} RFC822" ); $response = $this->connection->getLine(); if ( strpos( $response, ' NO ' ) !== false || strpos( $response, ' BAD ') !== false ) { throw new ezcMailTransportException( "The IMAP server sent a negative reply when requesting mail." ); } else { $response = $this->getResponse( 'FETCH (', $response ); if ( strpos( $response, 'FETCH (' ) !== false ) { $this->hasMoreMailData = true; // retrieve the message size from $response, eg. if $response is: // * 2 FETCH (FLAGS (\Answered \Seen) RFC822 {377} // then $this->bytesToRead will be 377 preg_match( '/\{(.*)\}/', $response, $matches ); if ( count( $matches ) > 0 ) { $this->bytesToRead = (int) $matches[1]; } return true; } else { $response = $this->getResponse( $tag ); if ( strpos( $response, 'OK ' ) === false ) { throw new ezcMailTransportException( "The IMAP server sent a negative reply when requesting mail." ); } } } } return false; }
[ "public", "function", "nextMail", "(", ")", "{", "if", "(", "$", "this", "->", "currentMessage", "===", "null", ")", "{", "$", "this", "->", "currentMessage", "=", "reset", "(", "$", "this", "->", "messages", ")", ";", "}", "else", "{", "$", "this", "->", "currentMessage", "=", "next", "(", "$", "this", "->", "messages", ")", ";", "}", "$", "this", "->", "nextData", "=", "null", ";", "$", "this", "->", "bytesToRead", "=", "false", ";", "if", "(", "$", "this", "->", "currentMessage", "!==", "false", ")", "{", "$", "tag", "=", "$", "this", "->", "getNextTag", "(", ")", ";", "$", "this", "->", "connection", "->", "sendData", "(", "\"{$tag} {$this->uid}FETCH {$this->currentMessage} RFC822\"", ")", ";", "$", "response", "=", "$", "this", "->", "connection", "->", "getLine", "(", ")", ";", "if", "(", "strpos", "(", "$", "response", ",", "' NO '", ")", "!==", "false", "||", "strpos", "(", "$", "response", ",", "' BAD '", ")", "!==", "false", ")", "{", "throw", "new", "ezcMailTransportException", "(", "\"The IMAP server sent a negative reply when requesting mail.\"", ")", ";", "}", "else", "{", "$", "response", "=", "$", "this", "->", "getResponse", "(", "'FETCH ('", ",", "$", "response", ")", ";", "if", "(", "strpos", "(", "$", "response", ",", "'FETCH ('", ")", "!==", "false", ")", "{", "$", "this", "->", "hasMoreMailData", "=", "true", ";", "// retrieve the message size from $response, eg. if $response is:", "// * 2 FETCH (FLAGS (\\Answered \\Seen) RFC822 {377}", "// then $this->bytesToRead will be 377", "preg_match", "(", "'/\\{(.*)\\}/'", ",", "$", "response", ",", "$", "matches", ")", ";", "if", "(", "count", "(", "$", "matches", ")", ">", "0", ")", "{", "$", "this", "->", "bytesToRead", "=", "(", "int", ")", "$", "matches", "[", "1", "]", ";", "}", "return", "true", ";", "}", "else", "{", "$", "response", "=", "$", "this", "->", "getResponse", "(", "$", "tag", ")", ";", "if", "(", "strpos", "(", "$", "response", ",", "'OK '", ")", "===", "false", ")", "{", "throw", "new", "ezcMailTransportException", "(", "\"The IMAP server sent a negative reply when requesting mail.\"", ")", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Moves the set to the next mail and returns true upon success. False is returned if there are no more mail in the set. @throws ezcMailTransportException if the server sent a negative response @return bool
[ "Moves", "the", "set", "to", "the", "next", "mail", "and", "returns", "true", "upon", "success", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/imap/imap_set.php#L223-L272
dave-redfern/laravel-doctrine-entity-audit
src/Utils/ArrayDiff.php
ArrayDiff.diff
public function diff(array $oldData, array $newData) { $diff = []; $keys = array_keys($oldData + $newData); foreach ($keys as $field) { $old = array_key_exists($field, $oldData) ? $oldData[$field] : null; $new = array_key_exists($field, $newData) ? $newData[$field] : null; if ($old == $new) { $row = ['old' => '', 'new' => '', 'same' => $old]; } else { $row = ['old' => $old, 'new' => $new, 'same' => '']; } $diff[$field] = $row; } return $diff; }
php
public function diff(array $oldData, array $newData) { $diff = []; $keys = array_keys($oldData + $newData); foreach ($keys as $field) { $old = array_key_exists($field, $oldData) ? $oldData[$field] : null; $new = array_key_exists($field, $newData) ? $newData[$field] : null; if ($old == $new) { $row = ['old' => '', 'new' => '', 'same' => $old]; } else { $row = ['old' => $old, 'new' => $new, 'same' => '']; } $diff[$field] = $row; } return $diff; }
[ "public", "function", "diff", "(", "array", "$", "oldData", ",", "array", "$", "newData", ")", "{", "$", "diff", "=", "[", "]", ";", "$", "keys", "=", "array_keys", "(", "$", "oldData", "+", "$", "newData", ")", ";", "foreach", "(", "$", "keys", "as", "$", "field", ")", "{", "$", "old", "=", "array_key_exists", "(", "$", "field", ",", "$", "oldData", ")", "?", "$", "oldData", "[", "$", "field", "]", ":", "null", ";", "$", "new", "=", "array_key_exists", "(", "$", "field", ",", "$", "newData", ")", "?", "$", "newData", "[", "$", "field", "]", ":", "null", ";", "if", "(", "$", "old", "==", "$", "new", ")", "{", "$", "row", "=", "[", "'old'", "=>", "''", ",", "'new'", "=>", "''", ",", "'same'", "=>", "$", "old", "]", ";", "}", "else", "{", "$", "row", "=", "[", "'old'", "=>", "$", "old", ",", "'new'", "=>", "$", "new", ",", "'same'", "=>", "''", "]", ";", "}", "$", "diff", "[", "$", "field", "]", "=", "$", "row", ";", "}", "return", "$", "diff", ";", "}" ]
@param array $oldData @param array $newData @return array
[ "@param", "array", "$oldData", "@param", "array", "$newData" ]
train
https://github.com/dave-redfern/laravel-doctrine-entity-audit/blob/ab79e305fe512ceefbc14d585fefe0a40cf911ab/src/Utils/ArrayDiff.php#L40-L59
mvccore/ext-router-module
src/MvcCore/Ext/Routers/Module/Canonical.php
Canonical.canonicalRedirectQueryStringStrategy
protected function canonicalRedirectQueryStringStrategy () { /** @var $request \MvcCore\Request */ $request = & $this->request; $redirectToCanonicalUrl = FALSE; $requestGlobalGet = & $request->GetGlobalCollection('get'); $requestedCtrlDc = isset($requestGlobalGet[static::URL_PARAM_CONTROLLER]) ? $requestGlobalGet[static::URL_PARAM_CONTROLLER] : NULL; $requestedActionDc = isset($requestGlobalGet[static::URL_PARAM_ACTION]) ? $requestGlobalGet[static::URL_PARAM_ACTION] : NULL; $toolClass = self::$toolClass; list($dfltCtrlPc, $dftlActionPc) = $this->application->GetDefaultControllerAndActionNames(); $dfltCtrlDc = $toolClass::GetDashedFromPascalCase($dfltCtrlPc); $dftlActionDc = $toolClass::GetDashedFromPascalCase($dftlActionPc); $requestedParamsClone = array_merge([], $this->requestedParams); if ($requestedCtrlDc !== NULL && $requestedCtrlDc === $dfltCtrlDc) { unset($requestedParamsClone[static::URL_PARAM_CONTROLLER]); $redirectToCanonicalUrl = TRUE; } if ($requestedActionDc !== NULL && $requestedActionDc === $dftlActionDc) { unset($requestedParamsClone[static::URL_PARAM_ACTION]); $redirectToCanonicalUrl = TRUE; } if ($this->currentDomainRoute !== NULL) { $targetDomainRoute = $this->currentDomainRoute; $domainParams = array_intersect_key($requestedParamsClone, $this->requestedDomainParams); $requestedParamsClone = array_diff_key($requestedParamsClone, $this->requestedDomainParams); list($domainUrlBaseSection,) = $targetDomainRoute->Url( $this->request, $domainParams, $this->requestedDomainParams, '', TRUE ); if (mb_strpos($domainUrlBaseSection, '//') === FALSE) $domainUrlBaseSection = $request->GetDomainUrl() . $domainUrlBaseSection; if (mb_strlen($domainUrlBaseSection) > 0 && $domainUrlBaseSection !== $request->GetBaseUrl()) $redirectToCanonicalUrl = TRUE; //x([$domainUrlBaseSection, $request->GetBaseUrl()]); } if ($redirectToCanonicalUrl) { $selfCanonicalUrl = $this->UrlByQueryString($this->selfRouteName, $requestedParamsClone); $this->redirect($selfCanonicalUrl, \MvcCore\IResponse::MOVED_PERMANENTLY); return FALSE; } return TRUE; }
php
protected function canonicalRedirectQueryStringStrategy () { /** @var $request \MvcCore\Request */ $request = & $this->request; $redirectToCanonicalUrl = FALSE; $requestGlobalGet = & $request->GetGlobalCollection('get'); $requestedCtrlDc = isset($requestGlobalGet[static::URL_PARAM_CONTROLLER]) ? $requestGlobalGet[static::URL_PARAM_CONTROLLER] : NULL; $requestedActionDc = isset($requestGlobalGet[static::URL_PARAM_ACTION]) ? $requestGlobalGet[static::URL_PARAM_ACTION] : NULL; $toolClass = self::$toolClass; list($dfltCtrlPc, $dftlActionPc) = $this->application->GetDefaultControllerAndActionNames(); $dfltCtrlDc = $toolClass::GetDashedFromPascalCase($dfltCtrlPc); $dftlActionDc = $toolClass::GetDashedFromPascalCase($dftlActionPc); $requestedParamsClone = array_merge([], $this->requestedParams); if ($requestedCtrlDc !== NULL && $requestedCtrlDc === $dfltCtrlDc) { unset($requestedParamsClone[static::URL_PARAM_CONTROLLER]); $redirectToCanonicalUrl = TRUE; } if ($requestedActionDc !== NULL && $requestedActionDc === $dftlActionDc) { unset($requestedParamsClone[static::URL_PARAM_ACTION]); $redirectToCanonicalUrl = TRUE; } if ($this->currentDomainRoute !== NULL) { $targetDomainRoute = $this->currentDomainRoute; $domainParams = array_intersect_key($requestedParamsClone, $this->requestedDomainParams); $requestedParamsClone = array_diff_key($requestedParamsClone, $this->requestedDomainParams); list($domainUrlBaseSection,) = $targetDomainRoute->Url( $this->request, $domainParams, $this->requestedDomainParams, '', TRUE ); if (mb_strpos($domainUrlBaseSection, '//') === FALSE) $domainUrlBaseSection = $request->GetDomainUrl() . $domainUrlBaseSection; if (mb_strlen($domainUrlBaseSection) > 0 && $domainUrlBaseSection !== $request->GetBaseUrl()) $redirectToCanonicalUrl = TRUE; //x([$domainUrlBaseSection, $request->GetBaseUrl()]); } if ($redirectToCanonicalUrl) { $selfCanonicalUrl = $this->UrlByQueryString($this->selfRouteName, $requestedParamsClone); $this->redirect($selfCanonicalUrl, \MvcCore\IResponse::MOVED_PERMANENTLY); return FALSE; } return TRUE; }
[ "protected", "function", "canonicalRedirectQueryStringStrategy", "(", ")", "{", "/** @var $request \\MvcCore\\Request */", "$", "request", "=", "&", "$", "this", "->", "request", ";", "$", "redirectToCanonicalUrl", "=", "FALSE", ";", "$", "requestGlobalGet", "=", "&", "$", "request", "->", "GetGlobalCollection", "(", "'get'", ")", ";", "$", "requestedCtrlDc", "=", "isset", "(", "$", "requestGlobalGet", "[", "static", "::", "URL_PARAM_CONTROLLER", "]", ")", "?", "$", "requestGlobalGet", "[", "static", "::", "URL_PARAM_CONTROLLER", "]", ":", "NULL", ";", "$", "requestedActionDc", "=", "isset", "(", "$", "requestGlobalGet", "[", "static", "::", "URL_PARAM_ACTION", "]", ")", "?", "$", "requestGlobalGet", "[", "static", "::", "URL_PARAM_ACTION", "]", ":", "NULL", ";", "$", "toolClass", "=", "self", "::", "$", "toolClass", ";", "list", "(", "$", "dfltCtrlPc", ",", "$", "dftlActionPc", ")", "=", "$", "this", "->", "application", "->", "GetDefaultControllerAndActionNames", "(", ")", ";", "$", "dfltCtrlDc", "=", "$", "toolClass", "::", "GetDashedFromPascalCase", "(", "$", "dfltCtrlPc", ")", ";", "$", "dftlActionDc", "=", "$", "toolClass", "::", "GetDashedFromPascalCase", "(", "$", "dftlActionPc", ")", ";", "$", "requestedParamsClone", "=", "array_merge", "(", "[", "]", ",", "$", "this", "->", "requestedParams", ")", ";", "if", "(", "$", "requestedCtrlDc", "!==", "NULL", "&&", "$", "requestedCtrlDc", "===", "$", "dfltCtrlDc", ")", "{", "unset", "(", "$", "requestedParamsClone", "[", "static", "::", "URL_PARAM_CONTROLLER", "]", ")", ";", "$", "redirectToCanonicalUrl", "=", "TRUE", ";", "}", "if", "(", "$", "requestedActionDc", "!==", "NULL", "&&", "$", "requestedActionDc", "===", "$", "dftlActionDc", ")", "{", "unset", "(", "$", "requestedParamsClone", "[", "static", "::", "URL_PARAM_ACTION", "]", ")", ";", "$", "redirectToCanonicalUrl", "=", "TRUE", ";", "}", "if", "(", "$", "this", "->", "currentDomainRoute", "!==", "NULL", ")", "{", "$", "targetDomainRoute", "=", "$", "this", "->", "currentDomainRoute", ";", "$", "domainParams", "=", "array_intersect_key", "(", "$", "requestedParamsClone", ",", "$", "this", "->", "requestedDomainParams", ")", ";", "$", "requestedParamsClone", "=", "array_diff_key", "(", "$", "requestedParamsClone", ",", "$", "this", "->", "requestedDomainParams", ")", ";", "list", "(", "$", "domainUrlBaseSection", ",", ")", "=", "$", "targetDomainRoute", "->", "Url", "(", "$", "this", "->", "request", ",", "$", "domainParams", ",", "$", "this", "->", "requestedDomainParams", ",", "''", ",", "TRUE", ")", ";", "if", "(", "mb_strpos", "(", "$", "domainUrlBaseSection", ",", "'//'", ")", "===", "FALSE", ")", "$", "domainUrlBaseSection", "=", "$", "request", "->", "GetDomainUrl", "(", ")", ".", "$", "domainUrlBaseSection", ";", "if", "(", "mb_strlen", "(", "$", "domainUrlBaseSection", ")", ">", "0", "&&", "$", "domainUrlBaseSection", "!==", "$", "request", "->", "GetBaseUrl", "(", ")", ")", "$", "redirectToCanonicalUrl", "=", "TRUE", ";", "//x([$domainUrlBaseSection, $request->GetBaseUrl()]);", "}", "if", "(", "$", "redirectToCanonicalUrl", ")", "{", "$", "selfCanonicalUrl", "=", "$", "this", "->", "UrlByQueryString", "(", "$", "this", "->", "selfRouteName", ",", "$", "requestedParamsClone", ")", ";", "$", "this", "->", "redirect", "(", "$", "selfCanonicalUrl", ",", "\\", "MvcCore", "\\", "IResponse", "::", "MOVED_PERMANENTLY", ")", ";", "return", "FALSE", ";", "}", "return", "TRUE", ";", "}" ]
If request is routed by query string strategy, check if request controller or request action is the same as default values. Then redirect to shorter canonical URL. Check also if there is routed/defined any module domain route and if there is any, try to complete base URL domain part and also compare this part with requested URL part. If there is difference, redirect to shorter URL version. @return bool
[ "If", "request", "is", "routed", "by", "query", "string", "strategy", "check", "if", "request", "controller", "or", "request", "action", "is", "the", "same", "as", "default", "values", ".", "Then", "redirect", "to", "shorter", "canonical", "URL", ".", "Check", "also", "if", "there", "is", "routed", "/", "defined", "any", "module", "domain", "route", "and", "if", "there", "is", "any", "try", "to", "complete", "base", "URL", "domain", "part", "and", "also", "compare", "this", "part", "with", "requested", "URL", "part", ".", "If", "there", "is", "difference", "redirect", "to", "shorter", "URL", "version", "." ]
train
https://github.com/mvccore/ext-router-module/blob/7695784a451db86cca6a43c98d076803cd0a50a7/src/MvcCore/Ext/Routers/Module/Canonical.php#L27-L66
mvccore/ext-router-module
src/MvcCore/Ext/Routers/Module/Canonical.php
Canonical.canonicalRedirectRewriteRoutesStrategy
protected function canonicalRedirectRewriteRoutesStrategy () { /** @var $request \MvcCore\Request */ $request = & $this->request; $redirectToCanonicalUrl = FALSE; $defaultParams = $this->GetDefaultParams() ?: []; if ($this->currentDomainRoute !== NULL) { $targetDomainRoute = $this->currentDomainRoute; $domainParams = array_intersect_key($defaultParams, $this->requestedDomainParams); $defaultParamsClone = array_diff_key($defaultParams, $this->requestedDomainParams); $requestedParamsClone = array_diff_key($this->requestedParams, $this->requestedDomainParams); list($domainUrlBaseSection,) = $targetDomainRoute->Url( $this->request, $domainParams, $defaultParams, '', TRUE ); list($selfUrlDomainAndBasePart, $selfUrlPathAndQueryPart) = $this->currentRoute->Url( $request, $requestedParamsClone, $defaultParamsClone, $this->getQueryStringParamsSepatator(), TRUE ); if (mb_strpos($domainUrlBaseSection, '//') === FALSE) $domainUrlBaseSection = $request->GetDomainUrl() . $domainUrlBaseSection; if (mb_strlen($domainUrlBaseSection) > 0 && $domainUrlBaseSection !== $request->GetBaseUrl()) $redirectToCanonicalUrl = TRUE; //x([1, $domainUrlBaseSection, $request->GetBaseUrl()]); } else { $domainUrlBaseSection = NULL; list($selfUrlDomainAndBasePart, $selfUrlPathAndQueryPart) = $this->currentRoute->Url( $request, $this->requestedParams, $defaultParams, $this->getQueryStringParamsSepatator(), TRUE ); if (mb_strpos($selfUrlDomainAndBasePart, '//') === FALSE) $selfUrlDomainAndBasePart = $request->GetDomainUrl() . $selfUrlDomainAndBasePart; if (mb_strlen($selfUrlDomainAndBasePart) > 0 && $selfUrlDomainAndBasePart !== $request->GetBaseUrl()) $redirectToCanonicalUrl = TRUE; //x([2, $selfUrlDomainAndBasePart, $request->GetBaseUrl()]); } if (mb_strlen($selfUrlPathAndQueryPart) > 0) { $path = $request->GetPath(FALSE); $requestedUrl = $path === '' ? '/' : $path ; if (mb_strpos($selfUrlPathAndQueryPart, '?') !== FALSE) { $selfUrlPathAndQueryPart = rawurldecode($selfUrlPathAndQueryPart); $requestedUrl .= $request->GetQuery(TRUE, FALSE); } //x([3, $selfUrlPathAndQueryPart, $requestedUrl]); if ($selfUrlPathAndQueryPart !== $requestedUrl) $redirectToCanonicalUrl = TRUE; } if ($redirectToCanonicalUrl) { $selfCanonicalUrl = $this->Url($this->selfRouteName, $this->requestedParams); //x($selfCanonicalUrl); //return true; $this->redirect($selfCanonicalUrl, \MvcCore\IResponse::MOVED_PERMANENTLY); return FALSE; } return TRUE; }
php
protected function canonicalRedirectRewriteRoutesStrategy () { /** @var $request \MvcCore\Request */ $request = & $this->request; $redirectToCanonicalUrl = FALSE; $defaultParams = $this->GetDefaultParams() ?: []; if ($this->currentDomainRoute !== NULL) { $targetDomainRoute = $this->currentDomainRoute; $domainParams = array_intersect_key($defaultParams, $this->requestedDomainParams); $defaultParamsClone = array_diff_key($defaultParams, $this->requestedDomainParams); $requestedParamsClone = array_diff_key($this->requestedParams, $this->requestedDomainParams); list($domainUrlBaseSection,) = $targetDomainRoute->Url( $this->request, $domainParams, $defaultParams, '', TRUE ); list($selfUrlDomainAndBasePart, $selfUrlPathAndQueryPart) = $this->currentRoute->Url( $request, $requestedParamsClone, $defaultParamsClone, $this->getQueryStringParamsSepatator(), TRUE ); if (mb_strpos($domainUrlBaseSection, '//') === FALSE) $domainUrlBaseSection = $request->GetDomainUrl() . $domainUrlBaseSection; if (mb_strlen($domainUrlBaseSection) > 0 && $domainUrlBaseSection !== $request->GetBaseUrl()) $redirectToCanonicalUrl = TRUE; //x([1, $domainUrlBaseSection, $request->GetBaseUrl()]); } else { $domainUrlBaseSection = NULL; list($selfUrlDomainAndBasePart, $selfUrlPathAndQueryPart) = $this->currentRoute->Url( $request, $this->requestedParams, $defaultParams, $this->getQueryStringParamsSepatator(), TRUE ); if (mb_strpos($selfUrlDomainAndBasePart, '//') === FALSE) $selfUrlDomainAndBasePart = $request->GetDomainUrl() . $selfUrlDomainAndBasePart; if (mb_strlen($selfUrlDomainAndBasePart) > 0 && $selfUrlDomainAndBasePart !== $request->GetBaseUrl()) $redirectToCanonicalUrl = TRUE; //x([2, $selfUrlDomainAndBasePart, $request->GetBaseUrl()]); } if (mb_strlen($selfUrlPathAndQueryPart) > 0) { $path = $request->GetPath(FALSE); $requestedUrl = $path === '' ? '/' : $path ; if (mb_strpos($selfUrlPathAndQueryPart, '?') !== FALSE) { $selfUrlPathAndQueryPart = rawurldecode($selfUrlPathAndQueryPart); $requestedUrl .= $request->GetQuery(TRUE, FALSE); } //x([3, $selfUrlPathAndQueryPart, $requestedUrl]); if ($selfUrlPathAndQueryPart !== $requestedUrl) $redirectToCanonicalUrl = TRUE; } if ($redirectToCanonicalUrl) { $selfCanonicalUrl = $this->Url($this->selfRouteName, $this->requestedParams); //x($selfCanonicalUrl); //return true; $this->redirect($selfCanonicalUrl, \MvcCore\IResponse::MOVED_PERMANENTLY); return FALSE; } return TRUE; }
[ "protected", "function", "canonicalRedirectRewriteRoutesStrategy", "(", ")", "{", "/** @var $request \\MvcCore\\Request */", "$", "request", "=", "&", "$", "this", "->", "request", ";", "$", "redirectToCanonicalUrl", "=", "FALSE", ";", "$", "defaultParams", "=", "$", "this", "->", "GetDefaultParams", "(", ")", "?", ":", "[", "]", ";", "if", "(", "$", "this", "->", "currentDomainRoute", "!==", "NULL", ")", "{", "$", "targetDomainRoute", "=", "$", "this", "->", "currentDomainRoute", ";", "$", "domainParams", "=", "array_intersect_key", "(", "$", "defaultParams", ",", "$", "this", "->", "requestedDomainParams", ")", ";", "$", "defaultParamsClone", "=", "array_diff_key", "(", "$", "defaultParams", ",", "$", "this", "->", "requestedDomainParams", ")", ";", "$", "requestedParamsClone", "=", "array_diff_key", "(", "$", "this", "->", "requestedParams", ",", "$", "this", "->", "requestedDomainParams", ")", ";", "list", "(", "$", "domainUrlBaseSection", ",", ")", "=", "$", "targetDomainRoute", "->", "Url", "(", "$", "this", "->", "request", ",", "$", "domainParams", ",", "$", "defaultParams", ",", "''", ",", "TRUE", ")", ";", "list", "(", "$", "selfUrlDomainAndBasePart", ",", "$", "selfUrlPathAndQueryPart", ")", "=", "$", "this", "->", "currentRoute", "->", "Url", "(", "$", "request", ",", "$", "requestedParamsClone", ",", "$", "defaultParamsClone", ",", "$", "this", "->", "getQueryStringParamsSepatator", "(", ")", ",", "TRUE", ")", ";", "if", "(", "mb_strpos", "(", "$", "domainUrlBaseSection", ",", "'//'", ")", "===", "FALSE", ")", "$", "domainUrlBaseSection", "=", "$", "request", "->", "GetDomainUrl", "(", ")", ".", "$", "domainUrlBaseSection", ";", "if", "(", "mb_strlen", "(", "$", "domainUrlBaseSection", ")", ">", "0", "&&", "$", "domainUrlBaseSection", "!==", "$", "request", "->", "GetBaseUrl", "(", ")", ")", "$", "redirectToCanonicalUrl", "=", "TRUE", ";", "//x([1, $domainUrlBaseSection, $request->GetBaseUrl()]);", "}", "else", "{", "$", "domainUrlBaseSection", "=", "NULL", ";", "list", "(", "$", "selfUrlDomainAndBasePart", ",", "$", "selfUrlPathAndQueryPart", ")", "=", "$", "this", "->", "currentRoute", "->", "Url", "(", "$", "request", ",", "$", "this", "->", "requestedParams", ",", "$", "defaultParams", ",", "$", "this", "->", "getQueryStringParamsSepatator", "(", ")", ",", "TRUE", ")", ";", "if", "(", "mb_strpos", "(", "$", "selfUrlDomainAndBasePart", ",", "'//'", ")", "===", "FALSE", ")", "$", "selfUrlDomainAndBasePart", "=", "$", "request", "->", "GetDomainUrl", "(", ")", ".", "$", "selfUrlDomainAndBasePart", ";", "if", "(", "mb_strlen", "(", "$", "selfUrlDomainAndBasePart", ")", ">", "0", "&&", "$", "selfUrlDomainAndBasePart", "!==", "$", "request", "->", "GetBaseUrl", "(", ")", ")", "$", "redirectToCanonicalUrl", "=", "TRUE", ";", "//x([2, $selfUrlDomainAndBasePart, $request->GetBaseUrl()]);", "}", "if", "(", "mb_strlen", "(", "$", "selfUrlPathAndQueryPart", ")", ">", "0", ")", "{", "$", "path", "=", "$", "request", "->", "GetPath", "(", "FALSE", ")", ";", "$", "requestedUrl", "=", "$", "path", "===", "''", "?", "'/'", ":", "$", "path", ";", "if", "(", "mb_strpos", "(", "$", "selfUrlPathAndQueryPart", ",", "'?'", ")", "!==", "FALSE", ")", "{", "$", "selfUrlPathAndQueryPart", "=", "rawurldecode", "(", "$", "selfUrlPathAndQueryPart", ")", ";", "$", "requestedUrl", ".=", "$", "request", "->", "GetQuery", "(", "TRUE", ",", "FALSE", ")", ";", "}", "//x([3, $selfUrlPathAndQueryPart, $requestedUrl]);", "if", "(", "$", "selfUrlPathAndQueryPart", "!==", "$", "requestedUrl", ")", "$", "redirectToCanonicalUrl", "=", "TRUE", ";", "}", "if", "(", "$", "redirectToCanonicalUrl", ")", "{", "$", "selfCanonicalUrl", "=", "$", "this", "->", "Url", "(", "$", "this", "->", "selfRouteName", ",", "$", "this", "->", "requestedParams", ")", ";", "//x($selfCanonicalUrl);", "//return true;", "$", "this", "->", "redirect", "(", "$", "selfCanonicalUrl", ",", "\\", "MvcCore", "\\", "IResponse", "::", "MOVED_PERMANENTLY", ")", ";", "return", "FALSE", ";", "}", "return", "TRUE", ";", "}" ]
If request is routed by rewrite routes strategy, try to complete canonical URL by current route. Then compare completed base URL part with requested base URL part or completed path and query part with requested path and query part. Check also if there is routed/defined any module domain route and if there is any, try to complete base URL domain part and also compare this part with requested URL part. If first URL part or second URL part is different, redirect to canonical shorter URL. @return bool
[ "If", "request", "is", "routed", "by", "rewrite", "routes", "strategy", "try", "to", "complete", "canonical", "URL", "by", "current", "route", ".", "Then", "compare", "completed", "base", "URL", "part", "with", "requested", "base", "URL", "part", "or", "completed", "path", "and", "query", "part", "with", "requested", "path", "and", "query", "part", ".", "Check", "also", "if", "there", "is", "routed", "/", "defined", "any", "module", "domain", "route", "and", "if", "there", "is", "any", "try", "to", "complete", "base", "URL", "domain", "part", "and", "also", "compare", "this", "part", "with", "requested", "URL", "part", ".", "If", "first", "URL", "part", "or", "second", "URL", "part", "is", "different", "redirect", "to", "canonical", "shorter", "URL", "." ]
train
https://github.com/mvccore/ext-router-module/blob/7695784a451db86cca6a43c98d076803cd0a50a7/src/MvcCore/Ext/Routers/Module/Canonical.php#L78-L132
KodiComponents/Support
src/Http/CollectionFilters.php
CollectionFilters.apply
public function apply(Collection $collection) { $this->collection = $collection; foreach ($this->filters() as $name => $value) { if (! method_exists($this, $name)) { continue; } if (is_array($value) or trim($value)) { $this->collection = $this->$name($value); } else { $this->collection = $this->$name(); } } return $this->collection; }
php
public function apply(Collection $collection) { $this->collection = $collection; foreach ($this->filters() as $name => $value) { if (! method_exists($this, $name)) { continue; } if (is_array($value) or trim($value)) { $this->collection = $this->$name($value); } else { $this->collection = $this->$name(); } } return $this->collection; }
[ "public", "function", "apply", "(", "Collection", "$", "collection", ")", "{", "$", "this", "->", "collection", "=", "$", "collection", ";", "foreach", "(", "$", "this", "->", "filters", "(", ")", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", "method_exists", "(", "$", "this", ",", "$", "name", ")", ")", "{", "continue", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", "or", "trim", "(", "$", "value", ")", ")", "{", "$", "this", "->", "collection", "=", "$", "this", "->", "$", "name", "(", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "collection", "=", "$", "this", "->", "$", "name", "(", ")", ";", "}", "}", "return", "$", "this", "->", "collection", ";", "}" ]
Apply the filters to the collection. @param Collection $collection @return Collection
[ "Apply", "the", "filters", "to", "the", "collection", "." ]
train
https://github.com/KodiComponents/Support/blob/9090543605a2354c7454d707650a0abdb815b60a/src/Http/CollectionFilters.php#L41-L58
ekuiter/feature-php
FeaturePhp/Generator/FileGenerator.php
FileGenerator.getFileOrDirectorySettings
private function getFileOrDirectorySettings($settings, $key) { $filesOrDirectories = $settings->getOptional($key, array()); if (!is_array($filesOrDirectories)) $filesOrDirectories = array($filesOrDirectories); return $filesOrDirectories; }
php
private function getFileOrDirectorySettings($settings, $key) { $filesOrDirectories = $settings->getOptional($key, array()); if (!is_array($filesOrDirectories)) $filesOrDirectories = array($filesOrDirectories); return $filesOrDirectories; }
[ "private", "function", "getFileOrDirectorySettings", "(", "$", "settings", ",", "$", "key", ")", "{", "$", "filesOrDirectories", "=", "$", "settings", "->", "getOptional", "(", "$", "key", ",", "array", "(", ")", ")", ";", "if", "(", "!", "is_array", "(", "$", "filesOrDirectories", ")", ")", "$", "filesOrDirectories", "=", "array", "(", "$", "filesOrDirectories", ")", ";", "return", "$", "filesOrDirectories", ";", "}" ]
Returns plain settings arrays with file or directory specifications. @param Settings $settings @param string $key @return array[]
[ "Returns", "plain", "settings", "arrays", "with", "file", "or", "directory", "specifications", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Generator/FileGenerator.php#L35-L40
ekuiter/feature-php
FeaturePhp/Generator/FileGenerator.php
FileGenerator._generateFiles
protected function _generateFiles() { foreach ($this->selectedArtifacts as $artifact) { $settings = $artifact->getGeneratorSettings(static::getKey()); foreach ($this->getFileOrDirectorySettings($settings, "files") as $file) $this->_processFileSpecification( $artifact, fphp\Specification\FileSpecification::fromArrayAndSettings($file, $settings)); foreach ($this->getFileOrDirectorySettings($settings, "directories") as $directory) { $directorySpecification = fphp\Specification\DirectorySpecification::fromArrayAndSettings($directory, $settings); foreach ($directorySpecification->getFileSpecifications() as $fileSpecification) $this->_processFileSpecification($artifact, $fileSpecification); } } }
php
protected function _generateFiles() { foreach ($this->selectedArtifacts as $artifact) { $settings = $artifact->getGeneratorSettings(static::getKey()); foreach ($this->getFileOrDirectorySettings($settings, "files") as $file) $this->_processFileSpecification( $artifact, fphp\Specification\FileSpecification::fromArrayAndSettings($file, $settings)); foreach ($this->getFileOrDirectorySettings($settings, "directories") as $directory) { $directorySpecification = fphp\Specification\DirectorySpecification::fromArrayAndSettings($directory, $settings); foreach ($directorySpecification->getFileSpecifications() as $fileSpecification) $this->_processFileSpecification($artifact, $fileSpecification); } } }
[ "protected", "function", "_generateFiles", "(", ")", "{", "foreach", "(", "$", "this", "->", "selectedArtifacts", "as", "$", "artifact", ")", "{", "$", "settings", "=", "$", "artifact", "->", "getGeneratorSettings", "(", "static", "::", "getKey", "(", ")", ")", ";", "foreach", "(", "$", "this", "->", "getFileOrDirectorySettings", "(", "$", "settings", ",", "\"files\"", ")", "as", "$", "file", ")", "$", "this", "->", "_processFileSpecification", "(", "$", "artifact", ",", "fphp", "\\", "Specification", "\\", "FileSpecification", "::", "fromArrayAndSettings", "(", "$", "file", ",", "$", "settings", ")", ")", ";", "foreach", "(", "$", "this", "->", "getFileOrDirectorySettings", "(", "$", "settings", ",", "\"directories\"", ")", "as", "$", "directory", ")", "{", "$", "directorySpecification", "=", "fphp", "\\", "Specification", "\\", "DirectorySpecification", "::", "fromArrayAndSettings", "(", "$", "directory", ",", "$", "settings", ")", ";", "foreach", "(", "$", "directorySpecification", "->", "getFileSpecifications", "(", ")", "as", "$", "fileSpecification", ")", "$", "this", "->", "_processFileSpecification", "(", "$", "artifact", ",", "$", "fileSpecification", ")", ";", "}", "}", "}" ]
Processes the files and directories.
[ "Processes", "the", "files", "and", "directories", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Generator/FileGenerator.php#L45-L60
ekuiter/feature-php
FeaturePhp/Generator/FileGenerator.php
FileGenerator._processFileSpecification
private function _processFileSpecification($artifact, $fileSpecification) { if (!in_array(basename($fileSpecification->getSource()), $this->exclude)) $this->processFileSpecification($artifact, $fileSpecification); }
php
private function _processFileSpecification($artifact, $fileSpecification) { if (!in_array(basename($fileSpecification->getSource()), $this->exclude)) $this->processFileSpecification($artifact, $fileSpecification); }
[ "private", "function", "_processFileSpecification", "(", "$", "artifact", ",", "$", "fileSpecification", ")", "{", "if", "(", "!", "in_array", "(", "basename", "(", "$", "fileSpecification", "->", "getSource", "(", ")", ")", ",", "$", "this", "->", "exclude", ")", ")", "$", "this", "->", "processFileSpecification", "(", "$", "artifact", ",", "$", "fileSpecification", ")", ";", "}" ]
Processes a file from a specification. Considers globally excluded files. Only exact file names are supported. @param \FeaturePhp\Artifact\Artifact $artifact @param \FeaturePhp\Specification\FileSpecification $fileSpecification
[ "Processes", "a", "file", "from", "a", "specification", ".", "Considers", "globally", "excluded", "files", ".", "Only", "exact", "file", "names", "are", "supported", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Generator/FileGenerator.php#L68-L71
ajgarlag/AjglCsv
src/Io/IoAbstract.php
IoAbstract.close
public function close() { if (is_resource($this->fileHandler)) { $res = @fclose($this->fileHandler); if (false === $res) { throw new \RuntimeException('Cannot close the given resource'); } } }
php
public function close() { if (is_resource($this->fileHandler)) { $res = @fclose($this->fileHandler); if (false === $res) { throw new \RuntimeException('Cannot close the given resource'); } } }
[ "public", "function", "close", "(", ")", "{", "if", "(", "is_resource", "(", "$", "this", "->", "fileHandler", ")", ")", "{", "$", "res", "=", "@", "fclose", "(", "$", "this", "->", "fileHandler", ")", ";", "if", "(", "false", "===", "$", "res", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot close the given resource'", ")", ";", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/ajgarlag/AjglCsv/blob/28872f58b9ef864893cac6faddfcb1229c2c2047/src/Io/IoAbstract.php#L129-L137
ajgarlag/AjglCsv
src/Io/IoAbstract.php
IoAbstract.setMode
protected function setMode($mode) { $mode = substr((string) $mode, 0, 2); if (!in_array($mode, $this->validModes, true)) { throw new \InvalidArgumentException("The given mode '$mode' is not valid for the requested operation"); } $this->mode = $mode; return $this; }
php
protected function setMode($mode) { $mode = substr((string) $mode, 0, 2); if (!in_array($mode, $this->validModes, true)) { throw new \InvalidArgumentException("The given mode '$mode' is not valid for the requested operation"); } $this->mode = $mode; return $this; }
[ "protected", "function", "setMode", "(", "$", "mode", ")", "{", "$", "mode", "=", "substr", "(", "(", "string", ")", "$", "mode", ",", "0", ",", "2", ")", ";", "if", "(", "!", "in_array", "(", "$", "mode", ",", "$", "this", "->", "validModes", ",", "true", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The given mode '$mode' is not valid for the requested operation\"", ")", ";", "}", "$", "this", "->", "mode", "=", "$", "mode", ";", "return", "$", "this", ";", "}" ]
@param string $mode @throws \InvalidArgumentException @return \Ajgl\Csv\Io\IoAbstract
[ "@param", "string", "$mode" ]
train
https://github.com/ajgarlag/AjglCsv/blob/28872f58b9ef864893cac6faddfcb1229c2c2047/src/Io/IoAbstract.php#L151-L160
ajgarlag/AjglCsv
src/Io/IoAbstract.php
IoAbstract.openHandler
protected function openHandler($filePath, $mode) { $fileHandler = @fopen($filePath, $mode); if (false === $fileHandler) { throw new \RuntimeException("Cannot open the file '$filePath' in '$mode' mode"); } return $fileHandler; }
php
protected function openHandler($filePath, $mode) { $fileHandler = @fopen($filePath, $mode); if (false === $fileHandler) { throw new \RuntimeException("Cannot open the file '$filePath' in '$mode' mode"); } return $fileHandler; }
[ "protected", "function", "openHandler", "(", "$", "filePath", ",", "$", "mode", ")", "{", "$", "fileHandler", "=", "@", "fopen", "(", "$", "filePath", ",", "$", "mode", ")", ";", "if", "(", "false", "===", "$", "fileHandler", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Cannot open the file '$filePath' in '$mode' mode\"", ")", ";", "}", "return", "$", "fileHandler", ";", "}" ]
@param string $filePath @param string $mode @throws \RuntimeException @return resource
[ "@param", "string", "$filePath", "@param", "string", "$mode" ]
train
https://github.com/ajgarlag/AjglCsv/blob/28872f58b9ef864893cac6faddfcb1229c2c2047/src/Io/IoAbstract.php#L182-L190
ajgarlag/AjglCsv
src/Io/IoAbstract.php
IoAbstract.convertRowCharset
protected function convertRowCharset(array $row, $inputCharset, $fileCharset) { foreach ($row as $k => $v) { $row[$k] = $this->getConverter()->convert($v, $inputCharset, $fileCharset); } return $row; }
php
protected function convertRowCharset(array $row, $inputCharset, $fileCharset) { foreach ($row as $k => $v) { $row[$k] = $this->getConverter()->convert($v, $inputCharset, $fileCharset); } return $row; }
[ "protected", "function", "convertRowCharset", "(", "array", "$", "row", ",", "$", "inputCharset", ",", "$", "fileCharset", ")", "{", "foreach", "(", "$", "row", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "row", "[", "$", "k", "]", "=", "$", "this", "->", "getConverter", "(", ")", "->", "convert", "(", "$", "v", ",", "$", "inputCharset", ",", "$", "fileCharset", ")", ";", "}", "return", "$", "row", ";", "}" ]
@param array $row @param string $inputCharset @param string $fileCharset @return array
[ "@param", "array", "$row", "@param", "string", "$inputCharset", "@param", "string", "$fileCharset" ]
train
https://github.com/ajgarlag/AjglCsv/blob/28872f58b9ef864893cac6faddfcb1229c2c2047/src/Io/IoAbstract.php#L199-L206
inhere/php-librarys
src/Traits/LiteContainerStaticTrait.php
LiteContainerStaticTrait.set
public static function set($name, $service, $replace = false) { // have been used. if (isset(self::$instances[$name])) { throw new \LogicException("The service [$name] have been instanced, don't allow override it."); } // setting if ($replace || !isset(self::$services[$name])) { self::$services[$name] = $service; } return true; }
php
public static function set($name, $service, $replace = false) { // have been used. if (isset(self::$instances[$name])) { throw new \LogicException("The service [$name] have been instanced, don't allow override it."); } // setting if ($replace || !isset(self::$services[$name])) { self::$services[$name] = $service; } return true; }
[ "public", "static", "function", "set", "(", "$", "name", ",", "$", "service", ",", "$", "replace", "=", "false", ")", "{", "// have been used.", "if", "(", "isset", "(", "self", "::", "$", "instances", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"The service [$name] have been instanced, don't allow override it.\"", ")", ";", "}", "// setting", "if", "(", "$", "replace", "||", "!", "isset", "(", "self", "::", "$", "services", "[", "$", "name", "]", ")", ")", "{", "self", "::", "$", "services", "[", "$", "name", "]", "=", "$", "service", ";", "}", "return", "true", ";", "}" ]
register a app service @param string $name @param mixed $service service @param bool $replace replace exists service @return bool @throws \LogicException
[ "register", "a", "app", "service" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Traits/LiteContainerStaticTrait.php#L53-L66
inhere/php-librarys
src/Traits/LiteContainerStaticTrait.php
LiteContainerStaticTrait.get
public static function get($name, $call = true) { if (!isset(self::$services[$name])) { throw new \RuntimeException("The service [$name] don't register."); } $service = self::$services[$name]; if (\is_object($service) && $service instanceof \Closure && $call) { if (!isset(self::$instances[$name])) { self::$instances[$name] = $service(); } return self::$instances[$name]; } return $service; }
php
public static function get($name, $call = true) { if (!isset(self::$services[$name])) { throw new \RuntimeException("The service [$name] don't register."); } $service = self::$services[$name]; if (\is_object($service) && $service instanceof \Closure && $call) { if (!isset(self::$instances[$name])) { self::$instances[$name] = $service(); } return self::$instances[$name]; } return $service; }
[ "public", "static", "function", "get", "(", "$", "name", ",", "$", "call", "=", "true", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "services", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"The service [$name] don't register.\"", ")", ";", "}", "$", "service", "=", "self", "::", "$", "services", "[", "$", "name", "]", ";", "if", "(", "\\", "is_object", "(", "$", "service", ")", "&&", "$", "service", "instanceof", "\\", "Closure", "&&", "$", "call", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "instances", "[", "$", "name", "]", ")", ")", "{", "self", "::", "$", "instances", "[", "$", "name", "]", "=", "$", "service", "(", ")", ";", "}", "return", "self", "::", "$", "instances", "[", "$", "name", "]", ";", "}", "return", "$", "service", ";", "}" ]
get a app service by name if is a closure, only run once. @param string $name @param bool $call if service is 'Closure', call it. @return mixed @throws \RuntimeException
[ "get", "a", "app", "service", "by", "name", "if", "is", "a", "closure", "only", "run", "once", "." ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Traits/LiteContainerStaticTrait.php#L76-L93
inhere/php-librarys
src/Traits/LiteContainerStaticTrait.php
LiteContainerStaticTrait.factory
public static function factory($name) { if (!isset(self::$services[$name])) { throw new \RuntimeException("The service [$name] don't register."); } $service = self::$services[$name]; if (\is_object($service) && method_exists($service, '__invoke')) { return $service(); } return $service; }
php
public static function factory($name) { if (!isset(self::$services[$name])) { throw new \RuntimeException("The service [$name] don't register."); } $service = self::$services[$name]; if (\is_object($service) && method_exists($service, '__invoke')) { return $service(); } return $service; }
[ "public", "static", "function", "factory", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "services", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"The service [$name] don't register.\"", ")", ";", "}", "$", "service", "=", "self", "::", "$", "services", "[", "$", "name", "]", ";", "if", "(", "\\", "is_object", "(", "$", "service", ")", "&&", "method_exists", "(", "$", "service", ",", "'__invoke'", ")", ")", "{", "return", "$", "service", "(", ")", ";", "}", "return", "$", "service", ";", "}" ]
create a app service by name it always return a new instance. @param string $name @return mixed @throws \RuntimeException
[ "create", "a", "app", "service", "by", "name", "it", "always", "return", "a", "new", "instance", "." ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Traits/LiteContainerStaticTrait.php#L116-L129
i-lateral/silverstripe-modeladminplus
src/ModelAdminSnippet.php
ModelAdminSnippet.addExtraClasses
public function addExtraClasses($classes) { if (!is_array($classes)) { $classes = explode(" ", $classes); } $this->extra_classes = array_merge( $this->extra_classes, $classes ); return $this; }
php
public function addExtraClasses($classes) { if (!is_array($classes)) { $classes = explode(" ", $classes); } $this->extra_classes = array_merge( $this->extra_classes, $classes ); return $this; }
[ "public", "function", "addExtraClasses", "(", "$", "classes", ")", "{", "if", "(", "!", "is_array", "(", "$", "classes", ")", ")", "{", "$", "classes", "=", "explode", "(", "\" \"", ",", "$", "classes", ")", ";", "}", "$", "this", "->", "extra_classes", "=", "array_merge", "(", "$", "this", "->", "extra_classes", ",", "$", "classes", ")", ";", "return", "$", "this", ";", "}" ]
Add additional css classes @param array|string $extra_classes extra CSS classes @return self
[ "Add", "additional", "css", "classes" ]
train
https://github.com/i-lateral/silverstripe-modeladminplus/blob/c5209d9610cdb36ddc7b9231fad342df7e75ffc0/src/ModelAdminSnippet.php#L170-L182
i-lateral/silverstripe-modeladminplus
src/ModelAdminSnippet.php
ModelAdminSnippet.removeExtraClasses
public function removeExtraClasses($classes) { if (!is_array($classes)) { $classes = explode(" ", $classes); } foreach ($classes as $class) { if (isset($this->extra_classes[$class])) { unset($this->extra_classes[$class]); } } return $this; }
php
public function removeExtraClasses($classes) { if (!is_array($classes)) { $classes = explode(" ", $classes); } foreach ($classes as $class) { if (isset($this->extra_classes[$class])) { unset($this->extra_classes[$class]); } } return $this; }
[ "public", "function", "removeExtraClasses", "(", "$", "classes", ")", "{", "if", "(", "!", "is_array", "(", "$", "classes", ")", ")", "{", "$", "classes", "=", "explode", "(", "\" \"", ",", "$", "classes", ")", ";", "}", "foreach", "(", "$", "classes", "as", "$", "class", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "extra_classes", "[", "$", "class", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "extra_classes", "[", "$", "class", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Remove provided CSS classes @param array|string $extra_classes extra CSS classes @return self
[ "Remove", "provided", "CSS", "classes" ]
train
https://github.com/i-lateral/silverstripe-modeladminplus/blob/c5209d9610cdb36ddc7b9231fad342df7e75ffc0/src/ModelAdminSnippet.php#L191-L204
rem42/scraper
Client.php
Client.api
public function api(Request $request) { $reflectClassRequest = new \ReflectionClass($request); $className = $reflectClassRequest->getShortName(); $className = str_replace('Request', 'Api', $className); $namespace = str_replace('\Request', '\Api\\', $reflectClassRequest->getNamespaceName()); /** @var UrlAnnotation $urlAnnotation */ $urlAnnotation = Reader::read($request); $data = $this->fetchData($request, $reflectClassRequest, $urlAnnotation); $reflectClassName = new \ReflectionClass($namespace . $className); $instance = $reflectClassName->newInstanceArgs([$request, $data, $urlAnnotation]); return call_user_func([$instance, 'execute']); }
php
public function api(Request $request) { $reflectClassRequest = new \ReflectionClass($request); $className = $reflectClassRequest->getShortName(); $className = str_replace('Request', 'Api', $className); $namespace = str_replace('\Request', '\Api\\', $reflectClassRequest->getNamespaceName()); /** @var UrlAnnotation $urlAnnotation */ $urlAnnotation = Reader::read($request); $data = $this->fetchData($request, $reflectClassRequest, $urlAnnotation); $reflectClassName = new \ReflectionClass($namespace . $className); $instance = $reflectClassName->newInstanceArgs([$request, $data, $urlAnnotation]); return call_user_func([$instance, 'execute']); }
[ "public", "function", "api", "(", "Request", "$", "request", ")", "{", "$", "reflectClassRequest", "=", "new", "\\", "ReflectionClass", "(", "$", "request", ")", ";", "$", "className", "=", "$", "reflectClassRequest", "->", "getShortName", "(", ")", ";", "$", "className", "=", "str_replace", "(", "'Request'", ",", "'Api'", ",", "$", "className", ")", ";", "$", "namespace", "=", "str_replace", "(", "'\\Request'", ",", "'\\Api\\\\'", ",", "$", "reflectClassRequest", "->", "getNamespaceName", "(", ")", ")", ";", "/** @var UrlAnnotation $urlAnnotation */", "$", "urlAnnotation", "=", "Reader", "::", "read", "(", "$", "request", ")", ";", "$", "data", "=", "$", "this", "->", "fetchData", "(", "$", "request", ",", "$", "reflectClassRequest", ",", "$", "urlAnnotation", ")", ";", "$", "reflectClassName", "=", "new", "\\", "ReflectionClass", "(", "$", "namespace", ".", "$", "className", ")", ";", "$", "instance", "=", "$", "reflectClassName", "->", "newInstanceArgs", "(", "[", "$", "request", ",", "$", "data", ",", "$", "urlAnnotation", "]", ")", ";", "return", "call_user_func", "(", "[", "$", "instance", ",", "'execute'", "]", ")", ";", "}" ]
@param Request $request @return mixed @throws \Doctrine\Common\Annotations\AnnotationException @throws \ReflectionException
[ "@param", "Request", "$request" ]
train
https://github.com/rem42/scraper/blob/7c4ec23ce61b8187f2d8cfebdd233525359adb83/Client.php#L32-L45
rem42/scraper
Client.php
Client.fetchData
private function fetchData(Request $request, \ReflectionClass $reflectionClass, UrlAnnotation $urlAnnotation) { if($this->cache && $this->cacheModel instanceof Cache){ $this->cacheModel->setRequest($request); $this->cacheModel->setReflectionClass($reflectionClass); }else{ $this->cache = false; } try { $cacheRequest = false; if ($this->cache && $this->cacheModel->exist()) { $cacheRequest = true; $response = new Response(200, [], $this->cacheModel->get()); } if (!$cacheRequest) { /** @var IProtocol $class */ $class = (new \ReflectionClass('\Scraper\\Scraper\\Protocol\\' . ucfirst(strtolower($urlAnnotation->protocol)))) ->newInstanceArgs([$reflectionClass, $request, $urlAnnotation]); /** @var Response $response */ $response = $class->execute(); } } catch (\Exception $e) { echo 'Exception: ', $e->getMessage(), "\n"; } try { if (in_array(strtolower($urlAnnotation->contentType), ['html', 'json', 'text', 'xml'])) { /** @var IContentType $class */ $class = (new \ReflectionClass('\Scraper\\Scraper\\ContentType\\' . ucfirst(strtolower($urlAnnotation->contentType)))) ->newInstanceArgs([$reflectionClass, $request, $response, $urlAnnotation, $this->cacheModel]); } else { /** @var IContentType $class */ $class = (new \ReflectionClass($urlAnnotation->contentType)) ->newInstanceArgs([$reflectionClass, $request, $response, $urlAnnotation]); } /** @var Response $response */ $response = $class->execute(); } catch (\Exception $e) { echo 'Exception: ', $e->getMessage(), "\n"; } return $response; }
php
private function fetchData(Request $request, \ReflectionClass $reflectionClass, UrlAnnotation $urlAnnotation) { if($this->cache && $this->cacheModel instanceof Cache){ $this->cacheModel->setRequest($request); $this->cacheModel->setReflectionClass($reflectionClass); }else{ $this->cache = false; } try { $cacheRequest = false; if ($this->cache && $this->cacheModel->exist()) { $cacheRequest = true; $response = new Response(200, [], $this->cacheModel->get()); } if (!$cacheRequest) { /** @var IProtocol $class */ $class = (new \ReflectionClass('\Scraper\\Scraper\\Protocol\\' . ucfirst(strtolower($urlAnnotation->protocol)))) ->newInstanceArgs([$reflectionClass, $request, $urlAnnotation]); /** @var Response $response */ $response = $class->execute(); } } catch (\Exception $e) { echo 'Exception: ', $e->getMessage(), "\n"; } try { if (in_array(strtolower($urlAnnotation->contentType), ['html', 'json', 'text', 'xml'])) { /** @var IContentType $class */ $class = (new \ReflectionClass('\Scraper\\Scraper\\ContentType\\' . ucfirst(strtolower($urlAnnotation->contentType)))) ->newInstanceArgs([$reflectionClass, $request, $response, $urlAnnotation, $this->cacheModel]); } else { /** @var IContentType $class */ $class = (new \ReflectionClass($urlAnnotation->contentType)) ->newInstanceArgs([$reflectionClass, $request, $response, $urlAnnotation]); } /** @var Response $response */ $response = $class->execute(); } catch (\Exception $e) { echo 'Exception: ', $e->getMessage(), "\n"; } return $response; }
[ "private", "function", "fetchData", "(", "Request", "$", "request", ",", "\\", "ReflectionClass", "$", "reflectionClass", ",", "UrlAnnotation", "$", "urlAnnotation", ")", "{", "if", "(", "$", "this", "->", "cache", "&&", "$", "this", "->", "cacheModel", "instanceof", "Cache", ")", "{", "$", "this", "->", "cacheModel", "->", "setRequest", "(", "$", "request", ")", ";", "$", "this", "->", "cacheModel", "->", "setReflectionClass", "(", "$", "reflectionClass", ")", ";", "}", "else", "{", "$", "this", "->", "cache", "=", "false", ";", "}", "try", "{", "$", "cacheRequest", "=", "false", ";", "if", "(", "$", "this", "->", "cache", "&&", "$", "this", "->", "cacheModel", "->", "exist", "(", ")", ")", "{", "$", "cacheRequest", "=", "true", ";", "$", "response", "=", "new", "Response", "(", "200", ",", "[", "]", ",", "$", "this", "->", "cacheModel", "->", "get", "(", ")", ")", ";", "}", "if", "(", "!", "$", "cacheRequest", ")", "{", "/** @var IProtocol $class */", "$", "class", "=", "(", "new", "\\", "ReflectionClass", "(", "'\\Scraper\\\\Scraper\\\\Protocol\\\\'", ".", "ucfirst", "(", "strtolower", "(", "$", "urlAnnotation", "->", "protocol", ")", ")", ")", ")", "->", "newInstanceArgs", "(", "[", "$", "reflectionClass", ",", "$", "request", ",", "$", "urlAnnotation", "]", ")", ";", "/** @var Response $response */", "$", "response", "=", "$", "class", "->", "execute", "(", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "echo", "'Exception: '", ",", "$", "e", "->", "getMessage", "(", ")", ",", "\"\\n\"", ";", "}", "try", "{", "if", "(", "in_array", "(", "strtolower", "(", "$", "urlAnnotation", "->", "contentType", ")", ",", "[", "'html'", ",", "'json'", ",", "'text'", ",", "'xml'", "]", ")", ")", "{", "/** @var IContentType $class */", "$", "class", "=", "(", "new", "\\", "ReflectionClass", "(", "'\\Scraper\\\\Scraper\\\\ContentType\\\\'", ".", "ucfirst", "(", "strtolower", "(", "$", "urlAnnotation", "->", "contentType", ")", ")", ")", ")", "->", "newInstanceArgs", "(", "[", "$", "reflectionClass", ",", "$", "request", ",", "$", "response", ",", "$", "urlAnnotation", ",", "$", "this", "->", "cacheModel", "]", ")", ";", "}", "else", "{", "/** @var IContentType $class */", "$", "class", "=", "(", "new", "\\", "ReflectionClass", "(", "$", "urlAnnotation", "->", "contentType", ")", ")", "->", "newInstanceArgs", "(", "[", "$", "reflectionClass", ",", "$", "request", ",", "$", "response", ",", "$", "urlAnnotation", "]", ")", ";", "}", "/** @var Response $response */", "$", "response", "=", "$", "class", "->", "execute", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "echo", "'Exception: '", ",", "$", "e", "->", "getMessage", "(", ")", ",", "\"\\n\"", ";", "}", "return", "$", "response", ";", "}" ]
@param Request $request @param \ReflectionClass $reflectionClass @param UrlAnnotation $urlAnnotation @return Response
[ "@param", "Request", "$request", "@param", "\\", "ReflectionClass", "$reflectionClass", "@param", "UrlAnnotation", "$urlAnnotation" ]
train
https://github.com/rem42/scraper/blob/7c4ec23ce61b8187f2d8cfebdd233525359adb83/Client.php#L64-L107
kusanagi/katana-sdk-php7
src/Api/Factory/MiddlewareApiFactory.php
MiddlewareApiFactory.build
public function build( $action, array $data, CliInput $input, Mapping $mapping ) { $payloadMeta = $this->mapper->getPayloadMeta($data); if ($action === 'request') { return new RequestApi( $this->logger->getRequestLogger($payloadMeta->getId()), $this->component, $mapping, dirname(realpath($_SERVER['SCRIPT_FILENAME'])), $input->getName(), $input->getVersion(), $input->getFrameworkVersion(), $input->getVariables(), $input->isDebug(), $this->mapper->getHttpRequest($data), $this->mapper->getServiceCall($data), $payloadMeta, $this->mapper->getRequestAttributes($data) ); } elseif($action === 'response') { return new ResponseApi( $this->logger->getRequestLogger($payloadMeta->getId()), $this->component, $mapping, dirname(realpath($_SERVER['SCRIPT_FILENAME'])), $input->getName(), $input->getVersion(), $input->getFrameworkVersion(), $input->getVariables(), $input->isDebug(), $this->mapper->getHttpRequest($data), $this->mapper->getHttpResponse($data), $this->mapper->getTransport($data), $this->mapper->getPayloadMeta($data), $this->mapper->getReturnValue($data) ); } }
php
public function build( $action, array $data, CliInput $input, Mapping $mapping ) { $payloadMeta = $this->mapper->getPayloadMeta($data); if ($action === 'request') { return new RequestApi( $this->logger->getRequestLogger($payloadMeta->getId()), $this->component, $mapping, dirname(realpath($_SERVER['SCRIPT_FILENAME'])), $input->getName(), $input->getVersion(), $input->getFrameworkVersion(), $input->getVariables(), $input->isDebug(), $this->mapper->getHttpRequest($data), $this->mapper->getServiceCall($data), $payloadMeta, $this->mapper->getRequestAttributes($data) ); } elseif($action === 'response') { return new ResponseApi( $this->logger->getRequestLogger($payloadMeta->getId()), $this->component, $mapping, dirname(realpath($_SERVER['SCRIPT_FILENAME'])), $input->getName(), $input->getVersion(), $input->getFrameworkVersion(), $input->getVariables(), $input->isDebug(), $this->mapper->getHttpRequest($data), $this->mapper->getHttpResponse($data), $this->mapper->getTransport($data), $this->mapper->getPayloadMeta($data), $this->mapper->getReturnValue($data) ); } }
[ "public", "function", "build", "(", "$", "action", ",", "array", "$", "data", ",", "CliInput", "$", "input", ",", "Mapping", "$", "mapping", ")", "{", "$", "payloadMeta", "=", "$", "this", "->", "mapper", "->", "getPayloadMeta", "(", "$", "data", ")", ";", "if", "(", "$", "action", "===", "'request'", ")", "{", "return", "new", "RequestApi", "(", "$", "this", "->", "logger", "->", "getRequestLogger", "(", "$", "payloadMeta", "->", "getId", "(", ")", ")", ",", "$", "this", "->", "component", ",", "$", "mapping", ",", "dirname", "(", "realpath", "(", "$", "_SERVER", "[", "'SCRIPT_FILENAME'", "]", ")", ")", ",", "$", "input", "->", "getName", "(", ")", ",", "$", "input", "->", "getVersion", "(", ")", ",", "$", "input", "->", "getFrameworkVersion", "(", ")", ",", "$", "input", "->", "getVariables", "(", ")", ",", "$", "input", "->", "isDebug", "(", ")", ",", "$", "this", "->", "mapper", "->", "getHttpRequest", "(", "$", "data", ")", ",", "$", "this", "->", "mapper", "->", "getServiceCall", "(", "$", "data", ")", ",", "$", "payloadMeta", ",", "$", "this", "->", "mapper", "->", "getRequestAttributes", "(", "$", "data", ")", ")", ";", "}", "elseif", "(", "$", "action", "===", "'response'", ")", "{", "return", "new", "ResponseApi", "(", "$", "this", "->", "logger", "->", "getRequestLogger", "(", "$", "payloadMeta", "->", "getId", "(", ")", ")", ",", "$", "this", "->", "component", ",", "$", "mapping", ",", "dirname", "(", "realpath", "(", "$", "_SERVER", "[", "'SCRIPT_FILENAME'", "]", ")", ")", ",", "$", "input", "->", "getName", "(", ")", ",", "$", "input", "->", "getVersion", "(", ")", ",", "$", "input", "->", "getFrameworkVersion", "(", ")", ",", "$", "input", "->", "getVariables", "(", ")", ",", "$", "input", "->", "isDebug", "(", ")", ",", "$", "this", "->", "mapper", "->", "getHttpRequest", "(", "$", "data", ")", ",", "$", "this", "->", "mapper", "->", "getHttpResponse", "(", "$", "data", ")", ",", "$", "this", "->", "mapper", "->", "getTransport", "(", "$", "data", ")", ",", "$", "this", "->", "mapper", "->", "getPayloadMeta", "(", "$", "data", ")", ",", "$", "this", "->", "mapper", "->", "getReturnValue", "(", "$", "data", ")", ")", ";", "}", "}" ]
Build a Request Api class instance @param string $action @param array $data @param CliInput $input @param Mapping $mapping @return Api
[ "Build", "a", "Request", "Api", "class", "instance" ]
train
https://github.com/kusanagi/katana-sdk-php7/blob/91e7860a1852c3ce79a7034f8c36f41840e69e1f/src/Api/Factory/MiddlewareApiFactory.php#L38-L82
NuclearCMS/Hierarchy
src/NodeSourceExtension.php
NodeSourceExtension.getAttribute
public function getAttribute($key) { if (isset($this->mutations[$key])) { return $this->mutations[$key]; } if (array_key_exists($key, $mutatables = static::getMutatables())) { return $this->mutateExtensionAttribute($key, $mutatables[$key]); } return parent::getAttribute($key); }
php
public function getAttribute($key) { if (isset($this->mutations[$key])) { return $this->mutations[$key]; } if (array_key_exists($key, $mutatables = static::getMutatables())) { return $this->mutateExtensionAttribute($key, $mutatables[$key]); } return parent::getAttribute($key); }
[ "public", "function", "getAttribute", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "mutations", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "mutations", "[", "$", "key", "]", ";", "}", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "mutatables", "=", "static", "::", "getMutatables", "(", ")", ")", ")", "{", "return", "$", "this", "->", "mutateExtensionAttribute", "(", "$", "key", ",", "$", "mutatables", "[", "$", "key", "]", ")", ";", "}", "return", "parent", "::", "getAttribute", "(", "$", "key", ")", ";", "}" ]
Get an attribute from the model with custom accessor. @param string $key @return mixed
[ "Get", "an", "attribute", "from", "the", "model", "with", "custom", "accessor", "." ]
train
https://github.com/NuclearCMS/Hierarchy/blob/535171c5e2db72265313fd2110aec8456e46f459/src/NodeSourceExtension.php#L42-L55
NuclearCMS/Hierarchy
src/NodeSourceExtension.php
NodeSourceExtension.setAttribute
public function setAttribute($key, $value) { if (isset($this->mutations[$key])) { unset($this->mutations[$key]); } return parent::setAttribute($key, $value); }
php
public function setAttribute($key, $value) { if (isset($this->mutations[$key])) { unset($this->mutations[$key]); } return parent::setAttribute($key, $value); }
[ "public", "function", "setAttribute", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "mutations", "[", "$", "key", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "mutations", "[", "$", "key", "]", ")", ";", "}", "return", "parent", "::", "setAttribute", "(", "$", "key", ",", "$", "value", ")", ";", "}" ]
Set a given attribute on the model. @param string $key @param mixed $value @return $this
[ "Set", "a", "given", "attribute", "on", "the", "model", "." ]
train
https://github.com/NuclearCMS/Hierarchy/blob/535171c5e2db72265313fd2110aec8456e46f459/src/NodeSourceExtension.php#L64-L72
NuclearCMS/Hierarchy
src/NodeSourceExtension.php
NodeSourceExtension.mutateExtensionAttribute
protected function mutateExtensionAttribute($key, $type) { $value = $this->getAttributeFromArray($key); $mutation = $this->{'make' . studly_case($type) . 'TypeMutation'}($value); $this->mutations[$key] = $mutation; return $mutation; }
php
protected function mutateExtensionAttribute($key, $type) { $value = $this->getAttributeFromArray($key); $mutation = $this->{'make' . studly_case($type) . 'TypeMutation'}($value); $this->mutations[$key] = $mutation; return $mutation; }
[ "protected", "function", "mutateExtensionAttribute", "(", "$", "key", ",", "$", "type", ")", "{", "$", "value", "=", "$", "this", "->", "getAttributeFromArray", "(", "$", "key", ")", ";", "$", "mutation", "=", "$", "this", "->", "{", "'make'", ".", "studly_case", "(", "$", "type", ")", ".", "'TypeMutation'", "}", "(", "$", "value", ")", ";", "$", "this", "->", "mutations", "[", "$", "key", "]", "=", "$", "mutation", ";", "return", "$", "mutation", ";", "}" ]
Mutates and stores an attribute in array @param string $key @param string $type @return mixed
[ "Mutates", "and", "stores", "an", "attribute", "in", "array" ]
train
https://github.com/NuclearCMS/Hierarchy/blob/535171c5e2db72265313fd2110aec8456e46f459/src/NodeSourceExtension.php#L81-L90
NuclearCMS/Hierarchy
src/NodeSourceExtension.php
NodeSourceExtension.toArray
public function toArray() { $attributes = []; foreach ($this->fillable as $attribute) { $attributes[$attribute] = $this->getAttributeFromArray($attribute); } return $attributes; }
php
public function toArray() { $attributes = []; foreach ($this->fillable as $attribute) { $attributes[$attribute] = $this->getAttributeFromArray($attribute); } return $attributes; }
[ "public", "function", "toArray", "(", ")", "{", "$", "attributes", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "fillable", "as", "$", "attribute", ")", "{", "$", "attributes", "[", "$", "attribute", "]", "=", "$", "this", "->", "getAttributeFromArray", "(", "$", "attribute", ")", ";", "}", "return", "$", "attributes", ";", "}" ]
Convert the model instance to an array. @return array
[ "Convert", "the", "model", "instance", "to", "an", "array", "." ]
train
https://github.com/NuclearCMS/Hierarchy/blob/535171c5e2db72265313fd2110aec8456e46f459/src/NodeSourceExtension.php#L152-L162
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/reader.php
ezcDbSchemaSqliteReader.convertToGenericType
static function convertToGenericType( $typeString, &$typeLength, &$typePrecision ) { preg_match( "@([a-z ]*)(\((\d*)(,(\d+))?\))?@", strtolower( $typeString ), $matches ); if ( !isset( self::$typeMap[$matches[1]] ) ) { throw new ezcDbSchemaUnsupportedTypeException( 'SQLite', $matches[1] ); } $genericType = self::$typeMap[$matches[1]]; if ( in_array( $genericType, array( 'text', 'decimal', 'float', 'integer' ) ) && isset( $matches[3] ) ) { $typeLength = $matches[3]; if ( is_numeric( $typeLength ) ) { $typeLength = (int) $typeLength; } } if ( in_array( $genericType, array( 'decimal', 'float' ) ) && isset( $matches[5] ) ) { $typePrecision = $matches[5]; } if ( $genericType == 'integer' && $typeLength == 1) { $genericType = 'boolean'; $typeLength = null; } return $genericType; }
php
static function convertToGenericType( $typeString, &$typeLength, &$typePrecision ) { preg_match( "@([a-z ]*)(\((\d*)(,(\d+))?\))?@", strtolower( $typeString ), $matches ); if ( !isset( self::$typeMap[$matches[1]] ) ) { throw new ezcDbSchemaUnsupportedTypeException( 'SQLite', $matches[1] ); } $genericType = self::$typeMap[$matches[1]]; if ( in_array( $genericType, array( 'text', 'decimal', 'float', 'integer' ) ) && isset( $matches[3] ) ) { $typeLength = $matches[3]; if ( is_numeric( $typeLength ) ) { $typeLength = (int) $typeLength; } } if ( in_array( $genericType, array( 'decimal', 'float' ) ) && isset( $matches[5] ) ) { $typePrecision = $matches[5]; } if ( $genericType == 'integer' && $typeLength == 1) { $genericType = 'boolean'; $typeLength = null; } return $genericType; }
[ "static", "function", "convertToGenericType", "(", "$", "typeString", ",", "&", "$", "typeLength", ",", "&", "$", "typePrecision", ")", "{", "preg_match", "(", "\"@([a-z ]*)(\\((\\d*)(,(\\d+))?\\))?@\"", ",", "strtolower", "(", "$", "typeString", ")", ",", "$", "matches", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "typeMap", "[", "$", "matches", "[", "1", "]", "]", ")", ")", "{", "throw", "new", "ezcDbSchemaUnsupportedTypeException", "(", "'SQLite'", ",", "$", "matches", "[", "1", "]", ")", ";", "}", "$", "genericType", "=", "self", "::", "$", "typeMap", "[", "$", "matches", "[", "1", "]", "]", ";", "if", "(", "in_array", "(", "$", "genericType", ",", "array", "(", "'text'", ",", "'decimal'", ",", "'float'", ",", "'integer'", ")", ")", "&&", "isset", "(", "$", "matches", "[", "3", "]", ")", ")", "{", "$", "typeLength", "=", "$", "matches", "[", "3", "]", ";", "if", "(", "is_numeric", "(", "$", "typeLength", ")", ")", "{", "$", "typeLength", "=", "(", "int", ")", "$", "typeLength", ";", "}", "}", "if", "(", "in_array", "(", "$", "genericType", ",", "array", "(", "'decimal'", ",", "'float'", ")", ")", "&&", "isset", "(", "$", "matches", "[", "5", "]", ")", ")", "{", "$", "typePrecision", "=", "$", "matches", "[", "5", "]", ";", "}", "if", "(", "$", "genericType", "==", "'integer'", "&&", "$", "typeLength", "==", "1", ")", "{", "$", "genericType", "=", "'boolean'", ";", "$", "typeLength", "=", "null", ";", "}", "return", "$", "genericType", ";", "}" ]
Converts the native SQLite type in $typeString to a generic DbSchema type. This method converts a string like "float(5,10)" to the generic DbSchema type and uses the by-reference parameters $typeLength and $typePrecision to communicate the optional length and precision of the field's type. @param string $typeString @param int &$typeLength @param int &$typePrecision @return string
[ "Converts", "the", "native", "SQLite", "type", "in", "$typeString", "to", "a", "generic", "DbSchema", "type", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/reader.php#L136-L164
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/reader.php
ezcDbSchemaSqliteReader.fetchTableIndexes
protected function fetchTableIndexes( $tableName ) { $indexBuffer = array(); $indexNamesArray = $this->db->query( "PRAGMA INDEX_LIST ('$tableName')" ); $primaryFound = false; foreach ( $indexNamesArray as $row ) { $row = $this->lowercase($row); $keyName = $row['1']; if ( $keyName == $tableName.'_pri' ) { $keyName = 'primary'; $indexBuffer[$keyName]['primary'] = true; $indexBuffer[$keyName]['unique'] = true; $primaryFound = true; } else { $indexBuffer[$keyName]['primary'] = false; $indexBuffer[$keyName]['unique'] = $row[2]?true:false; } $indexArray = $this->db->query( "PRAGMA INDEX_INFO ( '{$row[1]}' )" ); foreach ( $indexArray as $indexColumnRow ) { $indexBuffer[$keyName]['fields'][$indexColumnRow[2]] = ezcDbSchema::createNewIndexField(); } } // search primary index $fieldArray = $this->db->query( "PRAGMA TABLE_INFO ('$tableName')" ); foreach ( $fieldArray as $row ) { if ( $row[5] == '1' ) { $keyName = 'primary'; $indexBuffer[$keyName]['primary'] = true; $indexBuffer[$keyName]['unique'] = true; $indexBuffer[$keyName]['fields'][$row[1]] = ezcDbSchema::createNewIndexField(); } } $indexes = array(); foreach ( $indexBuffer as $indexName => $indexInfo ) { $indexes[$indexName] = ezcDbSchema::createNewIndex( $indexInfo['fields'], $indexInfo['primary'], $indexInfo['unique'] ); } return $indexes; }
php
protected function fetchTableIndexes( $tableName ) { $indexBuffer = array(); $indexNamesArray = $this->db->query( "PRAGMA INDEX_LIST ('$tableName')" ); $primaryFound = false; foreach ( $indexNamesArray as $row ) { $row = $this->lowercase($row); $keyName = $row['1']; if ( $keyName == $tableName.'_pri' ) { $keyName = 'primary'; $indexBuffer[$keyName]['primary'] = true; $indexBuffer[$keyName]['unique'] = true; $primaryFound = true; } else { $indexBuffer[$keyName]['primary'] = false; $indexBuffer[$keyName]['unique'] = $row[2]?true:false; } $indexArray = $this->db->query( "PRAGMA INDEX_INFO ( '{$row[1]}' )" ); foreach ( $indexArray as $indexColumnRow ) { $indexBuffer[$keyName]['fields'][$indexColumnRow[2]] = ezcDbSchema::createNewIndexField(); } } // search primary index $fieldArray = $this->db->query( "PRAGMA TABLE_INFO ('$tableName')" ); foreach ( $fieldArray as $row ) { if ( $row[5] == '1' ) { $keyName = 'primary'; $indexBuffer[$keyName]['primary'] = true; $indexBuffer[$keyName]['unique'] = true; $indexBuffer[$keyName]['fields'][$row[1]] = ezcDbSchema::createNewIndexField(); } } $indexes = array(); foreach ( $indexBuffer as $indexName => $indexInfo ) { $indexes[$indexName] = ezcDbSchema::createNewIndex( $indexInfo['fields'], $indexInfo['primary'], $indexInfo['unique'] ); } return $indexes; }
[ "protected", "function", "fetchTableIndexes", "(", "$", "tableName", ")", "{", "$", "indexBuffer", "=", "array", "(", ")", ";", "$", "indexNamesArray", "=", "$", "this", "->", "db", "->", "query", "(", "\"PRAGMA INDEX_LIST ('$tableName')\"", ")", ";", "$", "primaryFound", "=", "false", ";", "foreach", "(", "$", "indexNamesArray", "as", "$", "row", ")", "{", "$", "row", "=", "$", "this", "->", "lowercase", "(", "$", "row", ")", ";", "$", "keyName", "=", "$", "row", "[", "'1'", "]", ";", "if", "(", "$", "keyName", "==", "$", "tableName", ".", "'_pri'", ")", "{", "$", "keyName", "=", "'primary'", ";", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'primary'", "]", "=", "true", ";", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'unique'", "]", "=", "true", ";", "$", "primaryFound", "=", "true", ";", "}", "else", "{", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'primary'", "]", "=", "false", ";", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'unique'", "]", "=", "$", "row", "[", "2", "]", "?", "true", ":", "false", ";", "}", "$", "indexArray", "=", "$", "this", "->", "db", "->", "query", "(", "\"PRAGMA INDEX_INFO ( '{$row[1]}' )\"", ")", ";", "foreach", "(", "$", "indexArray", "as", "$", "indexColumnRow", ")", "{", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'fields'", "]", "[", "$", "indexColumnRow", "[", "2", "]", "]", "=", "ezcDbSchema", "::", "createNewIndexField", "(", ")", ";", "}", "}", "// search primary index", "$", "fieldArray", "=", "$", "this", "->", "db", "->", "query", "(", "\"PRAGMA TABLE_INFO ('$tableName')\"", ")", ";", "foreach", "(", "$", "fieldArray", "as", "$", "row", ")", "{", "if", "(", "$", "row", "[", "5", "]", "==", "'1'", ")", "{", "$", "keyName", "=", "'primary'", ";", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'primary'", "]", "=", "true", ";", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'unique'", "]", "=", "true", ";", "$", "indexBuffer", "[", "$", "keyName", "]", "[", "'fields'", "]", "[", "$", "row", "[", "1", "]", "]", "=", "ezcDbSchema", "::", "createNewIndexField", "(", ")", ";", "}", "}", "$", "indexes", "=", "array", "(", ")", ";", "foreach", "(", "$", "indexBuffer", "as", "$", "indexName", "=>", "$", "indexInfo", ")", "{", "$", "indexes", "[", "$", "indexName", "]", "=", "ezcDbSchema", "::", "createNewIndex", "(", "$", "indexInfo", "[", "'fields'", "]", ",", "$", "indexInfo", "[", "'primary'", "]", ",", "$", "indexInfo", "[", "'unique'", "]", ")", ";", "}", "return", "$", "indexes", ";", "}" ]
Loops over all the indexes in the table $table and extracts information. This method extracts information about the table $tableName's indexes from the database and returns this schema as an array of ezcDbSchemaIndex objects. The key in the array is the index' name. @param string $tableName @return array(string=>ezcDbSchemaIndex)
[ "Loops", "over", "all", "the", "indexes", "in", "the", "table", "$table", "and", "extracts", "information", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/sqlite/reader.php#L213-L267
surebert/surebert-framework
src/sb/Controller/Command/Line.php
Line.setLogger
public function setLogger(\sb\Logger\Base $logger, $logname=''){ $this->logger = $logger; $this->log_name = $logname ? $logname : get_called_class(); $this->log_name = preg_replace("~[^\w+]~", "_", $this->log_name); }
php
public function setLogger(\sb\Logger\Base $logger, $logname=''){ $this->logger = $logger; $this->log_name = $logname ? $logname : get_called_class(); $this->log_name = preg_replace("~[^\w+]~", "_", $this->log_name); }
[ "public", "function", "setLogger", "(", "\\", "sb", "\\", "Logger", "\\", "Base", "$", "logger", ",", "$", "logname", "=", "''", ")", "{", "$", "this", "->", "logger", "=", "$", "logger", ";", "$", "this", "->", "log_name", "=", "$", "logname", "?", "$", "logname", ":", "get_called_class", "(", ")", ";", "$", "this", "->", "log_name", "=", "preg_replace", "(", "\"~[^\\w+]~\"", ",", "\"_\"", ",", "$", "this", "->", "log_name", ")", ";", "}" ]
Set the logger that logs the full log message stream when the destructor runs @param \sb\Logger\Base $logger
[ "Set", "the", "logger", "that", "logs", "the", "full", "log", "message", "stream", "when", "the", "destructor", "runs" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Controller/Command/Line.php#L141-L145
surebert/surebert-framework
src/sb/Controller/Command/Line.php
Line.log
public function log($message, $type = "MESSAGE", $text_attributes = []) { $type = strtoupper($type); switch ($type) { case 'RAW': break; case 'ERROR': $this->number_of_errors++; $this->onError($message); default: $message = $type . ': ' . $message; } $this->logToFile($message); if(empty($text_attributes)){ file_put_contents("php://stdout", "\n".$message); return $message; } if(is_array($text_attributes)){ if(isset($text_attributes['bold']) && $text_attributes['bold']){ file_put_contents("php://stdout", "\033[1m"); } if(isset($text_attributes['underline']) && $text_attributes['underline']){ file_put_contents("php://stdout","\033[4m"); } if(isset($text_attributes['fgcolor']) && isset($this->fgcolors[$text_attributes['fgcolor']])){ file_put_contents("php://stdout", "\033[".$this->fgcolors[$text_attributes['fgcolor']]."m"); } if(isset($text_attributes['bgcolor']) && isset($this->fgcolors[$text_attributes['bgcolor']])){ file_put_contents("php://stdout", "\033[".$this->bgcolors[$bgcolor]."m"); } if(isset($text_attributes['underline']) && $text_attributes['underline']){ file_put_contents("php://stdout","\033[4m"); } if(isset($text_attributes['overwrite']) && $text_attributes['overwrite']){ file_put_contents("php://stdout", "\033[2K\033[A"); } } else if(is_string($text_attributes) && isset($this->fgcolors[$text_attributes])){ file_put_contents("php://stdout", "\033[".$this->fgcolors[$text_attributes]."m"); } file_put_contents("php://stdout", "\n".$message); if(!is_array($text_attributes) || !isset($text_attributes['keep']) || !$text_attributes['keep']){ file_put_contents("php://stdout","\033[0m"); } return $message; }
php
public function log($message, $type = "MESSAGE", $text_attributes = []) { $type = strtoupper($type); switch ($type) { case 'RAW': break; case 'ERROR': $this->number_of_errors++; $this->onError($message); default: $message = $type . ': ' . $message; } $this->logToFile($message); if(empty($text_attributes)){ file_put_contents("php://stdout", "\n".$message); return $message; } if(is_array($text_attributes)){ if(isset($text_attributes['bold']) && $text_attributes['bold']){ file_put_contents("php://stdout", "\033[1m"); } if(isset($text_attributes['underline']) && $text_attributes['underline']){ file_put_contents("php://stdout","\033[4m"); } if(isset($text_attributes['fgcolor']) && isset($this->fgcolors[$text_attributes['fgcolor']])){ file_put_contents("php://stdout", "\033[".$this->fgcolors[$text_attributes['fgcolor']]."m"); } if(isset($text_attributes['bgcolor']) && isset($this->fgcolors[$text_attributes['bgcolor']])){ file_put_contents("php://stdout", "\033[".$this->bgcolors[$bgcolor]."m"); } if(isset($text_attributes['underline']) && $text_attributes['underline']){ file_put_contents("php://stdout","\033[4m"); } if(isset($text_attributes['overwrite']) && $text_attributes['overwrite']){ file_put_contents("php://stdout", "\033[2K\033[A"); } } else if(is_string($text_attributes) && isset($this->fgcolors[$text_attributes])){ file_put_contents("php://stdout", "\033[".$this->fgcolors[$text_attributes]."m"); } file_put_contents("php://stdout", "\n".$message); if(!is_array($text_attributes) || !isset($text_attributes['keep']) || !$text_attributes['keep']){ file_put_contents("php://stdout","\033[0m"); } return $message; }
[ "public", "function", "log", "(", "$", "message", ",", "$", "type", "=", "\"MESSAGE\"", ",", "$", "text_attributes", "=", "[", "]", ")", "{", "$", "type", "=", "strtoupper", "(", "$", "type", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "'RAW'", ":", "break", ";", "case", "'ERROR'", ":", "$", "this", "->", "number_of_errors", "++", ";", "$", "this", "->", "onError", "(", "$", "message", ")", ";", "default", ":", "$", "message", "=", "$", "type", ".", "': '", ".", "$", "message", ";", "}", "$", "this", "->", "logToFile", "(", "$", "message", ")", ";", "if", "(", "empty", "(", "$", "text_attributes", ")", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\n\"", ".", "$", "message", ")", ";", "return", "$", "message", ";", "}", "if", "(", "is_array", "(", "$", "text_attributes", ")", ")", "{", "if", "(", "isset", "(", "$", "text_attributes", "[", "'bold'", "]", ")", "&&", "$", "text_attributes", "[", "'bold'", "]", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[1m\"", ")", ";", "}", "if", "(", "isset", "(", "$", "text_attributes", "[", "'underline'", "]", ")", "&&", "$", "text_attributes", "[", "'underline'", "]", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[4m\"", ")", ";", "}", "if", "(", "isset", "(", "$", "text_attributes", "[", "'fgcolor'", "]", ")", "&&", "isset", "(", "$", "this", "->", "fgcolors", "[", "$", "text_attributes", "[", "'fgcolor'", "]", "]", ")", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[\"", ".", "$", "this", "->", "fgcolors", "[", "$", "text_attributes", "[", "'fgcolor'", "]", "]", ".", "\"m\"", ")", ";", "}", "if", "(", "isset", "(", "$", "text_attributes", "[", "'bgcolor'", "]", ")", "&&", "isset", "(", "$", "this", "->", "fgcolors", "[", "$", "text_attributes", "[", "'bgcolor'", "]", "]", ")", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[\"", ".", "$", "this", "->", "bgcolors", "[", "$", "bgcolor", "]", ".", "\"m\"", ")", ";", "}", "if", "(", "isset", "(", "$", "text_attributes", "[", "'underline'", "]", ")", "&&", "$", "text_attributes", "[", "'underline'", "]", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[4m\"", ")", ";", "}", "if", "(", "isset", "(", "$", "text_attributes", "[", "'overwrite'", "]", ")", "&&", "$", "text_attributes", "[", "'overwrite'", "]", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[2K\\033[A\"", ")", ";", "}", "}", "else", "if", "(", "is_string", "(", "$", "text_attributes", ")", "&&", "isset", "(", "$", "this", "->", "fgcolors", "[", "$", "text_attributes", "]", ")", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[\"", ".", "$", "this", "->", "fgcolors", "[", "$", "text_attributes", "]", ".", "\"m\"", ")", ";", "}", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\n\"", ".", "$", "message", ")", ";", "if", "(", "!", "is_array", "(", "$", "text_attributes", ")", "||", "!", "isset", "(", "$", "text_attributes", "[", "'keep'", "]", ")", "||", "!", "$", "text_attributes", "[", "'keep'", "]", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "\"\\033[0m\"", ")", ";", "}", "return", "$", "message", ";", "}" ]
Logs to std out @param string $message The message of the line @param string $type The prefix of the line, if ERROR, encrements error count @param array|string $text_attributes, used to describe how output should look e.g. ['fgcolor' => 'red', 'bgcolor' => 'yellow', 'bold' => true, 'underline' => true, 'keep' => false] if keep is true then it keeps the style until you call a line with another style or you call $this->setNormalText() if string then its just the foreground color
[ "Logs", "to", "std", "out" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Controller/Command/Line.php#L202-L262
surebert/surebert-framework
src/sb/Controller/Command/Line.php
Line.logToFile
protected function logToFile($message){ if(isset($this->logger) && $this->logger instanceof \sb\Logger\Base){ return $this->logger->{$this->log_name}($message); } }
php
protected function logToFile($message){ if(isset($this->logger) && $this->logger instanceof \sb\Logger\Base){ return $this->logger->{$this->log_name}($message); } }
[ "protected", "function", "logToFile", "(", "$", "message", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "logger", ")", "&&", "$", "this", "->", "logger", "instanceof", "\\", "sb", "\\", "Logger", "\\", "Base", ")", "{", "return", "$", "this", "->", "logger", "->", "{", "$", "this", "->", "log_name", "}", "(", "$", "message", ")", ";", "}", "}" ]
Logs to file @param string $message @return string
[ "Logs", "to", "file" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Controller/Command/Line.php#L269-L273
surebert/surebert-framework
src/sb/Controller/Command/Line.php
Line.getCommandlineInvocation
public function getCommandlineInvocation($method_name, $http_host=null, $http_args=[]) { $command_prefix = "php " . ROOT . "/public/index.php"; // Match fully-qualified method name: e.g. \Foo\Controllers\Jobs\Bar::baz() preg_match('/Controllers.([^:]+)::([A-Za-z_]+)/', $method_name, $matches); if (count($matches) !== 3) { return ''; } $class_name = strtolower($matches[1]); $class_name = preg_replace('/\\\/', '_', $class_name); $method_name = strtolower($matches[2]); // Build argument for --request opt $request_arg = "/$class_name/$method_name"; if (!empty($http_args)) { $request_arg .= "?" . http_build_query($http_args); } // Build argument for --http_host opt if (is_null($http_host)) { $http_host = \sb\Gateway::$http_host; } return "$command_prefix --request=$request_arg --http_host=$http_host"; }
php
public function getCommandlineInvocation($method_name, $http_host=null, $http_args=[]) { $command_prefix = "php " . ROOT . "/public/index.php"; // Match fully-qualified method name: e.g. \Foo\Controllers\Jobs\Bar::baz() preg_match('/Controllers.([^:]+)::([A-Za-z_]+)/', $method_name, $matches); if (count($matches) !== 3) { return ''; } $class_name = strtolower($matches[1]); $class_name = preg_replace('/\\\/', '_', $class_name); $method_name = strtolower($matches[2]); // Build argument for --request opt $request_arg = "/$class_name/$method_name"; if (!empty($http_args)) { $request_arg .= "?" . http_build_query($http_args); } // Build argument for --http_host opt if (is_null($http_host)) { $http_host = \sb\Gateway::$http_host; } return "$command_prefix --request=$request_arg --http_host=$http_host"; }
[ "public", "function", "getCommandlineInvocation", "(", "$", "method_name", ",", "$", "http_host", "=", "null", ",", "$", "http_args", "=", "[", "]", ")", "{", "$", "command_prefix", "=", "\"php \"", ".", "ROOT", ".", "\"/public/index.php\"", ";", "// Match fully-qualified method name: e.g. \\Foo\\Controllers\\Jobs\\Bar::baz()", "preg_match", "(", "'/Controllers.([^:]+)::([A-Za-z_]+)/'", ",", "$", "method_name", ",", "$", "matches", ")", ";", "if", "(", "count", "(", "$", "matches", ")", "!==", "3", ")", "{", "return", "''", ";", "}", "$", "class_name", "=", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ";", "$", "class_name", "=", "preg_replace", "(", "'/\\\\\\/'", ",", "'_'", ",", "$", "class_name", ")", ";", "$", "method_name", "=", "strtolower", "(", "$", "matches", "[", "2", "]", ")", ";", "// Build argument for --request opt", "$", "request_arg", "=", "\"/$class_name/$method_name\"", ";", "if", "(", "!", "empty", "(", "$", "http_args", ")", ")", "{", "$", "request_arg", ".=", "\"?\"", ".", "http_build_query", "(", "$", "http_args", ")", ";", "}", "// Build argument for --http_host opt", "if", "(", "is_null", "(", "$", "http_host", ")", ")", "{", "$", "http_host", "=", "\\", "sb", "\\", "Gateway", "::", "$", "http_host", ";", "}", "return", "\"$command_prefix --request=$request_arg --http_host=$http_host\"", ";", "}" ]
Returns the name of a controller method in a format that can be used in a commandline invocation. @param string $method_name Fully qualified name to method whose invocation is being generated @param string $http_host --http_host arg, optional, defaults to Gateway::$http_host @param array $http_args Query string args, optional, defaults to empty array @return string The commandline invocation for the given args e.g. php /var/www/html/enterpriseteam/public/index.php '--request=/jobs_invision/load?doctype=obmt85' --http_host=enterpriseteam.roswellpark.org Note: It is up to client code to add any bash redirects
[ "Returns", "the", "name", "of", "a", "controller", "method", "in", "a", "format", "that", "can", "be", "used", "in", "a", "commandline", "invocation", "." ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Controller/Command/Line.php#L316-L341
Eresus/EresusCMS
src/core/PluginInfo.php
Eresus_PluginInfo.loadFromFile
public static function loadFromFile($filename) { $xmlFile = substr($filename, 0, -4) . '/plugin.xml'; if (file_exists($xmlFile)) { return self::loadFromXmlFile($xmlFile); } else { return self::loadFromPhpFile($filename); } }
php
public static function loadFromFile($filename) { $xmlFile = substr($filename, 0, -4) . '/plugin.xml'; if (file_exists($xmlFile)) { return self::loadFromXmlFile($xmlFile); } else { return self::loadFromPhpFile($filename); } }
[ "public", "static", "function", "loadFromFile", "(", "$", "filename", ")", "{", "$", "xmlFile", "=", "substr", "(", "$", "filename", ",", "0", ",", "-", "4", ")", ".", "'/plugin.xml'", ";", "if", "(", "file_exists", "(", "$", "xmlFile", ")", ")", "{", "return", "self", "::", "loadFromXmlFile", "(", "$", "xmlFile", ")", ";", "}", "else", "{", "return", "self", "::", "loadFromPhpFile", "(", "$", "filename", ")", ";", "}", "}" ]
Создаёт объект из файла @param string $filename @throws RuntimeException если файл содержит ошибки @return Eresus_PluginInfo @since 2.16
[ "Создаёт", "объект", "из", "файла" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/PluginInfo.php#L102-L113
Eresus/EresusCMS
src/core/PluginInfo.php
Eresus_PluginInfo.loadFromXmlFile
private static function loadFromXmlFile($filename) { /* Это временное решение до полного отказа от PHP-файла */ $info = self::loadFromPhpFile(substr($filename, 0, -11) . '.php'); libxml_use_internal_errors(true); libxml_clear_errors(); $xml = new SimpleXMLElement($filename, 0, true); $errors = libxml_get_errors(); if (count($errors)) { libxml_clear_errors(); $msg = array(); foreach ($errors as $e) { $msg []= $e->message . '(' . $e->file . ':' . $e->line . ':' . $e->column . ')'; } $msg = implode('; ', $msg); throw new RuntimeException($msg); } $info->uid = strval($xml['uid']); if (count($xml->requires) > 0 && count($xml->requires->children()) > 0) { foreach ($xml->requires as $requires) { foreach ($requires as $item) { switch ($item->getName()) { case 'plugin': $info->requiredPlugins []= array( strval($item['name']), strval($item['min']), strval($item['max']) ); break; } } } } return $info; }
php
private static function loadFromXmlFile($filename) { /* Это временное решение до полного отказа от PHP-файла */ $info = self::loadFromPhpFile(substr($filename, 0, -11) . '.php'); libxml_use_internal_errors(true); libxml_clear_errors(); $xml = new SimpleXMLElement($filename, 0, true); $errors = libxml_get_errors(); if (count($errors)) { libxml_clear_errors(); $msg = array(); foreach ($errors as $e) { $msg []= $e->message . '(' . $e->file . ':' . $e->line . ':' . $e->column . ')'; } $msg = implode('; ', $msg); throw new RuntimeException($msg); } $info->uid = strval($xml['uid']); if (count($xml->requires) > 0 && count($xml->requires->children()) > 0) { foreach ($xml->requires as $requires) { foreach ($requires as $item) { switch ($item->getName()) { case 'plugin': $info->requiredPlugins []= array( strval($item['name']), strval($item['min']), strval($item['max']) ); break; } } } } return $info; }
[ "private", "static", "function", "loadFromXmlFile", "(", "$", "filename", ")", "{", "/* Это временное решение до полного отказа от PHP-файла */", "$", "info", "=", "self", "::", "loadFromPhpFile", "(", "substr", "(", "$", "filename", ",", "0", ",", "-", "11", ")", ".", "'.php'", ")", ";", "libxml_use_internal_errors", "(", "true", ")", ";", "libxml_clear_errors", "(", ")", ";", "$", "xml", "=", "new", "SimpleXMLElement", "(", "$", "filename", ",", "0", ",", "true", ")", ";", "$", "errors", "=", "libxml_get_errors", "(", ")", ";", "if", "(", "count", "(", "$", "errors", ")", ")", "{", "libxml_clear_errors", "(", ")", ";", "$", "msg", "=", "array", "(", ")", ";", "foreach", "(", "$", "errors", "as", "$", "e", ")", "{", "$", "msg", "[", "]", "=", "$", "e", "->", "message", ".", "'('", ".", "$", "e", "->", "file", ".", "':'", ".", "$", "e", "->", "line", ".", "':'", ".", "$", "e", "->", "column", ".", "')'", ";", "}", "$", "msg", "=", "implode", "(", "'; '", ",", "$", "msg", ")", ";", "throw", "new", "RuntimeException", "(", "$", "msg", ")", ";", "}", "$", "info", "->", "uid", "=", "strval", "(", "$", "xml", "[", "'uid'", "]", ")", ";", "if", "(", "count", "(", "$", "xml", "->", "requires", ")", ">", "0", "&&", "count", "(", "$", "xml", "->", "requires", "->", "children", "(", ")", ")", ">", "0", ")", "{", "foreach", "(", "$", "xml", "->", "requires", "as", "$", "requires", ")", "{", "foreach", "(", "$", "requires", "as", "$", "item", ")", "{", "switch", "(", "$", "item", "->", "getName", "(", ")", ")", "{", "case", "'plugin'", ":", "$", "info", "->", "requiredPlugins", "[", "]", "=", "array", "(", "strval", "(", "$", "item", "[", "'name'", "]", ")", ",", "strval", "(", "$", "item", "[", "'min'", "]", ")", ",", "strval", "(", "$", "item", "[", "'max'", "]", ")", ")", ";", "break", ";", "}", "}", "}", "}", "return", "$", "info", ";", "}" ]
Создаёт объект из файла XML @param string $filename @throws RuntimeException если XML содержит ошибки @return Eresus_PluginInfo @since 2.16
[ "Создаёт", "объект", "из", "файла", "XML" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/PluginInfo.php#L232-L276
Eresus/EresusCMS
src/core/PluginInfo.php
Eresus_PluginInfo.loadFromPhpFile
private static function loadFromPhpFile($filename) { $source = file_get_contents($filename); $tokens = token_get_all($source); $skipTokens = array(T_COMMENT, T_DOC_COMMENT); $props = array('$version', '$kernel', '$title', '$description'); $info = new self; $state = null; foreach ($tokens as $token) { if (is_array($token)) { list($id, $text) = $token; if (in_array($id, $skipTokens)) { continue; } switch (true) { case T_CLASS == $id && null === $state: $state = 'class_name'; break; case T_STRING == $id && 'class_name' == $state && trim($text) != '': $info->name = basename($filename, '.php'); $state = 'prop_name'; break; case T_VARIABLE == $id && 'prop_name' == $state && in_array($text, $props): $property = substr($text, 1); $state = 'prop_value'; break; case T_CONSTANT_ENCAPSED_STRING == $id && 'prop_value' == $state: if (isset($property)) { $value = substr($text, 1, -1); if ('kernel' == $property) { $value = explode('/', $value); $info->requiredKernel = array( $value[0], isset($value[1]) ? $value[1] : null ); } else { $info->$property = $value; } } $state = 'prop_name'; break; } } } return $info; }
php
private static function loadFromPhpFile($filename) { $source = file_get_contents($filename); $tokens = token_get_all($source); $skipTokens = array(T_COMMENT, T_DOC_COMMENT); $props = array('$version', '$kernel', '$title', '$description'); $info = new self; $state = null; foreach ($tokens as $token) { if (is_array($token)) { list($id, $text) = $token; if (in_array($id, $skipTokens)) { continue; } switch (true) { case T_CLASS == $id && null === $state: $state = 'class_name'; break; case T_STRING == $id && 'class_name' == $state && trim($text) != '': $info->name = basename($filename, '.php'); $state = 'prop_name'; break; case T_VARIABLE == $id && 'prop_name' == $state && in_array($text, $props): $property = substr($text, 1); $state = 'prop_value'; break; case T_CONSTANT_ENCAPSED_STRING == $id && 'prop_value' == $state: if (isset($property)) { $value = substr($text, 1, -1); if ('kernel' == $property) { $value = explode('/', $value); $info->requiredKernel = array( $value[0], isset($value[1]) ? $value[1] : null ); } else { $info->$property = $value; } } $state = 'prop_name'; break; } } } return $info; }
[ "private", "static", "function", "loadFromPhpFile", "(", "$", "filename", ")", "{", "$", "source", "=", "file_get_contents", "(", "$", "filename", ")", ";", "$", "tokens", "=", "token_get_all", "(", "$", "source", ")", ";", "$", "skipTokens", "=", "array", "(", "T_COMMENT", ",", "T_DOC_COMMENT", ")", ";", "$", "props", "=", "array", "(", "'$version'", ",", "'$kernel'", ",", "'$title'", ",", "'$description'", ")", ";", "$", "info", "=", "new", "self", ";", "$", "state", "=", "null", ";", "foreach", "(", "$", "tokens", "as", "$", "token", ")", "{", "if", "(", "is_array", "(", "$", "token", ")", ")", "{", "list", "(", "$", "id", ",", "$", "text", ")", "=", "$", "token", ";", "if", "(", "in_array", "(", "$", "id", ",", "$", "skipTokens", ")", ")", "{", "continue", ";", "}", "switch", "(", "true", ")", "{", "case", "T_CLASS", "==", "$", "id", "&&", "null", "===", "$", "state", ":", "$", "state", "=", "'class_name'", ";", "break", ";", "case", "T_STRING", "==", "$", "id", "&&", "'class_name'", "==", "$", "state", "&&", "trim", "(", "$", "text", ")", "!=", "''", ":", "$", "info", "->", "name", "=", "basename", "(", "$", "filename", ",", "'.php'", ")", ";", "$", "state", "=", "'prop_name'", ";", "break", ";", "case", "T_VARIABLE", "==", "$", "id", "&&", "'prop_name'", "==", "$", "state", "&&", "in_array", "(", "$", "text", ",", "$", "props", ")", ":", "$", "property", "=", "substr", "(", "$", "text", ",", "1", ")", ";", "$", "state", "=", "'prop_value'", ";", "break", ";", "case", "T_CONSTANT_ENCAPSED_STRING", "==", "$", "id", "&&", "'prop_value'", "==", "$", "state", ":", "if", "(", "isset", "(", "$", "property", ")", ")", "{", "$", "value", "=", "substr", "(", "$", "text", ",", "1", ",", "-", "1", ")", ";", "if", "(", "'kernel'", "==", "$", "property", ")", "{", "$", "value", "=", "explode", "(", "'/'", ",", "$", "value", ")", ";", "$", "info", "->", "requiredKernel", "=", "array", "(", "$", "value", "[", "0", "]", ",", "isset", "(", "$", "value", "[", "1", "]", ")", "?", "$", "value", "[", "1", "]", ":", "null", ")", ";", "}", "else", "{", "$", "info", "->", "$", "property", "=", "$", "value", ";", "}", "}", "$", "state", "=", "'prop_name'", ";", "break", ";", "}", "}", "}", "return", "$", "info", ";", "}" ]
Создаёт объект из файла PHP @param string $filename @return Eresus_PluginInfo @since 2.16
[ "Создаёт", "объект", "из", "файла", "PHP" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/PluginInfo.php#L287-L345