idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
8,000
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
8,001
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
8,002
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
8,003
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
8,004
public function reply_link ( $ reply_text = 'Reply' ) { if ( is_singular ( ) && comments_open ( ) && get_option ( 'thread_comments' ) ) { wp_enqueue_script ( 'comment-reply' ) ; } $ max_depth = get_option ( 'thread_comments_depth' ) ; $ 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 .
8,005
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
8,006
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
8,007
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
8,008
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
8,009
public function terms ( $ args = array ( ) , $ merge = true , $ term_class = '' ) { 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 ; } } $ 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 ( ) ; if ( is_string ( $ merge ) && class_exists ( $ merge ) ) { $ term_class = $ merge ; } 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 ) ; } } $ 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 ) ) { 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 ; } $ 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 ( ) ; foreach ( $ taxonomies as $ taxonomy ) { $ terms_sorted [ $ taxonomy ] = array ( ) ; } foreach ( $ terms as $ term ) { $ terms_sorted [ $ term -> taxonomy ] [ ] = $ term ; } return $ terms_sorted ; } return $ terms ; }
Gets the terms associated with the post .
8,010
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 .
8,011
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!
8,012
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
8,013
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
8,014
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
8,015
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
8,016
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
8,017
public function audio ( ) { if ( isset ( $ this -> custom [ 'audio' ] ) ) { return $ this -> custom [ 'audio' ] ; } $ audio = false ; 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
8,018
public function video ( ) { if ( isset ( $ this -> custom [ 'video' ] ) ) { return $ this -> custom [ 'video' ] ; } $ video = false ; 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
8,019
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
8,020
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
8,021
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 ) { return false ; } $ enable_transients = false ; } 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
8,022
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
8,023
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
8,024
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
8,025
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 .
8,026
protected function get_roles ( $ roles ) { if ( empty ( $ roles ) ) { return null ; } $ 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 .
8,027
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
8,028
public function name ( ) { if ( $ title = $ this -> title ( ) ) { return $ title ; } if ( isset ( $ this -> _name ) ) { return $ this -> _name ; } return '' ; }
Get the label for the menu item .
8,029
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 .
8,030
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 .
8,031
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 .
8,032
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 .
8,033
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 .
8,034
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 .
8,035
private function getValue ( $ which = 'new' ) { $ which_value = $ which . '_value' ; $ main_model = $ this -> revisionable_type ; if ( class_exists ( $ main_model ) ) { $ main_model = new $ main_model ; try { if ( $ this -> isRelated ( ) ) { $ related_model = $ this -> getRelatedModel ( ) ; if ( ! method_exists ( $ main_model , $ related_model ) ) { $ related_model = camel_case ( $ related_model ) ; 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 ( ) ; $ 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 ( ) ) ; } if ( method_exists ( $ item , 'identifiableName' ) ) { $ 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 ) { } $ 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 .
8,036
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 .
8,037
private function getRelatedModel ( ) { $ idSuffix = '_id' ; return substr ( $ this -> key , 0 , strlen ( $ this -> key ) - strlen ( $ idSuffix ) ) ; }
Return the name of the related model .
8,038
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 .
8,039
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 .
8,040
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 .
8,041
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 .
8,042
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
8,043
private function changedRevisionableFields ( ) { $ changes_to_record = array ( ) ; foreach ( $ this -> dirtyData as $ key => $ value ) { if ( $ this -> isRevisionable ( $ key ) && ! is_array ( $ value ) ) { if ( ! isset ( $ this -> originalData [ $ key ] ) || $ this -> originalData [ $ key ] != $ this -> updatedData [ $ key ] ) { $ changes_to_record [ $ key ] = $ value ; } } else { 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
8,044
private function isSoftDelete ( ) { if ( isset ( $ this -> forceDeleting ) ) { return ! $ this -> forceDeleting ; } if ( isset ( $ this -> softDelete ) ) { return $ this -> softDelete ; } return false ; }
Check if soft deletes are currently enabled on this model
8,045
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
8,046
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
8,047
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
8,048
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
8,049
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
8,050
public function delete ( $ index , $ type , $ id , $ options = [ ] ) { return $ this -> db -> delete ( [ $ index , $ type , $ id ] , $ options ) ; }
deletes a document from the index
8,051
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
8,052
public function createIndex ( $ index , $ configuration = null ) { $ body = $ configuration !== null ? Json :: encode ( $ configuration ) : null ; return $ this -> db -> put ( [ $ index ] , [ ] , $ body ) ; }
creates an index
8,053
protected function selectActiveNode ( ) { $ keys = array_keys ( $ this -> nodes ) ; $ this -> activeNode = $ keys [ rand ( 0 , count ( $ keys ) - 1 ) ] ; }
select active node randomly
8,054
public function createBulkCommand ( $ config = [ ] ) { $ this -> open ( ) ; $ config [ 'db' ] = $ this ; $ command = new BulkCommand ( $ config ) ; return $ command ; }
Creates a bulk command for execution .
8,055
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
8,056
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 .
8,057
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 { $ 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
8,058
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 .
8,059
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 .
8,060
public function delete ( $ db = null , $ options = [ ] ) { if ( $ this -> emulateExecution ) { return [ ] ; } return $ this -> createCommand ( $ db ) -> deleteByQuery ( $ options ) ; }
Executes the query and deletes all matching documents .
8,061
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 .
8,062
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 .
8,063
public function from ( $ index , $ type = null ) { $ this -> index = $ index ; $ this -> type = $ type ; return $ this ; }
Sets the index and type to retrieve documents from .
8,064
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 .
8,065
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 .
8,066
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 .
8,067
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 .
8,068
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' ; } if ( is_array ( $ direction ) ) { $ orders [ ] = [ $ column => $ direction ] ; } else { $ orders [ ] = [ $ column => ( $ direction === SORT_DESC ? 'desc' : 'asc' ) ] ; } } return $ orders ; }
adds order by condition to the query
8,069
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 ] ; } if ( $ text instanceof \ Exception ) { $ 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 .
8,070
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 .
8,071
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 .
8,072
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 .
8,073
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 .
8,074
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 .
8,075
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
8,076
public function execute ( ) { 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 .
8,077
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 .
8,078
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 .
8,079
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 ) ; } if ( strlen ( $ message ) === 0 ) { array_shift ( $ this -> messages ) ; 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 .
8,080
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 .
8,081
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
8,082
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 .
8,083
private function getUnqualifiedCompletions ( string $ prefix , string $ currentNamespace , array $ importTables , bool $ requireCanBeInstantiated ) : \ Generator { list ( $ namespaceAliases , , ) = $ importTables ; yield from $ this -> getCompletionsForAliases ( $ prefix , $ namespaceAliases , $ requireCanBeInstantiated ) ; yield from $ this -> getCompletionsForFqnPrefix ( nameConcat ( $ currentNamespace , $ prefix ) , $ requireCanBeInstantiated , false ) ; if ( $ currentNamespace !== '' && $ prefix === '' ) { yield from $ this -> getCompletionsForFqnPrefix ( '' , $ requireCanBeInstantiated , true ) ; } if ( ! $ requireCanBeInstantiated ) { if ( $ currentNamespace !== '' && $ prefix !== '' ) { yield from $ this -> getRoamedCompletions ( $ prefix ) ; } yield from $ this -> getCompletionsForKeywords ( $ prefix ) ; } }
Yields completions for non - qualified global names .
8,084
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 .
8,085
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 .
8,086
private function getCompletionsFromAliasedNamespace ( string $ prefix , string $ alias , string $ aliasFqn , bool $ requireCanBeInstantiated ) : \ Generator { $ prefixFirstPart = nameGetFirstPart ( $ prefix ) ; $ resolvedPrefix = nameConcat ( $ aliasFqn , nameWithoutFirstPart ( $ prefix ) ) ; $ completionItems = $ this -> getCompletionsForFqnPrefix ( $ resolvedPrefix , $ requireCanBeInstantiated , false ) ; foreach ( $ completionItems as $ fqn => $ completionItem ) { $ 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 .
8,087
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 .
8,088
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
8,089
private function suggestVariablesAtNode ( Node $ node , string $ namePrefix = '' ) : array { $ vars = [ ] ; foreach ( $ this -> findVariableDefinitionsInNode ( $ node , $ namePrefix ) as $ var ) { if ( ! isset ( $ vars [ $ var -> name ] ) ) { $ vars [ $ var -> name ] = $ var ; } } $ level = $ node ; while ( $ level && ! ( $ level instanceof PhpParser \ FunctionLike ) ) { $ sibling = $ level ; while ( $ sibling = $ sibling -> getPreviousSibling ( ) ) { foreach ( $ this -> findVariableDefinitionsInNode ( $ sibling , $ namePrefix ) as $ var ) { $ vars [ $ var -> getName ( ) ] = $ var ; } } $ level = $ level -> parent ; } 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
8,090
private function findVariableDefinitionsInNode ( Node $ node , string $ namePrefix = '' ) : array { $ vars = [ ] ; $ 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 { 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
8,091
public function isComplete ( ) : bool { foreach ( $ this -> getIndexes ( ) as $ index ) { if ( ! $ index -> isComplete ( ) ) { return false ; } } return true ; }
Returns true if this index is complete
8,092
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
8,093
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
8,094
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
8,095
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
8,096
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
8,097
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 .
8,098
public function getSignatureHelp ( PhpDocument $ doc , Position $ position ) : Promise { return coroutine ( function ( ) use ( $ doc , $ position ) { $ node = $ doc -> getNodeAtPosition ( $ position ) ; list ( $ def , $ argumentExpressionList ) = yield $ this -> getCallingInfo ( $ node ) ; if ( ! $ def || ! $ def -> signatureInformation ) { return new SignatureHelp ( ) ; } $ activeParam = $ argumentExpressionList ? $ this -> findActiveParameter ( $ argumentExpressionList , $ position , $ doc ) : 0 ; return new SignatureHelp ( [ $ def -> signatureInformation ] , 0 , $ activeParam ) ; } ) ; }
Finds signature help for a callable position
8,099
private function getCallingInfo ( Node $ node ) { return coroutine ( function ( ) use ( $ node ) { $ fqn = null ; $ callingNode = null ; if ( $ node instanceof Node \ DelimitedList \ ArgumentExpressionList ) { $ argumentExpressionList = $ node ; if ( $ node -> parent instanceof Node \ Expression \ ObjectCreationExpression ) { $ callingNode = $ node -> parent -> classTypeDesignator ; if ( ! $ callingNode instanceof Node \ 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 ) { return null ; } $ fqn = $ this -> definitionResolver -> resolveReferenceNodeToFqn ( $ callingNode ) ; $ fqn = "{$fqn}->__construct()" ; } if ( ! $ callingNode ) { return null ; } $ 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