idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
3,000
protected function getInputValueDefinitions ( Collection $ argumentValues ) : array { return $ argumentValues -> mapWithKeys ( function ( ArgumentValue $ argumentValue ) : array { return [ $ argumentValue -> getName ( ) => $ this -> argumentFactory -> handle ( $ argumentValue ) , ] ; } ) -> all ( ) ; }
Transform the ArgumentValues into the final InputValueDefinitions .
3,001
public static function handle ( Error $ error , Closure $ next ) : array { $ underlyingException = $ error -> getPrevious ( ) ; if ( $ underlyingException instanceof RendersErrorsExtensions ) { $ error = new Error ( $ error -> message , $ error -> nodes , $ error -> getSource ( ) , $ error -> getPositions ( ) , $ error -> getPath ( ) , $ underlyingException , $ underlyingException -> extensionsContent ( ) ) ; } return $ next ( $ error ) ; }
Handle Exceptions that implement Nuwave \ Lighthouse \ Exceptions \ RendersErrorsExtensions and add extra content from them to the extensions key of the Error that is rendered to the User .
3,002
public function serialize ( GraphQLContext $ context ) : string { $ request = $ context -> request ( ) ; return serialize ( [ 'request' => [ 'query' => $ request -> query -> all ( ) , 'request' => $ request -> request -> all ( ) , 'attributes' => $ request -> attributes -> all ( ) , 'cookies' => [ ] , 'files' => [ ] , 'server' => Arr :: except ( $ request -> server -> all ( ) , [ 'HTTP_AUTHORIZATION' ] ) , 'content' => $ request -> getContent ( ) , ] , 'user' => serialize ( $ context -> user ( ) ) , ] ) ; }
Serialize the context .
3,003
public function unserialize ( string $ context ) : GraphQLContext { [ 'request' => $ rawRequest , 'user' => $ rawUser ] = unserialize ( $ context ) ; $ request = new Request ( $ rawRequest [ 'query' ] , $ rawRequest [ 'request' ] , $ rawRequest [ 'attributes' ] , $ rawRequest [ 'cookies' ] , $ rawRequest [ 'files' ] , $ rawRequest [ 'server' ] , $ rawRequest [ 'content' ] ) ; $ request -> setUserResolver ( function ( ) use ( $ rawUser ) { return unserialize ( $ rawUser ) ; } ) ; return $ this -> createsContext -> generate ( $ request ) ; }
Unserialize the context .
3,004
public function variables ( ) : array { $ variables = $ this -> fieldValue ( 'variables' ) ; if ( is_string ( $ variables ) ) { return json_decode ( $ variables , true ) ?? [ ] ; } return $ variables ?? [ ] ; }
Get the given variables for the query .
3,005
protected function fieldValue ( string $ key ) { return $ this -> request -> input ( $ key ) ?? $ this -> request -> input ( "{$this->batchIndex}.{$key}" ) ; }
Get the contents of a field by key .
3,006
public static function getInstance ( FieldValue $ value ) : self { $ handler = 'query.filter' . '.' . strtolower ( $ value -> getParentName ( ) ) . '.' . strtolower ( $ value -> getFieldName ( ) ) ; return app ( ) -> bound ( $ handler ) ? app ( $ handler ) : app ( ) -> instance ( $ handler , app ( static :: class ) ) ; }
Get the single instance of the query filter for a field .
3,007
public static function apply ( $ query , array $ args , array $ scopes , ResolveInfo $ resolveInfo ) { if ( $ queryFilter = $ resolveInfo -> queryFilter ?? false ) { $ query = $ queryFilter -> filter ( $ query , $ args ) ; } foreach ( $ scopes as $ scope ) { call_user_func ( [ $ query , $ scope ] , $ args ) ; } return $ query ; }
Check if the ResolveInfo contains a QueryFilter instance and apply it to the query if given .
3,008
public function filter ( $ query , array $ args = [ ] ) { $ valuesGroupedByFilterKey = [ ] ; foreach ( $ args as $ key => $ value ) { foreach ( $ this -> multiArgumentFiltersArgNames as $ filterKey => $ argNames ) { if ( in_array ( $ key , $ argNames ) ) { $ valuesGroupedByFilterKey [ $ filterKey ] [ ] = $ value ; } } if ( $ filterInfo = Arr :: get ( $ this -> singleArgumentFilters , $ key ) ) { $ argFilterDirective = $ filterInfo [ 'filter' ] ; $ columnName = $ filterInfo [ 'columnName' ] ; $ query = $ argFilterDirective -> applyFilter ( $ query , $ columnName , $ value ) ; } } foreach ( $ valuesGroupedByFilterKey as $ filterKey => $ values ) { $ columnName = Str :: before ( $ filterKey , '.' ) ; if ( $ values ) { $ argFilterDirective = $ this -> multiArgumentFilters [ $ filterKey ] ; $ query = $ argFilterDirective -> applyFilter ( $ query , $ columnName , $ values ) ; } } return $ query ; }
Apply all registered filters to the query .
3,009
public function addArgumentFilter ( string $ argumentName , string $ columnName , ArgFilterDirective $ argFilterDirective ) : self { if ( $ argFilterDirective -> combinesMultipleArguments ( ) ) { $ filterKey = "{$columnName}.{$argFilterDirective->name()}" ; $ this -> multiArgumentFilters [ $ filterKey ] = $ argFilterDirective ; $ this -> multiArgumentFiltersArgNames [ $ filterKey ] [ ] = $ argumentName ; } else { $ this -> singleArgumentFilters [ $ argumentName ] = [ 'filter' => $ argFilterDirective , 'columnName' => $ columnName , ] ; } return $ this ; }
Add the argument filter .
3,010
public function handleBuilder ( $ builder , $ value ) { $ clause = $ this -> directiveArgValue ( 'clause' , 'where' ) ; return $ builder -> { $ clause } ( $ this -> directiveArgValue ( 'key' , $ this -> definitionNode -> name -> value ) , $ operator = $ this -> directiveArgValue ( 'operator' , '=' ) , $ value ) ; }
Add any WHERE clause to the builder .
3,011
public function register ( ) : void { $ this -> app -> singleton ( BroadcastManager :: class ) ; $ this -> app -> singleton ( SubscriptionRegistry :: class ) ; $ this -> app -> singleton ( StoresSubscriptions :: class , StorageManager :: class ) ; $ this -> app -> bind ( ContextSerializer :: class , Serializer :: class ) ; $ this -> app -> bind ( AuthorizesSubscriptions :: class , Authorizer :: class ) ; $ this -> app -> bind ( SubscriptionIterator :: class , SyncIterator :: class ) ; $ this -> app -> bind ( SubscriptionExceptionHandler :: class , ExceptionHandler :: class ) ; $ this -> app -> bind ( BroadcastsSubscriptions :: class , SubscriptionBroadcaster :: class ) ; $ this -> app -> bind ( ProvidesSubscriptionResolver :: class , SubscriptionResolverProvider :: class ) ; }
Register subscription services .
3,012
public static function mergeUniqueNodeList ( $ original , $ addition , bool $ overwriteDuplicates = false ) : NodeList { $ newNames = ( new Collection ( $ addition ) ) -> pluck ( 'name.value' ) -> filter ( ) -> all ( ) ; $ remainingDefinitions = ( new Collection ( $ original ) ) -> reject ( function ( $ definition ) use ( $ newNames , $ overwriteDuplicates ) : bool { $ oldName = $ definition -> name -> value ; $ collisionOccurred = in_array ( $ oldName , $ newNames ) ; if ( $ collisionOccurred && ! $ overwriteDuplicates ) { throw new DefinitionException ( "Duplicate definition {$oldName} found when merging." ) ; } return $ collisionOccurred ; } ) -> values ( ) -> all ( ) ; return self :: mergeNodeList ( $ remainingDefinitions , $ addition ) ; }
This function will merge two lists uniquely by name .
3,013
public static function directiveHasArgument ( DirectiveNode $ directiveDefinition , string $ name ) : bool { return ( new Collection ( $ directiveDefinition -> arguments ) ) -> contains ( function ( ArgumentNode $ argumentNode ) use ( $ name ) : bool { return $ argumentNode -> name -> value === $ name ; } ) ; }
Does the given directive have an argument of the given name?
3,014
public static function argValue ( ArgumentNode $ arg , $ default = null ) { $ valueNode = $ arg -> value ; if ( ! $ valueNode ) { return $ default ; } return AST :: valueFromASTUntyped ( $ valueNode ) ; }
Get argument s value .
3,015
public static function directiveDefinition ( Node $ definitionNode , string $ name ) : ? DirectiveNode { return ( new Collection ( $ definitionNode -> directives ) ) -> first ( function ( DirectiveNode $ directiveDefinitionNode ) use ( $ name ) : bool { return $ directiveDefinitionNode -> name -> value === $ name ; } ) ; }
This can be at most one directive since directives can only be used once per location .
3,016
public static function hasDirectiveDefinition ( Node $ definitionNode , string $ name ) : bool { return ( new Collection ( $ definitionNode -> directives ) ) -> contains ( function ( DirectiveNode $ directiveDefinitionNode ) use ( $ name ) : bool { return $ directiveDefinitionNode -> name -> value === $ name ; } ) ; }
Check if a node has a particular directive defined upon it .
3,017
public static function attachDirectiveToObjectTypeFields ( DocumentAST $ documentAST , DirectiveNode $ directive ) : DocumentAST { return $ documentAST -> objectTypeDefinitions ( ) -> reduce ( function ( DocumentAST $ document , ObjectTypeDefinitionNode $ objectType ) use ( $ directive ) : DocumentAST { if ( ! data_get ( $ objectType , 'name.value' ) ) { return $ document ; } $ objectType -> fields = new NodeList ( ( new Collection ( $ objectType -> fields ) ) -> map ( function ( FieldDefinitionNode $ field ) use ( $ directive ) : FieldDefinitionNode { $ field -> directives = $ field -> directives -> merge ( [ $ directive ] ) ; return $ field ; } ) -> all ( ) ) ; $ document -> setDefinition ( $ objectType ) ; return $ document ; } , $ documentAST ) ; }
Attach directive to all registered object type fields .
3,018
public static function attachNodeInterfaceToObjectType ( ObjectTypeDefinitionNode $ objectType , DocumentAST $ documentAST ) : DocumentAST { $ objectType -> interfaces = self :: mergeNodeList ( $ objectType -> interfaces , [ Parser :: parseType ( 'Node' , [ 'noLocation' => true ] ) , ] ) ; $ globalIdFieldDefinition = PartialParser :: fieldDefinition ( config ( 'lighthouse.global_id_field' ) . ': ID! @globalId' ) ; $ objectType -> fields = $ objectType -> fields -> merge ( [ $ globalIdFieldDefinition ] ) ; return $ documentAST -> setDefinition ( $ objectType ) ; }
This adds an Interface called Node to an ObjectType definition .
3,019
public function pageInfoResolver ( LengthAwarePaginator $ paginator ) : array { return [ 'total' => $ paginator -> total ( ) , 'count' => $ paginator -> count ( ) , 'currentPage' => $ paginator -> currentPage ( ) , 'lastPage' => $ paginator -> lastPage ( ) , 'hasNextPage' => $ paginator -> hasMorePages ( ) , 'hasPreviousPage' => $ paginator -> currentPage ( ) > 1 , 'startCursor' => $ paginator -> firstItem ( ) ? Cursor :: encode ( $ paginator -> firstItem ( ) ) : null , 'endCursor' => $ paginator -> lastItem ( ) ? Cursor :: encode ( $ paginator -> lastItem ( ) ) : null , ] ; }
Resolve page info for connection .
3,020
public function edgeResolver ( LengthAwarePaginator $ paginator ) : Collection { $ firstItem = $ paginator -> firstItem ( ) ; return $ paginator -> values ( ) -> map ( function ( $ item , $ index ) use ( $ firstItem ) { return [ 'cursor' => Cursor :: encode ( $ firstItem + $ index ) , 'node' => $ item , ] ; } ) ; }
Resolve edges for connection .
3,021
public function resolve ( ) : array { $ modelRelationFetcher = $ this -> getRelationFetcher ( ) ; if ( $ this -> first !== null ) { $ modelRelationFetcher -> loadRelationsForPage ( $ this -> first , $ this -> page ) ; } else { $ modelRelationFetcher -> loadRelations ( ) ; } return $ modelRelationFetcher -> getRelationDictionary ( $ this -> relationName ) ; }
Resolve the keys .
3,022
protected function getRelationFetcher ( ) : ModelRelationFetcher { return new ModelRelationFetcher ( $ this -> getParentModels ( ) , [ $ this -> relationName => function ( $ query ) { return $ this -> resolveInfo -> builder -> addScopes ( $ this -> scopes ) -> apply ( $ query , $ this -> args ) ; } ] ) ; }
Construct a new instance of a relation fetcher .
3,023
public function getResolverFromArgument ( string $ argumentName ) : Closure { [ $ className , $ methodName ] = $ this -> getMethodArgumentParts ( $ argumentName ) ; $ namespacedClassName = $ this -> namespaceClassName ( $ className ) ; return Utils :: constructResolver ( $ namespacedClassName , $ methodName ) ; }
Get a Closure that is defined through an argument on the directive .
3,024
protected function getMethodArgumentParts ( string $ argumentName ) : array { $ argumentParts = explode ( '@' , $ this -> directiveArgValue ( $ argumentName ) ) ; if ( count ( $ argumentParts ) !== 2 || empty ( $ argumentParts [ 0 ] ) || empty ( $ argumentParts [ 1 ] ) ) { throw new DirectiveException ( "Directive '{$this->name()}' must have an argument '{$argumentName}' in the form 'ClassName@methodName'" ) ; } return $ argumentParts ; }
Split a single method argument into its parts .
3,025
protected function namespaceModelClass ( string $ modelClassCandidate ) : string { return $ this -> namespaceClassName ( $ modelClassCandidate , ( array ) config ( 'lighthouse.namespaces.models' ) , function ( string $ classCandidate ) : bool { return is_subclass_of ( $ classCandidate , Model :: class ) ; } ) ; }
Try adding the default model namespace and ensure the given class is a model .
3,026
public function registerModel ( string $ typeName , string $ modelName ) : self { $ this -> nodeResolver [ $ typeName ] = function ( $ id ) use ( $ modelName ) { return $ modelName :: find ( $ id ) ; } ; return $ this ; }
Register an Eloquent model that can be resolved as a Node .
3,027
public function resolve ( $ rootValue , array $ args , GraphQLContext $ context , ResolveInfo $ resolveInfo ) { [ $ decodedType , $ decodedId ] = $ args [ 'id' ] ; if ( ! $ resolver = Arr :: get ( $ this -> nodeResolver , $ decodedType ) ) { throw new Error ( "[{$decodedType}] is not a registered node and cannot be resolved." ) ; } $ this -> currentType = $ decodedType ; return $ resolver ( $ decodedId , $ context , $ resolveInfo ) ; }
Get the appropriate resolver for the node and call it with the decoded id .
3,028
protected static function getFirstAndValidateType ( NodeList $ list , string $ expectedType ) : Node { if ( $ list -> count ( ) !== 1 ) { throw new ParseException ( 'More than one definition was found in the passed in schema.' ) ; } $ node = $ list [ 0 ] ; return self :: validateType ( $ node , $ expectedType ) ; }
Get the first Node from a given NodeList and validate it .
3,029
protected function carry ( ) : Closure { return function ( $ stack , $ pipe ) { return function ( $ passable ) use ( $ stack , $ pipe ) { if ( $ this -> always !== null ) { $ passable = ( $ this -> always ) ( $ passable , $ pipe ) ; } $ slice = parent :: carry ( ) ; $ callable = $ slice ( $ stack , $ pipe ) ; return $ callable ( $ passable ) ; } ; } ; }
Get a \ Closure that represents a slice of the application onion .
3,030
public function executeRequest ( GraphQLRequest $ request ) : array { $ result = $ this -> executeQuery ( $ request -> query ( ) , $ this -> createsContext -> generate ( app ( 'request' ) ) , $ request -> variables ( ) , null , $ request -> operationName ( ) ) ; return $ this -> applyDebugSettings ( $ result ) ; }
Execute a set of batched queries on the lighthouse schema and return a collection of ExecutionResults .
3,031
public function executeQuery ( $ query , GraphQLContext $ context , ? array $ variables = [ ] , $ rootValue = null , ? string $ operationName = null ) : ExecutionResult { $ this -> prepSchema ( ) ; $ this -> eventDispatcher -> dispatch ( new StartExecution ) ; $ result = GraphQLBase :: executeQuery ( $ this -> executableSchema , $ query , $ rootValue , $ context , $ variables , $ operationName , null , $ this -> getValidationRules ( ) + DocumentValidator :: defaultRules ( ) ) ; $ extensionsResponses = ( array ) $ this -> eventDispatcher -> dispatch ( new BuildExtensionsResponse ) ; foreach ( $ extensionsResponses as $ extensionsResponse ) { if ( $ extensionsResponse ) { $ result -> extensions [ $ extensionsResponse -> key ( ) ] = $ extensionsResponse -> content ( ) ; } } $ result -> setErrorsHandler ( function ( array $ errors , callable $ formatter ) : array { $ handlers = config ( 'lighthouse.error_handlers' , [ ] ) ; return array_map ( function ( Error $ error ) use ( $ handlers , $ formatter ) { return $ this -> pipeline -> send ( $ error ) -> through ( $ handlers ) -> then ( function ( Error $ error ) use ( $ formatter ) { return $ formatter ( $ error ) ; } ) ; } , $ errors ) ; } ) ; $ this -> eventDispatcher -> dispatch ( new ManipulateResult ( $ result ) ) ; return $ result ; }
Execute a GraphQL query on the Lighthouse schema and return the raw ExecutionResult .
3,032
public function prepSchema ( ) : Schema { if ( empty ( $ this -> executableSchema ) ) { $ this -> executableSchema = $ this -> schemaBuilder -> build ( $ this -> documentAST ( ) ) ; } return $ this -> executableSchema ; }
Ensure an executable GraphQL schema is present .
3,033
protected function getValidationRules ( ) : array { return [ QueryComplexity :: class => new QueryComplexity ( config ( 'lighthouse.security.max_query_complexity' , 0 ) ) , QueryDepth :: class => new QueryDepth ( config ( 'lighthouse.security.max_query_depth' , 0 ) ) , DisableIntrospection :: class => new DisableIntrospection ( config ( 'lighthouse.security.disable_introspection' , false ) ) , ] ; }
Construct the validation rules with values given in the config .
3,034
public function documentAST ( ) : DocumentAST { if ( empty ( $ this -> documentAST ) ) { $ this -> documentAST = config ( 'lighthouse.cache.enable' ) ? app ( 'cache' ) -> rememberForever ( config ( 'lighthouse.cache.key' ) , function ( ) : DocumentAST { return $ this -> buildAST ( ) ; } ) : $ this -> buildAST ( ) ; } return $ this -> documentAST ; }
Get instance of DocumentAST .
3,035
protected function buildAST ( ) : DocumentAST { $ schemaString = $ this -> schemaSourceProvider -> getSchemaString ( ) ; $ additionalSchemas = ( array ) $ this -> eventDispatcher -> dispatch ( new BuildSchemaString ( $ schemaString ) ) ; $ documentAST = $ this -> astBuilder -> build ( implode ( PHP_EOL , Arr :: prepend ( $ additionalSchemas , $ schemaString ) ) ) ; $ this -> eventDispatcher -> dispatch ( new ManipulateAST ( $ documentAST ) ) ; return $ documentAST ; }
Get the schema string and build an AST out of it .
3,036
public function handleBuilder ( $ builder , $ value ) { foreach ( $ value as $ orderByClause ) { $ builder -> orderBy ( $ orderByClause [ 'field' ] , $ orderByClause [ 'order' ] ) ; } return $ builder ; }
Apply an ORDER BY clause .
3,037
public function manipulateSchema ( InputValueDefinitionNode $ argDefinition , FieldDefinitionNode $ fieldDefinition , ObjectTypeDefinitionNode $ parentType , DocumentAST $ current ) { $ expectedOrderByClause = ASTHelper :: cloneNode ( $ argDefinition ) ; if ( $ argDefinition -> type instanceof NonNullTypeNode ) { $ expectedOrderByClause = $ argDefinition -> type ; } if ( data_get ( $ expectedOrderByClause , 'type' . '.type' . '.type.name.value' ) !== 'OrderByClause' ) { throw new DefinitionException ( "Must define the argument type of {$argDefinition->name->value} on field {$fieldDefinition->name->value} as [OrderByClause!]." ) ; } return $ current ; }
Validate the input argument definition .
3,038
protected function loadRoutesFrom ( $ path ) : void { if ( Str :: contains ( $ this -> app -> version ( ) , 'Lumen' ) ) { require realpath ( $ path ) ; return ; } parent :: loadRoutesFrom ( $ path ) ; }
Load routes from provided path .
3,039
public function handle ( TypeDefinitionNode $ definition ) : Type { $ nodeValue = new NodeValue ( $ definition ) ; return $ this -> pipeline -> send ( $ nodeValue ) -> through ( $ this -> directiveFactory -> createNodeMiddleware ( $ definition ) ) -> via ( 'handleNode' ) -> then ( function ( NodeValue $ value ) use ( $ definition ) : Type { $ nodeResolver = $ this -> directiveFactory -> createNodeResolver ( $ definition ) ; if ( $ nodeResolver ) { return $ nodeResolver -> resolveNode ( $ value ) ; } return $ this -> resolveType ( $ definition ) ; } ) ; }
Transform node to type .
3,040
protected function resolveType ( TypeDefinitionNode $ typeDefinition ) : Type { switch ( get_class ( $ typeDefinition ) ) { case EnumTypeDefinitionNode :: class : return $ this -> resolveEnumType ( $ typeDefinition ) ; case ScalarTypeDefinitionNode :: class : return $ this -> resolveScalarType ( $ typeDefinition ) ; case ObjectTypeDefinitionNode :: class : return $ this -> resolveObjectType ( $ typeDefinition ) ; case InputObjectTypeDefinitionNode :: class : return $ this -> resolveInputObjectType ( $ typeDefinition ) ; case InterfaceTypeDefinitionNode :: class : return $ this -> resolveInterfaceType ( $ typeDefinition ) ; case UnionTypeDefinitionNode :: class : return $ this -> resolveUnionType ( $ typeDefinition ) ; default : throw new InvariantViolation ( "Unknown type for definition [{$typeDefinition->name->value}]" ) ; } }
Transform value to type .
3,041
protected function resolveFieldsFunction ( $ definition ) : Closure { return function ( ) use ( $ definition ) : array { return ( new Collection ( $ definition -> fields ) ) -> mapWithKeys ( function ( FieldDefinitionNode $ fieldDefinition ) use ( $ definition ) : array { $ fieldValue = new FieldValue ( new NodeValue ( $ definition ) , $ fieldDefinition ) ; return [ $ fieldDefinition -> name -> value => app ( FieldFactory :: class ) -> handle ( $ fieldValue ) , ] ; } ) -> toArray ( ) ; } ; }
Returns a closure that lazy loads the fields for a constructed type .
3,042
public function build ( $ documentAST ) { foreach ( $ documentAST -> typeDefinitions ( ) as $ typeDefinition ) { $ type = $ this -> nodeFactory -> handle ( $ typeDefinition ) ; $ this -> typeRegistry -> register ( $ type ) ; switch ( $ type -> name ) { case 'Query' : $ queryType = $ type ; continue 2 ; case 'Mutation' : $ mutationType = $ type ; continue 2 ; case 'Subscription' : $ subscriptionType = $ type ; continue 2 ; default : $ types [ ] = $ type ; } } if ( empty ( $ queryType ) ) { throw new InvariantViolation ( 'The root Query type must be present in the schema.' ) ; } $ config = SchemaConfig :: create ( ) -> setQuery ( $ queryType ) -> setDirectives ( $ this -> convertDirectives ( $ documentAST ) -> toArray ( ) ) ; if ( isset ( $ mutationType ) ) { $ config -> setMutation ( $ mutationType ) ; } if ( isset ( $ subscriptionType ) ) { $ config -> setSubscription ( $ subscriptionType ) ; } if ( isset ( $ types ) ) { $ config -> setTypes ( $ types ) ; } return new Schema ( $ config ) ; }
Build an executable schema from AST .
3,043
protected function convertDirectives ( DocumentAST $ document ) : Collection { return $ document -> directiveDefinitions ( ) -> map ( function ( DirectiveDefinitionNode $ directive ) { return new Directive ( [ 'name' => $ directive -> name -> value , 'description' => data_get ( $ directive -> description , 'value' ) , 'locations' => ( new Collection ( $ directive -> locations ) ) -> map ( function ( $ location ) { return $ location -> value ; } ) -> toArray ( ) , 'args' => ( new Collection ( $ directive -> arguments ) ) -> map ( function ( InputValueDefinitionNode $ argument ) { $ fieldArgumentConfig = [ 'name' => $ argument -> name -> value , 'description' => data_get ( $ argument -> description , 'value' ) , 'type' => $ this -> definitionNodeConverter -> toType ( $ argument -> type ) , ] ; if ( $ defaultValue = $ argument -> defaultValue ) { $ fieldArgumentConfig += [ 'defaultValue' => $ defaultValue , ] ; } return new FieldArgument ( $ fieldArgumentConfig ) ; } ) -> toArray ( ) , 'astNode' => $ directive , ] ) ; } ) ; }
Set custom client directives .
3,044
protected function shouldDefer ( TypeNode $ fieldType , ResolveInfo $ resolveInfo ) : bool { if ( strtolower ( $ resolveInfo -> operation -> operation ) === 'mutation' ) { return false ; } foreach ( $ resolveInfo -> fieldNodes as $ fieldNode ) { $ deferDirective = ASTHelper :: directiveDefinition ( $ fieldNode , 'defer' ) ; if ( ! $ deferDirective ) { return false ; } if ( ! ASTHelper :: directiveArgValue ( $ deferDirective , 'if' , true ) ) { return false ; } $ skipDirective = ASTHelper :: directiveDefinition ( $ fieldNode , 'skip' ) ; $ includeDirective = ASTHelper :: directiveDefinition ( $ fieldNode , 'include' ) ; $ shouldSkip = $ skipDirective ? ASTHelper :: directiveArgValue ( $ skipDirective , 'if' , false ) : false ; $ shouldInclude = $ includeDirective ? ASTHelper :: directiveArgValue ( $ includeDirective , 'if' , false ) : false ; if ( $ shouldSkip || $ shouldInclude ) { return false ; } } if ( $ fieldType instanceof NonNullTypeNode ) { throw new ParseClientException ( 'The @defer directive cannot be placed on a Non-Nullable field.' ) ; } return true ; }
Determine if field should be deferred .
3,045
public function handleField ( FieldValue $ value , Closure $ next ) : FieldValue { $ previousResolver = $ value -> getResolver ( ) ; return $ next ( $ value -> setResolver ( function ( $ root , array $ args , GraphQLContext $ context , ResolveInfo $ resolveInfo ) use ( $ previousResolver ) { $ gate = app ( Gate :: class ) ; $ gateArguments = $ this -> getGateArguments ( ) ; if ( $ id = $ args [ 'id' ] ?? null ) { $ modelClass = $ this -> getModelClass ( ) ; $ gateArguments [ 0 ] = $ modelClass :: findOrFail ( $ id ) ; } $ this -> getAbilities ( ) -> each ( function ( string $ ability ) use ( $ context , $ gate , $ gateArguments ) : void { $ this -> authorize ( $ context -> user ( ) , $ gate , $ ability , $ gateArguments ) ; } ) ; return call_user_func_array ( $ previousResolver , func_get_args ( ) ) ; } ) ) ; }
Ensure the user is authorized to access this field .
3,046
protected static function saveModelWithPotentialParent ( Model $ model , Collection $ args , ? Relation $ parentRelation = null ) : Model { [ $ belongsTo , $ remaining ] = self :: partitionArgsByRelationType ( new ReflectionClass ( $ model ) , $ args , BelongsTo :: class ) ; $ model -> fill ( $ remaining -> all ( ) ) ; $ belongsTo -> each ( function ( array $ nestedOperations , string $ relationName ) use ( $ model ) : void { $ relation = $ model -> { $ relationName } ( ) ; if ( $ create = $ nestedOperations [ 'create' ] ?? false ) { $ belongsToModel = self :: executeCreate ( $ relation -> getModel ( ) -> newInstance ( ) , new Collection ( $ create ) ) ; $ relation -> associate ( $ belongsToModel ) ; } if ( $ connect = $ nestedOperations [ 'connect' ] ?? false ) { $ belongsTo = $ model -> { $ relationName } ( ) ; $ belongsTo -> associate ( $ connect ) ; } if ( $ update = $ nestedOperations [ 'update' ] ?? false ) { $ belongsToModel = self :: executeUpdate ( $ relation -> getModel ( ) -> newInstance ( ) , new Collection ( $ update ) ) ; $ relation -> associate ( $ belongsToModel ) ; } if ( $ nestedOperations [ 'disconnect' ] ?? false ) { $ relation -> dissociate ( ) ; } if ( $ nestedOperations [ 'delete' ] ?? false ) { $ relation -> delete ( ) ; } } ) ; if ( $ parentRelation && ! $ parentRelation instanceof BelongsToMany ) { $ parentRelation -> save ( $ model ) ; return $ model ; } $ model -> save ( ) ; if ( $ parentRelation instanceof BelongsToMany ) { $ parentRelation -> syncWithoutDetaching ( $ model ) ; } return $ model ; }
Save a model that maybe has a parent .
3,047
protected static function handleMultiRelationCreate ( Collection $ multiValues , Relation $ relation ) : void { $ multiValues -> each ( function ( $ singleValues ) use ( $ relation ) : void { self :: handleSingleRelationCreate ( new Collection ( $ singleValues ) , $ relation ) ; } ) ; }
Handle the creation with multiple relations .
3,048
protected static function handleSingleRelationCreate ( Collection $ singleValues , Relation $ relation ) : void { self :: executeCreate ( $ relation -> getModel ( ) -> newInstance ( ) , $ singleValues , $ relation ) ; }
Handle the creation with a single relation .
3,049
protected static function partitionArgsByRelationType ( ReflectionClass $ modelReflection , Collection $ args , string $ relationClass ) : Collection { return $ args -> partition ( function ( $ value , string $ key ) use ( $ modelReflection , $ relationClass ) : bool { if ( ! $ modelReflection -> hasMethod ( $ key ) ) { return false ; } $ relationMethodCandidate = $ modelReflection -> getMethod ( $ key ) ; if ( ! $ returnType = $ relationMethodCandidate -> getReturnType ( ) ) { return false ; } if ( ! $ returnType instanceof ReflectionNamedType ) { return false ; } return $ relationClass === $ returnType -> getName ( ) ; } ) ; }
Extract all the arguments that correspond to a relation of a certain type on the model .
3,050
public function handleBuilder ( $ builder , $ value ) { return call_user_func ( $ this -> getResolverFromArgument ( 'method' ) , $ builder , $ value , $ this -> definitionNode ) ; }
Dynamically call a user - defined method to enhance the builder .
3,051
public function hook ( Request $ request ) : JsonResponse { ( new Collection ( $ request -> input ( 'events' , [ ] ) ) ) -> filter ( function ( $ event ) : bool { return Arr :: get ( $ event , 'name' ) === 'channel_vacated' ; } ) -> each ( function ( array $ event ) : void { $ this -> storage -> deleteSubscriber ( Arr :: get ( $ event , 'channel' ) ) ; } ) ; return response ( ) -> json ( [ 'message' => 'okay' ] ) ; }
Handle subscription web hook .
3,052
public static function instance ( string $ loaderClass , array $ pathToField , array $ constructorArgs = [ ] ) : self { $ instanceName = static :: instanceKey ( $ pathToField ) ; $ graphQLRequest = app ( GraphQLRequest :: class ) ; if ( $ graphQLRequest -> isBatched ( ) ) { $ currentBatchIndex = $ graphQLRequest -> batchIndex ( ) ; $ instanceName = "batch_{$currentBatchIndex}_{$instanceName}" ; } $ instance = app ( ) -> bound ( $ instanceName ) ? app ( $ instanceName ) : app ( ) -> instance ( $ instanceName , app ( ) -> makeWith ( $ loaderClass , $ constructorArgs ) ) ; if ( ! $ instance instanceof self ) { throw new Exception ( "The given class '$loaderClass' must resolve to an instance of Nuwave\Lighthouse\Execution\DataLoader\BatchLoader" ) ; } return $ instance ; }
Return an instance of a BatchLoader for a specific field .
3,053
public static function instanceKey ( array $ path ) : string { return ( new Collection ( $ path ) ) -> filter ( function ( $ path ) : bool { return ! is_numeric ( $ path ) ; } ) -> implode ( '_' ) ; }
Generate a unique key for the instance using the path in the query .
3,054
public function load ( $ key , array $ metaInfo = [ ] ) : Deferred { $ key = $ this -> buildKey ( $ key ) ; $ this -> keys [ $ key ] = $ metaInfo ; return new Deferred ( function ( ) use ( $ key ) { if ( ! $ this -> hasLoaded ) { $ this -> results = $ this -> resolve ( ) ; $ this -> hasLoaded = true ; } return $ this -> results [ $ key ] ; } ) ; }
Load object by key .
3,055
public function handle ( Request $ request , Closure $ next ) { $ request -> headers -> set ( 'Accept' , 'application/json' ) ; return $ next ( $ request ) ; }
Force the Accept header of the request .
3,056
protected function chunk ( array $ data , bool $ terminating ) : string { $ json = json_encode ( $ data , 0 ) ; $ length = $ terminating ? strlen ( $ json ) : strlen ( $ json . self :: EOL ) ; $ chunk = implode ( self :: EOL , [ 'Content-Type: application/json' , 'Content-Length: ' . $ length , null , $ json , null , ] ) ; return $ this -> boundary ( ) . $ chunk ; }
Format chunked data .
3,057
protected function emit ( string $ chunk ) : void { echo $ chunk ; $ this -> flush ( Closure :: fromCallable ( 'ob_flush' ) ) ; $ this -> flush ( Closure :: fromCallable ( 'flush' ) ) ; }
Stream chunked data to client .
3,058
public function subscriptions ( Subscriber $ subscriber ) : Collection { $ this -> graphQL -> prepSchema ( ) ; return ( new Collection ( $ subscriber -> query -> definitions ) ) -> filter ( function ( Node $ node ) : bool { return $ node instanceof OperationDefinitionNode ; } ) -> filter ( function ( OperationDefinitionNode $ node ) : bool { return $ node -> operation === 'subscription' ; } ) -> flatMap ( function ( OperationDefinitionNode $ node ) { return ( new Collection ( $ node -> selectionSet -> selections ) ) -> map ( function ( FieldNode $ field ) : string { return $ field -> name -> value ; } ) -> toArray ( ) ; } ) -> map ( function ( $ subscriptionField ) : GraphQLSubscription { return Arr :: get ( $ this -> subscriptions , $ subscriptionField , new NotFoundSubscription ) ; } ) ; }
Get registered subscriptions .
3,059
protected function typeExtensionUniqueKey ( TypeExtensionNode $ typeExtensionNode ) : string { $ fieldNames = ( new Collection ( $ typeExtensionNode -> fields ) ) -> map ( function ( $ field ) : string { return $ field -> name -> value ; } ) -> implode ( ':' ) ; return $ typeExtensionNode -> name -> value . $ fieldNames ; }
Return a unique key that identifies a type extension .
3,060
public static function fromSource ( string $ schema ) : self { try { return new static ( Parser :: parse ( $ schema , [ 'noLocation' => true ] ) ) ; } catch ( SyntaxError $ syntaxError ) { throw new ParseException ( $ syntaxError -> getMessage ( ) ) ; } }
Create a new DocumentAST instance from a schema .
3,061
public function serialize ( ) : string { return serialize ( $ this -> definitionMap -> mapWithKeys ( function ( DefinitionNode $ node , string $ key ) : array { return [ $ key => AST :: toArray ( $ node ) ] ; } ) ) ; }
Strip out irrelevant information to make serialization more efficient .
3,062
public function unserialize ( $ serialized ) : void { $ this -> definitionMap = unserialize ( $ serialized ) -> mapWithKeys ( function ( array $ node , string $ key ) : array { return [ $ key => AST :: fromArray ( $ node ) ] ; } ) ; }
Construct from the string representation .
3,063
public function typeDefinitions ( ) : Collection { return $ this -> definitionMap -> filter ( function ( DefinitionNode $ node ) { return $ node instanceof ScalarTypeDefinitionNode || $ node instanceof ObjectTypeDefinitionNode || $ node instanceof InterfaceTypeDefinitionNode || $ node instanceof UnionTypeDefinitionNode || $ node instanceof EnumTypeDefinitionNode || $ node instanceof InputObjectTypeDefinitionNode ; } ) ; }
Get all type definitions from the document .
3,064
public function extensionsForType ( string $ extendedTypeName ) : Collection { return $ this -> typeExtensionsMap -> filter ( function ( TypeExtensionNode $ typeExtension ) use ( $ extendedTypeName ) : bool { return $ extendedTypeName === $ typeExtension -> name -> value ; } ) ; }
Get all extensions that apply to a named type .
3,065
public function objectTypeDefinition ( string $ name ) : ? ObjectTypeDefinitionNode { return $ this -> objectTypeDefinitions ( ) -> first ( function ( ObjectTypeDefinitionNode $ objectType ) use ( $ name ) : bool { return $ objectType -> name -> value === $ name ; } ) ; }
Get a single object type definition by name .
3,066
protected function definitionsByType ( string $ typeClassName ) : Collection { return $ this -> definitionMap -> filter ( function ( Node $ node ) use ( $ typeClassName ) { return $ node instanceof $ typeClassName ; } ) ; }
Get all definitions of a given type .
3,067
public function addFieldToQueryType ( FieldDefinitionNode $ field ) : self { $ query = $ this -> queryTypeDefinition ( ) ; $ query -> fields = ASTHelper :: mergeNodeList ( $ query -> fields , [ $ field ] ) ; $ this -> setDefinition ( $ query ) ; return $ this ; }
Add a single field to the query type .
3,068
public function handleBuilder ( $ builder , $ value ) { $ within = $ this -> directiveArgValue ( 'within' ) ; $ modelClass = get_class ( $ builder -> getModel ( ) ) ; $ builder = $ modelClass :: search ( $ value ) ; if ( $ within !== null ) { $ builder -> within ( $ within ) ; } return $ builder ; }
Apply a scout search to the builder .
3,069
public function driver ( ? string $ name = null ) { $ name = $ name ? : $ this -> getDefaultDriver ( ) ; return $ this -> drivers [ $ name ] = $ this -> get ( $ name ) ; }
Get a driver instance by name .
3,070
protected function validateDriver ( $ driver ) { $ interface = $ this -> interface ( ) ; if ( ! ( new ReflectionClass ( $ driver ) ) -> implementsInterface ( $ interface ) ) { throw new InvalidDriverException ( get_class ( $ driver ) . " does not implement {$interface}" ) ; } return $ driver ; }
Validate driver implements the proper interface .
3,071
protected function createPusherDriver ( array $ config ) : PusherBroadcaster { $ connection = $ config [ 'connection' ] ?? 'pusher' ; $ driverConfig = config ( "broadcasting.connections.{$connection}" ) ; if ( empty ( $ driverConfig ) || $ driverConfig [ 'driver' ] !== 'pusher' ) { throw new RuntimeException ( "Could not initialize Pusher broadcast driver for connection: {$connection}." ) ; } $ appKey = Arr :: get ( $ driverConfig , 'key' ) ; $ appSecret = Arr :: get ( $ driverConfig , 'secret' ) ; $ appId = Arr :: get ( $ driverConfig , 'app_id' ) ; $ options = Arr :: get ( $ driverConfig , 'options' , [ ] ) ; $ pusher = new Pusher ( $ appKey , $ appSecret , $ appId , $ options ) ; return new PusherBroadcaster ( $ pusher ) ; }
Create instance of pusher driver .
3,072
public function serialize ( $ value ) : string { if ( $ value instanceof Carbon ) { return $ value -> toDateTimeString ( ) ; } return $ this -> tryParsingDateTime ( $ value , InvariantViolation :: class ) -> toDateTimeString ( ) ; }
Serialize an internal value ensuring it is a valid datetime string .
3,073
protected function chunkError ( string $ path , array $ data ) : ? array { if ( ! isset ( $ data [ 'errors' ] ) ) { return null ; } return ( new Collection ( $ data [ 'errors' ] ) ) -> filter ( function ( array $ error ) use ( $ path ) : bool { return Str :: startsWith ( implode ( '.' , $ error [ 'path' ] ) , $ path ) ; } ) -> values ( ) -> toArray ( ) ; }
Get error from chunk if it exists .
3,074
public function paginatorInfoResolver ( LengthAwarePaginator $ root ) : array { return [ 'count' => $ root -> count ( ) , 'currentPage' => $ root -> currentPage ( ) , 'firstItem' => $ root -> firstItem ( ) , 'hasMorePages' => $ root -> hasMorePages ( ) , 'lastItem' => $ root -> lastItem ( ) , 'lastPage' => $ root -> lastPage ( ) , 'perPage' => $ root -> perPage ( ) , 'total' => $ root -> total ( ) , ] ; }
Resolve paginator info for connection .
3,075
public function process ( Collection $ items , Closure $ cb , Closure $ error = null ) : void { $ items -> each ( function ( $ item ) use ( $ cb , $ error ) : void { try { $ cb ( $ item ) ; } catch ( Exception $ e ) { if ( ! $ error ) { throw $ e ; } $ error ( $ e ) ; } } ) ; }
Process collection of items .
3,076
public function create ( string $ directiveName , $ definitionNode = null ) : Directive { $ directive = $ this -> resolve ( $ directiveName ) ?? $ this -> createOrFail ( $ directiveName ) ; return $ definitionNode ? $ this -> hydrate ( $ directive , $ definitionNode ) : $ directive ; }
Create a directive by the given directive name .
3,077
protected function resolve ( string $ directiveName ) : ? Directive { if ( $ className = Arr :: get ( $ this -> resolved , $ directiveName ) ) { return app ( $ className ) ; } return null ; }
Create a directive from resolved directive classes .
3,078
protected function hydrate ( Directive $ directive , $ definitionNode ) : Directive { return $ directive instanceof BaseDirective ? $ directive -> hydrate ( $ definitionNode ) : $ directive ; }
Set the given definition on the directive .
3,079
protected function createAssociatedDirectivesOfType ( Node $ node , string $ directiveClass ) : Collection { return ( new Collection ( $ node -> directives ) ) -> map ( function ( DirectiveNode $ directive ) use ( $ node ) { return $ this -> create ( $ directive -> name -> value , $ node ) ; } ) -> filter ( function ( Directive $ directive ) use ( $ directiveClass ) { return $ directive instanceof $ directiveClass ; } ) ; }
Get all directives of a certain type that are associated with an AST node .
3,080
protected function createSingleDirectiveOfType ( Node $ node , string $ directiveClass ) : ? Directive { $ directives = $ this -> createAssociatedDirectivesOfType ( $ node , $ directiveClass ) ; if ( $ directives -> count ( ) > 1 ) { $ directiveNames = $ directives -> implode ( ', ' ) ; throw new DirectiveException ( "Node [{$node->name->value}] can only have one directive of type [{$directiveClass}] but found [{$directiveNames}]" ) ; } return $ directives -> first ( ) ; }
Get a single directive of a type that belongs to an AST node .
3,081
public function handle ( ArgumentValue $ argumentValue ) : array { $ definition = $ argumentValue -> getAstNode ( ) ; $ argumentType = $ argumentValue -> getType ( ) ; $ fieldArgument = [ 'name' => $ argumentValue -> getName ( ) , 'description' => data_get ( $ definition -> description , 'value' ) , 'type' => $ argumentType , 'astNode' => $ definition , ] ; if ( $ defaultValue = $ definition -> defaultValue ) { $ fieldArgument += [ 'defaultValue' => $ argumentType instanceof EnumType ? $ argumentType -> getValue ( $ defaultValue -> value ) -> value : AST :: valueFromASTUntyped ( $ defaultValue ) , ] ; } $ fieldArgument += get_object_vars ( $ argumentValue ) ; return $ fieldArgument ; }
Convert argument definition to type .
3,082
public function handleField ( FieldValue $ value , Closure $ next ) : FieldValue { $ resolver = $ value -> getResolver ( ) ; return $ next ( $ value -> setResolver ( function ( Model $ parent , array $ args , GraphQLContext $ context , ResolveInfo $ resolveInfo ) use ( $ resolver ) : Deferred { $ loader = BatchLoader :: instance ( RelationBatchLoader :: class , $ resolveInfo -> path , [ 'relationName' => $ this -> directiveArgValue ( 'relation' , $ this -> definitionNode -> name -> value ) , 'args' => $ args , 'scopes' => $ this -> directiveArgValue ( 'scopes' , [ ] ) , 'resolveInfo' => $ resolveInfo , ] ) ; return new Deferred ( function ( ) use ( $ loader , $ resolver , $ parent , $ args , $ context , $ resolveInfo ) { return $ loader -> load ( $ parent -> getKey ( ) , [ 'parent' => $ parent ] ) -> then ( function ( ) use ( $ resolver , $ parent , $ args , $ context , $ resolveInfo ) { return $ resolver ( $ parent , $ args , $ context , $ resolveInfo ) ; } ) ; } ) ; } ) ) ; }
Eager load a relation on the parent instance .
3,083
protected function defaultExceptionResolver ( ) : Closure { return function ( string $ errorMessage ) { return ( new GenericException ( $ errorMessage ) ) -> setExtensions ( [ $ this -> errorType => $ this -> errors ] ) -> setCategory ( $ this -> errorType ) ; } ; }
Construct a default exception resolver .
3,084
public function push ( string $ errorMessage , ? string $ key = null ) : self { if ( $ key === null ) { $ this -> errors [ ] = $ errorMessage ; } else { $ this -> errors [ $ key ] [ ] = $ errorMessage ; } return $ this ; }
Push an error message into the buffer .
3,085
public function flush ( string $ errorMessage ) : void { if ( ! $ this -> hasErrors ( ) ) { return ; } $ exception = $ this -> resolveException ( $ errorMessage , $ this ) ; $ this -> clearErrors ( ) ; throw $ exception ; }
Flush the errors .
3,086
public function getReturnType ( ) : Type { if ( ! isset ( $ this -> returnType ) ) { $ this -> returnType = app ( DefinitionNodeConverter :: class ) -> toType ( $ this -> field -> type ) ; } return $ this -> returnType ; }
Get an instance of the return type of the field .
3,087
public static function calculateCurrentPage ( int $ first , int $ after , int $ defaultPage = 1 ) : int { return $ first && $ after ? ( int ) floor ( ( $ first + $ after ) / $ first ) : $ defaultPage ; }
Calculate the current page to inform the user about the pagination state .
3,088
public function register ( Type $ type ) : self { $ this -> types [ $ type -> name ] = $ type ; return $ this ; }
Register type with registry .
3,089
public function get ( string $ typeName ) : Type { if ( ! isset ( $ this -> types [ $ typeName ] ) ) { throw new InvariantViolation ( "No type {$typeName} was registered." ) ; } return $ this -> types [ $ typeName ] ; }
Resolve type instance by name .
3,090
public static function transformToPaginatedField ( PaginationType $ paginationType , FieldDefinitionNode $ fieldDefinition , ObjectTypeDefinitionNode $ parentType , DocumentAST $ current , ? int $ defaultCount = null , ? int $ maxCount = null ) : DocumentAST { if ( $ paginationType -> isConnection ( ) ) { return self :: registerConnection ( $ fieldDefinition , $ parentType , $ current , $ defaultCount , $ maxCount ) ; } return self :: registerPaginator ( $ fieldDefinition , $ parentType , $ current , $ defaultCount , $ maxCount ) ; }
Transform the definition for a field to a field with pagination .
3,091
protected static function countArgument ( string $ argumentName , ? int $ defaultCount = null , ? int $ maxCount = null ) : string { $ description = '"Limits number of fetched elements.' ; if ( $ maxCount ) { $ description .= ' Maximum allowed value: ' . $ maxCount . '.' ; } $ description .= "\"\n" ; $ definition = $ argumentName . ': Int' . ( $ defaultCount ? ' = ' . $ defaultCount : '!' ) ; return $ description . $ definition ; }
Build the count argument definition string considering default and max values .
3,092
public function parseValue ( $ value ) : UploadedFile { if ( ! $ value instanceof UploadedFile ) { throw new Error ( 'Could not get uploaded file, be sure to conform to GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec Instead got: ' . Utils :: printSafe ( $ value ) ) ; } return $ value ; }
Parse a externally provided variable value into a Carbon instance .
3,093
public static function decode ( array $ args ) : int { if ( $ cursor = Arr :: get ( $ args , 'after' ) ) { return ( int ) base64_decode ( $ cursor ) ; } return 0 ; }
Decode cursor from query arguments .
3,094
protected function buildClass ( $ name ) { $ stub = parent :: buildClass ( $ name ) ; $ indexConfigurator = $ this -> getIndexConfigurator ( ) ; $ stub = str_replace ( 'DummyIndexConfigurator' , $ indexConfigurator ? "{$indexConfigurator}::class" : 'null' , $ stub ) ; $ searchRule = $ this -> getSearchRule ( ) ; $ stub = str_replace ( 'DummySearchRule' , $ searchRule ? "{$searchRule}::class" : '//' , $ stub ) ; return $ stub ; }
Build the class .
3,095
public function buildSearchQueryPayloadCollection ( Builder $ builder , array $ options = [ ] ) { $ payloadCollection = collect ( ) ; if ( $ builder instanceof SearchBuilder ) { $ searchRules = $ builder -> rules ? : $ builder -> model -> getSearchRules ( ) ; foreach ( $ searchRules as $ rule ) { $ payload = new TypePayload ( $ builder -> model ) ; if ( is_callable ( $ rule ) ) { $ payload -> setIfNotEmpty ( 'body.query.bool' , call_user_func ( $ rule , $ builder ) ) ; } else { $ ruleEntity = new $ rule ( $ builder ) ; if ( $ ruleEntity -> isApplicable ( ) ) { $ payload -> setIfNotEmpty ( 'body.query.bool' , $ ruleEntity -> buildQueryPayload ( ) ) ; if ( $ options [ 'highlight' ] ?? true ) { $ payload -> setIfNotEmpty ( 'body.highlight' , $ ruleEntity -> buildHighlightPayload ( ) ) ; } } else { continue ; } } $ payloadCollection -> push ( $ payload ) ; } } else { $ payload = ( new TypePayload ( $ builder -> model ) ) -> setIfNotEmpty ( 'body.query.bool.must.match_all' , new stdClass ( ) ) ; $ payloadCollection -> push ( $ payload ) ; } return $ payloadCollection -> map ( function ( TypePayload $ payload ) use ( $ builder , $ options ) { $ payload -> setIfNotEmpty ( 'body._source' , $ builder -> select ) -> setIfNotEmpty ( 'body.collapse.field' , $ builder -> collapse ) -> setIfNotEmpty ( 'body.sort' , $ builder -> orders ) -> setIfNotEmpty ( 'body.explain' , $ options [ 'explain' ] ?? null ) -> setIfNotEmpty ( 'body.profile' , $ options [ 'profile' ] ?? null ) -> setIfNotNull ( 'body.from' , $ builder -> offset ) -> setIfNotNull ( 'body.size' , $ builder -> limit ) ; foreach ( $ builder -> wheres as $ clause => $ filters ) { $ clauseKey = 'body.query.bool.filter.bool.' . $ clause ; $ clauseValue = array_merge ( $ payload -> get ( $ clauseKey , [ ] ) , $ filters ) ; $ payload -> setIfNotEmpty ( $ clauseKey , $ clauseValue ) ; } return $ payload -> get ( ) ; } ) ; }
Build the payload collection .
3,096
public function count ( Builder $ builder ) { $ count = 0 ; $ this -> buildSearchQueryPayloadCollection ( $ builder , [ 'highlight' => false ] ) -> each ( function ( $ payload ) use ( & $ count ) { $ result = ElasticClient :: count ( $ payload ) ; $ count = $ result [ 'count' ] ; if ( $ count > 0 ) { return false ; } } ) ; return $ count ; }
Return the number of documents found .
3,097
public function searchRaw ( Model $ model , $ query ) { $ payload = ( new TypePayload ( $ model ) ) -> setIfNotEmpty ( 'body' , $ query ) -> get ( ) ; return ElasticClient :: search ( $ payload ) ; }
Make a raw search .
3,098
public function setIfNotEmpty ( $ key , $ value ) { if ( empty ( $ value ) ) { return $ this ; } return $ this -> set ( $ key , $ value ) ; }
Set a value if it s not empty .
3,099
public function setIfNotNull ( $ key , $ value ) { if ( is_null ( $ value ) ) { return $ this ; } return $ this -> set ( $ key , $ value ) ; }
Set a value if it s not null .