repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
timber/timber | lib/QueryIterator.php | QueryIterator.handle_maybe_custom_posts_page | public static function handle_maybe_custom_posts_page( $query ) {
if ( $custom_posts_page = get_option('page_for_posts') ) {
if ( isset($query->query['p']) && $query->query['p'] == $custom_posts_page ) {
return new \WP_Query(array('post_type' => 'post'));
}
}
return $query;
} | php | public static function handle_maybe_custom_posts_page( $query ) {
if ( $custom_posts_page = get_option('page_for_posts') ) {
if ( isset($query->query['p']) && $query->query['p'] == $custom_posts_page ) {
return new \WP_Query(array('post_type' => 'post'));
}
}
return $query;
} | [
"public",
"static",
"function",
"handle_maybe_custom_posts_page",
"(",
"$",
"query",
")",
"{",
"if",
"(",
"$",
"custom_posts_page",
"=",
"get_option",
"(",
"'page_for_posts'",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"query",
"->",
"query",
"[",
"'p'",
"]",
")",
"&&",
"$",
"query",
"->",
"query",
"[",
"'p'",
"]",
"==",
"$",
"custom_posts_page",
")",
"{",
"return",
"new",
"\\",
"WP_Query",
"(",
"array",
"(",
"'post_type'",
"=>",
"'post'",
")",
")",
";",
"}",
"}",
"return",
"$",
"query",
";",
"}"
] | this will test for whether a custom page to display posts is active, and if so, set the query to the default
@param WP_Query $query the original query recived from WordPress
@return WP_Query | [
"this",
"will",
"test",
"for",
"whether",
"a",
"custom",
"page",
"to",
"display",
"posts",
"is",
"active",
"and",
"if",
"so",
"set",
"the",
"query",
"to",
"the",
"default"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/QueryIterator.php#L172-L179 | train |
timber/timber | lib/Site.php | Site.switch_to_blog | protected static function switch_to_blog( $site_name_or_id ) {
if ( $site_name_or_id === null ) {
$site_name_or_id = get_current_blog_id();
}
$info = get_blog_details($site_name_or_id);
switch_to_blog($info->blog_id);
return $info->blog_id;
} | php | protected static function switch_to_blog( $site_name_or_id ) {
if ( $site_name_or_id === null ) {
$site_name_or_id = get_current_blog_id();
}
$info = get_blog_details($site_name_or_id);
switch_to_blog($info->blog_id);
return $info->blog_id;
} | [
"protected",
"static",
"function",
"switch_to_blog",
"(",
"$",
"site_name_or_id",
")",
"{",
"if",
"(",
"$",
"site_name_or_id",
"===",
"null",
")",
"{",
"$",
"site_name_or_id",
"=",
"get_current_blog_id",
"(",
")",
";",
"}",
"$",
"info",
"=",
"get_blog_details",
"(",
"$",
"site_name_or_id",
")",
";",
"switch_to_blog",
"(",
"$",
"info",
"->",
"blog_id",
")",
";",
"return",
"$",
"info",
"->",
"blog_id",
";",
"}"
] | Switches to the blog requested in the request
@param string|integer|null $site_name_or_id
@return integer with the ID of the new blog | [
"Switches",
"to",
"the",
"blog",
"requested",
"in",
"the",
"request"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Site.php#L126-L133 | train |
timber/timber | lib/Site.php | Site.init_as_singlesite | protected function init_as_singlesite() {
$this->admin_email = get_bloginfo('admin_email');
$this->name = get_bloginfo('name');
$this->title = $this->name;
$this->description = get_bloginfo('description');
$this->theme = new Theme();
$this->multisite = false;
} | php | protected function init_as_singlesite() {
$this->admin_email = get_bloginfo('admin_email');
$this->name = get_bloginfo('name');
$this->title = $this->name;
$this->description = get_bloginfo('description');
$this->theme = new Theme();
$this->multisite = false;
} | [
"protected",
"function",
"init_as_singlesite",
"(",
")",
"{",
"$",
"this",
"->",
"admin_email",
"=",
"get_bloginfo",
"(",
"'admin_email'",
")",
";",
"$",
"this",
"->",
"name",
"=",
"get_bloginfo",
"(",
"'name'",
")",
";",
"$",
"this",
"->",
"title",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"description",
"=",
"get_bloginfo",
"(",
"'description'",
")",
";",
"$",
"this",
"->",
"theme",
"=",
"new",
"Theme",
"(",
")",
";",
"$",
"this",
"->",
"multisite",
"=",
"false",
";",
"}"
] | Executed for single-blog sites
@internal | [
"Executed",
"for",
"single",
"-",
"blog",
"sites"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Site.php#L157-L164 | train |
timber/timber | lib/Comment.php | Comment.avatar | public function avatar( $size = 92, $default = '' ) {
if ( !get_option('show_avatars') ) {
return false;
}
if ( !is_numeric($size) ) {
$size = '92';
}
$email = $this->avatar_email();
$args = array('size' => $size, 'default' => $default);
$args = apply_filters('pre_get_avatar_data', $args, $email);
if ( isset($args['url']) ) {
return $args['url'];
}
$email_hash = '';
if ( !empty($email) ) {
$email_hash = md5(strtolower(trim($email)));
}
$host = $this->avatar_host($email_hash);
$default = $this->avatar_default($default, $email, $size, $host);
if ( !empty($email) ) {
$avatar = $this->avatar_out($default, $host, $email_hash, $size);
} else {
$avatar = $default;
}
return $avatar;
} | php | public function avatar( $size = 92, $default = '' ) {
if ( !get_option('show_avatars') ) {
return false;
}
if ( !is_numeric($size) ) {
$size = '92';
}
$email = $this->avatar_email();
$args = array('size' => $size, 'default' => $default);
$args = apply_filters('pre_get_avatar_data', $args, $email);
if ( isset($args['url']) ) {
return $args['url'];
}
$email_hash = '';
if ( !empty($email) ) {
$email_hash = md5(strtolower(trim($email)));
}
$host = $this->avatar_host($email_hash);
$default = $this->avatar_default($default, $email, $size, $host);
if ( !empty($email) ) {
$avatar = $this->avatar_out($default, $host, $email_hash, $size);
} else {
$avatar = $default;
}
return $avatar;
} | [
"public",
"function",
"avatar",
"(",
"$",
"size",
"=",
"92",
",",
"$",
"default",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"get_option",
"(",
"'show_avatars'",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"size",
")",
")",
"{",
"$",
"size",
"=",
"'92'",
";",
"}",
"$",
"email",
"=",
"$",
"this",
"->",
"avatar_email",
"(",
")",
";",
"$",
"args",
"=",
"array",
"(",
"'size'",
"=>",
"$",
"size",
",",
"'default'",
"=>",
"$",
"default",
")",
";",
"$",
"args",
"=",
"apply_filters",
"(",
"'pre_get_avatar_data'",
",",
"$",
"args",
",",
"$",
"email",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"args",
"[",
"'url'",
"]",
")",
")",
"{",
"return",
"$",
"args",
"[",
"'url'",
"]",
";",
"}",
"$",
"email_hash",
"=",
"''",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"email",
")",
")",
"{",
"$",
"email_hash",
"=",
"md5",
"(",
"strtolower",
"(",
"trim",
"(",
"$",
"email",
")",
")",
")",
";",
"}",
"$",
"host",
"=",
"$",
"this",
"->",
"avatar_host",
"(",
"$",
"email_hash",
")",
";",
"$",
"default",
"=",
"$",
"this",
"->",
"avatar_default",
"(",
"$",
"default",
",",
"$",
"email",
",",
"$",
"size",
",",
"$",
"host",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"email",
")",
")",
"{",
"$",
"avatar",
"=",
"$",
"this",
"->",
"avatar_out",
"(",
"$",
"default",
",",
"$",
"host",
",",
"$",
"email_hash",
",",
"$",
"size",
")",
";",
"}",
"else",
"{",
"$",
"avatar",
"=",
"$",
"default",
";",
"}",
"return",
"$",
"avatar",
";",
"}"
] | Fetches the Gravatar
@api
@example
```twig
<img src="{{comment.avatar(36,template_uri~"/img/dude.jpg")}}" alt="Image of {{comment.author.name}}" />
```
```html
<img src="http://gravatar.com/i/sfsfsdfasdfsfa.jpg" alt="Image of Katherine Rich" />
```
@param int $size
@param string $default
@return bool|mixed|string | [
"Fetches",
"the",
"Gravatar"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Comment.php#L124-L152 | train |
timber/timber | lib/Comment.php | Comment.reply_link | public function reply_link( $reply_text = 'Reply' ) {
if ( is_singular() && comments_open() && get_option('thread_comments') ) {
wp_enqueue_script('comment-reply');
}
// Get the comments depth option from the admin panel
$max_depth = get_option('thread_comments_depth');
// Default args
$args = array(
'add_below' => 'comment',
'respond_id' => 'respond',
'reply_text' => $reply_text,
'depth' => $this->depth() + 1,
'max_depth' => $max_depth,
);
return get_comment_reply_link($args, $this->ID, $this->post_id);
} | php | public function reply_link( $reply_text = 'Reply' ) {
if ( is_singular() && comments_open() && get_option('thread_comments') ) {
wp_enqueue_script('comment-reply');
}
// Get the comments depth option from the admin panel
$max_depth = get_option('thread_comments_depth');
// Default args
$args = array(
'add_below' => 'comment',
'respond_id' => 'respond',
'reply_text' => $reply_text,
'depth' => $this->depth() + 1,
'max_depth' => $max_depth,
);
return get_comment_reply_link($args, $this->ID, $this->post_id);
} | [
"public",
"function",
"reply_link",
"(",
"$",
"reply_text",
"=",
"'Reply'",
")",
"{",
"if",
"(",
"is_singular",
"(",
")",
"&&",
"comments_open",
"(",
")",
"&&",
"get_option",
"(",
"'thread_comments'",
")",
")",
"{",
"wp_enqueue_script",
"(",
"'comment-reply'",
")",
";",
"}",
"// Get the comments depth option from the admin panel",
"$",
"max_depth",
"=",
"get_option",
"(",
"'thread_comments_depth'",
")",
";",
"// Default args",
"$",
"args",
"=",
"array",
"(",
"'add_below'",
"=>",
"'comment'",
",",
"'respond_id'",
"=>",
"'respond'",
",",
"'reply_text'",
"=>",
"$",
"reply_text",
",",
"'depth'",
"=>",
"$",
"this",
"->",
"depth",
"(",
")",
"+",
"1",
",",
"'max_depth'",
"=>",
"$",
"max_depth",
",",
")",
";",
"return",
"get_comment_reply_link",
"(",
"$",
"args",
",",
"$",
"this",
"->",
"ID",
",",
"$",
"this",
"->",
"post_id",
")",
";",
"}"
] | Enqueue the WP threaded comments javascript,
and fetch the reply link for various comments.
@api
@return string | [
"Enqueue",
"the",
"WP",
"threaded",
"comments",
"javascript",
"and",
"fetch",
"the",
"reply",
"link",
"for",
"various",
"comments",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Comment.php#L320-L338 | train |
timber/timber | lib/Post.php | Post.init | protected function init( $pid = false ) {
if ( $pid === false ) {
$pid = get_the_ID();
}
if ( is_numeric($pid) ) {
$this->ID = $pid;
}
$post_info = $this->get_info($pid);
$this->import($post_info);
} | php | protected function init( $pid = false ) {
if ( $pid === false ) {
$pid = get_the_ID();
}
if ( is_numeric($pid) ) {
$this->ID = $pid;
}
$post_info = $this->get_info($pid);
$this->import($post_info);
} | [
"protected",
"function",
"init",
"(",
"$",
"pid",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"pid",
"===",
"false",
")",
"{",
"$",
"pid",
"=",
"get_the_ID",
"(",
")",
";",
"}",
"if",
"(",
"is_numeric",
"(",
"$",
"pid",
")",
")",
"{",
"$",
"this",
"->",
"ID",
"=",
"$",
"pid",
";",
"}",
"$",
"post_info",
"=",
"$",
"this",
"->",
"get_info",
"(",
"$",
"pid",
")",
";",
"$",
"this",
"->",
"import",
"(",
"$",
"post_info",
")",
";",
"}"
] | Initializes a Post
@internal
@param integer $pid | [
"Initializes",
"a",
"Post"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L317-L326 | train |
timber/timber | lib/Post.php | Post.update | public function update( $field, $value ) {
if ( isset($this->ID) ) {
update_post_meta($this->ID, $field, $value);
$this->$field = $value;
}
} | php | public function update( $field, $value ) {
if ( isset($this->ID) ) {
update_post_meta($this->ID, $field, $value);
$this->$field = $value;
}
} | [
"public",
"function",
"update",
"(",
"$",
"field",
",",
"$",
"value",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"ID",
")",
")",
"{",
"update_post_meta",
"(",
"$",
"this",
"->",
"ID",
",",
"$",
"field",
",",
"$",
"value",
")",
";",
"$",
"this",
"->",
"$",
"field",
"=",
"$",
"value",
";",
"}",
"}"
] | updates the post_meta of the current object with the given value
@param string $field
@param mixed $value | [
"updates",
"the",
"post_meta",
"of",
"the",
"current",
"object",
"with",
"the",
"given",
"value"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L345-L350 | train |
timber/timber | lib/Post.php | Post.check_post_id | protected function check_post_id( $pid ) {
if ( is_numeric($pid) && $pid === 0 ) {
$pid = get_the_ID();
return $pid;
}
if ( !is_numeric($pid) && is_string($pid) ) {
$pid = PostGetter::get_post_id_by_name($pid);
return $pid;
}
if ( !$pid ) {
return null;
}
return $pid;
} | php | protected function check_post_id( $pid ) {
if ( is_numeric($pid) && $pid === 0 ) {
$pid = get_the_ID();
return $pid;
}
if ( !is_numeric($pid) && is_string($pid) ) {
$pid = PostGetter::get_post_id_by_name($pid);
return $pid;
}
if ( !$pid ) {
return null;
}
return $pid;
} | [
"protected",
"function",
"check_post_id",
"(",
"$",
"pid",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"pid",
")",
"&&",
"$",
"pid",
"===",
"0",
")",
"{",
"$",
"pid",
"=",
"get_the_ID",
"(",
")",
";",
"return",
"$",
"pid",
";",
"}",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"pid",
")",
"&&",
"is_string",
"(",
"$",
"pid",
")",
")",
"{",
"$",
"pid",
"=",
"PostGetter",
"::",
"get_post_id_by_name",
"(",
"$",
"pid",
")",
";",
"return",
"$",
"pid",
";",
"}",
"if",
"(",
"!",
"$",
"pid",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"pid",
";",
"}"
] | helps you find the post id regardless of whether you send a string or whatever
@param integer $pid ;
@internal
@return integer ID number of a post | [
"helps",
"you",
"find",
"the",
"post",
"id",
"regardless",
"of",
"whether",
"you",
"send",
"a",
"string",
"or",
"whatever"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L379-L392 | train |
timber/timber | lib/Post.php | Post.get_info | protected function get_info( $pid ) {
$post = $this->prepare_post_info($pid);
if ( !isset($post->post_status) ) {
return null;
}
do_action_ref_array('the_post', array(&$post, &$GLOBALS['wp_query']));
$post->status = $post->post_status;
$post->id = $post->ID;
$post->slug = $post->post_name;
$customs = $this->get_post_custom($post->ID);
if ( $this->is_previewing() ) {
global $wp_query;
$rev_id = $this->get_post_preview_id($wp_query);
$customs = $this->get_post_custom($rev_id);
}
$post->custom = $customs;
$post = (object) array_merge((array) $customs, (array) $post);
return $post;
} | php | protected function get_info( $pid ) {
$post = $this->prepare_post_info($pid);
if ( !isset($post->post_status) ) {
return null;
}
do_action_ref_array('the_post', array(&$post, &$GLOBALS['wp_query']));
$post->status = $post->post_status;
$post->id = $post->ID;
$post->slug = $post->post_name;
$customs = $this->get_post_custom($post->ID);
if ( $this->is_previewing() ) {
global $wp_query;
$rev_id = $this->get_post_preview_id($wp_query);
$customs = $this->get_post_custom($rev_id);
}
$post->custom = $customs;
$post = (object) array_merge((array) $customs, (array) $post);
return $post;
} | [
"protected",
"function",
"get_info",
"(",
"$",
"pid",
")",
"{",
"$",
"post",
"=",
"$",
"this",
"->",
"prepare_post_info",
"(",
"$",
"pid",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"post",
"->",
"post_status",
")",
")",
"{",
"return",
"null",
";",
"}",
"do_action_ref_array",
"(",
"'the_post'",
",",
"array",
"(",
"&",
"$",
"post",
",",
"&",
"$",
"GLOBALS",
"[",
"'wp_query'",
"]",
")",
")",
";",
"$",
"post",
"->",
"status",
"=",
"$",
"post",
"->",
"post_status",
";",
"$",
"post",
"->",
"id",
"=",
"$",
"post",
"->",
"ID",
";",
"$",
"post",
"->",
"slug",
"=",
"$",
"post",
"->",
"post_name",
";",
"$",
"customs",
"=",
"$",
"this",
"->",
"get_post_custom",
"(",
"$",
"post",
"->",
"ID",
")",
";",
"if",
"(",
"$",
"this",
"->",
"is_previewing",
"(",
")",
")",
"{",
"global",
"$",
"wp_query",
";",
"$",
"rev_id",
"=",
"$",
"this",
"->",
"get_post_preview_id",
"(",
"$",
"wp_query",
")",
";",
"$",
"customs",
"=",
"$",
"this",
"->",
"get_post_custom",
"(",
"$",
"rev_id",
")",
";",
"}",
"$",
"post",
"->",
"custom",
"=",
"$",
"customs",
";",
"$",
"post",
"=",
"(",
"object",
")",
"array_merge",
"(",
"(",
"array",
")",
"$",
"customs",
",",
"(",
"array",
")",
"$",
"post",
")",
";",
"return",
"$",
"post",
";",
"}"
] | Used internally by init, etc. to build TimberPost object
@internal
@param int $pid
@return null|object|WP_Post | [
"Used",
"internally",
"by",
"init",
"etc",
".",
"to",
"build",
"TimberPost",
"object"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L568-L588 | train |
timber/timber | lib/Post.php | Post.terms | public function terms( $args = array(), $merge = true, $term_class = '' ) {
// Ensure backwards compatibility.
if ( ! is_array( $args ) || isset( $args[0] ) ) {
$args = array(
'query' => array(
'taxonomy' => $args,
),
'merge' => $merge,
'term_class' => $term_class,
);
if ( empty( $args['term_class']) ) {
$args['term_class'] = $this->TermClass;
}
}
// Defaults.
$args = wp_parse_args( $args, array(
'query' => array(
'taxonomy' => 'all',
),
'merge' => true,
'term_class' => $this->TermClass,
) );
$tax = $args['query']['taxonomy'];
$merge = $args['merge'];
$term_class = $args['term_class'];
$taxonomies = array();
// @todo: Remove in 2.x
if ( is_string($merge) && class_exists($merge) ) {
$term_class = $merge;
}
// Build an array of taxonomies.
if ( is_array( $tax ) ) {
$taxonomies = $tax;
} elseif ( is_string( $tax ) ) {
if ( in_array( $tax, array( 'all', 'any', '' ) ) ) {
$taxonomies = get_object_taxonomies($this->post_type);
} else {
$taxonomies = array($tax);
}
}
// @todo Remove in 2.x
$taxonomies = array_map( function( $taxonomy ) {
if ( in_array( $taxonomy, array( 'tag', 'tags' ), true ) ) {
$taxonomy = 'post_tag';
} elseif ( 'categories' === $taxonomy ) {
$taxonomy = 'category';
}
return $taxonomy;
}, $taxonomies );
$terms = wp_get_post_terms( $this->ID, $taxonomies, $args['query'] );
if ( is_wp_error( $terms ) ) {
/**
* @var $terms \WP_Error
*/
Helper::error_log( "Error retrieving terms for taxonomies on a post in timber-post.php" );
Helper::error_log( 'tax = ' . print_r( $tax, true ) );
Helper::error_log( 'WP_Error: ' . $terms->get_error_message() );
return $terms;
}
// Map over array of WordPress terms and transform them into instances of the chosen term class.
$terms = array_map( function( $term ) use ( $term_class ) {
return call_user_func( array( $term_class, 'from' ), $term->term_id, $term->taxonomy );
}, $terms );
if ( ! $merge ) {
$terms_sorted = array();
// Initialize sub-arrays.
foreach ( $taxonomies as $taxonomy ) {
$terms_sorted[ $taxonomy ] = array();
}
// Fill terms into arrays.
foreach ( $terms as $term ) {
$terms_sorted[ $term->taxonomy ][] = $term;
}
return $terms_sorted;
}
return $terms;
} | php | public function terms( $args = array(), $merge = true, $term_class = '' ) {
// Ensure backwards compatibility.
if ( ! is_array( $args ) || isset( $args[0] ) ) {
$args = array(
'query' => array(
'taxonomy' => $args,
),
'merge' => $merge,
'term_class' => $term_class,
);
if ( empty( $args['term_class']) ) {
$args['term_class'] = $this->TermClass;
}
}
// Defaults.
$args = wp_parse_args( $args, array(
'query' => array(
'taxonomy' => 'all',
),
'merge' => true,
'term_class' => $this->TermClass,
) );
$tax = $args['query']['taxonomy'];
$merge = $args['merge'];
$term_class = $args['term_class'];
$taxonomies = array();
// @todo: Remove in 2.x
if ( is_string($merge) && class_exists($merge) ) {
$term_class = $merge;
}
// Build an array of taxonomies.
if ( is_array( $tax ) ) {
$taxonomies = $tax;
} elseif ( is_string( $tax ) ) {
if ( in_array( $tax, array( 'all', 'any', '' ) ) ) {
$taxonomies = get_object_taxonomies($this->post_type);
} else {
$taxonomies = array($tax);
}
}
// @todo Remove in 2.x
$taxonomies = array_map( function( $taxonomy ) {
if ( in_array( $taxonomy, array( 'tag', 'tags' ), true ) ) {
$taxonomy = 'post_tag';
} elseif ( 'categories' === $taxonomy ) {
$taxonomy = 'category';
}
return $taxonomy;
}, $taxonomies );
$terms = wp_get_post_terms( $this->ID, $taxonomies, $args['query'] );
if ( is_wp_error( $terms ) ) {
/**
* @var $terms \WP_Error
*/
Helper::error_log( "Error retrieving terms for taxonomies on a post in timber-post.php" );
Helper::error_log( 'tax = ' . print_r( $tax, true ) );
Helper::error_log( 'WP_Error: ' . $terms->get_error_message() );
return $terms;
}
// Map over array of WordPress terms and transform them into instances of the chosen term class.
$terms = array_map( function( $term ) use ( $term_class ) {
return call_user_func( array( $term_class, 'from' ), $term->term_id, $term->taxonomy );
}, $terms );
if ( ! $merge ) {
$terms_sorted = array();
// Initialize sub-arrays.
foreach ( $taxonomies as $taxonomy ) {
$terms_sorted[ $taxonomy ] = array();
}
// Fill terms into arrays.
foreach ( $terms as $term ) {
$terms_sorted[ $term->taxonomy ][] = $term;
}
return $terms_sorted;
}
return $terms;
} | [
"public",
"function",
"terms",
"(",
"$",
"args",
"=",
"array",
"(",
")",
",",
"$",
"merge",
"=",
"true",
",",
"$",
"term_class",
"=",
"''",
")",
"{",
"// Ensure backwards compatibility.",
"if",
"(",
"!",
"is_array",
"(",
"$",
"args",
")",
"||",
"isset",
"(",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"'query'",
"=>",
"array",
"(",
"'taxonomy'",
"=>",
"$",
"args",
",",
")",
",",
"'merge'",
"=>",
"$",
"merge",
",",
"'term_class'",
"=>",
"$",
"term_class",
",",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"args",
"[",
"'term_class'",
"]",
")",
")",
"{",
"$",
"args",
"[",
"'term_class'",
"]",
"=",
"$",
"this",
"->",
"TermClass",
";",
"}",
"}",
"// Defaults.",
"$",
"args",
"=",
"wp_parse_args",
"(",
"$",
"args",
",",
"array",
"(",
"'query'",
"=>",
"array",
"(",
"'taxonomy'",
"=>",
"'all'",
",",
")",
",",
"'merge'",
"=>",
"true",
",",
"'term_class'",
"=>",
"$",
"this",
"->",
"TermClass",
",",
")",
")",
";",
"$",
"tax",
"=",
"$",
"args",
"[",
"'query'",
"]",
"[",
"'taxonomy'",
"]",
";",
"$",
"merge",
"=",
"$",
"args",
"[",
"'merge'",
"]",
";",
"$",
"term_class",
"=",
"$",
"args",
"[",
"'term_class'",
"]",
";",
"$",
"taxonomies",
"=",
"array",
"(",
")",
";",
"// @todo: Remove in 2.x",
"if",
"(",
"is_string",
"(",
"$",
"merge",
")",
"&&",
"class_exists",
"(",
"$",
"merge",
")",
")",
"{",
"$",
"term_class",
"=",
"$",
"merge",
";",
"}",
"// Build an array of taxonomies.",
"if",
"(",
"is_array",
"(",
"$",
"tax",
")",
")",
"{",
"$",
"taxonomies",
"=",
"$",
"tax",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"tax",
")",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"tax",
",",
"array",
"(",
"'all'",
",",
"'any'",
",",
"''",
")",
")",
")",
"{",
"$",
"taxonomies",
"=",
"get_object_taxonomies",
"(",
"$",
"this",
"->",
"post_type",
")",
";",
"}",
"else",
"{",
"$",
"taxonomies",
"=",
"array",
"(",
"$",
"tax",
")",
";",
"}",
"}",
"// @todo Remove in 2.x",
"$",
"taxonomies",
"=",
"array_map",
"(",
"function",
"(",
"$",
"taxonomy",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"taxonomy",
",",
"array",
"(",
"'tag'",
",",
"'tags'",
")",
",",
"true",
")",
")",
"{",
"$",
"taxonomy",
"=",
"'post_tag'",
";",
"}",
"elseif",
"(",
"'categories'",
"===",
"$",
"taxonomy",
")",
"{",
"$",
"taxonomy",
"=",
"'category'",
";",
"}",
"return",
"$",
"taxonomy",
";",
"}",
",",
"$",
"taxonomies",
")",
";",
"$",
"terms",
"=",
"wp_get_post_terms",
"(",
"$",
"this",
"->",
"ID",
",",
"$",
"taxonomies",
",",
"$",
"args",
"[",
"'query'",
"]",
")",
";",
"if",
"(",
"is_wp_error",
"(",
"$",
"terms",
")",
")",
"{",
"/**\n\t\t\t * @var $terms \\WP_Error\n\t\t\t */",
"Helper",
"::",
"error_log",
"(",
"\"Error retrieving terms for taxonomies on a post in timber-post.php\"",
")",
";",
"Helper",
"::",
"error_log",
"(",
"'tax = '",
".",
"print_r",
"(",
"$",
"tax",
",",
"true",
")",
")",
";",
"Helper",
"::",
"error_log",
"(",
"'WP_Error: '",
".",
"$",
"terms",
"->",
"get_error_message",
"(",
")",
")",
";",
"return",
"$",
"terms",
";",
"}",
"// Map over array of WordPress terms and transform them into instances of the chosen term class.",
"$",
"terms",
"=",
"array_map",
"(",
"function",
"(",
"$",
"term",
")",
"use",
"(",
"$",
"term_class",
")",
"{",
"return",
"call_user_func",
"(",
"array",
"(",
"$",
"term_class",
",",
"'from'",
")",
",",
"$",
"term",
"->",
"term_id",
",",
"$",
"term",
"->",
"taxonomy",
")",
";",
"}",
",",
"$",
"terms",
")",
";",
"if",
"(",
"!",
"$",
"merge",
")",
"{",
"$",
"terms_sorted",
"=",
"array",
"(",
")",
";",
"// Initialize sub-arrays.",
"foreach",
"(",
"$",
"taxonomies",
"as",
"$",
"taxonomy",
")",
"{",
"$",
"terms_sorted",
"[",
"$",
"taxonomy",
"]",
"=",
"array",
"(",
")",
";",
"}",
"// Fill terms into arrays.",
"foreach",
"(",
"$",
"terms",
"as",
"$",
"term",
")",
"{",
"$",
"terms_sorted",
"[",
"$",
"term",
"->",
"taxonomy",
"]",
"[",
"]",
"=",
"$",
"term",
";",
"}",
"return",
"$",
"terms_sorted",
";",
"}",
"return",
"$",
"terms",
";",
"}"
] | Gets the terms associated with the post.
@api
@todo Remove deprecated parameters in 2.x
@example
```twig
<section id="job-feed">
{% for post in job %}
<div class="job">
<h2>{{ post.title }}</h2>
<p>{{ post.terms('category')|join(', ') }}</p>
</div>
{% endfor %}
</section>
```
```html
<section id="job-feed">
<div class="job">
<h2>Cheese Maker</h2>
<p>Food, Cheese, Fromage</p>
</div>
<div class="job">
<h2>Mime</h2>
<p>Performance, Silence</p>
</div>
</section>
```
```php
// Get all terms of a taxonomy.
$terms = $post->terms( 'category' );
// Get terms of multiple taxonomies.
$terms = $post->terms( array( 'books', 'movies' ) );
// Use custom arguments for taxonomy query and options.
$terms = $post->terms( array(
'query' => [
'taxonomy' => 'custom_tax',
'orderby' => 'count',
],
'merge' => false,
'term_class' => 'My_Term_Class'
) );
```
@param string|array $args {
Optional. Name of the taxonomy or array of arguments.
@type array $query Any array of term query parameters for getting the terms. See
`WP_Term_Query::__construct()` for supported arguments. Use the
`taxonomy` argument to choose which taxonomies to get. Defaults
to querying all registered taxonomies for the post type. You can
use custom or built-in WordPress taxonomies (category, tag).
Timber plays nice and figures out that `tag`, `tags` or
`post_tag` are all the same (also for `categories` or
`category`). For custom taxonomies you need to define the
proper name.
@type bool $merge Whether the resulting array should be one big one (`true`) or
whether it should be an array of sub-arrays for each taxonomy
(`false`). Default `true`.
@type string $term_class The Timber term class to use for the term objects.
}
@param bool $merge Deprecated. Optional. See `$merge` argument in `$args` parameter.
@param string $term_class Deprecated. Optional. See `$term_class` argument in `$args`
parameter.
@return array An array of taxonomies. | [
"Gets",
"the",
"terms",
"associated",
"with",
"the",
"post",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L668-L761 | train |
timber/timber | lib/Post.php | Post.field_object | public function field_object( $field_name ) {
$value = apply_filters('timber/post/meta_object_field', null, $this->ID, $field_name, $this);
$value = $this->convert($value);
return $value;
} | php | public function field_object( $field_name ) {
$value = apply_filters('timber/post/meta_object_field', null, $this->ID, $field_name, $this);
$value = $this->convert($value);
return $value;
} | [
"public",
"function",
"field_object",
"(",
"$",
"field_name",
")",
"{",
"$",
"value",
"=",
"apply_filters",
"(",
"'timber/post/meta_object_field'",
",",
"null",
",",
"$",
"this",
"->",
"ID",
",",
"$",
"field_name",
",",
"$",
"this",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"convert",
"(",
"$",
"value",
")",
";",
"return",
"$",
"value",
";",
"}"
] | Gets the field object data from Advanced Custom Fields.
This includes metadata on the field like whether it's conditional or not.
@since 1.6.0
@param string $field_name of the field you want to lookup.
@return mixed | [
"Gets",
"the",
"field",
"object",
"data",
"from",
"Advanced",
"Custom",
"Fields",
".",
"This",
"includes",
"metadata",
"on",
"the",
"field",
"like",
"whether",
"it",
"s",
"conditional",
"or",
"not",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L835-L839 | train |
timber/timber | lib/Post.php | Post.maybe_show_password_form | protected function maybe_show_password_form() {
if ( $this->password_required() ) {
$show_pw = false;
$show_pw = apply_filters('timber/post/content/show_password_form_for_protected', $show_pw);
if ( $show_pw ) {
return apply_filters('timber/post/content/password_form', get_the_password_form($this->ID), $this);
}
}
} | php | protected function maybe_show_password_form() {
if ( $this->password_required() ) {
$show_pw = false;
$show_pw = apply_filters('timber/post/content/show_password_form_for_protected', $show_pw);
if ( $show_pw ) {
return apply_filters('timber/post/content/password_form', get_the_password_form($this->ID), $this);
}
}
} | [
"protected",
"function",
"maybe_show_password_form",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"password_required",
"(",
")",
")",
"{",
"$",
"show_pw",
"=",
"false",
";",
"$",
"show_pw",
"=",
"apply_filters",
"(",
"'timber/post/content/show_password_form_for_protected'",
",",
"$",
"show_pw",
")",
";",
"if",
"(",
"$",
"show_pw",
")",
"{",
"return",
"apply_filters",
"(",
"'timber/post/content/password_form'",
",",
"get_the_password_form",
"(",
"$",
"this",
"->",
"ID",
")",
",",
"$",
"this",
")",
";",
"}",
"}",
"}"
] | If the Password form is to be shown, show it!
@return string|void | [
"If",
"the",
"Password",
"form",
"is",
"to",
"be",
"shown",
"show",
"it!"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1106-L1114 | train |
timber/timber | lib/Post.php | Post.type | public function type() {
if ( isset($this->custom['type']) ) {
return $this->custom['type'];
}
if ( !$this->__type instanceof PostType ) {
$this->__type = new PostType($this->post_type);
}
return $this->__type;
} | php | public function type() {
if ( isset($this->custom['type']) ) {
return $this->custom['type'];
}
if ( !$this->__type instanceof PostType ) {
$this->__type = new PostType($this->post_type);
}
return $this->__type;
} | [
"public",
"function",
"type",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"custom",
"[",
"'type'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"custom",
"[",
"'type'",
"]",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"__type",
"instanceof",
"PostType",
")",
"{",
"$",
"this",
"->",
"__type",
"=",
"new",
"PostType",
"(",
"$",
"this",
"->",
"post_type",
")",
";",
"}",
"return",
"$",
"this",
"->",
"__type",
";",
"}"
] | Returns the post_type object with labels and other info
@since 1.0.4
@example
```twig
This post is from <span>{{ post.type.labels.name }}</span>
```
```html
This post is from <span>Recipes</span>
```
@return PostType | [
"Returns",
"the",
"post_type",
"object",
"with",
"labels",
"and",
"other",
"info"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1242-L1250 | train |
timber/timber | lib/Post.php | Post.link | public function link() {
if ( isset($this->_permalink) ) {
return $this->_permalink;
}
$this->_permalink = get_permalink($this->ID);
return $this->_permalink;
} | php | public function link() {
if ( isset($this->_permalink) ) {
return $this->_permalink;
}
$this->_permalink = get_permalink($this->ID);
return $this->_permalink;
} | [
"public",
"function",
"link",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_permalink",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_permalink",
";",
"}",
"$",
"this",
"->",
"_permalink",
"=",
"get_permalink",
"(",
"$",
"this",
"->",
"ID",
")",
";",
"return",
"$",
"this",
"->",
"_permalink",
";",
"}"
] | get the permalink for a post object
@api
@example
```twig
<a href="{{post.link}}">Read my post</a>
```
@return string ex: http://example.org/2015/07/my-awesome-post | [
"get",
"the",
"permalink",
"for",
"a",
"post",
"object"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1288-L1294 | train |
timber/timber | lib/Post.php | Post.convert | public function convert( $data ) {
if ( is_object($data) ) {
$data = Helper::convert_wp_object($data);
} else if ( is_array($data) ) {
$func = __FUNCTION__;
foreach ( $data as &$ele ) {
if ( is_array($ele) ) {
$ele = $this->$func($ele);
} else if ( is_object($ele) ) {
$ele = Helper::convert_wp_object($ele);
}
}
}
return $data;
} | php | public function convert( $data ) {
if ( is_object($data) ) {
$data = Helper::convert_wp_object($data);
} else if ( is_array($data) ) {
$func = __FUNCTION__;
foreach ( $data as &$ele ) {
if ( is_array($ele) ) {
$ele = $this->$func($ele);
} else if ( is_object($ele) ) {
$ele = Helper::convert_wp_object($ele);
}
}
}
return $data;
} | [
"public",
"function",
"convert",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"data",
")",
")",
"{",
"$",
"data",
"=",
"Helper",
"::",
"convert_wp_object",
"(",
"$",
"data",
")",
";",
"}",
"else",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"$",
"func",
"=",
"__FUNCTION__",
";",
"foreach",
"(",
"$",
"data",
"as",
"&",
"$",
"ele",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"ele",
")",
")",
"{",
"$",
"ele",
"=",
"$",
"this",
"->",
"$",
"func",
"(",
"$",
"ele",
")",
";",
"}",
"else",
"if",
"(",
"is_object",
"(",
"$",
"ele",
")",
")",
"{",
"$",
"ele",
"=",
"Helper",
"::",
"convert_wp_object",
"(",
"$",
"ele",
")",
";",
"}",
"}",
"}",
"return",
"$",
"data",
";",
"}"
] | Finds any WP_Post objects and converts them to Timber\Posts
@param array|WP_Post $data
@param string $class | [
"Finds",
"any",
"WP_Post",
"objects",
"and",
"converts",
"them",
"to",
"Timber",
"\\",
"Posts"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1397-L1411 | train |
timber/timber | lib/Post.php | Post.prev | public function prev( $in_same_term = false ) {
if ( isset($this->_prev) && isset($this->_prev[$in_same_term]) ) {
return $this->_prev[$in_same_term];
}
global $post;
$old_global = $post;
$post = $this;
$within_taxonomy = ($in_same_term) ? $in_same_term : 'category';
$adjacent = get_adjacent_post(($in_same_term), '', true, $within_taxonomy);
$prev_in_taxonomy = false;
if ( $adjacent ) {
$prev_in_taxonomy = new $this->PostClass($adjacent);
}
$this->_prev[$in_same_term] = $prev_in_taxonomy;
$post = $old_global;
return $this->_prev[$in_same_term];
} | php | public function prev( $in_same_term = false ) {
if ( isset($this->_prev) && isset($this->_prev[$in_same_term]) ) {
return $this->_prev[$in_same_term];
}
global $post;
$old_global = $post;
$post = $this;
$within_taxonomy = ($in_same_term) ? $in_same_term : 'category';
$adjacent = get_adjacent_post(($in_same_term), '', true, $within_taxonomy);
$prev_in_taxonomy = false;
if ( $adjacent ) {
$prev_in_taxonomy = new $this->PostClass($adjacent);
}
$this->_prev[$in_same_term] = $prev_in_taxonomy;
$post = $old_global;
return $this->_prev[$in_same_term];
} | [
"public",
"function",
"prev",
"(",
"$",
"in_same_term",
"=",
"false",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_prev",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"_prev",
"[",
"$",
"in_same_term",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_prev",
"[",
"$",
"in_same_term",
"]",
";",
"}",
"global",
"$",
"post",
";",
"$",
"old_global",
"=",
"$",
"post",
";",
"$",
"post",
"=",
"$",
"this",
";",
"$",
"within_taxonomy",
"=",
"(",
"$",
"in_same_term",
")",
"?",
"$",
"in_same_term",
":",
"'category'",
";",
"$",
"adjacent",
"=",
"get_adjacent_post",
"(",
"(",
"$",
"in_same_term",
")",
",",
"''",
",",
"true",
",",
"$",
"within_taxonomy",
")",
";",
"$",
"prev_in_taxonomy",
"=",
"false",
";",
"if",
"(",
"$",
"adjacent",
")",
"{",
"$",
"prev_in_taxonomy",
"=",
"new",
"$",
"this",
"->",
"PostClass",
"(",
"$",
"adjacent",
")",
";",
"}",
"$",
"this",
"->",
"_prev",
"[",
"$",
"in_same_term",
"]",
"=",
"$",
"prev_in_taxonomy",
";",
"$",
"post",
"=",
"$",
"old_global",
";",
"return",
"$",
"this",
"->",
"_prev",
"[",
"$",
"in_same_term",
"]",
";",
"}"
] | Get the previous post in a set
@api
@example
```twig
<h4>Prior Entry:</h4>
<h3>{{post.prev.title}}</h3>
<p>{{post.prev.get_preview(25)}}</p>
```
@param bool $in_same_term
@return mixed | [
"Get",
"the",
"previous",
"post",
"in",
"a",
"set"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1458-L1474 | train |
timber/timber | lib/Post.php | Post.gallery | public function gallery( $html = true ) {
if ( isset($this->custom['gallery']) ) {
return $this->custom['gallery'];
}
$galleries = get_post_galleries($this->ID, $html);
$gallery = reset($galleries);
return apply_filters('get_post_gallery', $gallery, $this->ID, $galleries);
} | php | public function gallery( $html = true ) {
if ( isset($this->custom['gallery']) ) {
return $this->custom['gallery'];
}
$galleries = get_post_galleries($this->ID, $html);
$gallery = reset($galleries);
return apply_filters('get_post_gallery', $gallery, $this->ID, $galleries);
} | [
"public",
"function",
"gallery",
"(",
"$",
"html",
"=",
"true",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"custom",
"[",
"'gallery'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"custom",
"[",
"'gallery'",
"]",
";",
"}",
"$",
"galleries",
"=",
"get_post_galleries",
"(",
"$",
"this",
"->",
"ID",
",",
"$",
"html",
")",
";",
"$",
"gallery",
"=",
"reset",
"(",
"$",
"galleries",
")",
";",
"return",
"apply_filters",
"(",
"'get_post_gallery'",
",",
"$",
"gallery",
",",
"$",
"this",
"->",
"ID",
",",
"$",
"galleries",
")",
";",
"}"
] | Returns the gallery
@api
@example
```twig
{{ post.gallery }}
```
@return html | [
"Returns",
"the",
"gallery"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1528-L1536 | train |
timber/timber | lib/Post.php | Post.audio | public function audio() {
if ( isset($this->custom['audio']) ) {
return $this->custom['audio'];
}
$audio = false;
// Only get audio from the content if a playlist isn't present.
if ( false === strpos($this->get_content(), 'wp-playlist-script') ) {
$audio = get_media_embedded_in_content($this->get_content(), array('audio'));
}
return $audio;
} | php | public function audio() {
if ( isset($this->custom['audio']) ) {
return $this->custom['audio'];
}
$audio = false;
// Only get audio from the content if a playlist isn't present.
if ( false === strpos($this->get_content(), 'wp-playlist-script') ) {
$audio = get_media_embedded_in_content($this->get_content(), array('audio'));
}
return $audio;
} | [
"public",
"function",
"audio",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"custom",
"[",
"'audio'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"custom",
"[",
"'audio'",
"]",
";",
"}",
"$",
"audio",
"=",
"false",
";",
"// Only get audio from the content if a playlist isn't present.",
"if",
"(",
"false",
"===",
"strpos",
"(",
"$",
"this",
"->",
"get_content",
"(",
")",
",",
"'wp-playlist-script'",
")",
")",
"{",
"$",
"audio",
"=",
"get_media_embedded_in_content",
"(",
"$",
"this",
"->",
"get_content",
"(",
")",
",",
"array",
"(",
"'audio'",
")",
")",
";",
"}",
"return",
"$",
"audio",
";",
"}"
] | Returns the audio
@api
@example
```twig
{{ post.audio }}
```
@return html | [
"Returns",
"the",
"audio"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1547-L1559 | train |
timber/timber | lib/Post.php | Post.video | public function video() {
if ( isset($this->custom['video']) ) {
return $this->custom['video'];
}
$video = false;
// Only get video from the content if a playlist isn't present.
if ( false === strpos($this->get_content(), 'wp-playlist-script') ) {
$video = get_media_embedded_in_content($this->get_content(), array('video', 'object', 'embed', 'iframe'));
}
return $video;
} | php | public function video() {
if ( isset($this->custom['video']) ) {
return $this->custom['video'];
}
$video = false;
// Only get video from the content if a playlist isn't present.
if ( false === strpos($this->get_content(), 'wp-playlist-script') ) {
$video = get_media_embedded_in_content($this->get_content(), array('video', 'object', 'embed', 'iframe'));
}
return $video;
} | [
"public",
"function",
"video",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"custom",
"[",
"'video'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"custom",
"[",
"'video'",
"]",
";",
"}",
"$",
"video",
"=",
"false",
";",
"// Only get video from the content if a playlist isn't present.",
"if",
"(",
"false",
"===",
"strpos",
"(",
"$",
"this",
"->",
"get_content",
"(",
")",
",",
"'wp-playlist-script'",
")",
")",
"{",
"$",
"video",
"=",
"get_media_embedded_in_content",
"(",
"$",
"this",
"->",
"get_content",
"(",
")",
",",
"array",
"(",
"'video'",
",",
"'object'",
",",
"'embed'",
",",
"'iframe'",
")",
")",
";",
"}",
"return",
"$",
"video",
";",
"}"
] | Returns the video
@api
@example
```twig
{{ post.video }}
```
@return html | [
"Returns",
"the",
"video"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1570-L1582 | train |
timber/timber | lib/Post.php | Post.get_terms | public function get_terms( $tax = '', $merge = true, $TermClass = '' ) {
return $this->terms($tax, $merge, $TermClass);
} | php | public function get_terms( $tax = '', $merge = true, $TermClass = '' ) {
return $this->terms($tax, $merge, $TermClass);
} | [
"public",
"function",
"get_terms",
"(",
"$",
"tax",
"=",
"''",
",",
"$",
"merge",
"=",
"true",
",",
"$",
"TermClass",
"=",
"''",
")",
"{",
"return",
"$",
"this",
"->",
"terms",
"(",
"$",
"tax",
",",
"$",
"merge",
",",
"$",
"TermClass",
")",
";",
"}"
] | Get the terms associated with the post
This goes across all taxonomies by default
@internal
@deprecated since 1.0
@codeCoverageIgnore
@param string|array $tax What taxonom(y|ies) to pull from. Defaults to all registered taxonomies for the post type. You can use custom ones, or built-in WordPress taxonomies (category, tag). Timber plays nice and figures out that tag/tags/post_tag are all the same (and categories/category), for custom taxonomies you're on your own.
@param bool $merge Should the resulting array be one big one (true)? Or should it be an array of sub-arrays for each taxonomy (false)?
@return array | [
"Get",
"the",
"terms",
"associated",
"with",
"the",
"post",
"This",
"goes",
"across",
"all",
"taxonomies",
"by",
"default"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1703-L1705 | train |
timber/timber | lib/Post.php | Post.get_comments | public function get_comments( $count = null, $order = 'wp', $type = 'comment', $status = 'approve', $CommentClass = 'Timber\Comment' ) {
return $this->comments($count, $order, $type, $status, $CommentClass);
} | php | public function get_comments( $count = null, $order = 'wp', $type = 'comment', $status = 'approve', $CommentClass = 'Timber\Comment' ) {
return $this->comments($count, $order, $type, $status, $CommentClass);
} | [
"public",
"function",
"get_comments",
"(",
"$",
"count",
"=",
"null",
",",
"$",
"order",
"=",
"'wp'",
",",
"$",
"type",
"=",
"'comment'",
",",
"$",
"status",
"=",
"'approve'",
",",
"$",
"CommentClass",
"=",
"'Timber\\Comment'",
")",
"{",
"return",
"$",
"this",
"->",
"comments",
"(",
"$",
"count",
",",
"$",
"order",
",",
"$",
"type",
",",
"$",
"status",
",",
"$",
"CommentClass",
")",
";",
"}"
] | Get the comments for a post
@internal
@see Timber\Post::comments
@param int $count
@param string $order
@param string $type
@param string $status
@param string $CommentClass
@return array|mixed | [
"Get",
"the",
"comments",
"for",
"a",
"post"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Post.php#L1893-L1895 | train |
timber/timber | lib/Helper.php | Helper.handle_transient_locking | protected static function handle_transient_locking( $slug, $callback, $transient_time, $lock_timeout, $force, $enable_transients ) {
if ( $enable_transients && self::_is_transient_locked($slug) ) {
$force = apply_filters('timber_force_transients', $force);
$force = apply_filters('timber_force_transient_'.$slug, $force);
if ( !$force ) {
//the server is currently executing the process.
//We're just gonna dump these users. Sorry!
return false;
}
$enable_transients = false;
}
// lock timeout shouldn't be higher than 5 seconds, unless
// remote calls with high timeouts are made here
if ( $enable_transients ) {
self::_lock_transient($slug, $lock_timeout);
}
$data = $callback();
if ( $enable_transients ) {
set_transient($slug, $data, $transient_time);
self::_unlock_transient($slug);
}
return $data;
} | php | protected static function handle_transient_locking( $slug, $callback, $transient_time, $lock_timeout, $force, $enable_transients ) {
if ( $enable_transients && self::_is_transient_locked($slug) ) {
$force = apply_filters('timber_force_transients', $force);
$force = apply_filters('timber_force_transient_'.$slug, $force);
if ( !$force ) {
//the server is currently executing the process.
//We're just gonna dump these users. Sorry!
return false;
}
$enable_transients = false;
}
// lock timeout shouldn't be higher than 5 seconds, unless
// remote calls with high timeouts are made here
if ( $enable_transients ) {
self::_lock_transient($slug, $lock_timeout);
}
$data = $callback();
if ( $enable_transients ) {
set_transient($slug, $data, $transient_time);
self::_unlock_transient($slug);
}
return $data;
} | [
"protected",
"static",
"function",
"handle_transient_locking",
"(",
"$",
"slug",
",",
"$",
"callback",
",",
"$",
"transient_time",
",",
"$",
"lock_timeout",
",",
"$",
"force",
",",
"$",
"enable_transients",
")",
"{",
"if",
"(",
"$",
"enable_transients",
"&&",
"self",
"::",
"_is_transient_locked",
"(",
"$",
"slug",
")",
")",
"{",
"$",
"force",
"=",
"apply_filters",
"(",
"'timber_force_transients'",
",",
"$",
"force",
")",
";",
"$",
"force",
"=",
"apply_filters",
"(",
"'timber_force_transient_'",
".",
"$",
"slug",
",",
"$",
"force",
")",
";",
"if",
"(",
"!",
"$",
"force",
")",
"{",
"//the server is currently executing the process.",
"//We're just gonna dump these users. Sorry!",
"return",
"false",
";",
"}",
"$",
"enable_transients",
"=",
"false",
";",
"}",
"// lock timeout shouldn't be higher than 5 seconds, unless",
"// remote calls with high timeouts are made here",
"if",
"(",
"$",
"enable_transients",
")",
"{",
"self",
"::",
"_lock_transient",
"(",
"$",
"slug",
",",
"$",
"lock_timeout",
")",
";",
"}",
"$",
"data",
"=",
"$",
"callback",
"(",
")",
";",
"if",
"(",
"$",
"enable_transients",
")",
"{",
"set_transient",
"(",
"$",
"slug",
",",
"$",
"data",
",",
"$",
"transient_time",
")",
";",
"self",
"::",
"_unlock_transient",
"(",
"$",
"slug",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Does the dirty work of locking the transient, running the callback and unlocking
@param string $slug
@param callable $callback
@param integer $transient_time Expiration of transients in seconds
@param integer $lock_timeout How long (in seconds) to lock the transient to prevent race conditions
@param boolean $force Force callback to be executed when transient is locked
@param boolean $enable_transients Force callback to be executed when transient is locked | [
"Does",
"the",
"dirty",
"work",
"of",
"locking",
"the",
"transient",
"running",
"the",
"callback",
"and",
"unlocking"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Helper.php#L54-L76 | train |
timber/timber | lib/Helper.php | Helper.start_timer | public static function start_timer() {
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
return $time;
} | php | public static function start_timer() {
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
return $time;
} | [
"public",
"static",
"function",
"start_timer",
"(",
")",
"{",
"$",
"time",
"=",
"microtime",
"(",
")",
";",
"$",
"time",
"=",
"explode",
"(",
"' '",
",",
"$",
"time",
")",
";",
"$",
"time",
"=",
"$",
"time",
"[",
"1",
"]",
"+",
"$",
"time",
"[",
"0",
"]",
";",
"return",
"$",
"time",
";",
"}"
] | For measuring time, this will start a timer
@api
@return float | [
"For",
"measuring",
"time",
"this",
"will",
"start",
"a",
"timer"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Helper.php#L110-L115 | train |
timber/timber | lib/Helper.php | Helper.stop_timer | public static function stop_timer( $start ) {
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
return $total_time.' seconds.';
} | php | public static function stop_timer( $start ) {
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
return $total_time.' seconds.';
} | [
"public",
"static",
"function",
"stop_timer",
"(",
"$",
"start",
")",
"{",
"$",
"time",
"=",
"microtime",
"(",
")",
";",
"$",
"time",
"=",
"explode",
"(",
"' '",
",",
"$",
"time",
")",
";",
"$",
"time",
"=",
"$",
"time",
"[",
"1",
"]",
"+",
"$",
"time",
"[",
"0",
"]",
";",
"$",
"finish",
"=",
"$",
"time",
";",
"$",
"total_time",
"=",
"round",
"(",
"(",
"$",
"finish",
"-",
"$",
"start",
")",
",",
"4",
")",
";",
"return",
"$",
"total_time",
".",
"' seconds.'",
";",
"}"
] | For stopping time and getting the data
@example
```php
$start = TimberHelper::start_timer();
// do some stuff that takes awhile
echo TimberHelper::stop_timer( $start );
```
@param int $start
@return string | [
"For",
"stopping",
"time",
"and",
"getting",
"the",
"data"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Helper.php#L128-L135 | train |
timber/timber | lib/Helper.php | Helper.pluck | public static function pluck( $array, $key ) {
$return = array();
foreach ( $array as $obj ) {
if ( is_object($obj) && method_exists($obj, $key) ) {
$return[] = $obj->$key();
} elseif ( is_object($obj) && property_exists($obj, $key) ) {
$return[] = $obj->$key;
} elseif ( is_array($obj) && isset($obj[$key]) ) {
$return[] = $obj[$key];
}
}
return $return;
} | php | public static function pluck( $array, $key ) {
$return = array();
foreach ( $array as $obj ) {
if ( is_object($obj) && method_exists($obj, $key) ) {
$return[] = $obj->$key();
} elseif ( is_object($obj) && property_exists($obj, $key) ) {
$return[] = $obj->$key;
} elseif ( is_array($obj) && isset($obj[$key]) ) {
$return[] = $obj[$key];
}
}
return $return;
} | [
"public",
"static",
"function",
"pluck",
"(",
"$",
"array",
",",
"$",
"key",
")",
"{",
"$",
"return",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"obj",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"obj",
")",
"&&",
"method_exists",
"(",
"$",
"obj",
",",
"$",
"key",
")",
")",
"{",
"$",
"return",
"[",
"]",
"=",
"$",
"obj",
"->",
"$",
"key",
"(",
")",
";",
"}",
"elseif",
"(",
"is_object",
"(",
"$",
"obj",
")",
"&&",
"property_exists",
"(",
"$",
"obj",
",",
"$",
"key",
")",
")",
"{",
"$",
"return",
"[",
"]",
"=",
"$",
"obj",
"->",
"$",
"key",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"obj",
")",
"&&",
"isset",
"(",
"$",
"obj",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"return",
"[",
"]",
"=",
"$",
"obj",
"[",
"$",
"key",
"]",
";",
"}",
"}",
"return",
"$",
"return",
";",
"}"
] | Plucks the values of a certain key from an array of objects
@param array $array
@param string $key | [
"Plucks",
"the",
"values",
"of",
"a",
"certain",
"key",
"from",
"an",
"array",
"of",
"objects"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Helper.php#L410-L422 | train |
timber/timber | lib/Helper.php | Helper.filter_array | public static function filter_array( $list, $args, $operator = 'AND' ) {
if ( ! is_array($args) ) {
$args = array( 'slug' => $args );
}
if ( ! is_array( $list ) && ! is_a( $list, 'Traversable' ) ) {
return array();
}
$util = new \WP_List_Util( $list );
return $util->filter( $args, $operator );
} | php | public static function filter_array( $list, $args, $operator = 'AND' ) {
if ( ! is_array($args) ) {
$args = array( 'slug' => $args );
}
if ( ! is_array( $list ) && ! is_a( $list, 'Traversable' ) ) {
return array();
}
$util = new \WP_List_Util( $list );
return $util->filter( $args, $operator );
} | [
"public",
"static",
"function",
"filter_array",
"(",
"$",
"list",
",",
"$",
"args",
",",
"$",
"operator",
"=",
"'AND'",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"args",
")",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"'slug'",
"=>",
"$",
"args",
")",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"list",
")",
"&&",
"!",
"is_a",
"(",
"$",
"list",
",",
"'Traversable'",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"util",
"=",
"new",
"\\",
"WP_List_Util",
"(",
"$",
"list",
")",
";",
"return",
"$",
"util",
"->",
"filter",
"(",
"$",
"args",
",",
"$",
"operator",
")",
";",
"}"
] | Filters a list of objects, based on a set of key => value arguments.
@since 1.5.3
@ticket #1594
@param array $list to filter.
@param string|array $filter to search for.
@param string $operator to use (AND, NOT, OR).
@return array | [
"Filters",
"a",
"list",
"of",
"objects",
"based",
"on",
"a",
"set",
"of",
"key",
"=",
">",
"value",
"arguments",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Helper.php#L434-L445 | train |
timber/timber | lib/User.php | User.get_roles | protected function get_roles( $roles ) {
if ( empty($roles) ) {
// @codeCoverageIgnoreStart
return null;
// @codeCoverageIgnoreEnd
}
$wp_roles = wp_roles();
$names = $wp_roles->get_names();
$values = array();
foreach ( $roles as $role ) {
$name = $role;
if ( isset($names[ $role ]) ) {
$name = translate_user_role($names[ $role ]);
}
$values[ $role ] = $name;
}
return $values;
} | php | protected function get_roles( $roles ) {
if ( empty($roles) ) {
// @codeCoverageIgnoreStart
return null;
// @codeCoverageIgnoreEnd
}
$wp_roles = wp_roles();
$names = $wp_roles->get_names();
$values = array();
foreach ( $roles as $role ) {
$name = $role;
if ( isset($names[ $role ]) ) {
$name = translate_user_role($names[ $role ]);
}
$values[ $role ] = $name;
}
return $values;
} | [
"protected",
"function",
"get_roles",
"(",
"$",
"roles",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"roles",
")",
")",
"{",
"// @codeCoverageIgnoreStart",
"return",
"null",
";",
"// @codeCoverageIgnoreEnd",
"}",
"$",
"wp_roles",
"=",
"wp_roles",
"(",
")",
";",
"$",
"names",
"=",
"$",
"wp_roles",
"->",
"get_names",
"(",
")",
";",
"$",
"values",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"roles",
"as",
"$",
"role",
")",
"{",
"$",
"name",
"=",
"$",
"role",
";",
"if",
"(",
"isset",
"(",
"$",
"names",
"[",
"$",
"role",
"]",
")",
")",
"{",
"$",
"name",
"=",
"translate_user_role",
"(",
"$",
"names",
"[",
"$",
"role",
"]",
")",
";",
"}",
"$",
"values",
"[",
"$",
"role",
"]",
"=",
"$",
"name",
";",
"}",
"return",
"$",
"values",
";",
"}"
] | Creates an associative array with user role slugs and their translated names.
@internal
@since 1.8.5
@param array $roles user roles.
@return array|null | [
"Creates",
"an",
"associative",
"array",
"with",
"user",
"role",
"slugs",
"and",
"their",
"translated",
"names",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/User.php#L247-L268 | train |
timber/timber | lib/Integrations/Timber_WP_CLI_Command.php | Timber_WP_CLI_Command.clear_cache | public function clear_cache( $mode = 'all' ) {
$mode = $mode ? : 'all';
$cleared = Command::clear_cache( $mode );
if ( $cleared ) {
\WP_CLI::success("Cleared {$mode} cached contents");
} else {
\WP_CLI::warning("Failed to clear {$mode} cached contents");
}
} | php | public function clear_cache( $mode = 'all' ) {
$mode = $mode ? : 'all';
$cleared = Command::clear_cache( $mode );
if ( $cleared ) {
\WP_CLI::success("Cleared {$mode} cached contents");
} else {
\WP_CLI::warning("Failed to clear {$mode} cached contents");
}
} | [
"public",
"function",
"clear_cache",
"(",
"$",
"mode",
"=",
"'all'",
")",
"{",
"$",
"mode",
"=",
"$",
"mode",
"?",
":",
"'all'",
";",
"$",
"cleared",
"=",
"Command",
"::",
"clear_cache",
"(",
"$",
"mode",
")",
";",
"if",
"(",
"$",
"cleared",
")",
"{",
"\\",
"WP_CLI",
"::",
"success",
"(",
"\"Cleared {$mode} cached contents\"",
")",
";",
"}",
"else",
"{",
"\\",
"WP_CLI",
"::",
"warning",
"(",
"\"Failed to clear {$mode} cached contents\"",
")",
";",
"}",
"}"
] | Clears Timber and Twig's Cache
## EXAMPLES
wp timber clear_cache | [
"Clears",
"Timber",
"and",
"Twig",
"s",
"Cache"
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/Integrations/Timber_WP_CLI_Command.php#L21-L29 | train |
timber/timber | lib/MenuItem.php | MenuItem.name | public function name() {
if ( $title = $this->title() ) {
return $title;
}
if ( isset($this->_name) ) {
return $this->_name;
}
return '';
} | php | public function name() {
if ( $title = $this->title() ) {
return $title;
}
if ( isset($this->_name) ) {
return $this->_name;
}
return '';
} | [
"public",
"function",
"name",
"(",
")",
"{",
"if",
"(",
"$",
"title",
"=",
"$",
"this",
"->",
"title",
"(",
")",
")",
"{",
"return",
"$",
"title",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_name",
";",
"}",
"return",
"''",
";",
"}"
] | Get the label for the menu item.
@api
@return string The label for the menu item. | [
"Get",
"the",
"label",
"for",
"the",
"menu",
"item",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/MenuItem.php#L100-L108 | train |
timber/timber | lib/MenuItem.php | MenuItem.slug | public function slug() {
$mo = $this->master_object();
if ( $mo && $mo->post_name ) {
return $mo->post_name;
}
return $this->post_name;
} | php | public function slug() {
$mo = $this->master_object();
if ( $mo && $mo->post_name ) {
return $mo->post_name;
}
return $this->post_name;
} | [
"public",
"function",
"slug",
"(",
")",
"{",
"$",
"mo",
"=",
"$",
"this",
"->",
"master_object",
"(",
")",
";",
"if",
"(",
"$",
"mo",
"&&",
"$",
"mo",
"->",
"post_name",
")",
"{",
"return",
"$",
"mo",
"->",
"post_name",
";",
"}",
"return",
"$",
"this",
"->",
"post_name",
";",
"}"
] | Get the slug for the menu item.
@api
@example
```twig
<ul>
{% for item in menu.items %}
<li class="{{ item.slug }}">
<a href="{{ item.link }}">{{ item.name }}</a>
</li>
{% endfor %}
</ul>
```
@return string The URL-safe slug of the menu item. | [
"Get",
"the",
"slug",
"for",
"the",
"menu",
"item",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/MenuItem.php#L141-L147 | train |
timber/timber | lib/MenuItem.php | MenuItem.add_child | public function add_child( $item ) {
if ( !$this->has_child_class ) {
$this->add_class('menu-item-has-children');
$this->has_child_class = true;
}
$this->children[] = $item;
$item->level = $this->level + 1;
if ( count($this->children) ) {
$this->update_child_levels();
}
} | php | public function add_child( $item ) {
if ( !$this->has_child_class ) {
$this->add_class('menu-item-has-children');
$this->has_child_class = true;
}
$this->children[] = $item;
$item->level = $this->level + 1;
if ( count($this->children) ) {
$this->update_child_levels();
}
} | [
"public",
"function",
"add_child",
"(",
"$",
"item",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"has_child_class",
")",
"{",
"$",
"this",
"->",
"add_class",
"(",
"'menu-item-has-children'",
")",
";",
"$",
"this",
"->",
"has_child_class",
"=",
"true",
";",
"}",
"$",
"this",
"->",
"children",
"[",
"]",
"=",
"$",
"item",
";",
"$",
"item",
"->",
"level",
"=",
"$",
"this",
"->",
"level",
"+",
"1",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"children",
")",
")",
"{",
"$",
"this",
"->",
"update_child_levels",
"(",
")",
";",
"}",
"}"
] | Add a new `Timber\MenuItem` object as a child of this menu item.
@param \Timber\MenuItem $item The menu item to add. | [
"Add",
"a",
"new",
"Timber",
"\\",
"MenuItem",
"object",
"as",
"a",
"child",
"of",
"this",
"menu",
"item",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/MenuItem.php#L202-L212 | train |
timber/timber | lib/MenuItem.php | MenuItem.import_classes | public function import_classes( $data ) {
if ( is_array($data) ) {
$data = (object) $data;
}
$this->classes = array_merge($this->classes, $data->classes);
$this->classes = array_unique($this->classes);
$this->classes = apply_filters('nav_menu_css_class', $this->classes, $this, array(), 0);
$this->class = trim(implode(' ', $this->classes));
} | php | public function import_classes( $data ) {
if ( is_array($data) ) {
$data = (object) $data;
}
$this->classes = array_merge($this->classes, $data->classes);
$this->classes = array_unique($this->classes);
$this->classes = apply_filters('nav_menu_css_class', $this->classes, $this, array(), 0);
$this->class = trim(implode(' ', $this->classes));
} | [
"public",
"function",
"import_classes",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"$",
"data",
"=",
"(",
"object",
")",
"$",
"data",
";",
"}",
"$",
"this",
"->",
"classes",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"classes",
",",
"$",
"data",
"->",
"classes",
")",
";",
"$",
"this",
"->",
"classes",
"=",
"array_unique",
"(",
"$",
"this",
"->",
"classes",
")",
";",
"$",
"this",
"->",
"classes",
"=",
"apply_filters",
"(",
"'nav_menu_css_class'",
",",
"$",
"this",
"->",
"classes",
",",
"$",
"this",
",",
"array",
"(",
")",
",",
"0",
")",
";",
"$",
"this",
"->",
"class",
"=",
"trim",
"(",
"implode",
"(",
"' '",
",",
"$",
"this",
"->",
"classes",
")",
")",
";",
"}"
] | Imports the classes to be used in CSS.
@internal
@param array|object $data | [
"Imports",
"the",
"classes",
"to",
"be",
"used",
"in",
"CSS",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/MenuItem.php#L235-L243 | train |
timber/timber | lib/MenuItem.php | MenuItem.meta | public function meta( $key ) {
if ( is_object($this->menu_object) && method_exists($this->menu_object, 'meta') ) {
return $this->menu_object->meta($key);
}
if ( isset($this->$key) ) {
return $this->$key;
}
} | php | public function meta( $key ) {
if ( is_object($this->menu_object) && method_exists($this->menu_object, 'meta') ) {
return $this->menu_object->meta($key);
}
if ( isset($this->$key) ) {
return $this->$key;
}
} | [
"public",
"function",
"meta",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"this",
"->",
"menu_object",
")",
"&&",
"method_exists",
"(",
"$",
"this",
"->",
"menu_object",
",",
"'meta'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"menu_object",
"->",
"meta",
"(",
"$",
"key",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"$",
"key",
";",
"}",
"}"
] | Get a meta value of the menu item.
Plugins like Advanced Custom Fields allow you to set custom fields for menu items. With this
method you can retrieve the value of these.
@example
```twig
<a class="icon-{{ item.meta('icon') }}" href="{{ item.link }}">{{ item.title }}</a>
```
@api
@param string $key The meta key to get the value for.
@return mixed Whatever value is stored in the database. | [
"Get",
"a",
"meta",
"value",
"of",
"the",
"menu",
"item",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/MenuItem.php#L318-L325 | train |
timber/timber | lib/MenuItem.php | MenuItem.link | public function link() {
if ( !isset($this->url) || !$this->url ) {
if ( isset($this->_menu_item_type) && $this->_menu_item_type == 'custom' ) {
$this->url = $this->_menu_item_url;
} else if ( isset($this->menu_object) && method_exists($this->menu_object, 'get_link') ) {
$this->url = $this->menu_object->link();
}
}
return $this->url;
} | php | public function link() {
if ( !isset($this->url) || !$this->url ) {
if ( isset($this->_menu_item_type) && $this->_menu_item_type == 'custom' ) {
$this->url = $this->_menu_item_url;
} else if ( isset($this->menu_object) && method_exists($this->menu_object, 'get_link') ) {
$this->url = $this->menu_object->link();
}
}
return $this->url;
} | [
"public",
"function",
"link",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"url",
")",
"||",
"!",
"$",
"this",
"->",
"url",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_menu_item_type",
")",
"&&",
"$",
"this",
"->",
"_menu_item_type",
"==",
"'custom'",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"$",
"this",
"->",
"_menu_item_url",
";",
"}",
"else",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"menu_object",
")",
"&&",
"method_exists",
"(",
"$",
"this",
"->",
"menu_object",
",",
"'get_link'",
")",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"$",
"this",
"->",
"menu_object",
"->",
"link",
"(",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"url",
";",
"}"
] | Get the full link to a menu item.
@api
@example
```twig
{% for item in menu.items %}
<li><a href="{{ item.link }}">{{ item.title }}</a></li>
{% endfor %}
```
@return string A full URL, like `http://mysite.com/thing/`. | [
"Get",
"the",
"full",
"link",
"to",
"a",
"menu",
"item",
"."
] | baaa1960193cffb5fa7c43c09114d6831764eede | https://github.com/timber/timber/blob/baaa1960193cffb5fa7c43c09114d6831764eede/lib/MenuItem.php#L372-L381 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/Revision.php | Revision.formatFieldName | private function formatFieldName($key)
{
$related_model = $this->revisionable_type;
$related_model = new $related_model;
$revisionFormattedFieldNames = $related_model->getRevisionFormattedFieldNames();
if (isset($revisionFormattedFieldNames[$key])) {
return $revisionFormattedFieldNames[$key];
}
return false;
} | php | private function formatFieldName($key)
{
$related_model = $this->revisionable_type;
$related_model = new $related_model;
$revisionFormattedFieldNames = $related_model->getRevisionFormattedFieldNames();
if (isset($revisionFormattedFieldNames[$key])) {
return $revisionFormattedFieldNames[$key];
}
return false;
} | [
"private",
"function",
"formatFieldName",
"(",
"$",
"key",
")",
"{",
"$",
"related_model",
"=",
"$",
"this",
"->",
"revisionable_type",
";",
"$",
"related_model",
"=",
"new",
"$",
"related_model",
";",
"$",
"revisionFormattedFieldNames",
"=",
"$",
"related_model",
"->",
"getRevisionFormattedFieldNames",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"revisionFormattedFieldNames",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"$",
"revisionFormattedFieldNames",
"[",
"$",
"key",
"]",
";",
"}",
"return",
"false",
";",
"}"
] | Format field name.
Allow overrides for field names.
@param $key
@return bool | [
"Format",
"field",
"name",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/Revision.php#L76-L87 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/Revision.php | Revision.getValue | private function getValue($which = 'new')
{
$which_value = $which . '_value';
// First find the main model that was updated
$main_model = $this->revisionable_type;
// Load it, WITH the related model
if (class_exists($main_model)) {
$main_model = new $main_model;
try {
if ($this->isRelated()) {
$related_model = $this->getRelatedModel();
// Now we can find out the namespace of of related model
if (!method_exists($main_model, $related_model)) {
$related_model = camel_case($related_model); // for cases like published_status_id
if (!method_exists($main_model, $related_model)) {
throw new \Exception('Relation ' . $related_model . ' does not exist for ' . get_class($main_model));
}
}
$related_class = $main_model->$related_model()->getRelated();
// Finally, now that we know the namespace of the related model
// we can load it, to find the information we so desire
$item = $related_class::find($this->$which_value);
if (is_null($this->$which_value) || $this->$which_value == '') {
$item = new $related_class;
return $item->getRevisionNullString();
}
if (!$item) {
$item = new $related_class;
return $this->format($this->key, $item->getRevisionUnknownString());
}
// Check if model use RevisionableTrait
if(method_exists($item, 'identifiableName')) {
// see if there's an available mutator
$mutator = 'get' . studly_case($this->key) . 'Attribute';
if (method_exists($item, $mutator)) {
return $this->format($item->$mutator($this->key), $item->identifiableName());
}
return $this->format($this->key, $item->identifiableName());
}
}
} catch (\Exception $e) {
// Just a fail-safe, in the case the data setup isn't as expected
// Nothing to do here.
}
// if there was an issue
// or, if it's a normal value
$mutator = 'get' . studly_case($this->key) . 'Attribute';
if (method_exists($main_model, $mutator)) {
return $this->format($this->key, $main_model->$mutator($this->$which_value));
}
}
return $this->format($this->key, $this->$which_value);
} | php | private function getValue($which = 'new')
{
$which_value = $which . '_value';
// First find the main model that was updated
$main_model = $this->revisionable_type;
// Load it, WITH the related model
if (class_exists($main_model)) {
$main_model = new $main_model;
try {
if ($this->isRelated()) {
$related_model = $this->getRelatedModel();
// Now we can find out the namespace of of related model
if (!method_exists($main_model, $related_model)) {
$related_model = camel_case($related_model); // for cases like published_status_id
if (!method_exists($main_model, $related_model)) {
throw new \Exception('Relation ' . $related_model . ' does not exist for ' . get_class($main_model));
}
}
$related_class = $main_model->$related_model()->getRelated();
// Finally, now that we know the namespace of the related model
// we can load it, to find the information we so desire
$item = $related_class::find($this->$which_value);
if (is_null($this->$which_value) || $this->$which_value == '') {
$item = new $related_class;
return $item->getRevisionNullString();
}
if (!$item) {
$item = new $related_class;
return $this->format($this->key, $item->getRevisionUnknownString());
}
// Check if model use RevisionableTrait
if(method_exists($item, 'identifiableName')) {
// see if there's an available mutator
$mutator = 'get' . studly_case($this->key) . 'Attribute';
if (method_exists($item, $mutator)) {
return $this->format($item->$mutator($this->key), $item->identifiableName());
}
return $this->format($this->key, $item->identifiableName());
}
}
} catch (\Exception $e) {
// Just a fail-safe, in the case the data setup isn't as expected
// Nothing to do here.
}
// if there was an issue
// or, if it's a normal value
$mutator = 'get' . studly_case($this->key) . 'Attribute';
if (method_exists($main_model, $mutator)) {
return $this->format($this->key, $main_model->$mutator($this->$which_value));
}
}
return $this->format($this->key, $this->$which_value);
} | [
"private",
"function",
"getValue",
"(",
"$",
"which",
"=",
"'new'",
")",
"{",
"$",
"which_value",
"=",
"$",
"which",
".",
"'_value'",
";",
"// First find the main model that was updated",
"$",
"main_model",
"=",
"$",
"this",
"->",
"revisionable_type",
";",
"// Load it, WITH the related model",
"if",
"(",
"class_exists",
"(",
"$",
"main_model",
")",
")",
"{",
"$",
"main_model",
"=",
"new",
"$",
"main_model",
";",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"isRelated",
"(",
")",
")",
"{",
"$",
"related_model",
"=",
"$",
"this",
"->",
"getRelatedModel",
"(",
")",
";",
"// Now we can find out the namespace of of related model",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"main_model",
",",
"$",
"related_model",
")",
")",
"{",
"$",
"related_model",
"=",
"camel_case",
"(",
"$",
"related_model",
")",
";",
"// for cases like published_status_id",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"main_model",
",",
"$",
"related_model",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Relation '",
".",
"$",
"related_model",
".",
"' does not exist for '",
".",
"get_class",
"(",
"$",
"main_model",
")",
")",
";",
"}",
"}",
"$",
"related_class",
"=",
"$",
"main_model",
"->",
"$",
"related_model",
"(",
")",
"->",
"getRelated",
"(",
")",
";",
"// Finally, now that we know the namespace of the related model",
"// we can load it, to find the information we so desire",
"$",
"item",
"=",
"$",
"related_class",
"::",
"find",
"(",
"$",
"this",
"->",
"$",
"which_value",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"$",
"which_value",
")",
"||",
"$",
"this",
"->",
"$",
"which_value",
"==",
"''",
")",
"{",
"$",
"item",
"=",
"new",
"$",
"related_class",
";",
"return",
"$",
"item",
"->",
"getRevisionNullString",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"item",
")",
"{",
"$",
"item",
"=",
"new",
"$",
"related_class",
";",
"return",
"$",
"this",
"->",
"format",
"(",
"$",
"this",
"->",
"key",
",",
"$",
"item",
"->",
"getRevisionUnknownString",
"(",
")",
")",
";",
"}",
"// Check if model use RevisionableTrait",
"if",
"(",
"method_exists",
"(",
"$",
"item",
",",
"'identifiableName'",
")",
")",
"{",
"// see if there's an available mutator",
"$",
"mutator",
"=",
"'get'",
".",
"studly_case",
"(",
"$",
"this",
"->",
"key",
")",
".",
"'Attribute'",
";",
"if",
"(",
"method_exists",
"(",
"$",
"item",
",",
"$",
"mutator",
")",
")",
"{",
"return",
"$",
"this",
"->",
"format",
"(",
"$",
"item",
"->",
"$",
"mutator",
"(",
"$",
"this",
"->",
"key",
")",
",",
"$",
"item",
"->",
"identifiableName",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"format",
"(",
"$",
"this",
"->",
"key",
",",
"$",
"item",
"->",
"identifiableName",
"(",
")",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"// Just a fail-safe, in the case the data setup isn't as expected",
"// Nothing to do here.",
"}",
"// if there was an issue",
"// or, if it's a normal value",
"$",
"mutator",
"=",
"'get'",
".",
"studly_case",
"(",
"$",
"this",
"->",
"key",
")",
".",
"'Attribute'",
";",
"if",
"(",
"method_exists",
"(",
"$",
"main_model",
",",
"$",
"mutator",
")",
")",
"{",
"return",
"$",
"this",
"->",
"format",
"(",
"$",
"this",
"->",
"key",
",",
"$",
"main_model",
"->",
"$",
"mutator",
"(",
"$",
"this",
"->",
"$",
"which_value",
")",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"format",
"(",
"$",
"this",
"->",
"key",
",",
"$",
"this",
"->",
"$",
"which_value",
")",
";",
"}"
] | Responsible for actually doing the grunt work for getting the
old or new value for the revision.
@param string $which old or new
@return string value | [
"Responsible",
"for",
"actually",
"doing",
"the",
"grunt",
"work",
"for",
"getting",
"the",
"old",
"or",
"new",
"value",
"for",
"the",
"revision",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/Revision.php#L125-L189 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/Revision.php | Revision.isRelated | private function isRelated()
{
$isRelated = false;
$idSuffix = '_id';
$pos = strrpos($this->key, $idSuffix);
if ($pos !== false
&& strlen($this->key) - strlen($idSuffix) === $pos
) {
$isRelated = true;
}
return $isRelated;
} | php | private function isRelated()
{
$isRelated = false;
$idSuffix = '_id';
$pos = strrpos($this->key, $idSuffix);
if ($pos !== false
&& strlen($this->key) - strlen($idSuffix) === $pos
) {
$isRelated = true;
}
return $isRelated;
} | [
"private",
"function",
"isRelated",
"(",
")",
"{",
"$",
"isRelated",
"=",
"false",
";",
"$",
"idSuffix",
"=",
"'_id'",
";",
"$",
"pos",
"=",
"strrpos",
"(",
"$",
"this",
"->",
"key",
",",
"$",
"idSuffix",
")",
";",
"if",
"(",
"$",
"pos",
"!==",
"false",
"&&",
"strlen",
"(",
"$",
"this",
"->",
"key",
")",
"-",
"strlen",
"(",
"$",
"idSuffix",
")",
"===",
"$",
"pos",
")",
"{",
"$",
"isRelated",
"=",
"true",
";",
"}",
"return",
"$",
"isRelated",
";",
"}"
] | Return true if the key is for a related model.
@return bool | [
"Return",
"true",
"if",
"the",
"key",
"is",
"for",
"a",
"related",
"model",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/Revision.php#L196-L209 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/Revision.php | Revision.getRelatedModel | private function getRelatedModel()
{
$idSuffix = '_id';
return substr($this->key, 0, strlen($this->key) - strlen($idSuffix));
} | php | private function getRelatedModel()
{
$idSuffix = '_id';
return substr($this->key, 0, strlen($this->key) - strlen($idSuffix));
} | [
"private",
"function",
"getRelatedModel",
"(",
")",
"{",
"$",
"idSuffix",
"=",
"'_id'",
";",
"return",
"substr",
"(",
"$",
"this",
"->",
"key",
",",
"0",
",",
"strlen",
"(",
"$",
"this",
"->",
"key",
")",
"-",
"strlen",
"(",
"$",
"idSuffix",
")",
")",
";",
"}"
] | Return the name of the related model.
@return string | [
"Return",
"the",
"name",
"of",
"the",
"related",
"model",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/Revision.php#L216-L221 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/Revision.php | Revision.userResponsible | public function userResponsible()
{
if (empty($this->user_id)) { return false; }
if (class_exists($class = '\Cartalyst\Sentry\Facades\Laravel\Sentry')
|| class_exists($class = '\Cartalyst\Sentinel\Laravel\Facades\Sentinel')
) {
return $class::findUserById($this->user_id);
} else {
$user_model = app('config')->get('auth.model');
if (empty($user_model)) {
$user_model = app('config')->get('auth.providers.users.model');
if (empty($user_model)) {
return false;
}
}
if (!class_exists($user_model)) {
return false;
}
return $user_model::find($this->user_id);
}
} | php | public function userResponsible()
{
if (empty($this->user_id)) { return false; }
if (class_exists($class = '\Cartalyst\Sentry\Facades\Laravel\Sentry')
|| class_exists($class = '\Cartalyst\Sentinel\Laravel\Facades\Sentinel')
) {
return $class::findUserById($this->user_id);
} else {
$user_model = app('config')->get('auth.model');
if (empty($user_model)) {
$user_model = app('config')->get('auth.providers.users.model');
if (empty($user_model)) {
return false;
}
}
if (!class_exists($user_model)) {
return false;
}
return $user_model::find($this->user_id);
}
} | [
"public",
"function",
"userResponsible",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"user_id",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"class_exists",
"(",
"$",
"class",
"=",
"'\\Cartalyst\\Sentry\\Facades\\Laravel\\Sentry'",
")",
"||",
"class_exists",
"(",
"$",
"class",
"=",
"'\\Cartalyst\\Sentinel\\Laravel\\Facades\\Sentinel'",
")",
")",
"{",
"return",
"$",
"class",
"::",
"findUserById",
"(",
"$",
"this",
"->",
"user_id",
")",
";",
"}",
"else",
"{",
"$",
"user_model",
"=",
"app",
"(",
"'config'",
")",
"->",
"get",
"(",
"'auth.model'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"user_model",
")",
")",
"{",
"$",
"user_model",
"=",
"app",
"(",
"'config'",
")",
"->",
"get",
"(",
"'auth.providers.users.model'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"user_model",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"user_model",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"user_model",
"::",
"find",
"(",
"$",
"this",
"->",
"user_id",
")",
";",
"}",
"}"
] | User Responsible.
@return User user responsible for the change | [
"User",
"Responsible",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/Revision.php#L228-L249 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/FieldFormatter.php | FieldFormatter.format | public static function format($key, $value, $formats)
{
foreach ($formats as $pkey => $format) {
$parts = explode(':', $format);
if (sizeof($parts) === 1) {
continue;
}
if ($pkey == $key) {
$method = array_shift($parts);
if (method_exists(get_class(), $method)) {
return self::$method($value, implode(':', $parts));
}
break;
}
}
return $value;
} | php | public static function format($key, $value, $formats)
{
foreach ($formats as $pkey => $format) {
$parts = explode(':', $format);
if (sizeof($parts) === 1) {
continue;
}
if ($pkey == $key) {
$method = array_shift($parts);
if (method_exists(get_class(), $method)) {
return self::$method($value, implode(':', $parts));
}
break;
}
}
return $value;
} | [
"public",
"static",
"function",
"format",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"formats",
")",
"{",
"foreach",
"(",
"$",
"formats",
"as",
"$",
"pkey",
"=>",
"$",
"format",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"':'",
",",
"$",
"format",
")",
";",
"if",
"(",
"sizeof",
"(",
"$",
"parts",
")",
"===",
"1",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"pkey",
"==",
"$",
"key",
")",
"{",
"$",
"method",
"=",
"array_shift",
"(",
"$",
"parts",
")",
";",
"if",
"(",
"method_exists",
"(",
"get_class",
"(",
")",
",",
"$",
"method",
")",
")",
"{",
"return",
"self",
"::",
"$",
"method",
"(",
"$",
"value",
",",
"implode",
"(",
"':'",
",",
"$",
"parts",
")",
")",
";",
"}",
"break",
";",
"}",
"}",
"return",
"$",
"value",
";",
"}"
] | Format the value according to the provided formats.
@param $key
@param $value
@param $formats
@return string formatted value | [
"Format",
"the",
"value",
"according",
"to",
"the",
"provided",
"formats",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/FieldFormatter.php#L28-L47 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/FieldFormatter.php | FieldFormatter.isEmpty | public static function isEmpty($value, $options = array())
{
$value_set = isset($value) && $value != '';
return sprintf(self::boolean($value_set, $options), $value);
} | php | public static function isEmpty($value, $options = array())
{
$value_set = isset($value) && $value != '';
return sprintf(self::boolean($value_set, $options), $value);
} | [
"public",
"static",
"function",
"isEmpty",
"(",
"$",
"value",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"value_set",
"=",
"isset",
"(",
"$",
"value",
")",
"&&",
"$",
"value",
"!=",
"''",
";",
"return",
"sprintf",
"(",
"self",
"::",
"boolean",
"(",
"$",
"value_set",
",",
"$",
"options",
")",
",",
"$",
"value",
")",
";",
"}"
] | Check if a field is empty.
@param $value
@param array $options
@return string | [
"Check",
"if",
"a",
"field",
"is",
"empty",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/FieldFormatter.php#L57-L62 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/FieldFormatter.php | FieldFormatter.string | public static function string($value, $format = null)
{
if (is_null($format)) {
$format = '%s';
}
return sprintf($format, $value);
} | php | public static function string($value, $format = null)
{
if (is_null($format)) {
$format = '%s';
}
return sprintf($format, $value);
} | [
"public",
"static",
"function",
"string",
"(",
"$",
"value",
",",
"$",
"format",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"format",
")",
")",
"{",
"$",
"format",
"=",
"'%s'",
";",
"}",
"return",
"sprintf",
"(",
"$",
"format",
",",
"$",
"value",
")",
";",
"}"
] | Format the string response, default is to just return the string.
@param $value
@param $format
@return formatted string | [
"Format",
"the",
"string",
"response",
"default",
"is",
"to",
"just",
"return",
"the",
"string",
"."
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/FieldFormatter.php#L93-L100 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/FieldFormatter.php | FieldFormatter.datetime | public static function datetime($value, $format = 'Y-m-d H:i:s')
{
if (empty($value)) {
return null;
}
$datetime = new \DateTime($value);
return $datetime->format($format);
} | php | public static function datetime($value, $format = 'Y-m-d H:i:s')
{
if (empty($value)) {
return null;
}
$datetime = new \DateTime($value);
return $datetime->format($format);
} | [
"public",
"static",
"function",
"datetime",
"(",
"$",
"value",
",",
"$",
"format",
"=",
"'Y-m-d H:i:s'",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"datetime",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"value",
")",
";",
"return",
"$",
"datetime",
"->",
"format",
"(",
"$",
"format",
")",
";",
"}"
] | Format the datetime
@param string $value
@param string $format
@return formatted datetime | [
"Format",
"the",
"datetime"
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/FieldFormatter.php#L110-L119 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/Revisionable.php | Revisionable.changedRevisionableFields | private function changedRevisionableFields()
{
$changes_to_record = array();
foreach ($this->dirtyData as $key => $value) {
// check that the field is revisionable, and double check
// that it's actually new data in case dirty is, well, clean
if ($this->isRevisionable($key) && !is_array($value)) {
if (!isset($this->originalData[$key]) || $this->originalData[$key] != $this->updatedData[$key]) {
$changes_to_record[$key] = $value;
}
} else {
// we don't need these any more, and they could
// contain a lot of data, so lets trash them.
unset($this->updatedData[$key]);
unset($this->originalData[$key]);
}
}
return $changes_to_record;
} | php | private function changedRevisionableFields()
{
$changes_to_record = array();
foreach ($this->dirtyData as $key => $value) {
// check that the field is revisionable, and double check
// that it's actually new data in case dirty is, well, clean
if ($this->isRevisionable($key) && !is_array($value)) {
if (!isset($this->originalData[$key]) || $this->originalData[$key] != $this->updatedData[$key]) {
$changes_to_record[$key] = $value;
}
} else {
// we don't need these any more, and they could
// contain a lot of data, so lets trash them.
unset($this->updatedData[$key]);
unset($this->originalData[$key]);
}
}
return $changes_to_record;
} | [
"private",
"function",
"changedRevisionableFields",
"(",
")",
"{",
"$",
"changes_to_record",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"dirtyData",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"// check that the field is revisionable, and double check",
"// that it's actually new data in case dirty is, well, clean",
"if",
"(",
"$",
"this",
"->",
"isRevisionable",
"(",
"$",
"key",
")",
"&&",
"!",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"originalData",
"[",
"$",
"key",
"]",
")",
"||",
"$",
"this",
"->",
"originalData",
"[",
"$",
"key",
"]",
"!=",
"$",
"this",
"->",
"updatedData",
"[",
"$",
"key",
"]",
")",
"{",
"$",
"changes_to_record",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"else",
"{",
"// we don't need these any more, and they could",
"// contain a lot of data, so lets trash them.",
"unset",
"(",
"$",
"this",
"->",
"updatedData",
"[",
"$",
"key",
"]",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"originalData",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"return",
"$",
"changes_to_record",
";",
"}"
] | Get all of the changes that have been made, that are also supposed
to have their changes recorded
@return array fields with new data, that should be recorded | [
"Get",
"all",
"of",
"the",
"changes",
"that",
"have",
"been",
"made",
"that",
"are",
"also",
"supposed",
"to",
"have",
"their",
"changes",
"recorded"
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/Revisionable.php#L252-L271 | train |
VentureCraft/revisionable | src/Venturecraft/Revisionable/Revisionable.php | Revisionable.isSoftDelete | private function isSoftDelete()
{
// check flag variable used in laravel 4.2+
if (isset($this->forceDeleting)) {
return !$this->forceDeleting;
}
// otherwise, look for flag used in older versions
if (isset($this->softDelete)) {
return $this->softDelete;
}
return false;
} | php | private function isSoftDelete()
{
// check flag variable used in laravel 4.2+
if (isset($this->forceDeleting)) {
return !$this->forceDeleting;
}
// otherwise, look for flag used in older versions
if (isset($this->softDelete)) {
return $this->softDelete;
}
return false;
} | [
"private",
"function",
"isSoftDelete",
"(",
")",
"{",
"// check flag variable used in laravel 4.2+",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"forceDeleting",
")",
")",
"{",
"return",
"!",
"$",
"this",
"->",
"forceDeleting",
";",
"}",
"// otherwise, look for flag used in older versions",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"softDelete",
")",
")",
"{",
"return",
"$",
"this",
"->",
"softDelete",
";",
"}",
"return",
"false",
";",
"}"
] | Check if soft deletes are currently enabled on this model
@return bool | [
"Check",
"if",
"soft",
"deletes",
"are",
"currently",
"enabled",
"on",
"this",
"model"
] | 6b178df991e46b509d230a2bf1b6f8685e426a10 | https://github.com/VentureCraft/revisionable/blob/6b178df991e46b509d230a2bf1b6f8685e426a10/src/Venturecraft/Revisionable/Revisionable.php#L301-L314 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.search | public function search($options = [])
{
$query = $this->queryParts;
if (empty($query)) {
$query = '{}';
}
if (is_array($query)) {
$query = Json::encode($query);
}
$url = [$this->index !== null ? $this->index : '_all'];
if ($this->type !== null) {
$url[] = $this->type;
}
$url[] = '_search';
return $this->db->get($url, array_merge($this->options, $options), $query);
} | php | public function search($options = [])
{
$query = $this->queryParts;
if (empty($query)) {
$query = '{}';
}
if (is_array($query)) {
$query = Json::encode($query);
}
$url = [$this->index !== null ? $this->index : '_all'];
if ($this->type !== null) {
$url[] = $this->type;
}
$url[] = '_search';
return $this->db->get($url, array_merge($this->options, $options), $query);
} | [
"public",
"function",
"search",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"queryParts",
";",
"if",
"(",
"empty",
"(",
"$",
"query",
")",
")",
"{",
"$",
"query",
"=",
"'{}'",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"query",
")",
")",
"{",
"$",
"query",
"=",
"Json",
"::",
"encode",
"(",
"$",
"query",
")",
";",
"}",
"$",
"url",
"=",
"[",
"$",
"this",
"->",
"index",
"!==",
"null",
"?",
"$",
"this",
"->",
"index",
":",
"'_all'",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"type",
"!==",
"null",
")",
"{",
"$",
"url",
"[",
"]",
"=",
"$",
"this",
"->",
"type",
";",
"}",
"$",
"url",
"[",
"]",
"=",
"'_search'",
";",
"return",
"$",
"this",
"->",
"db",
"->",
"get",
"(",
"$",
"url",
",",
"array_merge",
"(",
"$",
"this",
"->",
"options",
",",
"$",
"options",
")",
",",
"$",
"query",
")",
";",
"}"
] | Sends a request to the _search API and returns the result
@param array $options
@return mixed | [
"Sends",
"a",
"request",
"to",
"the",
"_search",
"API",
"and",
"returns",
"the",
"result"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L53-L69 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.deleteByQuery | public function deleteByQuery($options = [])
{
if (!isset($this->queryParts['query'])) {
throw new InvalidCallException('Can not call deleteByQuery when no query is given.');
}
$query = [
'query' => $this->queryParts['query'],
];
if (isset($this->queryParts['filter'])) {
$query['filter'] = $this->queryParts['filter'];
}
$query = Json::encode($query);
$url = [$this->index !== null ? $this->index : '_all'];
if ($this->type !== null) {
$url[] = $this->type;
}
$url[] = '_query';
return $this->db->delete($url, array_merge($this->options, $options), $query);
} | php | public function deleteByQuery($options = [])
{
if (!isset($this->queryParts['query'])) {
throw new InvalidCallException('Can not call deleteByQuery when no query is given.');
}
$query = [
'query' => $this->queryParts['query'],
];
if (isset($this->queryParts['filter'])) {
$query['filter'] = $this->queryParts['filter'];
}
$query = Json::encode($query);
$url = [$this->index !== null ? $this->index : '_all'];
if ($this->type !== null) {
$url[] = $this->type;
}
$url[] = '_query';
return $this->db->delete($url, array_merge($this->options, $options), $query);
} | [
"public",
"function",
"deleteByQuery",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"queryParts",
"[",
"'query'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidCallException",
"(",
"'Can not call deleteByQuery when no query is given.'",
")",
";",
"}",
"$",
"query",
"=",
"[",
"'query'",
"=>",
"$",
"this",
"->",
"queryParts",
"[",
"'query'",
"]",
",",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"queryParts",
"[",
"'filter'",
"]",
")",
")",
"{",
"$",
"query",
"[",
"'filter'",
"]",
"=",
"$",
"this",
"->",
"queryParts",
"[",
"'filter'",
"]",
";",
"}",
"$",
"query",
"=",
"Json",
"::",
"encode",
"(",
"$",
"query",
")",
";",
"$",
"url",
"=",
"[",
"$",
"this",
"->",
"index",
"!==",
"null",
"?",
"$",
"this",
"->",
"index",
":",
"'_all'",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"type",
"!==",
"null",
")",
"{",
"$",
"url",
"[",
"]",
"=",
"$",
"this",
"->",
"type",
";",
"}",
"$",
"url",
"[",
"]",
"=",
"'_query'",
";",
"return",
"$",
"this",
"->",
"db",
"->",
"delete",
"(",
"$",
"url",
",",
"array_merge",
"(",
"$",
"this",
"->",
"options",
",",
"$",
"options",
")",
",",
"$",
"query",
")",
";",
"}"
] | Sends a request to the delete by query
@param array $options
@return mixed | [
"Sends",
"a",
"request",
"to",
"the",
"delete",
"by",
"query"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L76-L95 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.suggest | public function suggest($suggester, $options = [])
{
if (empty($suggester)) {
$suggester = '{}';
}
if (is_array($suggester)) {
$suggester = Json::encode($suggester);
}
$url = [
$this->index !== null ? $this->index : '_all',
'_suggest'
];
return $this->db->post($url, array_merge($this->options, $options), $suggester);
} | php | public function suggest($suggester, $options = [])
{
if (empty($suggester)) {
$suggester = '{}';
}
if (is_array($suggester)) {
$suggester = Json::encode($suggester);
}
$url = [
$this->index !== null ? $this->index : '_all',
'_suggest'
];
return $this->db->post($url, array_merge($this->options, $options), $suggester);
} | [
"public",
"function",
"suggest",
"(",
"$",
"suggester",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"suggester",
")",
")",
"{",
"$",
"suggester",
"=",
"'{}'",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"suggester",
")",
")",
"{",
"$",
"suggester",
"=",
"Json",
"::",
"encode",
"(",
"$",
"suggester",
")",
";",
"}",
"$",
"url",
"=",
"[",
"$",
"this",
"->",
"index",
"!==",
"null",
"?",
"$",
"this",
"->",
"index",
":",
"'_all'",
",",
"'_suggest'",
"]",
";",
"return",
"$",
"this",
"->",
"db",
"->",
"post",
"(",
"$",
"url",
",",
"array_merge",
"(",
"$",
"this",
"->",
"options",
",",
"$",
"options",
")",
",",
"$",
"suggester",
")",
";",
"}"
] | Sends a request to the _suggest API and returns the result
@param string|array $suggester the suggester body
@param array $options
@return mixed
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html | [
"Sends",
"a",
"request",
"to",
"the",
"_suggest",
"API",
"and",
"returns",
"the",
"result"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L104-L118 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.insert | public function insert($index, $type, $data, $id = null, $options = [])
{
if (empty($data)) {
$body = '{}';
} else {
$body = is_array($data) ? Json::encode($data) : $data;
}
if ($id !== null) {
return $this->db->put([$index, $type, $id], $options, $body);
} else {
return $this->db->post([$index, $type], $options, $body);
}
} | php | public function insert($index, $type, $data, $id = null, $options = [])
{
if (empty($data)) {
$body = '{}';
} else {
$body = is_array($data) ? Json::encode($data) : $data;
}
if ($id !== null) {
return $this->db->put([$index, $type, $id], $options, $body);
} else {
return $this->db->post([$index, $type], $options, $body);
}
} | [
"public",
"function",
"insert",
"(",
"$",
"index",
",",
"$",
"type",
",",
"$",
"data",
",",
"$",
"id",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"$",
"body",
"=",
"'{}'",
";",
"}",
"else",
"{",
"$",
"body",
"=",
"is_array",
"(",
"$",
"data",
")",
"?",
"Json",
"::",
"encode",
"(",
"$",
"data",
")",
":",
"$",
"data",
";",
"}",
"if",
"(",
"$",
"id",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"db",
"->",
"put",
"(",
"[",
"$",
"index",
",",
"$",
"type",
",",
"$",
"id",
"]",
",",
"$",
"options",
",",
"$",
"body",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"db",
"->",
"post",
"(",
"[",
"$",
"index",
",",
"$",
"type",
"]",
",",
"$",
"options",
",",
"$",
"body",
")",
";",
"}",
"}"
] | Inserts a document into an index
@param string $index
@param string $type
@param string|array $data json string or array of data to store
@param null $id the documents id. If not specified Id will be automatically chosen
@param array $options
@return mixed
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html | [
"Inserts",
"a",
"document",
"into",
"an",
"index"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L130-L143 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.mget | public function mget($index, $type, $ids, $options = [])
{
$body = Json::encode(['ids' => array_values($ids)]);
return $this->db->get([$index, $type, '_mget'], $options, $body);
} | php | public function mget($index, $type, $ids, $options = [])
{
$body = Json::encode(['ids' => array_values($ids)]);
return $this->db->get([$index, $type, '_mget'], $options, $body);
} | [
"public",
"function",
"mget",
"(",
"$",
"index",
",",
"$",
"type",
",",
"$",
"ids",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"body",
"=",
"Json",
"::",
"encode",
"(",
"[",
"'ids'",
"=>",
"array_values",
"(",
"$",
"ids",
")",
"]",
")",
";",
"return",
"$",
"this",
"->",
"db",
"->",
"get",
"(",
"[",
"$",
"index",
",",
"$",
"type",
",",
"'_mget'",
"]",
",",
"$",
"options",
",",
"$",
"body",
")",
";",
"}"
] | gets multiple documents from the index
TODO allow specifying type and index + fields
@param $index
@param $type
@param $ids
@param array $options
@return mixed
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html | [
"gets",
"multiple",
"documents",
"from",
"the",
"index"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L170-L175 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.delete | public function delete($index, $type, $id, $options = [])
{
return $this->db->delete([$index, $type, $id], $options);
} | php | public function delete($index, $type, $id, $options = [])
{
return $this->db->delete([$index, $type, $id], $options);
} | [
"public",
"function",
"delete",
"(",
"$",
"index",
",",
"$",
"type",
",",
"$",
"id",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"db",
"->",
"delete",
"(",
"[",
"$",
"index",
",",
"$",
"type",
",",
"$",
"id",
"]",
",",
"$",
"options",
")",
";",
"}"
] | deletes a document from the index
@param $index
@param $type
@param $id
@param array $options
@return mixed
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html | [
"deletes",
"a",
"document",
"from",
"the",
"index"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L212-L215 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.update | public function update($index, $type, $id, $data, $options = [])
{
$body = [
'doc' => empty($data) ? new \stdClass() : $data,
];
if (isset($options["detect_noop"])) {
$body["detect_noop"] = $options["detect_noop"];
unset($options["detect_noop"]);
}
return $this->db->post([$index, $type, $id, '_update'], $options, Json::encode($body));
} | php | public function update($index, $type, $id, $data, $options = [])
{
$body = [
'doc' => empty($data) ? new \stdClass() : $data,
];
if (isset($options["detect_noop"])) {
$body["detect_noop"] = $options["detect_noop"];
unset($options["detect_noop"]);
}
return $this->db->post([$index, $type, $id, '_update'], $options, Json::encode($body));
} | [
"public",
"function",
"update",
"(",
"$",
"index",
",",
"$",
"type",
",",
"$",
"id",
",",
"$",
"data",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"body",
"=",
"[",
"'doc'",
"=>",
"empty",
"(",
"$",
"data",
")",
"?",
"new",
"\\",
"stdClass",
"(",
")",
":",
"$",
"data",
",",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"\"detect_noop\"",
"]",
")",
")",
"{",
"$",
"body",
"[",
"\"detect_noop\"",
"]",
"=",
"$",
"options",
"[",
"\"detect_noop\"",
"]",
";",
"unset",
"(",
"$",
"options",
"[",
"\"detect_noop\"",
"]",
")",
";",
"}",
"return",
"$",
"this",
"->",
"db",
"->",
"post",
"(",
"[",
"$",
"index",
",",
"$",
"type",
",",
"$",
"id",
",",
"'_update'",
"]",
",",
"$",
"options",
",",
"Json",
"::",
"encode",
"(",
"$",
"body",
")",
")",
";",
"}"
] | updates a document
@param $index
@param $type
@param $id
@param array $options
@return mixed
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html | [
"updates",
"a",
"document"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L226-L237 | train |
yiisoft/yii2-elasticsearch | Command.php | Command.createIndex | public function createIndex($index, $configuration = null)
{
$body = $configuration !== null ? Json::encode($configuration) : null;
return $this->db->put([$index], [], $body);
} | php | public function createIndex($index, $configuration = null)
{
$body = $configuration !== null ? Json::encode($configuration) : null;
return $this->db->put([$index], [], $body);
} | [
"public",
"function",
"createIndex",
"(",
"$",
"index",
",",
"$",
"configuration",
"=",
"null",
")",
"{",
"$",
"body",
"=",
"$",
"configuration",
"!==",
"null",
"?",
"Json",
"::",
"encode",
"(",
"$",
"configuration",
")",
":",
"null",
";",
"return",
"$",
"this",
"->",
"db",
"->",
"put",
"(",
"[",
"$",
"index",
"]",
",",
"[",
"]",
",",
"$",
"body",
")",
";",
"}"
] | creates an index
@param $index
@param array $configuration
@return mixed
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html | [
"creates",
"an",
"index"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Command.php#L248-L253 | train |
yiisoft/yii2-elasticsearch | Connection.php | Connection.selectActiveNode | protected function selectActiveNode()
{
$keys = array_keys($this->nodes);
$this->activeNode = $keys[rand(0, count($keys) - 1)];
} | php | protected function selectActiveNode()
{
$keys = array_keys($this->nodes);
$this->activeNode = $keys[rand(0, count($keys) - 1)];
} | [
"protected",
"function",
"selectActiveNode",
"(",
")",
"{",
"$",
"keys",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"nodes",
")",
";",
"$",
"this",
"->",
"activeNode",
"=",
"$",
"keys",
"[",
"rand",
"(",
"0",
",",
"count",
"(",
"$",
"keys",
")",
"-",
"1",
")",
"]",
";",
"}"
] | select active node randomly | [
"select",
"active",
"node",
"randomly"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Connection.php#L206-L210 | train |
yiisoft/yii2-elasticsearch | Connection.php | Connection.createBulkCommand | public function createBulkCommand($config = [])
{
$this->open();
$config['db'] = $this;
$command = new BulkCommand($config);
return $command;
} | php | public function createBulkCommand($config = [])
{
$this->open();
$config['db'] = $this;
$command = new BulkCommand($config);
return $command;
} | [
"public",
"function",
"createBulkCommand",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"open",
"(",
")",
";",
"$",
"config",
"[",
"'db'",
"]",
"=",
"$",
"this",
";",
"$",
"command",
"=",
"new",
"BulkCommand",
"(",
"$",
"config",
")",
";",
"return",
"$",
"command",
";",
"}"
] | Creates a bulk command for execution.
@param array $config the configuration for the [[BulkCommand]] class
@return BulkCommand the DB command
@since 2.0.5 | [
"Creates",
"a",
"bulk",
"command",
"for",
"execution",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Connection.php#L269-L276 | train |
yiisoft/yii2-elasticsearch | Connection.php | Connection.post | public function post($url, $options = [], $body = null, $raw = false)
{
$this->open();
return $this->httpRequest('POST', $this->createUrl($url, $options), $body, $raw);
} | php | public function post($url, $options = [], $body = null, $raw = false)
{
$this->open();
return $this->httpRequest('POST', $this->createUrl($url, $options), $body, $raw);
} | [
"public",
"function",
"post",
"(",
"$",
"url",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"body",
"=",
"null",
",",
"$",
"raw",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"open",
"(",
")",
";",
"return",
"$",
"this",
"->",
"httpRequest",
"(",
"'POST'",
",",
"$",
"this",
"->",
"createUrl",
"(",
"$",
"url",
",",
"$",
"options",
")",
",",
"$",
"body",
",",
"$",
"raw",
")",
";",
"}"
] | Performs POST HTTP request
@param string|array $url URL
@param array $options URL options
@param string $body request body
@param bool $raw if response body contains JSON and should be decoded
@return mixed response
@throws Exception
@throws InvalidConfigException | [
"Performs",
"POST",
"HTTP",
"request"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Connection.php#L331-L335 | train |
yiisoft/yii2-elasticsearch | Connection.php | Connection.decodeErrorBody | protected function decodeErrorBody($body)
{
try {
$decoded = Json::decode($body);
if (isset($decoded['error']) && !is_array($decoded['error'])) {
$decoded['error'] = preg_replace('/\b\w+?Exception\[/', "<span style=\"color: red;\">\\0</span>\n ", $decoded['error']);
}
return $decoded;
} catch(InvalidParamException $e) {
return $body;
}
} | php | protected function decodeErrorBody($body)
{
try {
$decoded = Json::decode($body);
if (isset($decoded['error']) && !is_array($decoded['error'])) {
$decoded['error'] = preg_replace('/\b\w+?Exception\[/', "<span style=\"color: red;\">\\0</span>\n ", $decoded['error']);
}
return $decoded;
} catch(InvalidParamException $e) {
return $body;
}
} | [
"protected",
"function",
"decodeErrorBody",
"(",
"$",
"body",
")",
"{",
"try",
"{",
"$",
"decoded",
"=",
"Json",
"::",
"decode",
"(",
"$",
"body",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"decoded",
"[",
"'error'",
"]",
")",
"&&",
"!",
"is_array",
"(",
"$",
"decoded",
"[",
"'error'",
"]",
")",
")",
"{",
"$",
"decoded",
"[",
"'error'",
"]",
"=",
"preg_replace",
"(",
"'/\\b\\w+?Exception\\[/'",
",",
"\"<span style=\\\"color: red;\\\">\\\\0</span>\\n \"",
",",
"$",
"decoded",
"[",
"'error'",
"]",
")",
";",
"}",
"return",
"$",
"decoded",
";",
"}",
"catch",
"(",
"InvalidParamException",
"$",
"e",
")",
"{",
"return",
"$",
"body",
";",
"}",
"}"
] | Try to decode error information if it is valid json, return it if not.
@param $body
@return mixed | [
"Try",
"to",
"decode",
"error",
"information",
"if",
"it",
"is",
"valid",
"json",
"return",
"it",
"if",
"not",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Connection.php#L579-L590 | train |
yiisoft/yii2-elasticsearch | ActiveQuery.php | ActiveQuery.createModels | private function createModels($rows)
{
$models = [];
if ($this->asArray) {
if ($this->indexBy === null) {
return $rows;
}
foreach ($rows as $row) {
if (is_string($this->indexBy)) {
$key = isset($row['fields'][$this->indexBy]) ? reset($row['fields'][$this->indexBy]) : $row['_source'][$this->indexBy];
} else {
$key = call_user_func($this->indexBy, $row);
}
$models[$key] = $row;
}
} else {
/* @var $class ActiveRecord */
$class = $this->modelClass;
if ($this->indexBy === null) {
foreach ($rows as $row) {
$model = $class::instantiate($row);
$modelClass = get_class($model);
$modelClass::populateRecord($model, $row);
$models[] = $model;
}
} else {
foreach ($rows as $row) {
$model = $class::instantiate($row);
$modelClass = get_class($model);
$modelClass::populateRecord($model, $row);
if (is_string($this->indexBy)) {
$key = $model->{$this->indexBy};
} else {
$key = call_user_func($this->indexBy, $model);
}
$models[$key] = $model;
}
}
}
return $models;
} | php | private function createModels($rows)
{
$models = [];
if ($this->asArray) {
if ($this->indexBy === null) {
return $rows;
}
foreach ($rows as $row) {
if (is_string($this->indexBy)) {
$key = isset($row['fields'][$this->indexBy]) ? reset($row['fields'][$this->indexBy]) : $row['_source'][$this->indexBy];
} else {
$key = call_user_func($this->indexBy, $row);
}
$models[$key] = $row;
}
} else {
/* @var $class ActiveRecord */
$class = $this->modelClass;
if ($this->indexBy === null) {
foreach ($rows as $row) {
$model = $class::instantiate($row);
$modelClass = get_class($model);
$modelClass::populateRecord($model, $row);
$models[] = $model;
}
} else {
foreach ($rows as $row) {
$model = $class::instantiate($row);
$modelClass = get_class($model);
$modelClass::populateRecord($model, $row);
if (is_string($this->indexBy)) {
$key = $model->{$this->indexBy};
} else {
$key = call_user_func($this->indexBy, $model);
}
$models[$key] = $model;
}
}
}
return $models;
} | [
"private",
"function",
"createModels",
"(",
"$",
"rows",
")",
"{",
"$",
"models",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"asArray",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"indexBy",
"===",
"null",
")",
"{",
"return",
"$",
"rows",
";",
"}",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"row",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"this",
"->",
"indexBy",
")",
")",
"{",
"$",
"key",
"=",
"isset",
"(",
"$",
"row",
"[",
"'fields'",
"]",
"[",
"$",
"this",
"->",
"indexBy",
"]",
")",
"?",
"reset",
"(",
"$",
"row",
"[",
"'fields'",
"]",
"[",
"$",
"this",
"->",
"indexBy",
"]",
")",
":",
"$",
"row",
"[",
"'_source'",
"]",
"[",
"$",
"this",
"->",
"indexBy",
"]",
";",
"}",
"else",
"{",
"$",
"key",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"indexBy",
",",
"$",
"row",
")",
";",
"}",
"$",
"models",
"[",
"$",
"key",
"]",
"=",
"$",
"row",
";",
"}",
"}",
"else",
"{",
"/* @var $class ActiveRecord */",
"$",
"class",
"=",
"$",
"this",
"->",
"modelClass",
";",
"if",
"(",
"$",
"this",
"->",
"indexBy",
"===",
"null",
")",
"{",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"row",
")",
"{",
"$",
"model",
"=",
"$",
"class",
"::",
"instantiate",
"(",
"$",
"row",
")",
";",
"$",
"modelClass",
"=",
"get_class",
"(",
"$",
"model",
")",
";",
"$",
"modelClass",
"::",
"populateRecord",
"(",
"$",
"model",
",",
"$",
"row",
")",
";",
"$",
"models",
"[",
"]",
"=",
"$",
"model",
";",
"}",
"}",
"else",
"{",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"row",
")",
"{",
"$",
"model",
"=",
"$",
"class",
"::",
"instantiate",
"(",
"$",
"row",
")",
";",
"$",
"modelClass",
"=",
"get_class",
"(",
"$",
"model",
")",
";",
"$",
"modelClass",
"::",
"populateRecord",
"(",
"$",
"model",
",",
"$",
"row",
")",
";",
"if",
"(",
"is_string",
"(",
"$",
"this",
"->",
"indexBy",
")",
")",
"{",
"$",
"key",
"=",
"$",
"model",
"->",
"{",
"$",
"this",
"->",
"indexBy",
"}",
";",
"}",
"else",
"{",
"$",
"key",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"indexBy",
",",
"$",
"model",
")",
";",
"}",
"$",
"models",
"[",
"$",
"key",
"]",
"=",
"$",
"model",
";",
"}",
"}",
"}",
"return",
"$",
"models",
";",
"}"
] | Converts found rows into model instances
@param array $rows
@return array|ActiveRecord[]
@since 2.0.4 | [
"Converts",
"found",
"rows",
"into",
"model",
"instances"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveQuery.php#L174-L215 | train |
yiisoft/yii2-elasticsearch | ActiveFixture.php | ActiveFixture.resetIndex | protected function resetIndex()
{
$this->db->createCommand([
'index' => $this->index,
'type' => $this->type,
'queryParts' => ['query' => ['match_all' => new \stdClass()]],
])->deleteByQuery();
} | php | protected function resetIndex()
{
$this->db->createCommand([
'index' => $this->index,
'type' => $this->type,
'queryParts' => ['query' => ['match_all' => new \stdClass()]],
])->deleteByQuery();
} | [
"protected",
"function",
"resetIndex",
"(",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"createCommand",
"(",
"[",
"'index'",
"=>",
"$",
"this",
"->",
"index",
",",
"'type'",
"=>",
"$",
"this",
"->",
"type",
",",
"'queryParts'",
"=>",
"[",
"'query'",
"=>",
"[",
"'match_all'",
"=>",
"new",
"\\",
"stdClass",
"(",
")",
"]",
"]",
",",
"]",
")",
"->",
"deleteByQuery",
"(",
")",
";",
"}"
] | Removes all existing data from the specified index and type.
This method is called before populating fixture data into the index associated with this fixture. | [
"Removes",
"all",
"existing",
"data",
"from",
"the",
"specified",
"index",
"and",
"type",
".",
"This",
"method",
"is",
"called",
"before",
"populating",
"fixture",
"data",
"into",
"the",
"index",
"associated",
"with",
"this",
"fixture",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveFixture.php#L150-L157 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.populate | public function populate($rows)
{
if ($this->indexBy === null) {
return $rows;
}
$models = [];
foreach ($rows as $key => $row) {
if ($this->indexBy !== null) {
if (is_string($this->indexBy)) {
$key = isset($row['fields'][$this->indexBy]) ? reset($row['fields'][$this->indexBy]) : $row['_source'][$this->indexBy];
} else {
$key = call_user_func($this->indexBy, $row);
}
}
$models[$key] = $row;
}
return $models;
} | php | public function populate($rows)
{
if ($this->indexBy === null) {
return $rows;
}
$models = [];
foreach ($rows as $key => $row) {
if ($this->indexBy !== null) {
if (is_string($this->indexBy)) {
$key = isset($row['fields'][$this->indexBy]) ? reset($row['fields'][$this->indexBy]) : $row['_source'][$this->indexBy];
} else {
$key = call_user_func($this->indexBy, $row);
}
}
$models[$key] = $row;
}
return $models;
} | [
"public",
"function",
"populate",
"(",
"$",
"rows",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"indexBy",
"===",
"null",
")",
"{",
"return",
"$",
"rows",
";",
"}",
"$",
"models",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"key",
"=>",
"$",
"row",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"indexBy",
"!==",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"this",
"->",
"indexBy",
")",
")",
"{",
"$",
"key",
"=",
"isset",
"(",
"$",
"row",
"[",
"'fields'",
"]",
"[",
"$",
"this",
"->",
"indexBy",
"]",
")",
"?",
"reset",
"(",
"$",
"row",
"[",
"'fields'",
"]",
"[",
"$",
"this",
"->",
"indexBy",
"]",
")",
":",
"$",
"row",
"[",
"'_source'",
"]",
"[",
"$",
"this",
"->",
"indexBy",
"]",
";",
"}",
"else",
"{",
"$",
"key",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"indexBy",
",",
"$",
"row",
")",
";",
"}",
"}",
"$",
"models",
"[",
"$",
"key",
"]",
"=",
"$",
"row",
";",
"}",
"return",
"$",
"models",
";",
"}"
] | Converts the raw query results into the format as specified by this query.
This method is internally used to convert the data fetched from database
into the format as required by this query.
@param array $rows the raw query result from database
@return array the converted query result
@since 2.0.4 | [
"Converts",
"the",
"raw",
"query",
"results",
"into",
"the",
"format",
"as",
"specified",
"by",
"this",
"query",
".",
"This",
"method",
"is",
"internally",
"used",
"to",
"convert",
"the",
"data",
"fetched",
"from",
"database",
"into",
"the",
"format",
"as",
"required",
"by",
"this",
"query",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L239-L256 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.delete | public function delete($db = null, $options = [])
{
if ($this->emulateExecution) {
return [];
}
return $this->createCommand($db)->deleteByQuery($options);
} | php | public function delete($db = null, $options = [])
{
if ($this->emulateExecution) {
return [];
}
return $this->createCommand($db)->deleteByQuery($options);
} | [
"public",
"function",
"delete",
"(",
"$",
"db",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"emulateExecution",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"createCommand",
"(",
"$",
"db",
")",
"->",
"deleteByQuery",
"(",
"$",
"options",
")",
";",
"}"
] | Executes the query and deletes all matching documents.
Everything except query and filter will be ignored.
@param Connection $db the database connection used to execute the query.
If this parameter is not given, the `elasticsearch` application component will be used.
@param array $options The options given with this query.
@return array the query results. | [
"Executes",
"the",
"query",
"and",
"deletes",
"all",
"matching",
"documents",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L328-L334 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.scalar | public function scalar($field, $db = null)
{
if ($this->emulateExecution) {
return null;
}
$record = self::one($db);
if ($record !== false) {
if ($field === '_id') {
return $record['_id'];
} elseif (isset($record['_source'][$field])) {
return $record['_source'][$field];
} elseif (isset($record['fields'][$field])) {
return count($record['fields'][$field]) == 1 ? reset($record['fields'][$field]) : $record['fields'][$field];
}
}
return null;
} | php | public function scalar($field, $db = null)
{
if ($this->emulateExecution) {
return null;
}
$record = self::one($db);
if ($record !== false) {
if ($field === '_id') {
return $record['_id'];
} elseif (isset($record['_source'][$field])) {
return $record['_source'][$field];
} elseif (isset($record['fields'][$field])) {
return count($record['fields'][$field]) == 1 ? reset($record['fields'][$field]) : $record['fields'][$field];
}
}
return null;
} | [
"public",
"function",
"scalar",
"(",
"$",
"field",
",",
"$",
"db",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"emulateExecution",
")",
"{",
"return",
"null",
";",
"}",
"$",
"record",
"=",
"self",
"::",
"one",
"(",
"$",
"db",
")",
";",
"if",
"(",
"$",
"record",
"!==",
"false",
")",
"{",
"if",
"(",
"$",
"field",
"===",
"'_id'",
")",
"{",
"return",
"$",
"record",
"[",
"'_id'",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"record",
"[",
"'_source'",
"]",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"$",
"record",
"[",
"'_source'",
"]",
"[",
"$",
"field",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"record",
"[",
"'fields'",
"]",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"count",
"(",
"$",
"record",
"[",
"'fields'",
"]",
"[",
"$",
"field",
"]",
")",
"==",
"1",
"?",
"reset",
"(",
"$",
"record",
"[",
"'fields'",
"]",
"[",
"$",
"field",
"]",
")",
":",
"$",
"record",
"[",
"'fields'",
"]",
"[",
"$",
"field",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Returns the query result as a scalar value.
The value returned will be the specified field in the first document of the query results.
@param string $field name of the attribute to select
@param Connection $db the database connection used to execute the query.
If this parameter is not given, the `elasticsearch` application component will be used.
@return string the value of the specified attribute in the first record of the query result.
Null is returned if the query result is empty or the field does not exist. | [
"Returns",
"the",
"query",
"result",
"as",
"a",
"scalar",
"value",
".",
"The",
"value",
"returned",
"will",
"be",
"the",
"specified",
"field",
"in",
"the",
"first",
"document",
"of",
"the",
"query",
"results",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L345-L361 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.column | public function column($field, $db = null)
{
if ($this->emulateExecution) {
return [];
}
$command = $this->createCommand($db);
$command->queryParts['_source'] = [$field];
$result = $command->search();
if (empty($result['hits']['hits'])) {
return [];
}
$column = [];
foreach ($result['hits']['hits'] as $row) {
if (isset($row['fields'][$field])) {
$column[] = $row['fields'][$field];
} elseif (isset($row['_source'][$field])) {
$column[] = $row['_source'][$field];
} else {
$column[] = null;
}
}
return $column;
} | php | public function column($field, $db = null)
{
if ($this->emulateExecution) {
return [];
}
$command = $this->createCommand($db);
$command->queryParts['_source'] = [$field];
$result = $command->search();
if (empty($result['hits']['hits'])) {
return [];
}
$column = [];
foreach ($result['hits']['hits'] as $row) {
if (isset($row['fields'][$field])) {
$column[] = $row['fields'][$field];
} elseif (isset($row['_source'][$field])) {
$column[] = $row['_source'][$field];
} else {
$column[] = null;
}
}
return $column;
} | [
"public",
"function",
"column",
"(",
"$",
"field",
",",
"$",
"db",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"emulateExecution",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"command",
"=",
"$",
"this",
"->",
"createCommand",
"(",
"$",
"db",
")",
";",
"$",
"command",
"->",
"queryParts",
"[",
"'_source'",
"]",
"=",
"[",
"$",
"field",
"]",
";",
"$",
"result",
"=",
"$",
"command",
"->",
"search",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"result",
"[",
"'hits'",
"]",
"[",
"'hits'",
"]",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"column",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"result",
"[",
"'hits'",
"]",
"[",
"'hits'",
"]",
"as",
"$",
"row",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"row",
"[",
"'fields'",
"]",
"[",
"$",
"field",
"]",
")",
")",
"{",
"$",
"column",
"[",
"]",
"=",
"$",
"row",
"[",
"'fields'",
"]",
"[",
"$",
"field",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"row",
"[",
"'_source'",
"]",
"[",
"$",
"field",
"]",
")",
")",
"{",
"$",
"column",
"[",
"]",
"=",
"$",
"row",
"[",
"'_source'",
"]",
"[",
"$",
"field",
"]",
";",
"}",
"else",
"{",
"$",
"column",
"[",
"]",
"=",
"null",
";",
"}",
"}",
"return",
"$",
"column",
";",
"}"
] | Executes the query and returns the first column of the result.
@param string $field the field to query over
@param Connection $db the database connection used to execute the query.
If this parameter is not given, the `elasticsearch` application component will be used.
@return array the first column of the query result. An empty array is returned if the query results in nothing. | [
"Executes",
"the",
"query",
"and",
"returns",
"the",
"first",
"column",
"of",
"the",
"result",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L370-L392 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.from | public function from($index, $type = null)
{
$this->index = $index;
$this->type = $type;
return $this;
} | php | public function from($index, $type = null)
{
$this->index = $index;
$this->type = $type;
return $this;
} | [
"public",
"function",
"from",
"(",
"$",
"index",
",",
"$",
"type",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"index",
"=",
"$",
"index",
";",
"$",
"this",
"->",
"type",
"=",
"$",
"type",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the index and type to retrieve documents from.
@param string|array $index The index to retrieve data from. This can be a string representing a single index
or a an array of multiple indexes. If this is `null` it means that all indexes are being queried.
@param string|array $type The type to retrieve data from. This can be a string representing a single type
or a an array of multiple types. If this is `null` it means that all types are being queried.
@return $this the query object itself
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html#search-multi-index-type | [
"Sets",
"the",
"index",
"and",
"type",
"to",
"retrieve",
"documents",
"from",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L611-L616 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.fields | public function fields($fields)
{
if (is_array($fields) || $fields === null) {
$this->fields = $fields;
} else {
$this->fields = func_get_args();
}
return $this;
} | php | public function fields($fields)
{
if (is_array($fields) || $fields === null) {
$this->fields = $fields;
} else {
$this->fields = func_get_args();
}
return $this;
} | [
"public",
"function",
"fields",
"(",
"$",
"fields",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"fields",
")",
"||",
"$",
"fields",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"fields",
"=",
"$",
"fields",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"fields",
"=",
"func_get_args",
"(",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Sets the fields to retrieve from the documents.
@param array $fields the fields to be selected.
@return $this the query object itself
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-fields.html | [
"Sets",
"the",
"fields",
"to",
"retrieve",
"from",
"the",
"documents",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L624-L632 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.source | public function source($source)
{
if (is_array($source) || $source === null) {
$this->source = $source;
} else {
$this->source = func_get_args();
}
return $this;
} | php | public function source($source)
{
if (is_array($source) || $source === null) {
$this->source = $source;
} else {
$this->source = func_get_args();
}
return $this;
} | [
"public",
"function",
"source",
"(",
"$",
"source",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"source",
")",
"||",
"$",
"source",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"source",
"=",
"$",
"source",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"source",
"=",
"func_get_args",
"(",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Sets the source filtering, specifying how the `_source` field of the document should be returned.
@param array $source the source patterns to be selected.
@return $this the query object itself
@see http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html | [
"Sets",
"the",
"source",
"filtering",
"specifying",
"how",
"the",
"_source",
"field",
"of",
"the",
"document",
"should",
"be",
"returned",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L640-L648 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.options | public function options($options)
{
if (!is_array($options)) {
throw new InvalidParamException('Array parameter expected, ' . gettype($options) . ' received.');
}
$this->options = $options;
return $this;
} | php | public function options($options)
{
if (!is_array($options)) {
throw new InvalidParamException('Array parameter expected, ' . gettype($options) . ' received.');
}
$this->options = $options;
return $this;
} | [
"public",
"function",
"options",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"options",
")",
")",
"{",
"throw",
"new",
"InvalidParamException",
"(",
"'Array parameter expected, '",
".",
"gettype",
"(",
"$",
"options",
")",
".",
"' received.'",
")",
";",
"}",
"$",
"this",
"->",
"options",
"=",
"$",
"options",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the options to be passed to the command created by this query.
@param array $options the options to be set.
@return $this the query object itself
@throws InvalidParamException if $options is not an array
@see Command::$options
@since 2.0.4 | [
"Sets",
"the",
"options",
"to",
"be",
"passed",
"to",
"the",
"command",
"created",
"by",
"this",
"query",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L683-L691 | train |
yiisoft/yii2-elasticsearch | Query.php | Query.addOptions | public function addOptions($options)
{
if (!is_array($options)) {
throw new InvalidParamException('Array parameter expected, ' . gettype($options) . ' received.');
}
$this->options = array_merge($this->options, $options);
return $this;
} | php | public function addOptions($options)
{
if (!is_array($options)) {
throw new InvalidParamException('Array parameter expected, ' . gettype($options) . ' received.');
}
$this->options = array_merge($this->options, $options);
return $this;
} | [
"public",
"function",
"addOptions",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"options",
")",
")",
"{",
"throw",
"new",
"InvalidParamException",
"(",
"'Array parameter expected, '",
".",
"gettype",
"(",
"$",
"options",
")",
".",
"' received.'",
")",
";",
"}",
"$",
"this",
"->",
"options",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"options",
",",
"$",
"options",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Adds more options, overwriting existing options.
@param array $options the options to be added.
@return $this the query object itself
@throws InvalidParamException if $options is not an array
@see options()
@since 2.0.4 | [
"Adds",
"more",
"options",
"overwriting",
"existing",
"options",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/Query.php#L701-L709 | train |
yiisoft/yii2-elasticsearch | QueryBuilder.php | QueryBuilder.buildOrderBy | public function buildOrderBy($columns)
{
if (empty($columns)) {
return [];
}
$orders = [];
foreach ($columns as $name => $direction) {
if (is_string($direction)) {
$column = $direction;
$direction = SORT_ASC;
} else {
$column = $name;
}
if ($column == '_id') {
$column = '_uid';
}
// allow elasticsearch extended syntax as described in http://www.elastic.co/guide/en/elasticsearch/guide/master/_sorting.html
if (is_array($direction)) {
$orders[] = [$column => $direction];
} else {
$orders[] = [$column => ($direction === SORT_DESC ? 'desc' : 'asc')];
}
}
return $orders;
} | php | public function buildOrderBy($columns)
{
if (empty($columns)) {
return [];
}
$orders = [];
foreach ($columns as $name => $direction) {
if (is_string($direction)) {
$column = $direction;
$direction = SORT_ASC;
} else {
$column = $name;
}
if ($column == '_id') {
$column = '_uid';
}
// allow elasticsearch extended syntax as described in http://www.elastic.co/guide/en/elasticsearch/guide/master/_sorting.html
if (is_array($direction)) {
$orders[] = [$column => $direction];
} else {
$orders[] = [$column => ($direction === SORT_DESC ? 'desc' : 'asc')];
}
}
return $orders;
} | [
"public",
"function",
"buildOrderBy",
"(",
"$",
"columns",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"columns",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"orders",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"name",
"=>",
"$",
"direction",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"direction",
")",
")",
"{",
"$",
"column",
"=",
"$",
"direction",
";",
"$",
"direction",
"=",
"SORT_ASC",
";",
"}",
"else",
"{",
"$",
"column",
"=",
"$",
"name",
";",
"}",
"if",
"(",
"$",
"column",
"==",
"'_id'",
")",
"{",
"$",
"column",
"=",
"'_uid'",
";",
"}",
"// allow elasticsearch extended syntax as described in http://www.elastic.co/guide/en/elasticsearch/guide/master/_sorting.html",
"if",
"(",
"is_array",
"(",
"$",
"direction",
")",
")",
"{",
"$",
"orders",
"[",
"]",
"=",
"[",
"$",
"column",
"=>",
"$",
"direction",
"]",
";",
"}",
"else",
"{",
"$",
"orders",
"[",
"]",
"=",
"[",
"$",
"column",
"=>",
"(",
"$",
"direction",
"===",
"SORT_DESC",
"?",
"'desc'",
":",
"'asc'",
")",
"]",
";",
"}",
"}",
"return",
"$",
"orders",
";",
"}"
] | adds order by condition to the query | [
"adds",
"order",
"by",
"condition",
"to",
"the",
"query"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/QueryBuilder.php#L145-L171 | train |
yiisoft/yii2-elasticsearch | ElasticsearchTarget.php | ElasticsearchTarget.prepareMessage | public function prepareMessage($message)
{
list($text, $level, $category, $timestamp) = $message;
$result = [
'category' => $category,
'level' => Logger::getLevelName($level),
'@timestamp' => date('c', $timestamp),
];
if (isset($message[4])) {
$result['trace'] = $message[4];
}
//Exceptions get parsed into an array, text and arrays are passed as is, other types are var_dumped
if ($text instanceof \Exception) {
//convert exception to array for easier analysis
$result['message'] = [
'message' => $text->getMessage(),
'file' => $text->getFile(),
'line' => $text->getLine(),
'trace' => $text->getTraceAsString(),
];
} elseif (is_array($text) || is_string($text)) {
$result['message'] = $text;
} else {
$result['message'] = VarDumper::export($text);
}
if ($this->includeContext) {
$result['context'] = $this->getContextMessage();
}
$message = implode("\n", [
Json::encode([
'index' => new \stdClass()
]),
Json::encode($result)
]);
return $message;
} | php | public function prepareMessage($message)
{
list($text, $level, $category, $timestamp) = $message;
$result = [
'category' => $category,
'level' => Logger::getLevelName($level),
'@timestamp' => date('c', $timestamp),
];
if (isset($message[4])) {
$result['trace'] = $message[4];
}
//Exceptions get parsed into an array, text and arrays are passed as is, other types are var_dumped
if ($text instanceof \Exception) {
//convert exception to array for easier analysis
$result['message'] = [
'message' => $text->getMessage(),
'file' => $text->getFile(),
'line' => $text->getLine(),
'trace' => $text->getTraceAsString(),
];
} elseif (is_array($text) || is_string($text)) {
$result['message'] = $text;
} else {
$result['message'] = VarDumper::export($text);
}
if ($this->includeContext) {
$result['context'] = $this->getContextMessage();
}
$message = implode("\n", [
Json::encode([
'index' => new \stdClass()
]),
Json::encode($result)
]);
return $message;
} | [
"public",
"function",
"prepareMessage",
"(",
"$",
"message",
")",
"{",
"list",
"(",
"$",
"text",
",",
"$",
"level",
",",
"$",
"category",
",",
"$",
"timestamp",
")",
"=",
"$",
"message",
";",
"$",
"result",
"=",
"[",
"'category'",
"=>",
"$",
"category",
",",
"'level'",
"=>",
"Logger",
"::",
"getLevelName",
"(",
"$",
"level",
")",
",",
"'@timestamp'",
"=>",
"date",
"(",
"'c'",
",",
"$",
"timestamp",
")",
",",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"message",
"[",
"4",
"]",
")",
")",
"{",
"$",
"result",
"[",
"'trace'",
"]",
"=",
"$",
"message",
"[",
"4",
"]",
";",
"}",
"//Exceptions get parsed into an array, text and arrays are passed as is, other types are var_dumped",
"if",
"(",
"$",
"text",
"instanceof",
"\\",
"Exception",
")",
"{",
"//convert exception to array for easier analysis",
"$",
"result",
"[",
"'message'",
"]",
"=",
"[",
"'message'",
"=>",
"$",
"text",
"->",
"getMessage",
"(",
")",
",",
"'file'",
"=>",
"$",
"text",
"->",
"getFile",
"(",
")",
",",
"'line'",
"=>",
"$",
"text",
"->",
"getLine",
"(",
")",
",",
"'trace'",
"=>",
"$",
"text",
"->",
"getTraceAsString",
"(",
")",
",",
"]",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"text",
")",
"||",
"is_string",
"(",
"$",
"text",
")",
")",
"{",
"$",
"result",
"[",
"'message'",
"]",
"=",
"$",
"text",
";",
"}",
"else",
"{",
"$",
"result",
"[",
"'message'",
"]",
"=",
"VarDumper",
"::",
"export",
"(",
"$",
"text",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"includeContext",
")",
"{",
"$",
"result",
"[",
"'context'",
"]",
"=",
"$",
"this",
"->",
"getContextMessage",
"(",
")",
";",
"}",
"$",
"message",
"=",
"implode",
"(",
"\"\\n\"",
",",
"[",
"Json",
"::",
"encode",
"(",
"[",
"'index'",
"=>",
"new",
"\\",
"stdClass",
"(",
")",
"]",
")",
",",
"Json",
"::",
"encode",
"(",
"$",
"result",
")",
"]",
")",
";",
"return",
"$",
"message",
";",
"}"
] | Prepares a log message.
@param array $message The log message to be formatted.
@return string | [
"Prepares",
"a",
"log",
"message",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ElasticsearchTarget.php#L135-L176 | train |
yiisoft/yii2-elasticsearch | ActiveDataProvider.php | ActiveDataProvider.getAggregation | public function getAggregation($name)
{
$aggregations = $this->getAggregations();
if (!isset($aggregations[$name])) {
throw new InvalidCallException("Aggregation '{$name}' does not present.");
}
return $aggregations[$name];
} | php | public function getAggregation($name)
{
$aggregations = $this->getAggregations();
if (!isset($aggregations[$name])) {
throw new InvalidCallException("Aggregation '{$name}' does not present.");
}
return $aggregations[$name];
} | [
"public",
"function",
"getAggregation",
"(",
"$",
"name",
")",
"{",
"$",
"aggregations",
"=",
"$",
"this",
"->",
"getAggregations",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"aggregations",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidCallException",
"(",
"\"Aggregation '{$name}' does not present.\"",
")",
";",
"}",
"return",
"$",
"aggregations",
"[",
"$",
"name",
"]",
";",
"}"
] | Returns results of the specified aggregation.
@param string $name aggregation name.
@return array aggregation results.
@throws InvalidCallException if requested aggregation does not present in query results. | [
"Returns",
"results",
"of",
"the",
"specified",
"aggregation",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveDataProvider.php#L70-L77 | train |
yiisoft/yii2-elasticsearch | ActiveRecord.php | ActiveRecord.filterCondition | private static function filterCondition($condition)
{
foreach($condition as $k => $v) {
if (is_array($v)) {
$condition[$k] = array_values($v);
foreach($v as $vv) {
if (is_array($vv)) {
throw new InvalidArgumentException('Nested arrays are not allowed in condition for findAll() and findOne().');
}
}
}
}
return $condition;
} | php | private static function filterCondition($condition)
{
foreach($condition as $k => $v) {
if (is_array($v)) {
$condition[$k] = array_values($v);
foreach($v as $vv) {
if (is_array($vv)) {
throw new InvalidArgumentException('Nested arrays are not allowed in condition for findAll() and findOne().');
}
}
}
}
return $condition;
} | [
"private",
"static",
"function",
"filterCondition",
"(",
"$",
"condition",
")",
"{",
"foreach",
"(",
"$",
"condition",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"v",
")",
")",
"{",
"$",
"condition",
"[",
"$",
"k",
"]",
"=",
"array_values",
"(",
"$",
"v",
")",
";",
"foreach",
"(",
"$",
"v",
"as",
"$",
"vv",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"vv",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Nested arrays are not allowed in condition for findAll() and findOne().'",
")",
";",
"}",
"}",
"}",
"}",
"return",
"$",
"condition",
";",
"}"
] | Filter out condition parts that are array valued, to prevent building arbitrary conditions.
@param array $condition | [
"Filter",
"out",
"condition",
"parts",
"that",
"are",
"array",
"valued",
"to",
"prevent",
"building",
"arbitrary",
"conditions",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveRecord.php#L119-L132 | train |
yiisoft/yii2-elasticsearch | ActiveRecord.php | ActiveRecord.get | public static function get($primaryKey, $options = [])
{
if ($primaryKey === null) {
return null;
}
$command = static::getDb()->createCommand();
$result = $command->get(static::index(), static::type(), $primaryKey, $options);
if ($result['found']) {
$model = static::instantiate($result);
static::populateRecord($model, $result);
$model->afterFind();
return $model;
}
return null;
} | php | public static function get($primaryKey, $options = [])
{
if ($primaryKey === null) {
return null;
}
$command = static::getDb()->createCommand();
$result = $command->get(static::index(), static::type(), $primaryKey, $options);
if ($result['found']) {
$model = static::instantiate($result);
static::populateRecord($model, $result);
$model->afterFind();
return $model;
}
return null;
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"primaryKey",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"primaryKey",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"$",
"command",
"=",
"static",
"::",
"getDb",
"(",
")",
"->",
"createCommand",
"(",
")",
";",
"$",
"result",
"=",
"$",
"command",
"->",
"get",
"(",
"static",
"::",
"index",
"(",
")",
",",
"static",
"::",
"type",
"(",
")",
",",
"$",
"primaryKey",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"result",
"[",
"'found'",
"]",
")",
"{",
"$",
"model",
"=",
"static",
"::",
"instantiate",
"(",
"$",
"result",
")",
";",
"static",
"::",
"populateRecord",
"(",
"$",
"model",
",",
"$",
"result",
")",
";",
"$",
"model",
"->",
"afterFind",
"(",
")",
";",
"return",
"$",
"model",
";",
"}",
"return",
"null",
";",
"}"
] | Gets a record by its primary key.
@param mixed $primaryKey the primaryKey value
@param array $options options given in this parameter are passed to elasticsearch
as request URI parameters.
Please refer to the [elasticsearch documentation](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html)
for more details on these options.
@return static|null The record instance or null if it was not found. | [
"Gets",
"a",
"record",
"by",
"its",
"primary",
"key",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveRecord.php#L144-L160 | train |
yiisoft/yii2-elasticsearch | ActiveRecord.php | ActiveRecord.mget | public static function mget(array $primaryKeys, $options = [])
{
if (empty($primaryKeys)) {
return [];
}
if (count($primaryKeys) === 1) {
$model = static::get(reset($primaryKeys));
return $model === null ? [] : [$model];
}
$command = static::getDb()->createCommand();
$result = $command->mget(static::index(), static::type(), $primaryKeys, $options);
$models = [];
foreach ($result['docs'] as $doc) {
if ($doc['found']) {
$model = static::instantiate($doc);
static::populateRecord($model, $doc);
$model->afterFind();
$models[] = $model;
}
}
return $models;
} | php | public static function mget(array $primaryKeys, $options = [])
{
if (empty($primaryKeys)) {
return [];
}
if (count($primaryKeys) === 1) {
$model = static::get(reset($primaryKeys));
return $model === null ? [] : [$model];
}
$command = static::getDb()->createCommand();
$result = $command->mget(static::index(), static::type(), $primaryKeys, $options);
$models = [];
foreach ($result['docs'] as $doc) {
if ($doc['found']) {
$model = static::instantiate($doc);
static::populateRecord($model, $doc);
$model->afterFind();
$models[] = $model;
}
}
return $models;
} | [
"public",
"static",
"function",
"mget",
"(",
"array",
"$",
"primaryKeys",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"primaryKeys",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"primaryKeys",
")",
"===",
"1",
")",
"{",
"$",
"model",
"=",
"static",
"::",
"get",
"(",
"reset",
"(",
"$",
"primaryKeys",
")",
")",
";",
"return",
"$",
"model",
"===",
"null",
"?",
"[",
"]",
":",
"[",
"$",
"model",
"]",
";",
"}",
"$",
"command",
"=",
"static",
"::",
"getDb",
"(",
")",
"->",
"createCommand",
"(",
")",
";",
"$",
"result",
"=",
"$",
"command",
"->",
"mget",
"(",
"static",
"::",
"index",
"(",
")",
",",
"static",
"::",
"type",
"(",
")",
",",
"$",
"primaryKeys",
",",
"$",
"options",
")",
";",
"$",
"models",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"result",
"[",
"'docs'",
"]",
"as",
"$",
"doc",
")",
"{",
"if",
"(",
"$",
"doc",
"[",
"'found'",
"]",
")",
"{",
"$",
"model",
"=",
"static",
"::",
"instantiate",
"(",
"$",
"doc",
")",
";",
"static",
"::",
"populateRecord",
"(",
"$",
"model",
",",
"$",
"doc",
")",
";",
"$",
"model",
"->",
"afterFind",
"(",
")",
";",
"$",
"models",
"[",
"]",
"=",
"$",
"model",
";",
"}",
"}",
"return",
"$",
"models",
";",
"}"
] | Gets a list of records by its primary keys.
@param array $primaryKeys an array of primaryKey values
@param array $options options given in this parameter are passed to elasticsearch
as request URI parameters.
Please refer to the [elasticsearch documentation](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html)
for more details on these options.
@return array The record instances, or empty array if nothing was found | [
"Gets",
"a",
"list",
"of",
"records",
"by",
"its",
"primary",
"keys",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveRecord.php#L173-L196 | train |
yiisoft/yii2-elasticsearch | ActiveRecord.php | ActiveRecord.insert | public function insert($runValidation = true, $attributes = null, $options = ['op_type' => 'create'])
{
if ($runValidation && !$this->validate($attributes)) {
return false;
}
if (!$this->beforeSave(true)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
$response = static::getDb()->createCommand()->insert(
static::index(),
static::type(),
$values,
$this->getPrimaryKey(),
$options
);
$pk = static::primaryKey()[0];
$this->$pk = $response['_id'];
if ($pk != '_id') {
$values[$pk] = $response['_id'];
}
$this->_version = $response['_version'];
$this->_score = null;
$changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes);
return true;
} | php | public function insert($runValidation = true, $attributes = null, $options = ['op_type' => 'create'])
{
if ($runValidation && !$this->validate($attributes)) {
return false;
}
if (!$this->beforeSave(true)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
$response = static::getDb()->createCommand()->insert(
static::index(),
static::type(),
$values,
$this->getPrimaryKey(),
$options
);
$pk = static::primaryKey()[0];
$this->$pk = $response['_id'];
if ($pk != '_id') {
$values[$pk] = $response['_id'];
}
$this->_version = $response['_version'];
$this->_score = null;
$changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes);
return true;
} | [
"public",
"function",
"insert",
"(",
"$",
"runValidation",
"=",
"true",
",",
"$",
"attributes",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"'op_type'",
"=>",
"'create'",
"]",
")",
"{",
"if",
"(",
"$",
"runValidation",
"&&",
"!",
"$",
"this",
"->",
"validate",
"(",
"$",
"attributes",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"beforeSave",
"(",
"true",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"values",
"=",
"$",
"this",
"->",
"getDirtyAttributes",
"(",
"$",
"attributes",
")",
";",
"$",
"response",
"=",
"static",
"::",
"getDb",
"(",
")",
"->",
"createCommand",
"(",
")",
"->",
"insert",
"(",
"static",
"::",
"index",
"(",
")",
",",
"static",
"::",
"type",
"(",
")",
",",
"$",
"values",
",",
"$",
"this",
"->",
"getPrimaryKey",
"(",
")",
",",
"$",
"options",
")",
";",
"$",
"pk",
"=",
"static",
"::",
"primaryKey",
"(",
")",
"[",
"0",
"]",
";",
"$",
"this",
"->",
"$",
"pk",
"=",
"$",
"response",
"[",
"'_id'",
"]",
";",
"if",
"(",
"$",
"pk",
"!=",
"'_id'",
")",
"{",
"$",
"values",
"[",
"$",
"pk",
"]",
"=",
"$",
"response",
"[",
"'_id'",
"]",
";",
"}",
"$",
"this",
"->",
"_version",
"=",
"$",
"response",
"[",
"'_version'",
"]",
";",
"$",
"this",
"->",
"_score",
"=",
"null",
";",
"$",
"changedAttributes",
"=",
"array_fill_keys",
"(",
"array_keys",
"(",
"$",
"values",
")",
",",
"null",
")",
";",
"$",
"this",
"->",
"setOldAttributes",
"(",
"$",
"values",
")",
";",
"$",
"this",
"->",
"afterSave",
"(",
"true",
",",
"$",
"changedAttributes",
")",
";",
"return",
"true",
";",
"}"
] | Inserts a document into the associated index using the attribute values of this record.
This method performs the following steps in order:
1. call [[beforeValidate()]] when `$runValidation` is true. If validation
fails, it will skip the rest of the steps;
2. call [[afterValidate()]] when `$runValidation` is true.
3. call [[beforeSave()]]. If the method returns false, it will skip the
rest of the steps;
4. insert the record into database. If this fails, it will skip the rest of the steps;
5. call [[afterSave()]];
In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
[[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
will be raised by the corresponding methods.
Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
If the [[primaryKey|primary key]] is not set (null) during insertion,
it will be populated with a
[randomly generated value](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#_automatic_id_generation)
after insertion.
For example, to insert a customer record:
~~~
$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
~~~
@param bool $runValidation whether to perform validation before saving the record.
If the validation fails, the record will not be inserted into the database.
@param array $attributes list of attributes that need to be saved. Defaults to null,
meaning all attributes will be saved.
@param array $options options given in this parameter are passed to elasticsearch
as request URI parameters. These are among others:
- `routing` define shard placement of this record.
- `parent` by giving the primaryKey of another record this defines a parent-child relation
- `timestamp` specifies the timestamp to store along with the document. Default is indexing time.
Please refer to the [elasticsearch documentation](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html)
for more details on these options.
By default the `op_type` is set to `create`.
@return bool whether the attributes are valid and the record is inserted successfully. | [
"Inserts",
"a",
"document",
"into",
"the",
"associated",
"index",
"using",
"the",
"attribute",
"values",
"of",
"this",
"record",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveRecord.php#L453-L484 | train |
yiisoft/yii2-elasticsearch | ActiveRecord.php | ActiveRecord.updateAllCounters | public static function updateAllCounters($counters, $condition = [])
{
$primaryKeys = static::primaryKeysByCondition($condition);
if (empty($primaryKeys) || empty($counters)) {
return 0;
}
$bulkCommand = static::getDb()->createBulkCommand([
"index" => static::index(),
"type" => static::type(),
]);
foreach ($primaryKeys as $pk) {
$script = '';
foreach ($counters as $counter => $value) {
$script .= "ctx._source.{$counter} += {$counter};\n";
}
$bulkCommand->addAction(["update" => ["_id" => $pk]], ["script" => $script, "params" => $counters, "lang" => "groovy"]);
}
$response = $bulkCommand->execute();
$n = 0;
$errors = [];
foreach ($response['items'] as $item) {
if (isset($item['update']['status']) && $item['update']['status'] == 200) {
$n++;
} else {
$errors[] = $item['update'];
}
}
if (!empty($errors) || isset($response['errors']) && $response['errors']) {
throw new Exception(__METHOD__ . ' failed updating records counters.', $errors);
}
return $n;
} | php | public static function updateAllCounters($counters, $condition = [])
{
$primaryKeys = static::primaryKeysByCondition($condition);
if (empty($primaryKeys) || empty($counters)) {
return 0;
}
$bulkCommand = static::getDb()->createBulkCommand([
"index" => static::index(),
"type" => static::type(),
]);
foreach ($primaryKeys as $pk) {
$script = '';
foreach ($counters as $counter => $value) {
$script .= "ctx._source.{$counter} += {$counter};\n";
}
$bulkCommand->addAction(["update" => ["_id" => $pk]], ["script" => $script, "params" => $counters, "lang" => "groovy"]);
}
$response = $bulkCommand->execute();
$n = 0;
$errors = [];
foreach ($response['items'] as $item) {
if (isset($item['update']['status']) && $item['update']['status'] == 200) {
$n++;
} else {
$errors[] = $item['update'];
}
}
if (!empty($errors) || isset($response['errors']) && $response['errors']) {
throw new Exception(__METHOD__ . ' failed updating records counters.', $errors);
}
return $n;
} | [
"public",
"static",
"function",
"updateAllCounters",
"(",
"$",
"counters",
",",
"$",
"condition",
"=",
"[",
"]",
")",
"{",
"$",
"primaryKeys",
"=",
"static",
"::",
"primaryKeysByCondition",
"(",
"$",
"condition",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"primaryKeys",
")",
"||",
"empty",
"(",
"$",
"counters",
")",
")",
"{",
"return",
"0",
";",
"}",
"$",
"bulkCommand",
"=",
"static",
"::",
"getDb",
"(",
")",
"->",
"createBulkCommand",
"(",
"[",
"\"index\"",
"=>",
"static",
"::",
"index",
"(",
")",
",",
"\"type\"",
"=>",
"static",
"::",
"type",
"(",
")",
",",
"]",
")",
";",
"foreach",
"(",
"$",
"primaryKeys",
"as",
"$",
"pk",
")",
"{",
"$",
"script",
"=",
"''",
";",
"foreach",
"(",
"$",
"counters",
"as",
"$",
"counter",
"=>",
"$",
"value",
")",
"{",
"$",
"script",
".=",
"\"ctx._source.{$counter} += {$counter};\\n\"",
";",
"}",
"$",
"bulkCommand",
"->",
"addAction",
"(",
"[",
"\"update\"",
"=>",
"[",
"\"_id\"",
"=>",
"$",
"pk",
"]",
"]",
",",
"[",
"\"script\"",
"=>",
"$",
"script",
",",
"\"params\"",
"=>",
"$",
"counters",
",",
"\"lang\"",
"=>",
"\"groovy\"",
"]",
")",
";",
"}",
"$",
"response",
"=",
"$",
"bulkCommand",
"->",
"execute",
"(",
")",
";",
"$",
"n",
"=",
"0",
";",
"$",
"errors",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"response",
"[",
"'items'",
"]",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"item",
"[",
"'update'",
"]",
"[",
"'status'",
"]",
")",
"&&",
"$",
"item",
"[",
"'update'",
"]",
"[",
"'status'",
"]",
"==",
"200",
")",
"{",
"$",
"n",
"++",
";",
"}",
"else",
"{",
"$",
"errors",
"[",
"]",
"=",
"$",
"item",
"[",
"'update'",
"]",
";",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"errors",
")",
"||",
"isset",
"(",
"$",
"response",
"[",
"'errors'",
"]",
")",
"&&",
"$",
"response",
"[",
"'errors'",
"]",
")",
"{",
"throw",
"new",
"Exception",
"(",
"__METHOD__",
".",
"' failed updating records counters.'",
",",
"$",
"errors",
")",
";",
"}",
"return",
"$",
"n",
";",
"}"
] | Updates all matching records using the provided counter changes and conditions.
For example, to add 1 to age of all customers whose status is 2,
~~~
Customer::updateAllCounters(['age' => 1], ['status' => 2]);
~~~
@param array $counters the counters to be updated (attribute name => increment value).
Use negative values if you want to decrement the counters.
@param array $condition the conditions that will be passed to the `where()` method when building the query.
Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
@see [[ActiveRecord::primaryKeysByCondition()]]
@return int the number of rows updated
@throws Exception on error. | [
"Updates",
"all",
"matching",
"records",
"using",
"the",
"provided",
"counter",
"changes",
"and",
"conditions",
".",
"For",
"example",
"to",
"add",
"1",
"to",
"age",
"of",
"all",
"customers",
"whose",
"status",
"is",
"2"
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/ActiveRecord.php#L684-L718 | train |
yiisoft/yii2-elasticsearch | BulkCommand.php | BulkCommand.execute | public function execute()
{
//valid endpoints are /_bulk, /{index}/_bulk, and {index}/{type}/_bulk
if ($this->index === null && $this->type === null) {
$endpoint = ['_bulk'];
} elseif ($this->index !== null && $this->type === null) {
$endpoint = [$this->index, '_bulk'];
} elseif ($this->index !== null && $this->type !== null) {
$endpoint = [$this->index, $this->type, '_bulk'];
} else {
throw new InvalidCallException('Invalid endpoint: if type is defined, index must be defined too.');
}
if (empty($this->actions)) {
$body = '{}';
} elseif (is_array($this->actions)) {
$body = '';
foreach ($this->actions as $action) {
$body .= Json::encode($action) . "\n";
}
} else {
$body = $this->actions;
}
return $this->db->post($endpoint, $this->options, $body);
} | php | public function execute()
{
//valid endpoints are /_bulk, /{index}/_bulk, and {index}/{type}/_bulk
if ($this->index === null && $this->type === null) {
$endpoint = ['_bulk'];
} elseif ($this->index !== null && $this->type === null) {
$endpoint = [$this->index, '_bulk'];
} elseif ($this->index !== null && $this->type !== null) {
$endpoint = [$this->index, $this->type, '_bulk'];
} else {
throw new InvalidCallException('Invalid endpoint: if type is defined, index must be defined too.');
}
if (empty($this->actions)) {
$body = '{}';
} elseif (is_array($this->actions)) {
$body = '';
foreach ($this->actions as $action) {
$body .= Json::encode($action) . "\n";
}
} else {
$body = $this->actions;
}
return $this->db->post($endpoint, $this->options, $body);
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"//valid endpoints are /_bulk, /{index}/_bulk, and {index}/{type}/_bulk",
"if",
"(",
"$",
"this",
"->",
"index",
"===",
"null",
"&&",
"$",
"this",
"->",
"type",
"===",
"null",
")",
"{",
"$",
"endpoint",
"=",
"[",
"'_bulk'",
"]",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"index",
"!==",
"null",
"&&",
"$",
"this",
"->",
"type",
"===",
"null",
")",
"{",
"$",
"endpoint",
"=",
"[",
"$",
"this",
"->",
"index",
",",
"'_bulk'",
"]",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"index",
"!==",
"null",
"&&",
"$",
"this",
"->",
"type",
"!==",
"null",
")",
"{",
"$",
"endpoint",
"=",
"[",
"$",
"this",
"->",
"index",
",",
"$",
"this",
"->",
"type",
",",
"'_bulk'",
"]",
";",
"}",
"else",
"{",
"throw",
"new",
"InvalidCallException",
"(",
"'Invalid endpoint: if type is defined, index must be defined too.'",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"actions",
")",
")",
"{",
"$",
"body",
"=",
"'{}'",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"this",
"->",
"actions",
")",
")",
"{",
"$",
"body",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"actions",
"as",
"$",
"action",
")",
"{",
"$",
"body",
".=",
"Json",
"::",
"encode",
"(",
"$",
"action",
")",
".",
"\"\\n\"",
";",
"}",
"}",
"else",
"{",
"$",
"body",
"=",
"$",
"this",
"->",
"actions",
";",
"}",
"return",
"$",
"this",
"->",
"db",
"->",
"post",
"(",
"$",
"endpoint",
",",
"$",
"this",
"->",
"options",
",",
"$",
"body",
")",
";",
"}"
] | Executes the bulk command.
@return mixed
@throws yii\base\InvalidCallException | [
"Executes",
"the",
"bulk",
"command",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/BulkCommand.php#L53-L78 | train |
yiisoft/yii2-elasticsearch | BulkCommand.php | BulkCommand.addAction | public function addAction($line1, $line2 = null)
{
if (!is_array($this->actions)) {
$this->actions = [];
}
$this->actions[] = $line1;
if ($line2 !== null) {
$this->actions[] = $line2;
}
} | php | public function addAction($line1, $line2 = null)
{
if (!is_array($this->actions)) {
$this->actions = [];
}
$this->actions[] = $line1;
if ($line2 !== null) {
$this->actions[] = $line2;
}
} | [
"public",
"function",
"addAction",
"(",
"$",
"line1",
",",
"$",
"line2",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"this",
"->",
"actions",
")",
")",
"{",
"$",
"this",
"->",
"actions",
"=",
"[",
"]",
";",
"}",
"$",
"this",
"->",
"actions",
"[",
"]",
"=",
"$",
"line1",
";",
"if",
"(",
"$",
"line2",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"actions",
"[",
"]",
"=",
"$",
"line2",
";",
"}",
"}"
] | Adds an action to the command. Will overwrite existing actions if they are specified as a string.
@param array $action Action expressed as an array (will be encoded to JSON automatically). | [
"Adds",
"an",
"action",
"to",
"the",
"command",
".",
"Will",
"overwrite",
"existing",
"actions",
"if",
"they",
"are",
"specified",
"as",
"a",
"string",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/BulkCommand.php#L84-L95 | train |
yiisoft/yii2-elasticsearch | BulkCommand.php | BulkCommand.addDeleteAction | public function addDeleteAction($id, $index = null, $type = null)
{
$actionData = ['_id' => $id];
if (!empty($index)) {
$actionData['_index'] = $index;
}
if (!empty($type)) {
$actionData['_type'] = $type;
}
$this->addAction(['delete' => $actionData]);
} | php | public function addDeleteAction($id, $index = null, $type = null)
{
$actionData = ['_id' => $id];
if (!empty($index)) {
$actionData['_index'] = $index;
}
if (!empty($type)) {
$actionData['_type'] = $type;
}
$this->addAction(['delete' => $actionData]);
} | [
"public",
"function",
"addDeleteAction",
"(",
"$",
"id",
",",
"$",
"index",
"=",
"null",
",",
"$",
"type",
"=",
"null",
")",
"{",
"$",
"actionData",
"=",
"[",
"'_id'",
"=>",
"$",
"id",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"index",
")",
")",
"{",
"$",
"actionData",
"[",
"'_index'",
"]",
"=",
"$",
"index",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"type",
")",
")",
"{",
"$",
"actionData",
"[",
"'_type'",
"]",
"=",
"$",
"type",
";",
"}",
"$",
"this",
"->",
"addAction",
"(",
"[",
"'delete'",
"=>",
"$",
"actionData",
"]",
")",
";",
"}"
] | Adds a delete action to the command.
@param string $id Document ID
@param string $index Index that the document belogs to. Can be set to null if the command has
a default index ([[BulkCommand::$index]]) assigned.
@param string $type Type that the document belogs to. Can be set to null if the command has
a default type ([[BulkCommand::$type]]) assigned. | [
"Adds",
"a",
"delete",
"action",
"to",
"the",
"command",
"."
] | 1f48d816536876610b3831734cff4d2e72a3ebd8 | https://github.com/yiisoft/yii2-elasticsearch/blob/1f48d816536876610b3831734cff4d2e72a3ebd8/BulkCommand.php#L105-L118 | train |
felixfbecker/php-language-server | src/ProtocolStreamWriter.php | ProtocolStreamWriter.flush | private function flush()
{
$keepWriting = true;
while ($keepWriting) {
$message = $this->messages[0]['message'];
$promise = $this->messages[0]['promise'];
$bytesWritten = @fwrite($this->output, $message);
if ($bytesWritten > 0) {
$message = substr($message, $bytesWritten);
}
// Determine if this message was completely sent
if (strlen($message) === 0) {
array_shift($this->messages);
// This was the last message in the queue, remove the write handler.
if (count($this->messages) === 0) {
Loop\removeWriteStream($this->output);
$keepWriting = false;
}
$promise->fulfill();
} else {
$this->messages[0]['message'] = $message;
$keepWriting = false;
}
}
} | php | private function flush()
{
$keepWriting = true;
while ($keepWriting) {
$message = $this->messages[0]['message'];
$promise = $this->messages[0]['promise'];
$bytesWritten = @fwrite($this->output, $message);
if ($bytesWritten > 0) {
$message = substr($message, $bytesWritten);
}
// Determine if this message was completely sent
if (strlen($message) === 0) {
array_shift($this->messages);
// This was the last message in the queue, remove the write handler.
if (count($this->messages) === 0) {
Loop\removeWriteStream($this->output);
$keepWriting = false;
}
$promise->fulfill();
} else {
$this->messages[0]['message'] = $message;
$keepWriting = false;
}
}
} | [
"private",
"function",
"flush",
"(",
")",
"{",
"$",
"keepWriting",
"=",
"true",
";",
"while",
"(",
"$",
"keepWriting",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"messages",
"[",
"0",
"]",
"[",
"'message'",
"]",
";",
"$",
"promise",
"=",
"$",
"this",
"->",
"messages",
"[",
"0",
"]",
"[",
"'promise'",
"]",
";",
"$",
"bytesWritten",
"=",
"@",
"fwrite",
"(",
"$",
"this",
"->",
"output",
",",
"$",
"message",
")",
";",
"if",
"(",
"$",
"bytesWritten",
">",
"0",
")",
"{",
"$",
"message",
"=",
"substr",
"(",
"$",
"message",
",",
"$",
"bytesWritten",
")",
";",
"}",
"// Determine if this message was completely sent",
"if",
"(",
"strlen",
"(",
"$",
"message",
")",
"===",
"0",
")",
"{",
"array_shift",
"(",
"$",
"this",
"->",
"messages",
")",
";",
"// This was the last message in the queue, remove the write handler.",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"messages",
")",
"===",
"0",
")",
"{",
"Loop",
"\\",
"removeWriteStream",
"(",
"$",
"this",
"->",
"output",
")",
";",
"$",
"keepWriting",
"=",
"false",
";",
"}",
"$",
"promise",
"->",
"fulfill",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"messages",
"[",
"0",
"]",
"[",
"'message'",
"]",
"=",
"$",
"message",
";",
"$",
"keepWriting",
"=",
"false",
";",
"}",
"}",
"}"
] | Writes pending messages to the output stream.
@return void | [
"Writes",
"pending",
"messages",
"to",
"the",
"output",
"stream",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/ProtocolStreamWriter.php#L57-L86 | train |
felixfbecker/php-language-server | src/PhpDocumentLoader.php | PhpDocumentLoader.getOrLoad | public function getOrLoad(string $uri): Promise
{
return isset($this->documents[$uri]) ? Promise\resolve($this->documents[$uri]) : $this->load($uri);
} | php | public function getOrLoad(string $uri): Promise
{
return isset($this->documents[$uri]) ? Promise\resolve($this->documents[$uri]) : $this->load($uri);
} | [
"public",
"function",
"getOrLoad",
"(",
"string",
"$",
"uri",
")",
":",
"Promise",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"documents",
"[",
"$",
"uri",
"]",
")",
"?",
"Promise",
"\\",
"resolve",
"(",
"$",
"this",
"->",
"documents",
"[",
"$",
"uri",
"]",
")",
":",
"$",
"this",
"->",
"load",
"(",
"$",
"uri",
")",
";",
"}"
] | Returns the document indicated by uri.
If the document is not open, loads it.
@param string $uri
@return Promise <PhpDocument> | [
"Returns",
"the",
"document",
"indicated",
"by",
"uri",
".",
"If",
"the",
"document",
"is",
"not",
"open",
"loads",
"it",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/PhpDocumentLoader.php#L92-L95 | train |
felixfbecker/php-language-server | src/PhpDocumentLoader.php | PhpDocumentLoader.create | public function create(string $uri, string $content): PhpDocument
{
return new PhpDocument(
$uri,
$content,
$this->projectIndex->getIndexForUri($uri),
$this->parser,
$this->docBlockFactory,
$this->definitionResolver
);
} | php | public function create(string $uri, string $content): PhpDocument
{
return new PhpDocument(
$uri,
$content,
$this->projectIndex->getIndexForUri($uri),
$this->parser,
$this->docBlockFactory,
$this->definitionResolver
);
} | [
"public",
"function",
"create",
"(",
"string",
"$",
"uri",
",",
"string",
"$",
"content",
")",
":",
"PhpDocument",
"{",
"return",
"new",
"PhpDocument",
"(",
"$",
"uri",
",",
"$",
"content",
",",
"$",
"this",
"->",
"projectIndex",
"->",
"getIndexForUri",
"(",
"$",
"uri",
")",
",",
"$",
"this",
"->",
"parser",
",",
"$",
"this",
"->",
"docBlockFactory",
",",
"$",
"this",
"->",
"definitionResolver",
")",
";",
"}"
] | Builds a PhpDocument instance
@param string $uri
@param string $content
@return PhpDocument | [
"Builds",
"a",
"PhpDocument",
"instance"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/PhpDocumentLoader.php#L133-L143 | train |
felixfbecker/php-language-server | src/PhpDocumentLoader.php | PhpDocumentLoader.open | public function open(string $uri, string $content)
{
if (isset($this->documents[$uri])) {
$document = $this->documents[$uri];
$document->updateContent($content);
} else {
$document = $this->create($uri, $content);
$this->documents[$uri] = $document;
}
return $document;
} | php | public function open(string $uri, string $content)
{
if (isset($this->documents[$uri])) {
$document = $this->documents[$uri];
$document->updateContent($content);
} else {
$document = $this->create($uri, $content);
$this->documents[$uri] = $document;
}
return $document;
} | [
"public",
"function",
"open",
"(",
"string",
"$",
"uri",
",",
"string",
"$",
"content",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"documents",
"[",
"$",
"uri",
"]",
")",
")",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"documents",
"[",
"$",
"uri",
"]",
";",
"$",
"document",
"->",
"updateContent",
"(",
"$",
"content",
")",
";",
"}",
"else",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"create",
"(",
"$",
"uri",
",",
"$",
"content",
")",
";",
"$",
"this",
"->",
"documents",
"[",
"$",
"uri",
"]",
"=",
"$",
"document",
";",
"}",
"return",
"$",
"document",
";",
"}"
] | Ensures a document is loaded and added to the list of open documents.
@param string $uri
@param string $content
@return void | [
"Ensures",
"a",
"document",
"is",
"loaded",
"and",
"added",
"to",
"the",
"list",
"of",
"open",
"documents",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/PhpDocumentLoader.php#L152-L162 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.getUnqualifiedCompletions | private function getUnqualifiedCompletions(
string $prefix,
string $currentNamespace,
array $importTables,
bool $requireCanBeInstantiated
): \Generator {
// Aliases
list($namespaceAliases,,) = $importTables;
// use Foo\Bar
yield from $this->getCompletionsForAliases(
$prefix,
$namespaceAliases,
$requireCanBeInstantiated
);
// Completions from the current namespace
yield from $this->getCompletionsForFqnPrefix(
nameConcat($currentNamespace, $prefix),
$requireCanBeInstantiated,
false
);
if ($currentNamespace !== '' && $prefix === '') {
// Get additional suggestions from the global namespace.
// When completing e.g. for new |, suggest \DateTime
yield from $this->getCompletionsForFqnPrefix('', $requireCanBeInstantiated, true);
}
if (!$requireCanBeInstantiated) {
if ($currentNamespace !== '' && $prefix !== '') {
// Roamed definitions (i.e. global constants and functions). The prefix is checked against '', since
// in that case global completions have already been provided (including non-roamed definitions.)
yield from $this->getRoamedCompletions($prefix);
}
// Lastly and least importantly, suggest keywords.
yield from $this->getCompletionsForKeywords($prefix);
}
} | php | private function getUnqualifiedCompletions(
string $prefix,
string $currentNamespace,
array $importTables,
bool $requireCanBeInstantiated
): \Generator {
// Aliases
list($namespaceAliases,,) = $importTables;
// use Foo\Bar
yield from $this->getCompletionsForAliases(
$prefix,
$namespaceAliases,
$requireCanBeInstantiated
);
// Completions from the current namespace
yield from $this->getCompletionsForFqnPrefix(
nameConcat($currentNamespace, $prefix),
$requireCanBeInstantiated,
false
);
if ($currentNamespace !== '' && $prefix === '') {
// Get additional suggestions from the global namespace.
// When completing e.g. for new |, suggest \DateTime
yield from $this->getCompletionsForFqnPrefix('', $requireCanBeInstantiated, true);
}
if (!$requireCanBeInstantiated) {
if ($currentNamespace !== '' && $prefix !== '') {
// Roamed definitions (i.e. global constants and functions). The prefix is checked against '', since
// in that case global completions have already been provided (including non-roamed definitions.)
yield from $this->getRoamedCompletions($prefix);
}
// Lastly and least importantly, suggest keywords.
yield from $this->getCompletionsForKeywords($prefix);
}
} | [
"private",
"function",
"getUnqualifiedCompletions",
"(",
"string",
"$",
"prefix",
",",
"string",
"$",
"currentNamespace",
",",
"array",
"$",
"importTables",
",",
"bool",
"$",
"requireCanBeInstantiated",
")",
":",
"\\",
"Generator",
"{",
"// Aliases",
"list",
"(",
"$",
"namespaceAliases",
",",
",",
")",
"=",
"$",
"importTables",
";",
"// use Foo\\Bar",
"yield",
"from",
"$",
"this",
"->",
"getCompletionsForAliases",
"(",
"$",
"prefix",
",",
"$",
"namespaceAliases",
",",
"$",
"requireCanBeInstantiated",
")",
";",
"// Completions from the current namespace",
"yield",
"from",
"$",
"this",
"->",
"getCompletionsForFqnPrefix",
"(",
"nameConcat",
"(",
"$",
"currentNamespace",
",",
"$",
"prefix",
")",
",",
"$",
"requireCanBeInstantiated",
",",
"false",
")",
";",
"if",
"(",
"$",
"currentNamespace",
"!==",
"''",
"&&",
"$",
"prefix",
"===",
"''",
")",
"{",
"// Get additional suggestions from the global namespace.",
"// When completing e.g. for new |, suggest \\DateTime",
"yield",
"from",
"$",
"this",
"->",
"getCompletionsForFqnPrefix",
"(",
"''",
",",
"$",
"requireCanBeInstantiated",
",",
"true",
")",
";",
"}",
"if",
"(",
"!",
"$",
"requireCanBeInstantiated",
")",
"{",
"if",
"(",
"$",
"currentNamespace",
"!==",
"''",
"&&",
"$",
"prefix",
"!==",
"''",
")",
"{",
"// Roamed definitions (i.e. global constants and functions). The prefix is checked against '', since",
"// in that case global completions have already been provided (including non-roamed definitions.)",
"yield",
"from",
"$",
"this",
"->",
"getRoamedCompletions",
"(",
"$",
"prefix",
")",
";",
"}",
"// Lastly and least importantly, suggest keywords.",
"yield",
"from",
"$",
"this",
"->",
"getCompletionsForKeywords",
"(",
"$",
"prefix",
")",
";",
"}",
"}"
] | Yields completions for non-qualified global names.
Yields
- Aliased classes
- Completions from current namespace
- Roamed completions from the global namespace (when not creating and not already in root NS)
- PHP keywords (when not creating)
@return \Generator|CompletionItem[]
Yields CompletionItems | [
"Yields",
"completions",
"for",
"non",
"-",
"qualified",
"global",
"names",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L416-L454 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.getCompletionsForFqnPrefix | private function getCompletionsForFqnPrefix(
string $prefix,
bool $requireCanBeInstantiated,
bool $insertFullyQualified
): \Generator {
$namespace = nameGetParent($prefix);
foreach ($this->index->getChildDefinitionsForFqn($namespace) as $fqn => $def) {
if ($requireCanBeInstantiated && !$def->canBeInstantiated) {
continue;
}
if (!nameStartsWith($fqn, $prefix)) {
continue;
}
$completion = CompletionItemFactory::fromDefinition($def);
if ($insertFullyQualified) {
$completion->insertText = '\\' . $fqn;
}
yield $fqn => $completion;
}
} | php | private function getCompletionsForFqnPrefix(
string $prefix,
bool $requireCanBeInstantiated,
bool $insertFullyQualified
): \Generator {
$namespace = nameGetParent($prefix);
foreach ($this->index->getChildDefinitionsForFqn($namespace) as $fqn => $def) {
if ($requireCanBeInstantiated && !$def->canBeInstantiated) {
continue;
}
if (!nameStartsWith($fqn, $prefix)) {
continue;
}
$completion = CompletionItemFactory::fromDefinition($def);
if ($insertFullyQualified) {
$completion->insertText = '\\' . $fqn;
}
yield $fqn => $completion;
}
} | [
"private",
"function",
"getCompletionsForFqnPrefix",
"(",
"string",
"$",
"prefix",
",",
"bool",
"$",
"requireCanBeInstantiated",
",",
"bool",
"$",
"insertFullyQualified",
")",
":",
"\\",
"Generator",
"{",
"$",
"namespace",
"=",
"nameGetParent",
"(",
"$",
"prefix",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"index",
"->",
"getChildDefinitionsForFqn",
"(",
"$",
"namespace",
")",
"as",
"$",
"fqn",
"=>",
"$",
"def",
")",
"{",
"if",
"(",
"$",
"requireCanBeInstantiated",
"&&",
"!",
"$",
"def",
"->",
"canBeInstantiated",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"nameStartsWith",
"(",
"$",
"fqn",
",",
"$",
"prefix",
")",
")",
"{",
"continue",
";",
"}",
"$",
"completion",
"=",
"CompletionItemFactory",
"::",
"fromDefinition",
"(",
"$",
"def",
")",
";",
"if",
"(",
"$",
"insertFullyQualified",
")",
"{",
"$",
"completion",
"->",
"insertText",
"=",
"'\\\\'",
".",
"$",
"fqn",
";",
"}",
"yield",
"$",
"fqn",
"=>",
"$",
"completion",
";",
"}",
"}"
] | Gets completions for prefixes of fully qualified names in their parent namespace.
@param string $prefix Prefix to complete for. Fully qualified.
@param bool $requireCanBeInstantiated If set, only return classes.
@param bool $insertFullyQualified If set, return completion with the leading \ inserted.
@return \Generator|CompletionItem[]
Yields CompletionItems. | [
"Gets",
"completions",
"for",
"prefixes",
"of",
"fully",
"qualified",
"names",
"in",
"their",
"parent",
"namespace",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L465-L484 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.getCompletionsForAliases | private function getCompletionsForAliases(
string $prefix,
array $aliases,
bool $requireCanBeInstantiated
): \Generator {
foreach ($aliases as $alias => $aliasFqn) {
if (!nameStartsWith($alias, $prefix)) {
continue;
}
$definition = $this->index->getDefinition((string)$aliasFqn);
if ($definition) {
if ($requireCanBeInstantiated && !$definition->canBeInstantiated) {
continue;
}
$completionItem = CompletionItemFactory::fromDefinition($definition);
$completionItem->insertText = $alias;
yield (string)$aliasFqn => $completionItem;
}
}
} | php | private function getCompletionsForAliases(
string $prefix,
array $aliases,
bool $requireCanBeInstantiated
): \Generator {
foreach ($aliases as $alias => $aliasFqn) {
if (!nameStartsWith($alias, $prefix)) {
continue;
}
$definition = $this->index->getDefinition((string)$aliasFqn);
if ($definition) {
if ($requireCanBeInstantiated && !$definition->canBeInstantiated) {
continue;
}
$completionItem = CompletionItemFactory::fromDefinition($definition);
$completionItem->insertText = $alias;
yield (string)$aliasFqn => $completionItem;
}
}
} | [
"private",
"function",
"getCompletionsForAliases",
"(",
"string",
"$",
"prefix",
",",
"array",
"$",
"aliases",
",",
"bool",
"$",
"requireCanBeInstantiated",
")",
":",
"\\",
"Generator",
"{",
"foreach",
"(",
"$",
"aliases",
"as",
"$",
"alias",
"=>",
"$",
"aliasFqn",
")",
"{",
"if",
"(",
"!",
"nameStartsWith",
"(",
"$",
"alias",
",",
"$",
"prefix",
")",
")",
"{",
"continue",
";",
"}",
"$",
"definition",
"=",
"$",
"this",
"->",
"index",
"->",
"getDefinition",
"(",
"(",
"string",
")",
"$",
"aliasFqn",
")",
";",
"if",
"(",
"$",
"definition",
")",
"{",
"if",
"(",
"$",
"requireCanBeInstantiated",
"&&",
"!",
"$",
"definition",
"->",
"canBeInstantiated",
")",
"{",
"continue",
";",
"}",
"$",
"completionItem",
"=",
"CompletionItemFactory",
"::",
"fromDefinition",
"(",
"$",
"definition",
")",
";",
"$",
"completionItem",
"->",
"insertText",
"=",
"$",
"alias",
";",
"yield",
"(",
"string",
")",
"$",
"aliasFqn",
"=>",
"$",
"completionItem",
";",
"}",
"}",
"}"
] | Gets completions for non-qualified names matching the start of an used class, function, or constant.
@param string $prefix Non-qualified name being completed for
@param QualifiedName[] $aliases Array of alias FQNs indexed by the alias.
@return \Generator|CompletionItem[]
Yields CompletionItems. | [
"Gets",
"completions",
"for",
"non",
"-",
"qualified",
"names",
"matching",
"the",
"start",
"of",
"an",
"used",
"class",
"function",
"or",
"constant",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L494-L513 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.getCompletionsFromAliasedNamespace | private function getCompletionsFromAliasedNamespace(
string $prefix,
string $alias,
string $aliasFqn,
bool $requireCanBeInstantiated
): \Generator {
$prefixFirstPart = nameGetFirstPart($prefix);
// Matched alias.
$resolvedPrefix = nameConcat($aliasFqn, nameWithoutFirstPart($prefix));
$completionItems = $this->getCompletionsForFqnPrefix(
$resolvedPrefix,
$requireCanBeInstantiated,
false
);
// Convert FQNs in the CompletionItems so they are expressed in terms of the alias.
foreach ($completionItems as $fqn => $completionItem) {
/** @var string $fqn with the leading parts determined by the alias removed. Has the leading backslash. */
$nameWithoutAliasedPart = substr($fqn, strlen($aliasFqn));
$completionItem->insertText = $alias . $nameWithoutAliasedPart;
yield $fqn => $completionItem;
}
} | php | private function getCompletionsFromAliasedNamespace(
string $prefix,
string $alias,
string $aliasFqn,
bool $requireCanBeInstantiated
): \Generator {
$prefixFirstPart = nameGetFirstPart($prefix);
// Matched alias.
$resolvedPrefix = nameConcat($aliasFqn, nameWithoutFirstPart($prefix));
$completionItems = $this->getCompletionsForFqnPrefix(
$resolvedPrefix,
$requireCanBeInstantiated,
false
);
// Convert FQNs in the CompletionItems so they are expressed in terms of the alias.
foreach ($completionItems as $fqn => $completionItem) {
/** @var string $fqn with the leading parts determined by the alias removed. Has the leading backslash. */
$nameWithoutAliasedPart = substr($fqn, strlen($aliasFqn));
$completionItem->insertText = $alias . $nameWithoutAliasedPart;
yield $fqn => $completionItem;
}
} | [
"private",
"function",
"getCompletionsFromAliasedNamespace",
"(",
"string",
"$",
"prefix",
",",
"string",
"$",
"alias",
",",
"string",
"$",
"aliasFqn",
",",
"bool",
"$",
"requireCanBeInstantiated",
")",
":",
"\\",
"Generator",
"{",
"$",
"prefixFirstPart",
"=",
"nameGetFirstPart",
"(",
"$",
"prefix",
")",
";",
"// Matched alias.",
"$",
"resolvedPrefix",
"=",
"nameConcat",
"(",
"$",
"aliasFqn",
",",
"nameWithoutFirstPart",
"(",
"$",
"prefix",
")",
")",
";",
"$",
"completionItems",
"=",
"$",
"this",
"->",
"getCompletionsForFqnPrefix",
"(",
"$",
"resolvedPrefix",
",",
"$",
"requireCanBeInstantiated",
",",
"false",
")",
";",
"// Convert FQNs in the CompletionItems so they are expressed in terms of the alias.",
"foreach",
"(",
"$",
"completionItems",
"as",
"$",
"fqn",
"=>",
"$",
"completionItem",
")",
"{",
"/** @var string $fqn with the leading parts determined by the alias removed. Has the leading backslash. */",
"$",
"nameWithoutAliasedPart",
"=",
"substr",
"(",
"$",
"fqn",
",",
"strlen",
"(",
"$",
"aliasFqn",
")",
")",
";",
"$",
"completionItem",
"->",
"insertText",
"=",
"$",
"alias",
".",
"$",
"nameWithoutAliasedPart",
";",
"yield",
"$",
"fqn",
"=>",
"$",
"completionItem",
";",
"}",
"}"
] | Gets completions for partially qualified names, where the first part is matched by an alias.
@return \Generator|CompletionItem[]
Yields CompletionItems. | [
"Gets",
"completions",
"for",
"partially",
"qualified",
"names",
"where",
"the",
"first",
"part",
"is",
"matched",
"by",
"an",
"alias",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L521-L542 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.getCompletionsForKeywords | private function getCompletionsForKeywords(string $prefix): \Generator
{
foreach (self::KEYWORDS as $keyword) {
if (nameStartsWith($keyword, $prefix)) {
$item = new CompletionItem($keyword, CompletionItemKind::KEYWORD);
$item->insertText = $keyword;
yield $keyword => $item;
}
}
} | php | private function getCompletionsForKeywords(string $prefix): \Generator
{
foreach (self::KEYWORDS as $keyword) {
if (nameStartsWith($keyword, $prefix)) {
$item = new CompletionItem($keyword, CompletionItemKind::KEYWORD);
$item->insertText = $keyword;
yield $keyword => $item;
}
}
} | [
"private",
"function",
"getCompletionsForKeywords",
"(",
"string",
"$",
"prefix",
")",
":",
"\\",
"Generator",
"{",
"foreach",
"(",
"self",
"::",
"KEYWORDS",
"as",
"$",
"keyword",
")",
"{",
"if",
"(",
"nameStartsWith",
"(",
"$",
"keyword",
",",
"$",
"prefix",
")",
")",
"{",
"$",
"item",
"=",
"new",
"CompletionItem",
"(",
"$",
"keyword",
",",
"CompletionItemKind",
"::",
"KEYWORD",
")",
";",
"$",
"item",
"->",
"insertText",
"=",
"$",
"keyword",
";",
"yield",
"$",
"keyword",
"=>",
"$",
"item",
";",
"}",
"}",
"}"
] | Completes PHP keywords.
@return \Generator|CompletionItem[]
Yields CompletionItems. | [
"Completes",
"PHP",
"keywords",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L570-L579 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.expandParentFqns | private function expandParentFqns(array $fqns) : Generator
{
foreach ($fqns as $fqn) {
yield $fqn;
$def = $this->index->getDefinition($fqn);
if ($def !== null) {
foreach ($def->getAncestorDefinitions($this->index) as $name => $def) {
yield $name;
}
}
}
} | php | private function expandParentFqns(array $fqns) : Generator
{
foreach ($fqns as $fqn) {
yield $fqn;
$def = $this->index->getDefinition($fqn);
if ($def !== null) {
foreach ($def->getAncestorDefinitions($this->index) as $name => $def) {
yield $name;
}
}
}
} | [
"private",
"function",
"expandParentFqns",
"(",
"array",
"$",
"fqns",
")",
":",
"Generator",
"{",
"foreach",
"(",
"$",
"fqns",
"as",
"$",
"fqn",
")",
"{",
"yield",
"$",
"fqn",
";",
"$",
"def",
"=",
"$",
"this",
"->",
"index",
"->",
"getDefinition",
"(",
"$",
"fqn",
")",
";",
"if",
"(",
"$",
"def",
"!==",
"null",
")",
"{",
"foreach",
"(",
"$",
"def",
"->",
"getAncestorDefinitions",
"(",
"$",
"this",
"->",
"index",
")",
"as",
"$",
"name",
"=>",
"$",
"def",
")",
"{",
"yield",
"$",
"name",
";",
"}",
"}",
"}",
"}"
] | Yields FQNs from an array along with the FQNs of all parent classes
@param string[] $fqns
@return Generator | [
"Yields",
"FQNs",
"from",
"an",
"array",
"along",
"with",
"the",
"FQNs",
"of",
"all",
"parent",
"classes"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L587-L598 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.suggestVariablesAtNode | private function suggestVariablesAtNode(Node $node, string $namePrefix = ''): array
{
$vars = [];
// Find variables in the node itself
// When getting completion in the middle of a function, $node will be the function node
// so we need to search it
foreach ($this->findVariableDefinitionsInNode($node, $namePrefix) as $var) {
// Only use the first definition
if (!isset($vars[$var->name])) {
$vars[$var->name] = $var;
}
}
// Walk the AST upwards until a scope boundary is met
$level = $node;
while ($level && !($level instanceof PhpParser\FunctionLike)) {
// Walk siblings before the node
$sibling = $level;
while ($sibling = $sibling->getPreviousSibling()) {
// Collect all variables inside the sibling node
foreach ($this->findVariableDefinitionsInNode($sibling, $namePrefix) as $var) {
$vars[$var->getName()] = $var;
}
}
$level = $level->parent;
}
// If the traversal ended because a function was met,
// also add its parameters and closure uses to the result list
if ($level && $level instanceof PhpParser\FunctionLike && $level->parameters !== null) {
foreach ($level->parameters->getValues() as $param) {
$paramName = $param->getName();
if (empty($namePrefix) || strpos($paramName, $namePrefix) !== false) {
$vars[$paramName] = $param;
}
}
if ($level instanceof Node\Expression\AnonymousFunctionCreationExpression
&& $level->anonymousFunctionUseClause !== null
&& $level->anonymousFunctionUseClause->useVariableNameList !== null) {
foreach ($level->anonymousFunctionUseClause->useVariableNameList->getValues() as $use) {
$useName = $use->getName();
if (empty($namePrefix) || strpos($useName, $namePrefix) !== false) {
$vars[$useName] = $use;
}
}
}
}
return array_values($vars);
} | php | private function suggestVariablesAtNode(Node $node, string $namePrefix = ''): array
{
$vars = [];
// Find variables in the node itself
// When getting completion in the middle of a function, $node will be the function node
// so we need to search it
foreach ($this->findVariableDefinitionsInNode($node, $namePrefix) as $var) {
// Only use the first definition
if (!isset($vars[$var->name])) {
$vars[$var->name] = $var;
}
}
// Walk the AST upwards until a scope boundary is met
$level = $node;
while ($level && !($level instanceof PhpParser\FunctionLike)) {
// Walk siblings before the node
$sibling = $level;
while ($sibling = $sibling->getPreviousSibling()) {
// Collect all variables inside the sibling node
foreach ($this->findVariableDefinitionsInNode($sibling, $namePrefix) as $var) {
$vars[$var->getName()] = $var;
}
}
$level = $level->parent;
}
// If the traversal ended because a function was met,
// also add its parameters and closure uses to the result list
if ($level && $level instanceof PhpParser\FunctionLike && $level->parameters !== null) {
foreach ($level->parameters->getValues() as $param) {
$paramName = $param->getName();
if (empty($namePrefix) || strpos($paramName, $namePrefix) !== false) {
$vars[$paramName] = $param;
}
}
if ($level instanceof Node\Expression\AnonymousFunctionCreationExpression
&& $level->anonymousFunctionUseClause !== null
&& $level->anonymousFunctionUseClause->useVariableNameList !== null) {
foreach ($level->anonymousFunctionUseClause->useVariableNameList->getValues() as $use) {
$useName = $use->getName();
if (empty($namePrefix) || strpos($useName, $namePrefix) !== false) {
$vars[$useName] = $use;
}
}
}
}
return array_values($vars);
} | [
"private",
"function",
"suggestVariablesAtNode",
"(",
"Node",
"$",
"node",
",",
"string",
"$",
"namePrefix",
"=",
"''",
")",
":",
"array",
"{",
"$",
"vars",
"=",
"[",
"]",
";",
"// Find variables in the node itself",
"// When getting completion in the middle of a function, $node will be the function node",
"// so we need to search it",
"foreach",
"(",
"$",
"this",
"->",
"findVariableDefinitionsInNode",
"(",
"$",
"node",
",",
"$",
"namePrefix",
")",
"as",
"$",
"var",
")",
"{",
"// Only use the first definition",
"if",
"(",
"!",
"isset",
"(",
"$",
"vars",
"[",
"$",
"var",
"->",
"name",
"]",
")",
")",
"{",
"$",
"vars",
"[",
"$",
"var",
"->",
"name",
"]",
"=",
"$",
"var",
";",
"}",
"}",
"// Walk the AST upwards until a scope boundary is met",
"$",
"level",
"=",
"$",
"node",
";",
"while",
"(",
"$",
"level",
"&&",
"!",
"(",
"$",
"level",
"instanceof",
"PhpParser",
"\\",
"FunctionLike",
")",
")",
"{",
"// Walk siblings before the node",
"$",
"sibling",
"=",
"$",
"level",
";",
"while",
"(",
"$",
"sibling",
"=",
"$",
"sibling",
"->",
"getPreviousSibling",
"(",
")",
")",
"{",
"// Collect all variables inside the sibling node",
"foreach",
"(",
"$",
"this",
"->",
"findVariableDefinitionsInNode",
"(",
"$",
"sibling",
",",
"$",
"namePrefix",
")",
"as",
"$",
"var",
")",
"{",
"$",
"vars",
"[",
"$",
"var",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"var",
";",
"}",
"}",
"$",
"level",
"=",
"$",
"level",
"->",
"parent",
";",
"}",
"// If the traversal ended because a function was met,",
"// also add its parameters and closure uses to the result list",
"if",
"(",
"$",
"level",
"&&",
"$",
"level",
"instanceof",
"PhpParser",
"\\",
"FunctionLike",
"&&",
"$",
"level",
"->",
"parameters",
"!==",
"null",
")",
"{",
"foreach",
"(",
"$",
"level",
"->",
"parameters",
"->",
"getValues",
"(",
")",
"as",
"$",
"param",
")",
"{",
"$",
"paramName",
"=",
"$",
"param",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"namePrefix",
")",
"||",
"strpos",
"(",
"$",
"paramName",
",",
"$",
"namePrefix",
")",
"!==",
"false",
")",
"{",
"$",
"vars",
"[",
"$",
"paramName",
"]",
"=",
"$",
"param",
";",
"}",
"}",
"if",
"(",
"$",
"level",
"instanceof",
"Node",
"\\",
"Expression",
"\\",
"AnonymousFunctionCreationExpression",
"&&",
"$",
"level",
"->",
"anonymousFunctionUseClause",
"!==",
"null",
"&&",
"$",
"level",
"->",
"anonymousFunctionUseClause",
"->",
"useVariableNameList",
"!==",
"null",
")",
"{",
"foreach",
"(",
"$",
"level",
"->",
"anonymousFunctionUseClause",
"->",
"useVariableNameList",
"->",
"getValues",
"(",
")",
"as",
"$",
"use",
")",
"{",
"$",
"useName",
"=",
"$",
"use",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"namePrefix",
")",
"||",
"strpos",
"(",
"$",
"useName",
",",
"$",
"namePrefix",
")",
"!==",
"false",
")",
"{",
"$",
"vars",
"[",
"$",
"useName",
"]",
"=",
"$",
"use",
";",
"}",
"}",
"}",
"}",
"return",
"array_values",
"(",
"$",
"vars",
")",
";",
"}"
] | Will walk the AST upwards until a function-like node is met
and at each level walk all previous siblings and their children to search for definitions
of that variable
@param Node $node
@param string $namePrefix Prefix to filter
@return array <Node\Expr\Variable|Node\Param|Node\Expr\ClosureUse> | [
"Will",
"walk",
"the",
"AST",
"upwards",
"until",
"a",
"function",
"-",
"like",
"node",
"is",
"met",
"and",
"at",
"each",
"level",
"walk",
"all",
"previous",
"siblings",
"and",
"their",
"children",
"to",
"search",
"for",
"definitions",
"of",
"that",
"variable"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L609-L660 | train |
felixfbecker/php-language-server | src/CompletionProvider.php | CompletionProvider.findVariableDefinitionsInNode | private function findVariableDefinitionsInNode(Node $node, string $namePrefix = ''): array
{
$vars = [];
// If the child node is a variable assignment, save it
$isAssignmentToVariable = function ($node) {
return $node instanceof Node\Expression\AssignmentExpression;
};
if ($this->isAssignmentToVariableWithPrefix($node, $namePrefix)) {
$vars[] = $node->leftOperand;
} elseif ($node instanceof Node\ForeachKey || $node instanceof Node\ForeachValue) {
foreach ($node->getDescendantNodes() as $descendantNode) {
if ($descendantNode instanceof Node\Expression\Variable
&& ($namePrefix === '' || strpos($descendantNode->getName(), $namePrefix) !== false)
) {
$vars[] = $descendantNode;
}
}
} else {
// Get all descendent variables, then filter to ones that start with $namePrefix.
// Avoiding closure usage in tight loop
foreach ($node->getDescendantNodes($isAssignmentToVariable) as $descendantNode) {
if ($this->isAssignmentToVariableWithPrefix($descendantNode, $namePrefix)) {
$vars[] = $descendantNode->leftOperand;
}
}
}
return $vars;
} | php | private function findVariableDefinitionsInNode(Node $node, string $namePrefix = ''): array
{
$vars = [];
// If the child node is a variable assignment, save it
$isAssignmentToVariable = function ($node) {
return $node instanceof Node\Expression\AssignmentExpression;
};
if ($this->isAssignmentToVariableWithPrefix($node, $namePrefix)) {
$vars[] = $node->leftOperand;
} elseif ($node instanceof Node\ForeachKey || $node instanceof Node\ForeachValue) {
foreach ($node->getDescendantNodes() as $descendantNode) {
if ($descendantNode instanceof Node\Expression\Variable
&& ($namePrefix === '' || strpos($descendantNode->getName(), $namePrefix) !== false)
) {
$vars[] = $descendantNode;
}
}
} else {
// Get all descendent variables, then filter to ones that start with $namePrefix.
// Avoiding closure usage in tight loop
foreach ($node->getDescendantNodes($isAssignmentToVariable) as $descendantNode) {
if ($this->isAssignmentToVariableWithPrefix($descendantNode, $namePrefix)) {
$vars[] = $descendantNode->leftOperand;
}
}
}
return $vars;
} | [
"private",
"function",
"findVariableDefinitionsInNode",
"(",
"Node",
"$",
"node",
",",
"string",
"$",
"namePrefix",
"=",
"''",
")",
":",
"array",
"{",
"$",
"vars",
"=",
"[",
"]",
";",
"// If the child node is a variable assignment, save it",
"$",
"isAssignmentToVariable",
"=",
"function",
"(",
"$",
"node",
")",
"{",
"return",
"$",
"node",
"instanceof",
"Node",
"\\",
"Expression",
"\\",
"AssignmentExpression",
";",
"}",
";",
"if",
"(",
"$",
"this",
"->",
"isAssignmentToVariableWithPrefix",
"(",
"$",
"node",
",",
"$",
"namePrefix",
")",
")",
"{",
"$",
"vars",
"[",
"]",
"=",
"$",
"node",
"->",
"leftOperand",
";",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"Node",
"\\",
"ForeachKey",
"||",
"$",
"node",
"instanceof",
"Node",
"\\",
"ForeachValue",
")",
"{",
"foreach",
"(",
"$",
"node",
"->",
"getDescendantNodes",
"(",
")",
"as",
"$",
"descendantNode",
")",
"{",
"if",
"(",
"$",
"descendantNode",
"instanceof",
"Node",
"\\",
"Expression",
"\\",
"Variable",
"&&",
"(",
"$",
"namePrefix",
"===",
"''",
"||",
"strpos",
"(",
"$",
"descendantNode",
"->",
"getName",
"(",
")",
",",
"$",
"namePrefix",
")",
"!==",
"false",
")",
")",
"{",
"$",
"vars",
"[",
"]",
"=",
"$",
"descendantNode",
";",
"}",
"}",
"}",
"else",
"{",
"// Get all descendent variables, then filter to ones that start with $namePrefix.",
"// Avoiding closure usage in tight loop",
"foreach",
"(",
"$",
"node",
"->",
"getDescendantNodes",
"(",
"$",
"isAssignmentToVariable",
")",
"as",
"$",
"descendantNode",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isAssignmentToVariableWithPrefix",
"(",
"$",
"descendantNode",
",",
"$",
"namePrefix",
")",
")",
"{",
"$",
"vars",
"[",
"]",
"=",
"$",
"descendantNode",
"->",
"leftOperand",
";",
"}",
"}",
"}",
"return",
"$",
"vars",
";",
"}"
] | Searches the subnodes of a node for variable assignments
@param Node $node
@param string $namePrefix Prefix to filter
@return Node\Expression\Variable[] | [
"Searches",
"the",
"subnodes",
"of",
"a",
"node",
"for",
"variable",
"assignments"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/CompletionProvider.php#L669-L699 | train |
felixfbecker/php-language-server | src/Index/AbstractAggregateIndex.php | AbstractAggregateIndex.isComplete | public function isComplete(): bool
{
foreach ($this->getIndexes() as $index) {
if (!$index->isComplete()) {
return false;
}
}
return true;
} | php | public function isComplete(): bool
{
foreach ($this->getIndexes() as $index) {
if (!$index->isComplete()) {
return false;
}
}
return true;
} | [
"public",
"function",
"isComplete",
"(",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getIndexes",
"(",
")",
"as",
"$",
"index",
")",
"{",
"if",
"(",
"!",
"$",
"index",
"->",
"isComplete",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Returns true if this index is complete
@return bool | [
"Returns",
"true",
"if",
"this",
"index",
"is",
"complete"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/Index/AbstractAggregateIndex.php#L76-L84 | train |
felixfbecker/php-language-server | src/Index/AbstractAggregateIndex.php | AbstractAggregateIndex.isStaticComplete | public function isStaticComplete(): bool
{
foreach ($this->getIndexes() as $index) {
if (!$index->isStaticComplete()) {
return false;
}
}
return true;
} | php | public function isStaticComplete(): bool
{
foreach ($this->getIndexes() as $index) {
if (!$index->isStaticComplete()) {
return false;
}
}
return true;
} | [
"public",
"function",
"isStaticComplete",
"(",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getIndexes",
"(",
")",
"as",
"$",
"index",
")",
"{",
"if",
"(",
"!",
"$",
"index",
"->",
"isStaticComplete",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Returns true if this index is complete for static definitions or references
@return bool | [
"Returns",
"true",
"if",
"this",
"index",
"is",
"complete",
"for",
"static",
"definitions",
"or",
"references"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/Index/AbstractAggregateIndex.php#L91-L99 | train |
felixfbecker/php-language-server | src/SignatureInformationFactory.php | SignatureInformationFactory.create | public function create(FunctionLike $node): SignatureInformation
{
$params = $this->createParameters($node);
$label = $this->createLabel($params);
return new SignatureInformation(
$label,
$params,
$this->definitionResolver->getDocumentationFromNode($node)
);
} | php | public function create(FunctionLike $node): SignatureInformation
{
$params = $this->createParameters($node);
$label = $this->createLabel($params);
return new SignatureInformation(
$label,
$params,
$this->definitionResolver->getDocumentationFromNode($node)
);
} | [
"public",
"function",
"create",
"(",
"FunctionLike",
"$",
"node",
")",
":",
"SignatureInformation",
"{",
"$",
"params",
"=",
"$",
"this",
"->",
"createParameters",
"(",
"$",
"node",
")",
";",
"$",
"label",
"=",
"$",
"this",
"->",
"createLabel",
"(",
"$",
"params",
")",
";",
"return",
"new",
"SignatureInformation",
"(",
"$",
"label",
",",
"$",
"params",
",",
"$",
"this",
"->",
"definitionResolver",
"->",
"getDocumentationFromNode",
"(",
"$",
"node",
")",
")",
";",
"}"
] | Create a SignatureInformation from a FunctionLike node
@param FunctionLike $node Node to create signature information from
@return SignatureInformation | [
"Create",
"a",
"SignatureInformation",
"from",
"a",
"FunctionLike",
"node"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/SignatureInformationFactory.php#L31-L40 | train |
felixfbecker/php-language-server | src/SignatureInformationFactory.php | SignatureInformationFactory.createParameters | private function createParameters(FunctionLike $node): array
{
$params = [];
if ($node->parameters) {
foreach ($node->parameters->getElements() as $element) {
$param = (string) $this->definitionResolver->getTypeFromNode($element);
$param .= ' ';
if ($element->dotDotDotToken) {
$param .= '...';
}
$param .= '$' . $element->getName();
if ($element->default) {
$param .= ' = ' . $element->default->getText();
}
$params[] = new ParameterInformation(
$param,
$this->definitionResolver->getDocumentationFromNode($element)
);
}
}
return $params;
} | php | private function createParameters(FunctionLike $node): array
{
$params = [];
if ($node->parameters) {
foreach ($node->parameters->getElements() as $element) {
$param = (string) $this->definitionResolver->getTypeFromNode($element);
$param .= ' ';
if ($element->dotDotDotToken) {
$param .= '...';
}
$param .= '$' . $element->getName();
if ($element->default) {
$param .= ' = ' . $element->default->getText();
}
$params[] = new ParameterInformation(
$param,
$this->definitionResolver->getDocumentationFromNode($element)
);
}
}
return $params;
} | [
"private",
"function",
"createParameters",
"(",
"FunctionLike",
"$",
"node",
")",
":",
"array",
"{",
"$",
"params",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"node",
"->",
"parameters",
")",
"{",
"foreach",
"(",
"$",
"node",
"->",
"parameters",
"->",
"getElements",
"(",
")",
"as",
"$",
"element",
")",
"{",
"$",
"param",
"=",
"(",
"string",
")",
"$",
"this",
"->",
"definitionResolver",
"->",
"getTypeFromNode",
"(",
"$",
"element",
")",
";",
"$",
"param",
".=",
"' '",
";",
"if",
"(",
"$",
"element",
"->",
"dotDotDotToken",
")",
"{",
"$",
"param",
".=",
"'...'",
";",
"}",
"$",
"param",
".=",
"'$'",
".",
"$",
"element",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"$",
"element",
"->",
"default",
")",
"{",
"$",
"param",
".=",
"' = '",
".",
"$",
"element",
"->",
"default",
"->",
"getText",
"(",
")",
";",
"}",
"$",
"params",
"[",
"]",
"=",
"new",
"ParameterInformation",
"(",
"$",
"param",
",",
"$",
"this",
"->",
"definitionResolver",
"->",
"getDocumentationFromNode",
"(",
"$",
"element",
")",
")",
";",
"}",
"}",
"return",
"$",
"params",
";",
"}"
] | Gets parameters from a FunctionLike node
@param FunctionLike $node Node to get parameters from
@return ParameterInformation[] | [
"Gets",
"parameters",
"from",
"a",
"FunctionLike",
"node"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/SignatureInformationFactory.php#L49-L70 | train |
felixfbecker/php-language-server | src/SignatureInformationFactory.php | SignatureInformationFactory.createLabel | private function createLabel(array $params): string
{
$label = '(';
if ($params) {
foreach ($params as $param) {
$label .= $param->label . ', ';
}
$label = substr($label, 0, -2);
}
$label .= ')';
return $label;
} | php | private function createLabel(array $params): string
{
$label = '(';
if ($params) {
foreach ($params as $param) {
$label .= $param->label . ', ';
}
$label = substr($label, 0, -2);
}
$label .= ')';
return $label;
} | [
"private",
"function",
"createLabel",
"(",
"array",
"$",
"params",
")",
":",
"string",
"{",
"$",
"label",
"=",
"'('",
";",
"if",
"(",
"$",
"params",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"param",
")",
"{",
"$",
"label",
".=",
"$",
"param",
"->",
"label",
".",
"', '",
";",
"}",
"$",
"label",
"=",
"substr",
"(",
"$",
"label",
",",
"0",
",",
"-",
"2",
")",
";",
"}",
"$",
"label",
".=",
"')'",
";",
"return",
"$",
"label",
";",
"}"
] | Creates a signature information label from parameters
@param ParameterInformation[] $params Parameters to create the label from
@return string | [
"Creates",
"a",
"signature",
"information",
"label",
"from",
"parameters"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/SignatureInformationFactory.php#L79-L90 | train |
felixfbecker/php-language-server | src/Factory/CompletionItemFactory.php | CompletionItemFactory.fromDefinition | public static function fromDefinition(Definition $def)
{
$item = new CompletionItem;
$item->label = $def->symbolInformation->name;
$item->kind = CompletionItemKind::fromSymbolKind($def->symbolInformation->kind);
if ($def->type) {
$item->detail = (string)$def->type;
} else if ($def->symbolInformation->containerName) {
$item->detail = $def->symbolInformation->containerName;
}
if ($def->documentation) {
$item->documentation = $def->documentation;
}
if ($def->isStatic && $def->symbolInformation->kind === SymbolKind::PROPERTY) {
$item->insertText = '$' . $def->symbolInformation->name;
}
return $item;
} | php | public static function fromDefinition(Definition $def)
{
$item = new CompletionItem;
$item->label = $def->symbolInformation->name;
$item->kind = CompletionItemKind::fromSymbolKind($def->symbolInformation->kind);
if ($def->type) {
$item->detail = (string)$def->type;
} else if ($def->symbolInformation->containerName) {
$item->detail = $def->symbolInformation->containerName;
}
if ($def->documentation) {
$item->documentation = $def->documentation;
}
if ($def->isStatic && $def->symbolInformation->kind === SymbolKind::PROPERTY) {
$item->insertText = '$' . $def->symbolInformation->name;
}
return $item;
} | [
"public",
"static",
"function",
"fromDefinition",
"(",
"Definition",
"$",
"def",
")",
"{",
"$",
"item",
"=",
"new",
"CompletionItem",
";",
"$",
"item",
"->",
"label",
"=",
"$",
"def",
"->",
"symbolInformation",
"->",
"name",
";",
"$",
"item",
"->",
"kind",
"=",
"CompletionItemKind",
"::",
"fromSymbolKind",
"(",
"$",
"def",
"->",
"symbolInformation",
"->",
"kind",
")",
";",
"if",
"(",
"$",
"def",
"->",
"type",
")",
"{",
"$",
"item",
"->",
"detail",
"=",
"(",
"string",
")",
"$",
"def",
"->",
"type",
";",
"}",
"else",
"if",
"(",
"$",
"def",
"->",
"symbolInformation",
"->",
"containerName",
")",
"{",
"$",
"item",
"->",
"detail",
"=",
"$",
"def",
"->",
"symbolInformation",
"->",
"containerName",
";",
"}",
"if",
"(",
"$",
"def",
"->",
"documentation",
")",
"{",
"$",
"item",
"->",
"documentation",
"=",
"$",
"def",
"->",
"documentation",
";",
"}",
"if",
"(",
"$",
"def",
"->",
"isStatic",
"&&",
"$",
"def",
"->",
"symbolInformation",
"->",
"kind",
"===",
"SymbolKind",
"::",
"PROPERTY",
")",
"{",
"$",
"item",
"->",
"insertText",
"=",
"'$'",
".",
"$",
"def",
"->",
"symbolInformation",
"->",
"name",
";",
"}",
"return",
"$",
"item",
";",
"}"
] | Creates a CompletionItem for a Definition
@param Definition $def
@return CompletionItem|null | [
"Creates",
"a",
"CompletionItem",
"for",
"a",
"Definition"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/Factory/CompletionItemFactory.php#L18-L35 | train |
felixfbecker/php-language-server | src/Client/Window.php | Window.showMessage | public function showMessage(int $type, string $message): Promise
{
return $this->handler->notify('window/showMessage', ['type' => $type, 'message' => $message]);
} | php | public function showMessage(int $type, string $message): Promise
{
return $this->handler->notify('window/showMessage', ['type' => $type, 'message' => $message]);
} | [
"public",
"function",
"showMessage",
"(",
"int",
"$",
"type",
",",
"string",
"$",
"message",
")",
":",
"Promise",
"{",
"return",
"$",
"this",
"->",
"handler",
"->",
"notify",
"(",
"'window/showMessage'",
",",
"[",
"'type'",
"=>",
"$",
"type",
",",
"'message'",
"=>",
"$",
"message",
"]",
")",
";",
"}"
] | The show message notification is sent from a server to a client
to ask the client to display a particular message in the user interface.
@param int $type
@param string $message
@return Promise <void> | [
"The",
"show",
"message",
"notification",
"is",
"sent",
"from",
"a",
"server",
"to",
"a",
"client",
"to",
"ask",
"the",
"client",
"to",
"display",
"a",
"particular",
"message",
"in",
"the",
"user",
"interface",
"."
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/Client/Window.php#L32-L35 | train |
felixfbecker/php-language-server | src/SignatureHelpProvider.php | SignatureHelpProvider.getSignatureHelp | public function getSignatureHelp(PhpDocument $doc, Position $position): Promise
{
return coroutine(function () use ($doc, $position) {
// Find the node under the cursor
$node = $doc->getNodeAtPosition($position);
// Find the definition of the item being called
list($def, $argumentExpressionList) = yield $this->getCallingInfo($node);
if (!$def || !$def->signatureInformation) {
return new SignatureHelp();
}
// Find the active parameter
$activeParam = $argumentExpressionList
? $this->findActiveParameter($argumentExpressionList, $position, $doc)
: 0;
return new SignatureHelp([$def->signatureInformation], 0, $activeParam);
});
} | php | public function getSignatureHelp(PhpDocument $doc, Position $position): Promise
{
return coroutine(function () use ($doc, $position) {
// Find the node under the cursor
$node = $doc->getNodeAtPosition($position);
// Find the definition of the item being called
list($def, $argumentExpressionList) = yield $this->getCallingInfo($node);
if (!$def || !$def->signatureInformation) {
return new SignatureHelp();
}
// Find the active parameter
$activeParam = $argumentExpressionList
? $this->findActiveParameter($argumentExpressionList, $position, $doc)
: 0;
return new SignatureHelp([$def->signatureInformation], 0, $activeParam);
});
} | [
"public",
"function",
"getSignatureHelp",
"(",
"PhpDocument",
"$",
"doc",
",",
"Position",
"$",
"position",
")",
":",
"Promise",
"{",
"return",
"coroutine",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"doc",
",",
"$",
"position",
")",
"{",
"// Find the node under the cursor",
"$",
"node",
"=",
"$",
"doc",
"->",
"getNodeAtPosition",
"(",
"$",
"position",
")",
";",
"// Find the definition of the item being called",
"list",
"(",
"$",
"def",
",",
"$",
"argumentExpressionList",
")",
"=",
"yield",
"$",
"this",
"->",
"getCallingInfo",
"(",
"$",
"node",
")",
";",
"if",
"(",
"!",
"$",
"def",
"||",
"!",
"$",
"def",
"->",
"signatureInformation",
")",
"{",
"return",
"new",
"SignatureHelp",
"(",
")",
";",
"}",
"// Find the active parameter",
"$",
"activeParam",
"=",
"$",
"argumentExpressionList",
"?",
"$",
"this",
"->",
"findActiveParameter",
"(",
"$",
"argumentExpressionList",
",",
"$",
"position",
",",
"$",
"doc",
")",
":",
"0",
";",
"return",
"new",
"SignatureHelp",
"(",
"[",
"$",
"def",
"->",
"signatureInformation",
"]",
",",
"0",
",",
"$",
"activeParam",
")",
";",
"}",
")",
";",
"}"
] | Finds signature help for a callable position
@param PhpDocument $doc The document the position belongs to
@param Position $position The position to detect a call from
@return Promise <SignatureHelp> | [
"Finds",
"signature",
"help",
"for",
"a",
"callable",
"position"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/SignatureHelpProvider.php#L48-L68 | train |
felixfbecker/php-language-server | src/SignatureHelpProvider.php | SignatureHelpProvider.getCallingInfo | private function getCallingInfo(Node $node)
{
return coroutine(function () use ($node) {
$fqn = null;
$callingNode = null;
if ($node instanceof Node\DelimitedList\ArgumentExpressionList) {
// Cursor is already inside a (
$argumentExpressionList = $node;
if ($node->parent instanceof Node\Expression\ObjectCreationExpression) {
// Constructing something
$callingNode = $node->parent->classTypeDesignator;
if (!$callingNode instanceof Node\QualifiedName) {
// We only support constructing from a QualifiedName
return null;
}
$fqn = $this->definitionResolver->resolveReferenceNodeToFqn($callingNode);
$fqn = "{$fqn}->__construct()";
} else {
$callingNode = $node->parent->getFirstChildNode(
Node\Expression\MemberAccessExpression::class,
Node\Expression\ScopedPropertyAccessExpression::class,
Node\QualifiedName::class
);
}
} elseif ($node instanceof Node\Expression\CallExpression) {
$argumentExpressionList = $node->getFirstChildNode(Node\DelimitedList\ArgumentExpressionList::class);
$callingNode = $node->getFirstChildNode(
Node\Expression\MemberAccessExpression::class,
Node\Expression\ScopedPropertyAccessExpression::class,
Node\QualifiedName::class
);
} elseif ($node instanceof Node\Expression\ObjectCreationExpression) {
$argumentExpressionList = $node->getFirstChildNode(Node\DelimitedList\ArgumentExpressionList::class);
$callingNode = $node->classTypeDesignator;
if (!$callingNode instanceof Node\QualifiedName) {
// We only support constructing from a QualifiedName
return null;
}
// Manually build the __construct fqn
$fqn = $this->definitionResolver->resolveReferenceNodeToFqn($callingNode);
$fqn = "{$fqn}->__construct()";
}
if (!$callingNode) {
return null;
}
// Now find the definition of the call
$fqn = $fqn ?: DefinitionResolver::getDefinedFqn($callingNode);
while (true) {
if ($fqn) {
$def = $this->index->getDefinition($fqn);
} else {
$def = $this->definitionResolver->resolveReferenceNodeToDefinition($callingNode);
}
if ($def !== null || $this->index->isComplete()) {
break;
}
yield waitForEvent($this->index, 'definition-added');
}
if (!$def) {
return null;
}
return [$def, $argumentExpressionList];
});
} | php | private function getCallingInfo(Node $node)
{
return coroutine(function () use ($node) {
$fqn = null;
$callingNode = null;
if ($node instanceof Node\DelimitedList\ArgumentExpressionList) {
// Cursor is already inside a (
$argumentExpressionList = $node;
if ($node->parent instanceof Node\Expression\ObjectCreationExpression) {
// Constructing something
$callingNode = $node->parent->classTypeDesignator;
if (!$callingNode instanceof Node\QualifiedName) {
// We only support constructing from a QualifiedName
return null;
}
$fqn = $this->definitionResolver->resolveReferenceNodeToFqn($callingNode);
$fqn = "{$fqn}->__construct()";
} else {
$callingNode = $node->parent->getFirstChildNode(
Node\Expression\MemberAccessExpression::class,
Node\Expression\ScopedPropertyAccessExpression::class,
Node\QualifiedName::class
);
}
} elseif ($node instanceof Node\Expression\CallExpression) {
$argumentExpressionList = $node->getFirstChildNode(Node\DelimitedList\ArgumentExpressionList::class);
$callingNode = $node->getFirstChildNode(
Node\Expression\MemberAccessExpression::class,
Node\Expression\ScopedPropertyAccessExpression::class,
Node\QualifiedName::class
);
} elseif ($node instanceof Node\Expression\ObjectCreationExpression) {
$argumentExpressionList = $node->getFirstChildNode(Node\DelimitedList\ArgumentExpressionList::class);
$callingNode = $node->classTypeDesignator;
if (!$callingNode instanceof Node\QualifiedName) {
// We only support constructing from a QualifiedName
return null;
}
// Manually build the __construct fqn
$fqn = $this->definitionResolver->resolveReferenceNodeToFqn($callingNode);
$fqn = "{$fqn}->__construct()";
}
if (!$callingNode) {
return null;
}
// Now find the definition of the call
$fqn = $fqn ?: DefinitionResolver::getDefinedFqn($callingNode);
while (true) {
if ($fqn) {
$def = $this->index->getDefinition($fqn);
} else {
$def = $this->definitionResolver->resolveReferenceNodeToDefinition($callingNode);
}
if ($def !== null || $this->index->isComplete()) {
break;
}
yield waitForEvent($this->index, 'definition-added');
}
if (!$def) {
return null;
}
return [$def, $argumentExpressionList];
});
} | [
"private",
"function",
"getCallingInfo",
"(",
"Node",
"$",
"node",
")",
"{",
"return",
"coroutine",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"node",
")",
"{",
"$",
"fqn",
"=",
"null",
";",
"$",
"callingNode",
"=",
"null",
";",
"if",
"(",
"$",
"node",
"instanceof",
"Node",
"\\",
"DelimitedList",
"\\",
"ArgumentExpressionList",
")",
"{",
"// Cursor is already inside a (",
"$",
"argumentExpressionList",
"=",
"$",
"node",
";",
"if",
"(",
"$",
"node",
"->",
"parent",
"instanceof",
"Node",
"\\",
"Expression",
"\\",
"ObjectCreationExpression",
")",
"{",
"// Constructing something",
"$",
"callingNode",
"=",
"$",
"node",
"->",
"parent",
"->",
"classTypeDesignator",
";",
"if",
"(",
"!",
"$",
"callingNode",
"instanceof",
"Node",
"\\",
"QualifiedName",
")",
"{",
"// We only support constructing from a QualifiedName",
"return",
"null",
";",
"}",
"$",
"fqn",
"=",
"$",
"this",
"->",
"definitionResolver",
"->",
"resolveReferenceNodeToFqn",
"(",
"$",
"callingNode",
")",
";",
"$",
"fqn",
"=",
"\"{$fqn}->__construct()\"",
";",
"}",
"else",
"{",
"$",
"callingNode",
"=",
"$",
"node",
"->",
"parent",
"->",
"getFirstChildNode",
"(",
"Node",
"\\",
"Expression",
"\\",
"MemberAccessExpression",
"::",
"class",
",",
"Node",
"\\",
"Expression",
"\\",
"ScopedPropertyAccessExpression",
"::",
"class",
",",
"Node",
"\\",
"QualifiedName",
"::",
"class",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"Node",
"\\",
"Expression",
"\\",
"CallExpression",
")",
"{",
"$",
"argumentExpressionList",
"=",
"$",
"node",
"->",
"getFirstChildNode",
"(",
"Node",
"\\",
"DelimitedList",
"\\",
"ArgumentExpressionList",
"::",
"class",
")",
";",
"$",
"callingNode",
"=",
"$",
"node",
"->",
"getFirstChildNode",
"(",
"Node",
"\\",
"Expression",
"\\",
"MemberAccessExpression",
"::",
"class",
",",
"Node",
"\\",
"Expression",
"\\",
"ScopedPropertyAccessExpression",
"::",
"class",
",",
"Node",
"\\",
"QualifiedName",
"::",
"class",
")",
";",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"Node",
"\\",
"Expression",
"\\",
"ObjectCreationExpression",
")",
"{",
"$",
"argumentExpressionList",
"=",
"$",
"node",
"->",
"getFirstChildNode",
"(",
"Node",
"\\",
"DelimitedList",
"\\",
"ArgumentExpressionList",
"::",
"class",
")",
";",
"$",
"callingNode",
"=",
"$",
"node",
"->",
"classTypeDesignator",
";",
"if",
"(",
"!",
"$",
"callingNode",
"instanceof",
"Node",
"\\",
"QualifiedName",
")",
"{",
"// We only support constructing from a QualifiedName",
"return",
"null",
";",
"}",
"// Manually build the __construct fqn",
"$",
"fqn",
"=",
"$",
"this",
"->",
"definitionResolver",
"->",
"resolveReferenceNodeToFqn",
"(",
"$",
"callingNode",
")",
";",
"$",
"fqn",
"=",
"\"{$fqn}->__construct()\"",
";",
"}",
"if",
"(",
"!",
"$",
"callingNode",
")",
"{",
"return",
"null",
";",
"}",
"// Now find the definition of the call",
"$",
"fqn",
"=",
"$",
"fqn",
"?",
":",
"DefinitionResolver",
"::",
"getDefinedFqn",
"(",
"$",
"callingNode",
")",
";",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"$",
"fqn",
")",
"{",
"$",
"def",
"=",
"$",
"this",
"->",
"index",
"->",
"getDefinition",
"(",
"$",
"fqn",
")",
";",
"}",
"else",
"{",
"$",
"def",
"=",
"$",
"this",
"->",
"definitionResolver",
"->",
"resolveReferenceNodeToDefinition",
"(",
"$",
"callingNode",
")",
";",
"}",
"if",
"(",
"$",
"def",
"!==",
"null",
"||",
"$",
"this",
"->",
"index",
"->",
"isComplete",
"(",
")",
")",
"{",
"break",
";",
"}",
"yield",
"waitForEvent",
"(",
"$",
"this",
"->",
"index",
",",
"'definition-added'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"def",
")",
"{",
"return",
"null",
";",
"}",
"return",
"[",
"$",
"def",
",",
"$",
"argumentExpressionList",
"]",
";",
"}",
")",
";",
"}"
] | Given a node that could be a callable, finds the definition of the call and the argument expression list of
the node
@param Node $node The node to find calling information from
@return Promise <array|null> | [
"Given",
"a",
"node",
"that",
"could",
"be",
"a",
"callable",
"finds",
"the",
"definition",
"of",
"the",
"call",
"and",
"the",
"argument",
"expression",
"list",
"of",
"the",
"node"
] | 9dc16565922ae1fcf18a69b15b3cd15152ea21e6 | https://github.com/felixfbecker/php-language-server/blob/9dc16565922ae1fcf18a69b15b3cd15152ea21e6/src/SignatureHelpProvider.php#L78-L145 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.