From aae17f10a6ae4ae694d69baf66e6a56bd9c98d22 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 26 Jul 2021 19:46:18 +0200 Subject: [PATCH] new Deps --- .../haydenpierce/class-finder/.gitattributes | 7 + vendor/haydenpierce/class-finder/LICENSE | 13 + vendor/haydenpierce/class-finder/README.md | 126 + .../haydenpierce/class-finder/composer.json | 27 + .../class-finder/src/AppConfig.php | 82 + .../class-finder/src/ClassFinder.php | 208 ++ .../src/Classmap/ClassmapEntry.php | 77 + .../src/Classmap/ClassmapEntryFactory.php | 36 + .../src/Classmap/ClassmapFinder.php | 51 + .../src/Exception/ClassFinderException.php | 8 + .../class-finder/src/Files/FilesEntry.php | 101 + .../src/Files/FilesEntryFactory.php | 66 + .../class-finder/src/Files/FilesFinder.php | 59 + .../class-finder/src/FinderInterface.php | 29 + .../class-finder/src/PSR4/PSR4Finder.php | 106 + .../class-finder/src/PSR4/PSR4Namespace.php | 302 ++ .../src/PSR4/PSR4NamespaceFactory.php | 153 + vendor/laragraph/utils/.styleci.yml | 5 + vendor/laragraph/utils/CHANGELOG.md | 13 + vendor/laragraph/utils/LICENSE | 16 + vendor/laragraph/utils/README.md | 39 + vendor/laragraph/utils/composer.json | 55 + vendor/laragraph/utils/src/RequestParser.php | 118 + .../utils/tests/Unit/RequestParserTest.php | 253 ++ vendor/nuwave/lighthouse/README.md | 71 +- vendor/nuwave/lighthouse/_ide_helper.php | 122 + vendor/nuwave/lighthouse/composer.json | 111 +- vendor/nuwave/lighthouse/config/config.php | 240 -- vendor/nuwave/lighthouse/rector.php | 29 + .../src/ClientDirectives/ClientDirective.php | 79 + .../lighthouse/src/Console/CacheCommand.php | 20 + .../src/Console/ClearCacheCommand.php | 50 +- .../src/Console/DirectiveCommand.php | 228 ++ .../src/Console/FieldGeneratorCommand.php | 27 + .../src/Console/IdeHelperCommand.php | 213 +- .../src/Console/InterfaceCommand.php | 30 +- .../Console/LighthouseGeneratorCommand.php | 79 +- .../src/Console/MutationCommand.php | 37 +- .../src/Console/PrintSchemaCommand.php | 77 +- .../lighthouse/src/Console/QueryCommand.php | 37 +- .../lighthouse/src/Console/ScalarCommand.php | 30 +- .../src/Console/SubscriptionCommand.php | 30 +- .../lighthouse/src/Console/UnionCommand.php | 30 +- .../src/Console/ValidateSchemaCommand.php | 62 +- .../src/Console/ValidatorCommand.php | 40 + .../src/Console/stubs/directive.stub | 12 + .../arg_builder_directive_methods.stub | 11 + .../directives/arg_manipulator_imports.stub | 4 + .../directives/arg_manipulator_methods.stub | 17 + .../directives/arg_resolver_imports.stub | 0 .../directives/arg_resolver_methods.stub | 9 + .../arg_transformer_directive_methods.stub | 10 + .../directives/field_manipulator_imports.stub | 3 + .../directives/field_manipulator_methods.stub | 15 + .../directives/field_middleware_imports.stub | 2 + .../directives/field_middleware_methods.stub | 11 + .../directives/field_resolver_imports.stub | 1 + .../directives/field_resolver_methods.stub | 13 + .../type_extension_manipulator_imports.stub | 2 + .../type_extension_manipulator_methods.stub | 11 + .../directives/type_manipulator_imports.stub | 2 + .../directives/type_manipulator_methods.stub | 11 + .../directives/type_middleware_imports.stub | 2 + .../directives/type_middleware_methods.stub | 11 + .../directives/type_resolver_imports.stub | 1 + .../directives/type_resolver_methods.stub | 10 + .../lighthouse/src/Console/stubs/field.stub | 23 - .../src/Console/stubs/field_full.stub | 23 + .../src/Console/stubs/field_simple.stub | 15 + .../lighthouse/src/Console/stubs/scalar.stub | 4 +- .../src/Console/stubs/typeResolver.stub | 7 +- .../src/Console/stubs/validator.stub | 20 + vendor/nuwave/lighthouse/src/Defer/Defer.php | 257 +- .../src/Defer/DeferServiceProvider.php | 62 +- .../src/Defer/DeferrableDirective.php | 115 +- .../src/Events/BuildExtensionsResponse.php | 5 +- .../src/Events/BuildSchemaString.php | 6 - .../lighthouse/src/Events/EndExecution.php | 32 + .../src/Events/EndOperationOrOperations.php | 24 + .../lighthouse/src/Events/EndRequest.php | 37 + .../lighthouse/src/Events/ManipulateAST.php | 6 - .../src/Events/ManipulateResult.php | 6 - .../Events/RegisterDirectiveNamespaces.php | 2 +- .../lighthouse/src/Events/StartExecution.php | 49 +- .../src/Events/StartOperationOrOperations.php | 24 + .../lighthouse/src/Events/StartRequest.php | 18 +- .../lighthouse/src/Events/ValidateSchema.php | 25 + .../Exceptions/AuthenticationException.php | 24 +- .../src/Exceptions/AuthorizationException.php | 19 +- .../src/Exceptions/DefinitionException.php | 19 +- .../src/Exceptions/DirectiveException.php | 14 - .../src/Exceptions/FederationException.php | 10 + .../src/Exceptions/GenericException.php | 16 +- .../src/Exceptions/ParseException.php | 31 +- .../src/Exceptions/RateLimitException.php | 30 + .../Exceptions/RendersErrorsExtensions.php | 2 +- .../src/Exceptions/SubscriptionException.php | 35 - .../UnknownCacheVersionException.php | 16 + .../src/Exceptions/ValidationException.php | 64 +- .../Execution/Arguments/ArgPartitioner.php | 209 ++ .../src/Execution/Arguments/Argument.php | 70 + .../src/Execution/Arguments/ArgumentSet.php | 275 ++ .../Arguments/ArgumentSetFactory.php | 179 + .../Arguments/ArgumentTypeNodeConverter.php | 36 + .../src/Execution/Arguments/ListType.php | 28 + .../src/Execution/Arguments/NamedType.php | 25 + .../Execution/Arguments/NestedBelongsTo.php | 88 + .../Execution/Arguments/NestedManyToMany.php | 99 + .../src/Execution/Arguments/NestedMorphTo.php | 44 + .../Execution/Arguments/NestedOneToMany.php | 119 + .../Execution/Arguments/NestedOneToOne.php | 52 + .../src/Execution/Arguments/ResolveNested.php | 47 + .../src/Execution/Arguments/SaveModel.php | 95 + .../src/Execution/Arguments/UpdateModel.php | 45 + .../src/Execution/Arguments/UpsertModel.php | 45 + .../lighthouse/src/Execution/BaseRequest.php | 98 - .../BatchLoader/BatchLoaderRegistry.php | 69 + .../BatchLoader/RelationBatchLoader.php | 85 + .../lighthouse/src/Execution/Builder.php | 79 - .../src/Execution/ContextFactory.php | 6 - .../src/Execution/DataLoader/BatchLoader.php | 112 +- .../DataLoader/ModelRelationFetcher.php | 410 --- .../DataLoader/RelationBatchLoader.php | 122 - .../lighthouse/src/Execution/ErrorBuffer.php | 159 - .../lighthouse/src/Execution/ErrorHandler.php | 16 +- .../lighthouse/src/Execution/ErrorPool.php | 53 + .../src/Execution/ExtensionErrorHandler.php | 30 +- .../src/Execution/ExtensionsResponse.php | 19 +- .../src/Execution/GraphQLRequest.php | 50 - .../src/Execution/GraphQLValidator.php | 54 - .../src/Execution/LighthouseRequest.php | 75 - .../ModelsLoader/AggregateModelsLoader.php | 59 + .../ModelsLoader/CountModelsLoader.php | 94 + .../Execution/ModelsLoader/ModelsLoader.php | 21 + .../ModelsLoader/PaginatedModelsLoader.php | 208 ++ .../ModelsLoader/SimpleModelsLoader.php | 48 + .../src/Execution/MultipartFormRequest.php | 93 - .../src/Execution/MutationExecutor.php | 426 --- .../lighthouse/src/Execution/QueryAST.php | 76 - .../src/Execution/ReportingErrorHandler.php | 44 + .../lighthouse/src/Execution/Resolved.php | 24 + .../src/Execution/SingleResponse.php | 8 +- .../src/Execution/Utils/ModelKey.php | 24 + .../src/Execution/Utils/Subscription.php | 40 +- .../src/Execution/ValidationErrorHandler.php | 36 + .../src/Execution/ValidationRulesProvider.php | 32 + .../src/Federation/ASTManipulator.php | 100 + .../Directives/ExtendsDirective.php | 30 + .../Directives/ExternalDirective.php | 41 + .../Federation/Directives/KeyDirective.php | 44 + .../Directives/ProvidesDirective.php | 44 + .../Directives/RequiresDirective.php | 37 + .../src/Federation/EntityResolverProvider.php | 277 ++ .../src/Federation/FederationPrinter.php | 124 + .../Federation/FederationServiceProvider.php | 30 + .../src/Federation/Resolvers/Entities.php | 43 + .../src/Federation/Resolvers/Service.php | 21 + .../src/Federation/SchemaPrinter.php | 113 + .../src/Federation/SchemaValidator.php | 91 + .../lighthouse/src/Federation/Types/Any.php | 68 + .../src/Federation/Types/FieldSet.php | 24 + .../Utils => GlobalId}/GlobalId.php | 40 +- .../src/GlobalId/GlobalIdDirective.php | 110 + .../src/GlobalId/GlobalIdException.php | 18 + .../src/GlobalId/GlobalIdServiceProvider.php | 89 + .../lighthouse/src/GlobalId/NodeDirective.php | 100 + .../src/{Schema => GlobalId}/NodeRegistry.php | 51 +- vendor/nuwave/lighthouse/src/GraphQL.php | 381 +- .../src/LighthouseServiceProvider.php | 218 +- .../src/OrderBy/OrderByDirective.php | 121 + .../src/OrderBy/OrderByServiceProvider.php | 70 + .../src/Pagination/ConnectionField.php | 54 +- .../lighthouse/src/Pagination/Cursor.php | 10 +- .../src/Pagination/PaginateDirective.php | 148 + .../src/Pagination/PaginationArgs.php | 111 + .../src/Pagination/PaginationManipulator.php | 269 +- .../Pagination/PaginationServiceProvider.php | 120 + .../src/Pagination/PaginationType.php | 31 +- .../src/Pagination/PaginationUtils.php | 66 - .../src/Pagination/PaginatorField.php | 11 +- .../src/Pagination/SimplePaginatorField.php | 38 + .../lighthouse/src/Schema/AST/ASTBuilder.php | 420 ++- .../lighthouse/src/Schema/AST/ASTHelper.php | 430 ++- .../lighthouse/src/Schema/AST/DocumentAST.php | 140 +- .../src/Schema/AST/PartialParser.php | 323 -- .../src/Schema/AST/TypeNodeConverter.php | 85 + .../nuwave/lighthouse/src/Schema/Context.php | 13 +- .../Conversion/DefinitionNodeConverter.php | 100 - .../src/Schema/DirectiveLocator.php | 279 ++ .../src/Schema/DirectiveNamespacer.php | 50 - .../Schema/Directives/AggregateDirective.php | 147 + .../src/Schema/Directives/AllDirective.php | 52 +- .../Directives/ArgTraversalDirective.php | 86 + .../src/Schema/Directives/AuthDirective.php | 43 +- .../src/Schema/Directives/BaseDirective.php | 221 +- .../src/Schema/Directives/BcryptDirective.php | 42 - .../Schema/Directives/BelongsToDirective.php | 21 +- .../Directives/BelongsToManyDirective.php | 57 +- .../Schema/Directives/BroadcastDirective.php | 72 - .../Schema/Directives/BuilderDirective.php | 81 +- .../src/Schema/Directives/CacheDirective.php | 187 +- .../Schema/Directives/CacheKeyDirective.php | 17 +- .../src/Schema/Directives/CanDirective.php | 228 +- .../Schema/Directives/ComplexityDirective.php | 46 +- .../src/Schema/Directives/CountDirective.php | 93 + .../src/Schema/Directives/CreateDirective.php | 78 +- .../src/Schema/Directives/DeleteDirective.php | 113 +- .../Schema/Directives/DeprecatedDirective.php | 42 +- .../src/Schema/Directives/EnumDirective.php | 38 + .../src/Schema/Directives/EqDirective.php | 87 +- .../src/Schema/Directives/EventDirective.php | 71 +- .../src/Schema/Directives/FieldDirective.php | 25 +- .../src/Schema/Directives/FindDirective.php | 43 +- .../src/Schema/Directives/FirstDirective.php | 43 +- .../Schema/Directives/GlobalIdDirective.php | 113 - .../src/Schema/Directives/GuardDirective.php | 114 + .../Schema/Directives/HasManyDirective.php | 58 +- .../src/Schema/Directives/HasOneDirective.php | 23 +- .../src/Schema/Directives/HashDirective.php | 41 + .../src/Schema/Directives/InDirective.php | 39 +- .../src/Schema/Directives/InjectDirective.php | 47 +- .../Schema/Directives/InterfaceDirective.php | 20 +- .../Schema/Directives/LazyLoadDirective.php | 84 +- .../src/Schema/Directives/LikeDirective.php | 93 + .../src/Schema/Directives/LimitDirective.php | 90 + .../src/Schema/Directives/MethodDirective.php | 60 +- .../Schema/Directives/MiddlewareDirective.php | 201 -- .../src/Schema/Directives/ModelDirective.php | 82 +- .../ModifyModelExistenceDirective.php | 142 +- .../Schema/Directives/MorphManyDirective.php | 66 +- .../Schema/Directives/MorphOneDirective.php | 32 +- .../Schema/Directives/MorphToDirective.php | 32 +- .../Directives/MorphToManyDirective.php | 29 + .../Directives/MutationExecutorDirective.php | 99 + .../Schema/Directives/NamespaceDirective.php | 49 +- .../src/Schema/Directives/NeqDirective.php | 38 +- .../src/Schema/Directives/NestDirective.php | 40 + .../src/Schema/Directives/NodeDirective.php | 87 - .../src/Schema/Directives/NotInDirective.php | 40 +- .../Schema/Directives/OrderByDirective.php | 98 - .../Schema/Directives/PaginateDirective.php | 192 - .../Schema/Directives/RelationDirective.php | 169 +- .../Directives/RelationDirectiveHelpers.php | 67 + .../Schema/Directives/RenameArgsDirective.php | 42 + .../src/Schema/Directives/RenameDirective.php | 63 +- .../src/Schema/Directives/RulesDirective.php | 82 - .../Directives/RulesForArrayDirective.php | 87 - .../Schema/Directives/SanitizeDirective.php | 28 + .../src/Schema/Directives/ScalarDirective.php | 18 +- .../src/Schema/Directives/ScopeDirective.php | 46 + .../src/Schema/Directives/SearchDirective.php | 58 - .../src/Schema/Directives/SpreadDirective.php | 48 +- .../Schema/Directives/ThrottleDirective.php | 159 + .../Directives/TransformArgsDirective.php | 28 + .../src/Schema/Directives/TrimDirective.php | 91 +- .../src/Schema/Directives/UnionDirective.php | 18 +- .../src/Schema/Directives/UpdateDirective.php | 91 +- .../src/Schema/Directives/UpsertDirective.php | 46 + .../Schema/Directives/ValidationDirective.php | 81 - .../Schema/Directives/WhereAuthDirective.php | 59 + .../Directives/WhereBetweenDirective.php | 39 +- .../src/Schema/Directives/WhereDirective.php | 36 +- .../Directives/WhereJsonContainsDirective.php | 32 +- .../Directives/WhereNotBetweenDirective.php | 39 +- .../Schema/Directives/WithCountDirective.php | 63 + .../src/Schema/Directives/WithDirective.php | 83 +- .../Directives/WithRelationDirective.php | 54 + .../Schema/ExecutableTypeNodeConverter.php | 37 + .../src/Schema/Factories/ArgumentFactory.php | 18 +- .../Factories/ClientDirectiveFactory.php | 70 - .../src/Schema/Factories/DirectiveFactory.php | 229 +- .../src/Schema/Factories/FieldFactory.php | 485 +-- .../src/Schema/FallbackTypeNodeConverter.php | 50 + .../src/Schema/ResolverProvider.php | 59 +- .../nuwave/lighthouse/src/Schema/RootType.php | 22 + .../lighthouse/src/Schema/SchemaBuilder.php | 94 +- .../Schema/Source/SchemaSourceProvider.php | 13 - .../src/Schema/Source/SchemaStitcher.php | 72 +- .../lighthouse/src/Schema/TypeRegistry.php | 394 +- .../src/Schema/Types/GraphQLSubscription.php | 20 +- .../src/Schema/Types/LaravelEnumType.php | 22 +- .../src/Schema/Types/NotFoundSubscription.php | 19 +- .../src/Schema/Types/Scalars/Date.php | 77 +- .../src/Schema/Types/Scalars/DateScalar.php | 113 + .../src/Schema/Types/Scalars/DateTime.php | 80 +- .../src/Schema/Types/Scalars/DateTimeTz.php | 23 + .../src/Schema/Types/Scalars/DateTimeUtc.php | 22 + .../src/Schema/Types/Scalars/Upload.php | 13 +- .../src/Schema/Values/CacheValue.php | 117 +- .../src/Schema/Values/FieldValue.php | 166 +- .../src/Schema/Values/TypeValue.php | 21 - .../src/Scout/ScoutBuilderDirective.php | 15 + .../lighthouse/src/Scout/ScoutEnhancer.php | 149 + .../lighthouse/src/Scout/ScoutException.php | 9 + .../src/Scout/ScoutServiceProvider.php | 20 + .../lighthouse/src/Scout/SearchDirective.php | 39 + .../src/SoftDeletes/ForceDeleteDirective.php | 58 +- .../src/SoftDeletes/RestoreDirective.php | 63 +- .../src/SoftDeletes/SoftDeletesDirective.php | 33 +- .../SoftDeletesServiceProvider.php | 39 +- .../src/SoftDeletes/TrashedDirective.php | 99 +- .../src/Subscriptions/Authorizer.php | 61 +- .../src/Subscriptions/BroadcastManager.php | 49 +- .../BroadcastSubscriptionJob.php | 47 + .../Broadcasters/EchoBroadcaster.php | 62 + .../Broadcasters/LogBroadcaster.php | 61 +- .../Broadcasters/PusherBroadcaster.php | 96 +- .../Contracts/AuthorizesSubscriptions.php | 3 +- .../Subscriptions/Contracts/Broadcaster.php | 10 +- .../Contracts/BroadcastsSubscriptions.php | 8 +- .../Contracts/ContextSerializer.php | 2 - .../Contracts/StoresSubscriptions.php | 22 +- .../SubscriptionExceptionHandler.php | 2 - .../Contracts/SubscriptionIterator.php | 16 +- .../Directives/BroadcastDirective.php | 50 + .../Directives/SubscriptionDirective.php | 22 +- .../Events/BroadcastSubscriptionEvent.php | 39 - .../Events/BroadcastSubscriptionListener.php | 38 - .../Events/EchoSubscriptionEvent.php | 44 + .../src/Subscriptions/ExceptionHandler.php | 8 +- .../Iterators/AuthenticatingSyncIterator.php | 70 + .../Subscriptions/Iterators/SyncIterator.php | 18 +- .../src/Subscriptions/Serializer.php | 27 +- .../Storage/CacheStorageManager.php | 170 + .../Storage/RedisStorageManager.php | 184 + .../src/Subscriptions/StorageManager.php | 136 - .../src/Subscriptions/Subscriber.php | 147 +- .../Subscriptions/SubscriptionBroadcaster.php | 91 +- .../Subscriptions/SubscriptionController.php | 20 + .../src/Subscriptions/SubscriptionGuard.php | 40 + .../Subscriptions/SubscriptionRegistry.php | 163 +- .../SubscriptionResolverProvider.php | 30 +- .../src/Subscriptions/SubscriptionRouter.php | 18 +- .../SubscriptionServiceProvider.php | 116 +- .../lighthouse/src/Support/AppVersion.php | 39 + .../LaravelMiddlewareAdapter.php | 16 - .../Compatibility/LumenMiddlewareAdapter.php | 20 +- .../Compatibility/MiddlewareAdapter.php | 4 +- .../Support/Contracts/ArgBuilderDirective.php | 8 +- .../Contracts/ArgDirectiveForArray.php | 2 +- .../src/Support/Contracts/ArgManipulator.php | 8 +- .../src/Support/Contracts/ArgResolver.php | 13 + .../Contracts/ArgSanitizerDirective.php | 14 + .../Contracts/ArgTransformerDirective.php | 6 +- .../Contracts/ArgumentSetValidation.php | 39 + .../Support/Contracts/ArgumentValidation.php | 36 + .../Support/Contracts/CanStreamResponse.php | 9 +- .../src/Support/Contracts/CreatesContext.php | 1 - .../src/Support/Contracts/CreatesResponse.php | 2 +- .../Support/Contracts/DefinedDirective.php | 13 - .../src/Support/Contracts/Directive.php | 9 +- .../Contracts/FieldBuilderDirective.php | 14 + .../Support/Contracts/FieldManipulator.php | 5 +- .../src/Support/Contracts/FieldMiddleware.php | 3 +- .../src/Support/Contracts/FieldResolver.php | 1 - .../src/Support/Contracts/GlobalId.php | 17 +- .../src/Support/Contracts/GraphQLContext.php | 2 +- .../src/Support/Contracts/HasArgumentPath.php | 19 - .../src/Support/Contracts/HasErrorBuffer.php | 23 - .../Support/Contracts/ProvidesResolver.php | 3 - .../src/Support/Contracts/ProvidesRules.php | 25 - .../ProvidesSubscriptionResolver.php | 3 +- .../Contracts/ProvidesValidationRules.php | 16 + .../Contracts/TypeExtensionManipulator.php | 4 +- .../src/Support/Contracts/TypeManipulator.php | 3 +- .../src/Support/Contracts/TypeMiddleware.php | 2 - .../src/Support/Contracts/TypeResolver.php | 1 - .../lighthouse/src/Support/DriverManager.php | 52 +- .../Http/Controllers/GraphQLController.php | 101 +- .../Controllers/SubscriptionController.php | 55 - .../Support/Http/Middleware/AcceptJson.php | 13 +- .../Http/Middleware/AttemptAuthentication.php | 52 + .../Http/Middleware/LogGraphQLQueries.php | 38 + .../Support/Http/Responses/MemoryStream.php | 40 +- .../Support/Http/Responses/ResponseStream.php | 99 +- .../src/Support/Http/Responses/Stream.php | 21 +- .../lighthouse/src/Support/Http/routes.php | 30 +- .../lighthouse/src/Support/Pipeline.php | 61 - .../Support/Traits/GeneratesColumnsEnum.php | 104 + .../Support/Traits/HandlesCompositeKey.php | 21 - .../src/Support/Traits/HasArgumentPath.php | 38 - .../src/Support/Traits/HasArgumentValue.php | 30 + .../src/Support/Traits/HasErrorBuffer.php | 36 - .../Support/Traits/HasResolverArguments.php | 166 - .../nuwave/lighthouse/src/Support/Utils.php | 59 +- .../src/Testing/MakesGraphQLRequests.php | 183 +- .../src/Testing/MakesGraphQLRequestsLumen.php | 232 ++ .../lighthouse/src/Testing/MockDirective.php | 50 + .../lighthouse/src/Testing/MockResolver.php | 18 + .../src/Testing/MockResolverService.php | 27 + .../lighthouse/src/Testing/MocksResolvers.php | 55 + .../src/Testing/RethrowingErrorHandler.php | 22 + .../src/Testing/TestResponseMixin.php | 98 + .../src/Testing/TestResponseUtils.php | 29 + .../src/Testing/TestSchemaProvider.php | 26 + .../src/Testing/TestingServiceProvider.php | 31 + .../lighthouse/src/Testing/UsesTestSchema.php | 29 + .../nuwave/lighthouse/src/Tracing/Tracing.php | 39 +- .../src/Tracing/TracingDirective.php | 57 +- .../src/Tracing/TracingServiceProvider.php | 44 +- .../src/Validation/BaseRulesDirective.php | 156 + .../src/Validation/RulesDirective.php | 53 + .../src/Validation/RulesForArrayDirective.php | 62 + .../src/Validation/RulesGatherer.php | 280 ++ .../src/Validation/ValidateDirective.php | 65 + .../Validation/ValidationServiceProvider.php | 20 + .../lighthouse/src/Validation/Validator.php | 51 + .../src/Validation/ValidatorDirective.php | 156 + .../src/WhereConditions/Operator.php | 38 + .../src/WhereConditions/SQLOperator.php | 128 + .../WhereConditionsBaseDirective.php | 200 ++ .../WhereConditionsDirective.php | 47 + .../WhereConditionsServiceProvider.php | 142 + .../WhereHasConditionsDirective.php | 97 + .../WhereConstraintsDirective.php | 224 -- .../WhereConstraintsServiceProvider.php | 61 - .../{assets => src}/default-schema.graphql | 10 +- vendor/nuwave/lighthouse/src/lighthouse.php | 447 +++ vendor/thecodingmachine/safe/LICENSE | 21 + vendor/thecodingmachine/safe/README.md | 178 + vendor/thecodingmachine/safe/composer.json | 123 + .../deprecated/Exceptions/ApcException.php | 11 + .../Exceptions/LibeventException.php | 11 + .../deprecated/Exceptions/MssqlException.php | 11 + .../deprecated/Exceptions/StatsException.php | 11 + .../thecodingmachine/safe/deprecated/apc.php | 238 ++ .../safe/deprecated/functionsList.php | 56 + .../safe/deprecated/libevent.php | 496 +++ .../safe/deprecated/mssql.php | 426 +++ .../safe/deprecated/stats.php | 108 + .../safe/generated/Exceptions/.gitkeep | 0 .../generated/Exceptions/ApacheException.php | 11 + .../generated/Exceptions/ApcuException.php | 11 + .../generated/Exceptions/ArrayException.php | 11 + .../generated/Exceptions/Bzip2Exception.php | 11 + .../Exceptions/CalendarException.php | 11 + .../Exceptions/ClassobjException.php | 11 + .../generated/Exceptions/ComException.php | 11 + .../generated/Exceptions/CubridException.php | 11 + .../Exceptions/DatetimeException.php | 11 + .../generated/Exceptions/DirException.php | 11 + .../generated/Exceptions/EioException.php | 11 + .../Exceptions/ErrorfuncException.php | 11 + .../generated/Exceptions/ExecException.php | 11 + .../Exceptions/FileinfoException.php | 11 + .../Exceptions/FilesystemException.php | 11 + .../generated/Exceptions/FilterException.php | 11 + .../generated/Exceptions/FpmException.php | 11 + .../generated/Exceptions/FtpException.php | 11 + .../Exceptions/FunchandException.php | 11 + .../generated/Exceptions/GmpException.php | 11 + .../generated/Exceptions/GnupgException.php | 11 + .../generated/Exceptions/HashException.php | 11 + .../generated/Exceptions/IbaseException.php | 11 + .../generated/Exceptions/IbmDb2Exception.php | 11 + .../generated/Exceptions/IconvException.php | 11 + .../generated/Exceptions/ImageException.php | 11 + .../generated/Exceptions/ImapException.php | 11 + .../generated/Exceptions/InfoException.php | 11 + .../Exceptions/IngresiiException.php | 11 + .../generated/Exceptions/InotifyException.php | 11 + .../generated/Exceptions/LdapException.php | 11 + .../generated/Exceptions/LibxmlException.php | 11 + .../generated/Exceptions/LzfException.php | 11 + .../Exceptions/MailparseException.php | 11 + .../Exceptions/MbstringException.php | 11 + .../generated/Exceptions/MiscException.php | 11 + .../generated/Exceptions/MsqlException.php | 11 + .../generated/Exceptions/MysqlException.php | 11 + .../generated/Exceptions/MysqliException.php | 11 + .../Exceptions/MysqlndMsException.php | 11 + .../Exceptions/MysqlndQcException.php | 11 + .../generated/Exceptions/NetworkException.php | 11 + .../generated/Exceptions/Oci8Exception.php | 11 + .../generated/Exceptions/OpcacheException.php | 11 + .../Exceptions/OutcontrolException.php | 11 + .../Exceptions/PasswordException.php | 11 + .../generated/Exceptions/PcntlException.php | 11 + .../generated/Exceptions/PdfException.php | 11 + .../generated/Exceptions/PgsqlException.php | 11 + .../generated/Exceptions/PosixException.php | 11 + .../safe/generated/Exceptions/PsException.php | 11 + .../generated/Exceptions/PspellException.php | 11 + .../Exceptions/ReadlineException.php | 11 + .../generated/Exceptions/RpminfoException.php | 11 + .../generated/Exceptions/RrdException.php | 11 + .../generated/Exceptions/SemException.php | 11 + .../generated/Exceptions/SessionException.php | 11 + .../generated/Exceptions/ShmopException.php | 11 + .../Exceptions/SimplexmlException.php | 11 + .../generated/Exceptions/SocketsException.php | 11 + .../generated/Exceptions/SodiumException.php | 11 + .../generated/Exceptions/SolrException.php | 11 + .../generated/Exceptions/SplException.php | 11 + .../generated/Exceptions/SqlsrvException.php | 11 + .../generated/Exceptions/SsdeepException.php | 11 + .../generated/Exceptions/Ssh2Exception.php | 11 + .../generated/Exceptions/StreamException.php | 11 + .../generated/Exceptions/StringsException.php | 11 + .../generated/Exceptions/SwooleException.php | 11 + .../generated/Exceptions/UodbcException.php | 11 + .../generated/Exceptions/UopzException.php | 11 + .../generated/Exceptions/UrlException.php | 11 + .../generated/Exceptions/VarException.php | 11 + .../generated/Exceptions/XdiffException.php | 11 + .../generated/Exceptions/XmlException.php | 11 + .../generated/Exceptions/XmlrpcException.php | 11 + .../generated/Exceptions/YamlException.php | 11 + .../generated/Exceptions/YazException.php | 11 + .../generated/Exceptions/ZipException.php | 11 + .../generated/Exceptions/ZlibException.php | 11 + .../safe/generated/apache.php | 177 + .../thecodingmachine/safe/generated/apcu.php | 112 + .../thecodingmachine/safe/generated/array.php | 464 +++ .../thecodingmachine/safe/generated/bzip2.php | 96 + .../safe/generated/calendar.php | 27 + .../safe/generated/classobj.php | 25 + .../thecodingmachine/safe/generated/com.php | 127 + .../safe/generated/cubrid.php | 395 +++ .../thecodingmachine/safe/generated/curl.php | 3156 +++++++++++++++++ .../safe/generated/datetime.php | 631 ++++ .../thecodingmachine/safe/generated/dir.php | 157 + .../thecodingmachine/safe/generated/eio.php | 2071 +++++++++++ .../safe/generated/errorfunc.php | 82 + .../thecodingmachine/safe/generated/exec.php | 159 + .../safe/generated/fileinfo.php | 75 + .../safe/generated/filesystem.php | 1488 ++++++++ .../safe/generated/filter.php | 93 + .../thecodingmachine/safe/generated/fpm.php | 22 + .../thecodingmachine/safe/generated/ftp.php | 496 +++ .../safe/generated/funchand.php | 47 + .../safe/generated/functionsList.php | 1070 ++++++ .../thecodingmachine/safe/generated/gmp.php | 87 + .../thecodingmachine/safe/generated/gnupg.php | 168 + .../thecodingmachine/safe/generated/hash.php | 61 + .../thecodingmachine/safe/generated/ibase.php | 633 ++++ .../safe/generated/ibmDb2.php | 1221 +++++++ .../thecodingmachine/safe/generated/iconv.php | 96 + .../thecodingmachine/safe/generated/image.php | 2704 ++++++++++++++ .../thecodingmachine/safe/generated/imap.php | 1481 ++++++++ .../thecodingmachine/safe/generated/info.php | 511 +++ .../safe/generated/ingres-ii.php | 720 ++++ .../safe/generated/inotify.php | 44 + .../thecodingmachine/safe/generated/json.php | 73 + .../thecodingmachine/safe/generated/ldap.php | 1603 +++++++++ .../safe/generated/libxml.php | 43 + .../thecodingmachine/safe/generated/lzf.php | 44 + .../safe/generated/mailparse.php | 127 + .../safe/generated/mbstring.php | 526 +++ .../thecodingmachine/safe/generated/misc.php | 464 +++ .../thecodingmachine/safe/generated/msql.php | 443 +++ .../thecodingmachine/safe/generated/mysql.php | 938 +++++ .../safe/generated/mysqli.php | 42 + .../safe/generated/mysqlndMs.php | 119 + .../safe/generated/mysqlndQc.php | 103 + .../safe/generated/network.php | 639 ++++ .../thecodingmachine/safe/generated/oci8.php | 1721 +++++++++ .../safe/generated/opcache.php | 42 + .../safe/generated/openssl.php | 1088 ++++++ .../safe/generated/outcontrol.php | 100 + .../safe/generated/password.php | 126 + .../thecodingmachine/safe/generated/pcntl.php | 166 + .../thecodingmachine/safe/generated/pcre.php | 659 ++++ .../thecodingmachine/safe/generated/pdf.php | 1553 ++++++++ .../thecodingmachine/safe/generated/pgsql.php | 1878 ++++++++++ .../thecodingmachine/safe/generated/posix.php | 329 ++ vendor/thecodingmachine/safe/generated/ps.php | 1812 ++++++++++ .../safe/generated/pspell.php | 451 +++ .../safe/generated/readline.php | 157 + .../safe/generated/rpminfo.php | 21 + .../thecodingmachine/safe/generated/rrd.php | 23 + .../thecodingmachine/safe/generated/sem.php | 367 ++ .../safe/generated/session.php | 153 + .../thecodingmachine/safe/generated/shmop.php | 68 + .../safe/generated/simplexml.php | 94 + .../safe/generated/sockets.php | 813 +++++ .../safe/generated/sodium.php | 58 + .../thecodingmachine/safe/generated/solr.php | 22 + .../thecodingmachine/safe/generated/spl.php | 139 + .../safe/generated/sqlsrv.php | 429 +++ .../safe/generated/ssdeep.php | 70 + .../thecodingmachine/safe/generated/ssh2.php | 641 ++++ .../safe/generated/stream.php | 609 ++++ .../safe/generated/strings.php | 846 +++++ .../safe/generated/swoole.php | 108 + .../thecodingmachine/safe/generated/uodbc.php | 1009 ++++++ .../thecodingmachine/safe/generated/uopz.php | 40 + .../thecodingmachine/safe/generated/url.php | 144 + .../thecodingmachine/safe/generated/var.php | 60 + .../thecodingmachine/safe/generated/xdiff.php | 236 ++ .../thecodingmachine/safe/generated/xml.php | 95 + .../safe/generated/xmlrpc.php | 22 + .../thecodingmachine/safe/generated/yaml.php | 97 + .../thecodingmachine/safe/generated/yaz.php | 438 +++ .../thecodingmachine/safe/generated/zip.php | 71 + .../thecodingmachine/safe/generated/zlib.php | 611 ++++ vendor/thecodingmachine/safe/lib/DateTime.php | 81 + .../safe/lib/DateTimeImmutable.php | 262 ++ .../safe/lib/Exceptions/CurlException.php | 15 + .../safe/lib/Exceptions/JsonException.php | 12 + .../safe/lib/Exceptions/OpensslException.php | 12 + .../safe/lib/Exceptions/PcreException.php | 21 + .../lib/Exceptions/SafeExceptionInterface.php | 9 + .../safe/lib/special_cases.php | 241 ++ .../safe/rector-migrate-0.7.php | 1081 ++++++ vendor/webonyx/graphql-php/.coveralls.yml | 2 + .../webonyx/graphql-php/.github/FUNDING.yml | 2 + .../.github/workflows/ci-build.yml | 162 + vendor/webonyx/graphql-php/CHANGELOG.md | 174 +- vendor/webonyx/graphql-php/README.md | 13 +- vendor/webonyx/graphql-php/UPGRADE.md | 204 ++ vendor/webonyx/graphql-php/composer.json | 25 +- .../graphql-php/docs/best-practices.md | 12 +- .../graphql-php/docs/complementary-tools.md | 3 + .../webonyx/graphql-php/docs/data-fetching.md | 31 +- .../graphql-php/docs/error-handling.md | 24 +- .../graphql-php/docs/executing-queries.md | 10 +- .../graphql-php/docs/getting-started.md | 4 +- vendor/webonyx/graphql-php/docs/reference.md | 296 +- .../docs/type-system/enum-types.md | 2 +- .../docs/type-system/input-types.md | 2 +- .../docs/type-system/interfaces.md | 38 + .../docs/type-system/object-types.md | 2 +- .../docs/type-system/scalar-types.md | 2 +- .../graphql-php/docs/type-system/schema.md | 2 +- .../examples/00-hello-world/README.md | 18 - .../examples/00-hello-world/graphql.php | 69 - .../examples/01-blog/Blog/AppContext.php | 28 - .../examples/01-blog/Blog/Data/Comment.php | 25 - .../examples/01-blog/Blog/Data/DataSource.php | 206 -- .../examples/01-blog/Blog/Data/Image.php | 29 - .../examples/01-blog/Blog/Data/Story.php | 22 - .../examples/01-blog/Blog/Data/User.php | 22 - .../01-blog/Blog/Type/CommentType.php | 76 - .../Blog/Type/Enum/ContentFormatEnum.php | 19 - .../Blog/Type/Enum/ImageSizeEnumType.php | 23 - .../01-blog/Blog/Type/Field/HtmlField.php | 52 - .../examples/01-blog/Blog/Type/ImageType.php | 62 - .../examples/01-blog/Blog/Type/NodeType.php | 34 - .../examples/01-blog/Blog/Type/QueryType.php | 97 - .../01-blog/Blog/Type/Scalar/EmailType.php | 70 - .../01-blog/Blog/Type/Scalar/UrlType.php | 63 - .../01-blog/Blog/Type/SearchResultType.php | 31 - .../examples/01-blog/Blog/Type/StoryType.php | 127 - .../examples/01-blog/Blog/Type/UserType.php | 68 - .../examples/01-blog/Blog/Types.php | 209 -- .../graphql-php/examples/01-blog/README.md | 120 - .../graphql-php/examples/01-blog/graphql.php | 71 - .../examples/02-shorthand/README.md | 19 - .../examples/02-shorthand/graphql.php | 31 - .../examples/02-shorthand/rootvalue.php | 35 - .../examples/02-shorthand/schema.graphqls | 13 - .../graphql-php/examples/03-server/README.md | 19 - .../examples/03-server/graphql.php | 61 - .../webonyx/graphql-php/phpstan-baseline.neon | 652 ++++ vendor/webonyx/graphql-php/phpstan.neon.dist | 46 +- vendor/webonyx/graphql-php/src/Deferred.php | 61 +- .../webonyx/graphql-php/src/Error/Debug.php | 16 - .../graphql-php/src/Error/DebugFlag.php | 17 + .../webonyx/graphql-php/src/Error/Error.php | 86 +- .../graphql-php/src/Error/FormattedError.php | 112 +- .../src/Error/InvariantViolation.php | 4 + .../webonyx/graphql-php/src/Error/Warning.php | 48 +- .../src/Exception/InvalidArgument.php | 20 + .../src/Executor/ExecutionContext.php | 16 +- .../src/Executor/ExecutionResult.php | 22 +- .../graphql-php/src/Executor/Executor.php | 61 +- .../Promise/Adapter/AmpPromiseAdapter.php | 147 + .../Promise/Adapter/ReactPromiseAdapter.php | 2 +- .../Executor/Promise/Adapter/SyncPromise.php | 74 +- .../Promise/Adapter/SyncPromiseAdapter.php | 19 +- .../src/Executor/ReferenceExecutor.php | 636 ++-- .../graphql-php/src/Executor/Values.php | 224 +- .../src/Experimental/Executor/Collector.php | 47 +- .../Executor/CoroutineContext.php | 2 +- .../Executor/CoroutineExecutor.php | 82 +- .../src/Experimental/Executor/Runtime.php | 8 + vendor/webonyx/graphql-php/src/GraphQL.php | 36 +- .../src/Language/AST/ArgumentNode.php | 2 +- .../src/Language/AST/DefinitionNode.php | 2 +- .../Language/AST/DirectiveDefinitionNode.php | 15 +- .../src/Language/AST/DirectiveNode.php | 2 +- .../src/Language/AST/DocumentNode.php | 2 +- .../Language/AST/EnumTypeDefinitionNode.php | 4 +- .../Language/AST/EnumTypeExtensionNode.php | 4 +- .../Language/AST/EnumValueDefinitionNode.php | 2 +- .../src/Language/AST/FieldDefinitionNode.php | 6 +- .../src/Language/AST/FieldNode.php | 4 +- .../Language/AST/FragmentDefinitionNode.php | 4 +- .../src/Language/AST/FragmentSpreadNode.php | 2 +- .../src/Language/AST/HasSelectionSet.php | 10 +- .../src/Language/AST/InlineFragmentNode.php | 2 +- .../AST/InputObjectTypeDefinitionNode.php | 4 +- .../AST/InputObjectTypeExtensionNode.php | 4 +- .../Language/AST/InputValueDefinitionNode.php | 6 +- .../AST/InterfaceTypeDefinitionNode.php | 7 +- .../AST/InterfaceTypeExtensionNode.php | 7 +- .../src/Language/AST/ListTypeNode.php | 2 +- .../src/Language/AST/ListValueNode.php | 2 +- .../graphql-php/src/Language/AST/Location.php | 6 +- .../graphql-php/src/Language/AST/Node.php | 21 +- .../graphql-php/src/Language/AST/NodeList.php | 93 +- .../src/Language/AST/NonNullTypeNode.php | 2 +- .../src/Language/AST/ObjectFieldNode.php | 2 +- .../Language/AST/ObjectTypeDefinitionNode.php | 8 +- .../Language/AST/ObjectTypeExtensionNode.php | 8 +- .../src/Language/AST/ObjectValueNode.php | 2 +- .../Language/AST/OperationDefinitionNode.php | 8 +- .../Language/AST/ScalarTypeDefinitionNode.php | 2 +- .../Language/AST/ScalarTypeExtensionNode.php | 2 +- .../src/Language/AST/SchemaDefinitionNode.php | 4 +- .../Language/AST/SchemaTypeExtensionNode.php | 4 +- .../src/Language/AST/SelectionSetNode.php | 2 +- .../src/Language/AST/StringValueNode.php | 2 +- .../Language/AST/TypeSystemDefinitionNode.php | 2 + .../Language/AST/UnionTypeDefinitionNode.php | 4 +- .../Language/AST/UnionTypeExtensionNode.php | 4 +- .../Language/AST/VariableDefinitionNode.php | 7 +- .../src/Language/DirectiveLocation.php | 8 +- .../graphql-php/src/Language/Lexer.php | 36 +- .../graphql-php/src/Language/Parser.php | 670 ++-- .../graphql-php/src/Language/Printer.php | 127 +- .../graphql-php/src/Language/Source.php | 4 +- .../graphql-php/src/Language/Token.php | 64 +- .../graphql-php/src/Language/Visitor.php | 89 +- vendor/webonyx/graphql-php/src/Schema.php | 22 - .../webonyx/graphql-php/src/Server/Helper.php | 88 +- .../src/Server/OperationParams.php | 8 +- .../graphql-php/src/Server/ServerConfig.php | 44 +- .../graphql-php/src/Server/StandardServer.php | 11 +- .../src/Type/Definition/AbstractType.php | 11 +- .../src/Type/Definition/BooleanType.php | 18 +- .../src/Type/Definition/CustomScalarType.php | 14 +- .../src/Type/Definition/Directive.php | 54 +- .../src/Type/Definition/EnumType.php | 35 +- .../src/Type/Definition/FieldArgument.php | 48 +- .../src/Type/Definition/FieldDefinition.php | 112 +- .../src/Type/Definition/FloatType.php | 50 +- .../src/Type/Definition/HasFieldsType.php | 33 + .../src/Type/Definition/IDType.php | 32 +- .../src/Type/Definition/ImplementingType.php | 20 + .../src/Type/Definition/InputObjectField.php | 106 +- .../src/Type/Definition/InputObjectType.php | 70 +- .../src/Type/Definition/InputType.php | 23 +- .../src/Type/Definition/IntType.php | 74 +- .../src/Type/Definition/InterfaceType.php | 94 +- .../src/Type/Definition/LeafType.php | 11 +- .../src/Type/Definition/ListOfType.php | 29 +- .../src/Type/Definition/NamedType.php | 17 +- .../src/Type/Definition/NonNull.php | 66 +- .../src/Type/Definition/ObjectType.php | 132 +- .../src/Type/Definition/QueryPlan.php | 118 +- .../src/Type/Definition/ResolveInfo.php | 81 +- .../src/Type/Definition/StringType.php | 45 +- .../graphql-php/src/Type/Definition/Type.php | 181 +- .../src/Type/Definition/TypeWithFields.php | 81 + .../src/Type/Definition/UnionType.php | 47 +- .../Definition/UnresolvedFieldDefinition.php | 71 + .../src/Type/Definition/WrappingType.php | 7 +- .../graphql-php/src/Type/Introspection.php | 230 +- .../webonyx/graphql-php/src/Type/Schema.php | 246 +- .../graphql-php/src/Type/SchemaConfig.php | 45 +- .../src/Type/SchemaValidationContext.php | 597 +++- .../webonyx/graphql-php/src/Type/TypeKind.php | 16 +- .../Validation/InputObjectCircularRefs.php | 105 + vendor/webonyx/graphql-php/src/Utils/AST.php | 89 +- .../src/Utils/ASTDefinitionBuilder.php | 334 +- .../src/Utils/BreakingChangesFinder.php | 97 +- .../src/Utils/BuildClientSchema.php | 496 +++ .../graphql-php/src/Utils/BuildSchema.php | 102 +- .../src/Utils/InterfaceImplementations.php | 48 + .../graphql-php/src/Utils/MixedStore.php | 2 +- .../graphql-php/src/Utils/SchemaExtender.php | 108 +- .../graphql-php/src/Utils/SchemaPrinter.php | 223 +- .../graphql-php/src/Utils/TypeComparators.php | 18 +- .../graphql-php/src/Utils/TypeInfo.php | 235 +- .../webonyx/graphql-php/src/Utils/Utils.php | 114 +- .../webonyx/graphql-php/src/Utils/Value.php | 19 +- .../src/Validator/ASTValidationContext.php | 54 + .../src/Validator/DocumentValidator.php | 77 +- .../Validator/Rules/DisableIntrospection.php | 2 +- .../Validator/Rules/ExecutableDefinitions.php | 14 +- .../Validator/Rules/FieldsOnCorrectType.php | 13 +- .../Rules/FragmentsOnCompositeTypes.php | 4 +- .../Validator/Rules/KnownArgumentNames.php | 93 +- .../Rules/KnownArgumentNamesOnDirectives.php | 56 +- .../src/Validator/Rules/KnownDirectives.php | 102 +- .../Validator/Rules/KnownFragmentNames.php | 2 +- .../src/Validator/Rules/KnownTypeNames.php | 8 +- .../Rules/LoneAnonymousOperation.php | 10 +- .../Validator/Rules/LoneSchemaDefinition.php | 34 +- .../src/Validator/Rules/NoFragmentCycles.php | 55 +- .../Validator/Rules/NoUndefinedVariables.php | 12 +- .../src/Validator/Rules/NoUnusedFragments.php | 9 +- .../src/Validator/Rules/NoUnusedVariables.php | 12 +- .../Rules/OverlappingFieldsCanBeMerged.php | 47 +- .../Rules/PossibleFragmentSpreads.php | 8 +- .../Rules/ProvidedNonNullArguments.php | 98 - .../Rules/ProvidedRequiredArguments.php | 62 + .../ProvidedRequiredArgumentsOnDirectives.php | 106 +- .../src/Validator/Rules/QueryComplexity.php | 41 +- .../src/Validator/Rules/QueryDepth.php | 16 +- .../src/Validator/Rules/QuerySecurityRule.php | 28 +- .../src/Validator/Rules/ScalarLeafs.php | 2 +- .../Rules/SingleFieldSubscription.php | 57 + .../Validator/Rules/UniqueArgumentNames.php | 21 +- .../Rules/UniqueDirectivesPerLocation.php | 49 +- .../Validator/Rules/UniqueFragmentNames.php | 7 +- .../Validator/Rules/UniqueInputFieldNames.php | 26 +- .../Validator/Rules/UniqueOperationNames.php | 9 +- .../Validator/Rules/UniqueVariableNames.php | 6 +- .../src/Validator/Rules/ValidationRule.php | 20 +- .../Validator/Rules/ValuesOfCorrectType.php | 64 +- .../Rules/VariablesAreInputTypes.php | 2 +- .../Rules/VariablesDefaultValueAllowed.php | 65 - .../Rules/VariablesInAllowedPosition.php | 68 +- .../src/Validator/SDLValidationContext.php | 9 + .../src/Validator/ValidationContext.php | 116 +- 818 files changed, 70695 insertions(+), 16408 deletions(-) create mode 100644 vendor/haydenpierce/class-finder/.gitattributes create mode 100644 vendor/haydenpierce/class-finder/LICENSE create mode 100644 vendor/haydenpierce/class-finder/README.md create mode 100644 vendor/haydenpierce/class-finder/composer.json create mode 100644 vendor/haydenpierce/class-finder/src/AppConfig.php create mode 100644 vendor/haydenpierce/class-finder/src/ClassFinder.php create mode 100644 vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntry.php create mode 100644 vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntryFactory.php create mode 100644 vendor/haydenpierce/class-finder/src/Classmap/ClassmapFinder.php create mode 100644 vendor/haydenpierce/class-finder/src/Exception/ClassFinderException.php create mode 100644 vendor/haydenpierce/class-finder/src/Files/FilesEntry.php create mode 100644 vendor/haydenpierce/class-finder/src/Files/FilesEntryFactory.php create mode 100644 vendor/haydenpierce/class-finder/src/Files/FilesFinder.php create mode 100644 vendor/haydenpierce/class-finder/src/FinderInterface.php create mode 100644 vendor/haydenpierce/class-finder/src/PSR4/PSR4Finder.php create mode 100644 vendor/haydenpierce/class-finder/src/PSR4/PSR4Namespace.php create mode 100644 vendor/haydenpierce/class-finder/src/PSR4/PSR4NamespaceFactory.php create mode 100644 vendor/laragraph/utils/.styleci.yml create mode 100644 vendor/laragraph/utils/CHANGELOG.md create mode 100644 vendor/laragraph/utils/LICENSE create mode 100644 vendor/laragraph/utils/README.md create mode 100644 vendor/laragraph/utils/composer.json create mode 100644 vendor/laragraph/utils/src/RequestParser.php create mode 100644 vendor/laragraph/utils/tests/Unit/RequestParserTest.php create mode 100644 vendor/nuwave/lighthouse/_ide_helper.php delete mode 100644 vendor/nuwave/lighthouse/config/config.php create mode 100644 vendor/nuwave/lighthouse/rector.php create mode 100644 vendor/nuwave/lighthouse/src/ClientDirectives/ClientDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Console/CacheCommand.php create mode 100644 vendor/nuwave/lighthouse/src/Console/DirectiveCommand.php create mode 100644 vendor/nuwave/lighthouse/src/Console/FieldGeneratorCommand.php create mode 100644 vendor/nuwave/lighthouse/src/Console/ValidatorCommand.php create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directive.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_builder_directive_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_manipulator_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_manipulator_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_resolver_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_resolver_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_transformer_directive_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_methods.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_imports.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_methods.stub delete mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/field.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/field_full.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/field_simple.stub create mode 100644 vendor/nuwave/lighthouse/src/Console/stubs/validator.stub create mode 100644 vendor/nuwave/lighthouse/src/Events/EndExecution.php create mode 100644 vendor/nuwave/lighthouse/src/Events/EndOperationOrOperations.php create mode 100644 vendor/nuwave/lighthouse/src/Events/EndRequest.php create mode 100644 vendor/nuwave/lighthouse/src/Events/StartOperationOrOperations.php create mode 100644 vendor/nuwave/lighthouse/src/Events/ValidateSchema.php create mode 100644 vendor/nuwave/lighthouse/src/Exceptions/FederationException.php create mode 100644 vendor/nuwave/lighthouse/src/Exceptions/RateLimitException.php delete mode 100644 vendor/nuwave/lighthouse/src/Exceptions/SubscriptionException.php create mode 100644 vendor/nuwave/lighthouse/src/Exceptions/UnknownCacheVersionException.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/ArgPartitioner.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/Argument.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSet.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSetFactory.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentTypeNodeConverter.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/ListType.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/NamedType.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/NestedBelongsTo.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/NestedManyToMany.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/NestedMorphTo.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToMany.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToOne.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/ResolveNested.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/SaveModel.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/UpdateModel.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Arguments/UpsertModel.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/BaseRequest.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/BatchLoader/BatchLoaderRegistry.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/BatchLoader/RelationBatchLoader.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/Builder.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/DataLoader/ModelRelationFetcher.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/DataLoader/RelationBatchLoader.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/ErrorBuffer.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ErrorPool.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/GraphQLRequest.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/GraphQLValidator.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/LighthouseRequest.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ModelsLoader/AggregateModelsLoader.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ModelsLoader/CountModelsLoader.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ModelsLoader/ModelsLoader.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ModelsLoader/PaginatedModelsLoader.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ModelsLoader/SimpleModelsLoader.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/MultipartFormRequest.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/MutationExecutor.php delete mode 100644 vendor/nuwave/lighthouse/src/Execution/QueryAST.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ReportingErrorHandler.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Resolved.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/Utils/ModelKey.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ValidationErrorHandler.php create mode 100644 vendor/nuwave/lighthouse/src/Execution/ValidationRulesProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/ASTManipulator.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Directives/ExtendsDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Directives/ExternalDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Directives/KeyDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Directives/ProvidesDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Directives/RequiresDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/EntityResolverProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/FederationPrinter.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/FederationServiceProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Resolvers/Entities.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Resolvers/Service.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/SchemaPrinter.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/SchemaValidator.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Types/Any.php create mode 100644 vendor/nuwave/lighthouse/src/Federation/Types/FieldSet.php rename vendor/nuwave/lighthouse/src/{Execution/Utils => GlobalId}/GlobalId.php (55%) create mode 100644 vendor/nuwave/lighthouse/src/GlobalId/GlobalIdDirective.php create mode 100644 vendor/nuwave/lighthouse/src/GlobalId/GlobalIdException.php create mode 100644 vendor/nuwave/lighthouse/src/GlobalId/GlobalIdServiceProvider.php create mode 100644 vendor/nuwave/lighthouse/src/GlobalId/NodeDirective.php rename vendor/nuwave/lighthouse/src/{Schema => GlobalId}/NodeRegistry.php (68%) create mode 100644 vendor/nuwave/lighthouse/src/OrderBy/OrderByDirective.php create mode 100644 vendor/nuwave/lighthouse/src/OrderBy/OrderByServiceProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Pagination/PaginateDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Pagination/PaginationArgs.php create mode 100644 vendor/nuwave/lighthouse/src/Pagination/PaginationServiceProvider.php delete mode 100644 vendor/nuwave/lighthouse/src/Pagination/PaginationUtils.php create mode 100644 vendor/nuwave/lighthouse/src/Pagination/SimplePaginatorField.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/AST/PartialParser.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/AST/TypeNodeConverter.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Conversion/DefinitionNodeConverter.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/DirectiveLocator.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/DirectiveNamespacer.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/AggregateDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/ArgTraversalDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/BcryptDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/BroadcastDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/CountDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/EnumDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/GlobalIdDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/GuardDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/HashDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/LikeDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/LimitDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/MiddlewareDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/MorphToManyDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/MutationExecutorDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/NestDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/NodeDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/OrderByDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/PaginateDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirectiveHelpers.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/RenameArgsDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/RulesDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/RulesForArrayDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/SanitizeDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/ScopeDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/SearchDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/ThrottleDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/TransformArgsDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/UpsertDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/ValidationDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/WhereAuthDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/WithCountDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Directives/WithRelationDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/ExecutableTypeNodeConverter.php delete mode 100644 vendor/nuwave/lighthouse/src/Schema/Factories/ClientDirectiveFactory.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/FallbackTypeNodeConverter.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/RootType.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateScalar.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeTz.php create mode 100644 vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeUtc.php create mode 100644 vendor/nuwave/lighthouse/src/Scout/ScoutBuilderDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Scout/ScoutEnhancer.php create mode 100644 vendor/nuwave/lighthouse/src/Scout/ScoutException.php create mode 100644 vendor/nuwave/lighthouse/src/Scout/ScoutServiceProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Scout/SearchDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/BroadcastSubscriptionJob.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/EchoBroadcaster.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Directives/BroadcastDirective.php rename vendor/nuwave/lighthouse/src/{Schema => Subscriptions}/Directives/SubscriptionDirective.php (60%) delete mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Events/BroadcastSubscriptionEvent.php delete mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Events/BroadcastSubscriptionListener.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Events/EchoSubscriptionEvent.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Storage/CacheStorageManager.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/Storage/RedisStorageManager.php delete mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/StorageManager.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionController.php create mode 100644 vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionGuard.php create mode 100644 vendor/nuwave/lighthouse/src/Support/AppVersion.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/ArgResolver.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/ArgSanitizerDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/ArgumentSetValidation.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/ArgumentValidation.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/DefinedDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/FieldBuilderDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/HasArgumentPath.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/HasErrorBuffer.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/ProvidesRules.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Contracts/ProvidesValidationRules.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Http/Controllers/SubscriptionController.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Http/Middleware/AttemptAuthentication.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Http/Middleware/LogGraphQLQueries.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Pipeline.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Traits/GeneratesColumnsEnum.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Traits/HandlesCompositeKey.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Traits/HasArgumentPath.php create mode 100644 vendor/nuwave/lighthouse/src/Support/Traits/HasArgumentValue.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Traits/HasErrorBuffer.php delete mode 100644 vendor/nuwave/lighthouse/src/Support/Traits/HasResolverArguments.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequestsLumen.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/MockDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/MockResolver.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/MockResolverService.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/MocksResolvers.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/RethrowingErrorHandler.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/TestResponseMixin.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/TestResponseUtils.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/TestSchemaProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/TestingServiceProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Testing/UsesTestSchema.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/BaseRulesDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/RulesDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/RulesForArrayDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/RulesGatherer.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/ValidateDirective.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/ValidationServiceProvider.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/Validator.php create mode 100644 vendor/nuwave/lighthouse/src/Validation/ValidatorDirective.php create mode 100644 vendor/nuwave/lighthouse/src/WhereConditions/Operator.php create mode 100644 vendor/nuwave/lighthouse/src/WhereConditions/SQLOperator.php create mode 100644 vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsBaseDirective.php create mode 100644 vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsDirective.php create mode 100644 vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsServiceProvider.php create mode 100644 vendor/nuwave/lighthouse/src/WhereConditions/WhereHasConditionsDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsDirective.php delete mode 100644 vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsServiceProvider.php rename vendor/nuwave/lighthouse/{assets => src}/default-schema.graphql (64%) create mode 100644 vendor/nuwave/lighthouse/src/lighthouse.php create mode 100644 vendor/thecodingmachine/safe/LICENSE create mode 100644 vendor/thecodingmachine/safe/README.md create mode 100644 vendor/thecodingmachine/safe/composer.json create mode 100644 vendor/thecodingmachine/safe/deprecated/Exceptions/ApcException.php create mode 100644 vendor/thecodingmachine/safe/deprecated/Exceptions/LibeventException.php create mode 100644 vendor/thecodingmachine/safe/deprecated/Exceptions/MssqlException.php create mode 100644 vendor/thecodingmachine/safe/deprecated/Exceptions/StatsException.php create mode 100644 vendor/thecodingmachine/safe/deprecated/apc.php create mode 100644 vendor/thecodingmachine/safe/deprecated/functionsList.php create mode 100644 vendor/thecodingmachine/safe/deprecated/libevent.php create mode 100644 vendor/thecodingmachine/safe/deprecated/mssql.php create mode 100644 vendor/thecodingmachine/safe/deprecated/stats.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/.gitkeep create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ApacheException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ApcuException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ArrayException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/Bzip2Exception.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/CalendarException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ClassobjException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ComException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/CubridException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/DatetimeException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/DirException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/EioException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ErrorfuncException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ExecException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/FileinfoException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/FilesystemException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/FilterException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/FpmException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/FtpException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/FunchandException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/GmpException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/GnupgException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/HashException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/IbaseException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/IbmDb2Exception.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/IconvException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ImageException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ImapException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/InfoException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/IngresiiException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/InotifyException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/LdapException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/LibxmlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/LzfException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MailparseException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MbstringException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MiscException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MsqlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MysqlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MysqliException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MysqlndMsException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/MysqlndQcException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/NetworkException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/Oci8Exception.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/OpcacheException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/OutcontrolException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/PasswordException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/PcntlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/PdfException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/PgsqlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/PosixException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/PsException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/PspellException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ReadlineException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/RpminfoException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/RrdException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SemException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SessionException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ShmopException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SimplexmlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SocketsException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SodiumException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SolrException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SplException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SqlsrvException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SsdeepException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/Ssh2Exception.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/StreamException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/StringsException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/SwooleException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/UodbcException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/UopzException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/UrlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/VarException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/XdiffException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/XmlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/XmlrpcException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/YamlException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/YazException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ZipException.php create mode 100644 vendor/thecodingmachine/safe/generated/Exceptions/ZlibException.php create mode 100644 vendor/thecodingmachine/safe/generated/apache.php create mode 100644 vendor/thecodingmachine/safe/generated/apcu.php create mode 100644 vendor/thecodingmachine/safe/generated/array.php create mode 100644 vendor/thecodingmachine/safe/generated/bzip2.php create mode 100644 vendor/thecodingmachine/safe/generated/calendar.php create mode 100644 vendor/thecodingmachine/safe/generated/classobj.php create mode 100644 vendor/thecodingmachine/safe/generated/com.php create mode 100644 vendor/thecodingmachine/safe/generated/cubrid.php create mode 100644 vendor/thecodingmachine/safe/generated/curl.php create mode 100644 vendor/thecodingmachine/safe/generated/datetime.php create mode 100644 vendor/thecodingmachine/safe/generated/dir.php create mode 100644 vendor/thecodingmachine/safe/generated/eio.php create mode 100644 vendor/thecodingmachine/safe/generated/errorfunc.php create mode 100644 vendor/thecodingmachine/safe/generated/exec.php create mode 100644 vendor/thecodingmachine/safe/generated/fileinfo.php create mode 100644 vendor/thecodingmachine/safe/generated/filesystem.php create mode 100644 vendor/thecodingmachine/safe/generated/filter.php create mode 100644 vendor/thecodingmachine/safe/generated/fpm.php create mode 100644 vendor/thecodingmachine/safe/generated/ftp.php create mode 100644 vendor/thecodingmachine/safe/generated/funchand.php create mode 100644 vendor/thecodingmachine/safe/generated/functionsList.php create mode 100644 vendor/thecodingmachine/safe/generated/gmp.php create mode 100644 vendor/thecodingmachine/safe/generated/gnupg.php create mode 100644 vendor/thecodingmachine/safe/generated/hash.php create mode 100644 vendor/thecodingmachine/safe/generated/ibase.php create mode 100644 vendor/thecodingmachine/safe/generated/ibmDb2.php create mode 100644 vendor/thecodingmachine/safe/generated/iconv.php create mode 100644 vendor/thecodingmachine/safe/generated/image.php create mode 100644 vendor/thecodingmachine/safe/generated/imap.php create mode 100644 vendor/thecodingmachine/safe/generated/info.php create mode 100644 vendor/thecodingmachine/safe/generated/ingres-ii.php create mode 100644 vendor/thecodingmachine/safe/generated/inotify.php create mode 100644 vendor/thecodingmachine/safe/generated/json.php create mode 100644 vendor/thecodingmachine/safe/generated/ldap.php create mode 100644 vendor/thecodingmachine/safe/generated/libxml.php create mode 100644 vendor/thecodingmachine/safe/generated/lzf.php create mode 100644 vendor/thecodingmachine/safe/generated/mailparse.php create mode 100644 vendor/thecodingmachine/safe/generated/mbstring.php create mode 100644 vendor/thecodingmachine/safe/generated/misc.php create mode 100644 vendor/thecodingmachine/safe/generated/msql.php create mode 100644 vendor/thecodingmachine/safe/generated/mysql.php create mode 100644 vendor/thecodingmachine/safe/generated/mysqli.php create mode 100644 vendor/thecodingmachine/safe/generated/mysqlndMs.php create mode 100644 vendor/thecodingmachine/safe/generated/mysqlndQc.php create mode 100644 vendor/thecodingmachine/safe/generated/network.php create mode 100644 vendor/thecodingmachine/safe/generated/oci8.php create mode 100644 vendor/thecodingmachine/safe/generated/opcache.php create mode 100644 vendor/thecodingmachine/safe/generated/openssl.php create mode 100644 vendor/thecodingmachine/safe/generated/outcontrol.php create mode 100644 vendor/thecodingmachine/safe/generated/password.php create mode 100644 vendor/thecodingmachine/safe/generated/pcntl.php create mode 100644 vendor/thecodingmachine/safe/generated/pcre.php create mode 100644 vendor/thecodingmachine/safe/generated/pdf.php create mode 100644 vendor/thecodingmachine/safe/generated/pgsql.php create mode 100644 vendor/thecodingmachine/safe/generated/posix.php create mode 100644 vendor/thecodingmachine/safe/generated/ps.php create mode 100644 vendor/thecodingmachine/safe/generated/pspell.php create mode 100644 vendor/thecodingmachine/safe/generated/readline.php create mode 100644 vendor/thecodingmachine/safe/generated/rpminfo.php create mode 100644 vendor/thecodingmachine/safe/generated/rrd.php create mode 100644 vendor/thecodingmachine/safe/generated/sem.php create mode 100644 vendor/thecodingmachine/safe/generated/session.php create mode 100644 vendor/thecodingmachine/safe/generated/shmop.php create mode 100644 vendor/thecodingmachine/safe/generated/simplexml.php create mode 100644 vendor/thecodingmachine/safe/generated/sockets.php create mode 100644 vendor/thecodingmachine/safe/generated/sodium.php create mode 100644 vendor/thecodingmachine/safe/generated/solr.php create mode 100644 vendor/thecodingmachine/safe/generated/spl.php create mode 100644 vendor/thecodingmachine/safe/generated/sqlsrv.php create mode 100644 vendor/thecodingmachine/safe/generated/ssdeep.php create mode 100644 vendor/thecodingmachine/safe/generated/ssh2.php create mode 100644 vendor/thecodingmachine/safe/generated/stream.php create mode 100644 vendor/thecodingmachine/safe/generated/strings.php create mode 100644 vendor/thecodingmachine/safe/generated/swoole.php create mode 100644 vendor/thecodingmachine/safe/generated/uodbc.php create mode 100644 vendor/thecodingmachine/safe/generated/uopz.php create mode 100644 vendor/thecodingmachine/safe/generated/url.php create mode 100644 vendor/thecodingmachine/safe/generated/var.php create mode 100644 vendor/thecodingmachine/safe/generated/xdiff.php create mode 100644 vendor/thecodingmachine/safe/generated/xml.php create mode 100644 vendor/thecodingmachine/safe/generated/xmlrpc.php create mode 100644 vendor/thecodingmachine/safe/generated/yaml.php create mode 100644 vendor/thecodingmachine/safe/generated/yaz.php create mode 100644 vendor/thecodingmachine/safe/generated/zip.php create mode 100644 vendor/thecodingmachine/safe/generated/zlib.php create mode 100644 vendor/thecodingmachine/safe/lib/DateTime.php create mode 100644 vendor/thecodingmachine/safe/lib/DateTimeImmutable.php create mode 100644 vendor/thecodingmachine/safe/lib/Exceptions/CurlException.php create mode 100644 vendor/thecodingmachine/safe/lib/Exceptions/JsonException.php create mode 100644 vendor/thecodingmachine/safe/lib/Exceptions/OpensslException.php create mode 100644 vendor/thecodingmachine/safe/lib/Exceptions/PcreException.php create mode 100644 vendor/thecodingmachine/safe/lib/Exceptions/SafeExceptionInterface.php create mode 100644 vendor/thecodingmachine/safe/lib/special_cases.php create mode 100644 vendor/thecodingmachine/safe/rector-migrate-0.7.php create mode 100644 vendor/webonyx/graphql-php/.coveralls.yml create mode 100644 vendor/webonyx/graphql-php/.github/FUNDING.yml create mode 100644 vendor/webonyx/graphql-php/.github/workflows/ci-build.yml delete mode 100644 vendor/webonyx/graphql-php/examples/00-hello-world/README.md delete mode 100644 vendor/webonyx/graphql-php/examples/00-hello-world/graphql.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/AppContext.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/Comment.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/DataSource.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/Image.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/Story.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/User.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/CommentType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ContentFormatEnum.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ImageSizeEnumType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Field/HtmlField.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/ImageType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/NodeType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/QueryType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/EmailType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/UrlType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/SearchResultType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/StoryType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/UserType.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/Blog/Types.php delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/README.md delete mode 100644 vendor/webonyx/graphql-php/examples/01-blog/graphql.php delete mode 100644 vendor/webonyx/graphql-php/examples/02-shorthand/README.md delete mode 100644 vendor/webonyx/graphql-php/examples/02-shorthand/graphql.php delete mode 100644 vendor/webonyx/graphql-php/examples/02-shorthand/rootvalue.php delete mode 100644 vendor/webonyx/graphql-php/examples/02-shorthand/schema.graphqls delete mode 100644 vendor/webonyx/graphql-php/examples/03-server/README.md delete mode 100644 vendor/webonyx/graphql-php/examples/03-server/graphql.php create mode 100644 vendor/webonyx/graphql-php/phpstan-baseline.neon delete mode 100644 vendor/webonyx/graphql-php/src/Error/Debug.php create mode 100644 vendor/webonyx/graphql-php/src/Error/DebugFlag.php create mode 100644 vendor/webonyx/graphql-php/src/Exception/InvalidArgument.php create mode 100644 vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/AmpPromiseAdapter.php delete mode 100644 vendor/webonyx/graphql-php/src/Schema.php create mode 100644 vendor/webonyx/graphql-php/src/Type/Definition/HasFieldsType.php create mode 100644 vendor/webonyx/graphql-php/src/Type/Definition/ImplementingType.php create mode 100644 vendor/webonyx/graphql-php/src/Type/Definition/TypeWithFields.php create mode 100644 vendor/webonyx/graphql-php/src/Type/Definition/UnresolvedFieldDefinition.php create mode 100644 vendor/webonyx/graphql-php/src/Type/Validation/InputObjectCircularRefs.php create mode 100644 vendor/webonyx/graphql-php/src/Utils/BuildClientSchema.php create mode 100644 vendor/webonyx/graphql-php/src/Utils/InterfaceImplementations.php create mode 100644 vendor/webonyx/graphql-php/src/Validator/ASTValidationContext.php delete mode 100644 vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedNonNullArguments.php create mode 100644 vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArguments.php create mode 100644 vendor/webonyx/graphql-php/src/Validator/Rules/SingleFieldSubscription.php delete mode 100644 vendor/webonyx/graphql-php/src/Validator/Rules/VariablesDefaultValueAllowed.php create mode 100644 vendor/webonyx/graphql-php/src/Validator/SDLValidationContext.php diff --git a/vendor/haydenpierce/class-finder/.gitattributes b/vendor/haydenpierce/class-finder/.gitattributes new file mode 100644 index 0000000..2491398 --- /dev/null +++ b/vendor/haydenpierce/class-finder/.gitattributes @@ -0,0 +1,7 @@ +/ci/ export-ignore +/docs/ export-ignore +/test/ export-ignore +/.gitignore export-ignore +/.gitlab-ci.yml export-ignore +/composer.lock export-ignore +/phpunit.xml export-ignore diff --git a/vendor/haydenpierce/class-finder/LICENSE b/vendor/haydenpierce/class-finder/LICENSE new file mode 100644 index 0000000..b8dbabd --- /dev/null +++ b/vendor/haydenpierce/class-finder/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2018 Hayden Pierce + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/haydenpierce/class-finder/README.md b/vendor/haydenpierce/class-finder/README.md new file mode 100644 index 0000000..5ca5b3a --- /dev/null +++ b/vendor/haydenpierce/class-finder/README.md @@ -0,0 +1,126 @@ +ClassFinder +=========== + +A dead simple utility to identify classes in a given namespace. + +This package is an improved implementation of an [answer on Stack Overflow](https://stackoverflow.com/a/40229665/3000068) +and provides additional features with less configuration required. + +Requirements +------------ + +* Application is using Composer. +* Classes can be autoloaded with Composer. +* PHP >= 5.3.0 + +Installing +---------- + +Installing is done by requiring it with Composer. + +``` +$ composer require haydenpierce/class-finder +``` + +No other installation methods are currently supported. + +Supported Autoloading Methods +-------------------------------- + +| Method | Supported | with `ClassFinder::RECURSIVE_MODE` | +| ---------- | --------- | ---------------------------------- | +| PSR-4 | ✔️ | ✔️ | +| PSR-0 | ❌️* | ❌️* | +| Classmap | ✔️ | ✔️ | +| Files | ✔️^ | ❌️** | + +\^ Experimental. + +\* Planned. + +\** Not planned. Open an issue if you need this feature. + +Examples +-------- + +**Standard Mode** + +``` + **WARNING**: Before 1.0.0, expect that bug fixes _will not_ be backported to older versions. Backwards incompatible changes +may be introduced in minor 0.X.Y versions, where X changes. + +* `psr0` support + +* Additional features: + +Various ideas: + +* ~~`ClassFinder::getClassesInNamespace('TestApp1\Foo', ClassFinder::RECURSIVE_MODE)`. +Providing classes multiple namespaces deep.~~ (included v0.3-beta) + +* `ClassFinder::getClassesImplementingInterface('TestApp1\Foo', 'TestApp1\FooInterface', ClassFinder::RECURSIVE_MODE)`. +Filtering classes to only classes that implement a namespace. + +* `ClassFinder::debugRenderReport('TestApp1\Foo\Baz')` +Guidance for solving "class not found" errors resulting from typos in namespaces, missing directories, etc. Would print +an HTML report. Not intended for production use, but debugging. diff --git a/vendor/haydenpierce/class-finder/composer.json b/vendor/haydenpierce/class-finder/composer.json new file mode 100644 index 0000000..17682f2 --- /dev/null +++ b/vendor/haydenpierce/class-finder/composer.json @@ -0,0 +1,27 @@ +{ + "name": "haydenpierce/class-finder", + "description" : "A library that can provide of a list of classes in a given namespace", + "type": "library", + "license": "MIT", + "version": "0.4.3", + "authors": [ + { + "name": "Hayden Pierce", + "email": "hayden@haydenpierce.com" + } + ], + "require": { + "php": ">=5.3", + "ext-json": "*" + }, + "require-dev": { + "phpunit/phpunit": "~9.0", + "mikey179/vfsstream": "^1.6" + }, + "autoload": { + "psr-4": { + "HaydenPierce\\ClassFinder\\": "src/", + "HaydenPierce\\ClassFinder\\UnitTest\\": "test/unit" + } + } +} diff --git a/vendor/haydenpierce/class-finder/src/AppConfig.php b/vendor/haydenpierce/class-finder/src/AppConfig.php new file mode 100644 index 0000000..92993b6 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/AppConfig.php @@ -0,0 +1,82 @@ +appRoot = $this->findAppRoot(); + } + + /** + * @return string + */ + private function findAppRoot() + { + if ($this->appRoot) { + $appRoot = $this->appRoot; + } else { + $workingDirectory = str_replace('\\', '/', __DIR__); + $workingDirectory = str_replace('/vendor/haydenpierce/class-finder/src', '', $workingDirectory); + $directoryPathPieces = explode('/', $workingDirectory); + + $appRoot = null; + do { + $path = implode('/', $directoryPathPieces) . '/composer.json'; + if (file_exists($path)) { + $appRoot = implode('/', $directoryPathPieces) . '/'; + } else { + array_pop($directoryPathPieces); + } + } while (is_null($appRoot) && count($directoryPathPieces) > 0); + } + + $this->throwIfInvalidAppRoot($appRoot); + + $this->appRoot= $appRoot; + return $this->appRoot; + } + + /** + * @param string $appRoot + * @return void + * @throws ClassFinderException + */ + private function throwIfInvalidAppRoot($appRoot) + { + if (!file_exists($appRoot . '/composer.json')) { + throw new ClassFinderException(sprintf("Could not locate composer.json. You can get around this by setting ClassFinder::\$appRoot manually. See '%s' for details.", + 'https://gitlab.com/hpierce1102/ClassFinder/blob/master/docs/exceptions/missingComposerConfig.md' + )); + } + } + + /** + * @return string + */ + public function getAppRoot() + { + if ($this->appRoot === null) { + $this->appRoot = $this->findAppRoot(); + } + + $this->throwIfInvalidAppRoot($this->appRoot); + + return $this->appRoot; + } + + /** + * @param string $appRoot + * @return void + */ + public function setAppRoot($appRoot) + { + $this->appRoot = $appRoot; + } +} diff --git a/vendor/haydenpierce/class-finder/src/ClassFinder.php b/vendor/haydenpierce/class-finder/src/ClassFinder.php new file mode 100644 index 0000000..c20ddc3 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/ClassFinder.php @@ -0,0 +1,208 @@ +findClasses($namespace, $options)); + }, array()); + + return array_unique($classes); + } + + /** + * Check if a given namespace contains any classes. + * + * @param string $namespace + * @return bool + */ + public static function namespaceHasClasses($namespace) + { + self::initialize(); + + return count(self::findersWithNamespace($namespace)) > 0; + } + + /** + * @param string $appRoot + * @return void + */ + public static function setAppRoot($appRoot) + { + self::initialize(); + self::$config->setAppRoot($appRoot); + } + + /** + * @return void + */ + public static function enableExperimentalFilesSupport() + { + self::$useFilesSupport = true; + } + + /** + * @return void + */ + public static function disableExperimentalFilesSupport() + { + self::$useFilesSupport = false; + } + + /** + * @return void + */ + public static function enablePSR4Support() + { + self::$usePSR4Support = true; + } + + /** + * @return void + */ + public static function disablePSR4Support() + { + self::$usePSR4Support = false; + } + + /** + * @return void + */ + public static function enableClassmapSupport() + { + self::$useClassmapSupport = true; + } + + /** + * @return void + */ + public static function disableClassmapSupport() + { + self::$useClassmapSupport = false; + } + + /** + * @return FinderInterface[] + */ + private static function getSupportedFinders() + { + $supportedFinders = array(); + + /* + * This is done for testing. For some tests, allowing PSR4 classes contaminates the test results. This could also be + * disabled for performance reasons (less finders in use means less work), but most people probably won't do that. + */ + if (self::$usePSR4Support) { + $supportedFinders[] = self::$psr4; + } + + /* + * This is done for testing. For some tests, allowing classmap classes contaminates the test results. This could also be + * disabled for performance reasons (less finders in use means less work), but most people probably won't do that. + */ + if (self::$useClassmapSupport) { + $supportedFinders[] = self::$classmap; + } + + /* + * Files support is tucked away behind a flag because it will need to use some kind of shell access via exec, or + * system. + * + * #1 Many environments (such as shared space hosts) may not allow these functions, and attempting to call + * these functions will blow up. + * #2 I've heard of performance issues with calling these functions. + * #3 Files support probably doesn't benefit most projects. + * #4 Using exec() or system() is against many PHP developers' religions. + */ + if (self::$useFilesSupport) { + $supportedFinders[] = self::$files; + } + + return $supportedFinders; + } + + /** + * @param string $namespace + * @return FinderInterface[] + */ + private static function findersWithNamespace($namespace) + { + $findersWithNamespace = array_filter(self::getSupportedFinders(), function (FinderInterface $finder) use ($namespace) { + return $finder->isNamespaceKnown($namespace); + }); + + return $findersWithNamespace; + } +} diff --git a/vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntry.php b/vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntry.php new file mode 100644 index 0000000..b6dcf05 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntry.php @@ -0,0 +1,77 @@ +className = $fullyQualifiedClassName; + } + + /** + * @param string $namespace + * @return bool + */ + public function knowsNamespace($namespace) + { + return strpos($this->className, $namespace) !== false; + } + + /** + * @param string $namespace + * @return bool + */ + public function matches($namespace, $options) + { + if ($options === ClassFinder::RECURSIVE_MODE) { + return $this->doesMatchAnyNamespace($namespace); + } else { + return $this->doesMatchDirectNamespace($namespace); + } + } + + /** + * @return string + */ + public function getClassName() + { + return $this->className; + } + + /** + * Checks if the class is a child or subchild of the given namespace. + * + * @param $namespace + * @return bool + */ + private function doesMatchAnyNamespace($namespace) + { + return strpos($this->getClassName(),$namespace) === 0; + } + + /** + * Checks if the class is a DIRECT child of the given namespace. + * + * @param string $namespace + * @return bool + */ + private function doesMatchDirectNamespace($namespace) + { + $classNameFragments = explode('\\', $this->getClassName()); + array_pop($classNameFragments); + $classNamespace = implode('\\', $classNameFragments); + + $namespace = trim($namespace, '\\'); + + return $namespace === $classNamespace; + } +} diff --git a/vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntryFactory.php b/vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntryFactory.php new file mode 100644 index 0000000..d1f2539 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/Classmap/ClassmapEntryFactory.php @@ -0,0 +1,36 @@ +appConfig = $appConfig; + } + + /** + * @return ClassmapEntry[] + */ + public function getClassmapEntries() + { + // Composer will compile user declared mappings to autoload_classmap.php. So no additional work is needed + // to fetch user provided entries. + $classmap = require($this->appConfig->getAppRoot() . 'vendor/composer/autoload_classmap.php'); + + // if classmap has no entries return empty array + if(count($classmap) == 0) { + return array(); + } + + $classmapKeys = array_keys($classmap); + return array_map(function($index) use ($classmapKeys){ + return new ClassmapEntry($classmapKeys[$index]); + }, range(0, count($classmap) - 1)); + } +} diff --git a/vendor/haydenpierce/class-finder/src/Classmap/ClassmapFinder.php b/vendor/haydenpierce/class-finder/src/Classmap/ClassmapFinder.php new file mode 100644 index 0000000..f5875a4 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/Classmap/ClassmapFinder.php @@ -0,0 +1,51 @@ +factory = $factory; + } + + /** + * @param string $namespace + * @return bool + */ + public function isNamespaceKnown($namespace) + { + $classmapEntries = $this->factory->getClassmapEntries(); + + foreach($classmapEntries as $classmapEntry) { + if ($classmapEntry->knowsNamespace($namespace)) { + return true; + } + } + + return false; + } + + /** + * @param string $namespace + * @param int $options + * @return string[] + */ + public function findClasses($namespace, $options) + { + $classmapEntries = $this->factory->getClassmapEntries(); + + $matchingEntries = array_filter($classmapEntries, function(ClassmapEntry $entry) use ($namespace, $options) { + return $entry->matches($namespace, $options); + }); + + return array_map(function(ClassmapEntry $entry) { + return $entry->getClassName(); + }, $matchingEntries); + } +} diff --git a/vendor/haydenpierce/class-finder/src/Exception/ClassFinderException.php b/vendor/haydenpierce/class-finder/src/Exception/ClassFinderException.php new file mode 100644 index 0000000..685a691 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/Exception/ClassFinderException.php @@ -0,0 +1,8 @@ +file = $this->normalizePath($fileToInclude); + $this->php = $php; + } + + /** + * @param string $namespace + * @return bool + */ + public function knowsNamespace($namespace) + { + $classes = $this->getClassesInFile(); + + foreach($classes as $class) { + if (strpos($class, $namespace) !== false) { + return true; + }; + } + + return false; + } + + /** + * Gets a list of classes that belong to the given namespace. + * + * @param string $namespace + * @return string[] + */ + public function getClasses($namespace) + { + $classes = $this->getClassesInFile(); + + return array_values(array_filter($classes, function($class) use ($namespace) { + $classNameFragments = explode('\\', $class); + array_pop($classNameFragments); + $classNamespace = implode('\\', $classNameFragments); + + $namespace = trim($namespace, '\\'); + + return $namespace === $classNamespace; + })); + } + + /** + * Dynamically execute files and check for defined classes. + * + * This is where the real magic happens. Since classes in a randomly included file could contain classes in any namespace, + * (or even multiple namespaces!) we must execute the file and check for newly defined classes. This has a potential + * downside that files being executed will execute their side effects - which may be undesirable. However, Composer + * will require these files anyway - so hopefully causing those side effects isn't that big of a deal. + * + * @return array + */ + private function getClassesInFile() + { + // get_declared_classes() returns a bunch of classes that are built into PHP. So we need a control here. + $script = "var_export(get_declared_classes());"; + exec($this->php . " -r \"$script\"", $output); + $classes = 'return ' . implode('', $output) . ';'; + $initialClasses = eval($classes); + + // clear the exec() buffer. + unset($output); + + // This brings in the new classes. so $classes here will include the PHP defaults and the newly defined classes + $script = "require_once '{$this->file}'; var_export(get_declared_classes());"; + exec($this->php . ' -r "' . $script . '"', $output); + $classes = 'return ' . implode('', $output) . ';'; + $allClasses = eval($classes); + + return array_diff($allClasses, $initialClasses); + } + + /** + * TODO: Similar to PSR4Namespace::normalizePath. Maybe we refactor? + * @param string $path + * @return string + */ + private function normalizePath($path) + { + $path = str_replace('\\', '/', $path); + return $path; + } +} diff --git a/vendor/haydenpierce/class-finder/src/Files/FilesEntryFactory.php b/vendor/haydenpierce/class-finder/src/Files/FilesEntryFactory.php new file mode 100644 index 0000000..0ecb1d1 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/Files/FilesEntryFactory.php @@ -0,0 +1,66 @@ +appConfig = $appConfig; + } + + /** + * @return FilesEntry[] + */ + public function getFilesEntries() + { + $files = require($this->appConfig->getAppRoot() . 'vendor/composer/autoload_files.php'); + $phpPath = $this->findPHP(); + + $filesKeys = array_values($files); + return array_map(function($index) use ($filesKeys, $phpPath){ + return new FilesEntry($filesKeys[$index], $phpPath); + }, range(0, count($files) - 1)); + } + + /** + * Locates the PHP interrupter. + * + * If PHP 5.4 or newer is used, the PHP_BINARY value is used. + * Otherwise we attempt to find it from shell commands. + * + * @return string + * @throws ClassFinderException + */ + private function findPHP() + { + if (defined("PHP_BINARY")) { + // PHP_BINARY was made available in PHP 5.4 + $php = PHP_BINARY; + } else { + $isHostWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; + if ($isHostWindows) { + exec('where php', $output); + $php = $output[0]; + } else { + exec('which php', $output); + $php = $output[0]; + } + } + + if (!isset($php)) { + throw new ClassFinderException(sprintf( + 'Could not locate PHP interrupter. See "%s" for details.', + 'https://gitlab.com/hpierce1102/ClassFinder/blob/master/docs/exceptions/filesCouldNotLocatePHP.md' + )); + } + + return $php; + } +} diff --git a/vendor/haydenpierce/class-finder/src/Files/FilesFinder.php b/vendor/haydenpierce/class-finder/src/Files/FilesFinder.php new file mode 100644 index 0000000..0370ed2 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/Files/FilesFinder.php @@ -0,0 +1,59 @@ +factory = $factory; + + if (!function_exists('exec')) { + throw new ClassFinderException(sprintf( + 'FilesFinder requires that exec() is available. Check your php.ini to see if it is disabled. See "%s" for details.', + 'https://gitlab.com/hpierce1102/ClassFinder/blob/master/docs/exceptions/filesExecNotAvailable.md' + )); + } + } + + /** + * @param string $namespace + * @return bool + */ + public function isNamespaceKnown($namespace) + { + $filesEntries = $this->factory->getFilesEntries(); + + foreach($filesEntries as $filesEntry) { + if ($filesEntry->knowsNamespace($namespace)) { + return true; + } + } + + return false; + } + + /** + * @param string $namespace + * @param int $options + * @return string[] + */ + public function findClasses($namespace, $options) + { + $filesEntries = $this->factory->getFilesEntries(); + + return array_reduce($filesEntries, function($carry, FilesEntry $entry) use ($namespace){ + return array_merge($carry, $entry->getClasses($namespace)); + }, array()); + } +} diff --git a/vendor/haydenpierce/class-finder/src/FinderInterface.php b/vendor/haydenpierce/class-finder/src/FinderInterface.php new file mode 100644 index 0000000..d241397 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/FinderInterface.php @@ -0,0 +1,29 @@ +factory = $factory; + } + + /** + * @param string $namespace + * @param int $options + * @return string[] + */ + public function findClasses($namespace, $options) + { + if ($options === ClassFinder::RECURSIVE_MODE) { + $applicableNamespaces = $this->findAllApplicableNamespaces($namespace); + } + + if (empty($applicableNamespaces)) { + $bestNamespace = $this->findBestPSR4Namespace($namespace); + $applicableNamespaces = array($bestNamespace); + } + + return array_reduce($applicableNamespaces, function($carry, $psr4NamespaceOrNull) use ($namespace, $options) { + if ($psr4NamespaceOrNull instanceof PSR4Namespace) { + $classes = $psr4NamespaceOrNull->findClasses($namespace, $options); + } else { + $classes = array(); + } + + return array_merge($carry, $classes); + }, array()); + + } + + /** + * @param string $namespace + * @return bool + */ + public function isNamespaceKnown($namespace) + { + $composerNamespaces = $this->factory->getPSR4Namespaces(); + + foreach($composerNamespaces as $psr4Namespace) { + if ($psr4Namespace->knowsNamespace($namespace)) { + return true; + } + } + + return false; + } + + /** + * @param string $namespace + * @return PSR4Namespace[] + */ + private function findAllApplicableNamespaces($namespace) + { + $composerNamespaces = $this->factory->getPSR4Namespaces(); + + return array_filter($composerNamespaces, function(PSR4Namespace $potentialNamespace) use ($namespace){ + return $potentialNamespace->isAcceptableNamespaceRecursiveMode($namespace); + }); + } + + /** + * @param string $namespace + * @return PSR4Namespace + */ + private function findBestPSR4Namespace($namespace) + { + $composerNamespaces = $this->factory->getPSR4Namespaces(); + + $acceptableNamespaces = array_filter($composerNamespaces, function(PSR4Namespace $potentialNamespace) use ($namespace){ + return $potentialNamespace->isAcceptableNamespace($namespace); + }); + + $carry = new \stdClass(); + $carry->highestMatchingSegments = 0; + $carry->bestNamespace = null; + + /** @var PSR4Namespace $bestNamespace */ + $bestNamespace = array_reduce($acceptableNamespaces, function ($carry, PSR4Namespace $potentialNamespace) use ($namespace) { + $matchingSegments = $potentialNamespace->countMatchingNamespaceSegments($namespace); + + if ($matchingSegments > $carry->highestMatchingSegments) { + $carry->highestMatchingSegments = $matchingSegments; + $carry->bestNamespace = $potentialNamespace; + } + + return $carry; + }, $carry); + + return $bestNamespace->bestNamespace; + } +} diff --git a/vendor/haydenpierce/class-finder/src/PSR4/PSR4Namespace.php b/vendor/haydenpierce/class-finder/src/PSR4/PSR4Namespace.php new file mode 100644 index 0000000..2b2bd9b --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/PSR4/PSR4Namespace.php @@ -0,0 +1,302 @@ +namespace = $namespace; + $this->directories = $directories; + } + + /** + * @param string $namespace + * @return bool + */ + public function knowsNamespace($namespace) + { + $numberOfSegments = count(explode('\\', $namespace)); + $matchingSegments = $this->countMatchingNamespaceSegments($namespace); + + if ($matchingSegments === 0) { + // Provided namespace doesn't map to anything registered. + return false; + } elseif ($numberOfSegments <= $matchingSegments) { + // This namespace is a superset of the provided namespace. Namespace is known. + return true; + } else { + // This namespace is a subset of the provided namespace. We must resolve the remaining segments to a directory. + $relativePath = substr($namespace, strlen($this->namespace)); + foreach ($this->directories as $directory) { + $path = $this->normalizePath($directory, $relativePath); + if (is_dir($path)) { + return true; + } + } + + return false; + } + } + + /** + * Determines how many namespace segments match the internal namespace. This is useful because multiple namespaces + * may technically match a registered namespace root, but one of the matches may be a better match. Namespaces that + * match, but are not _the best_ match are incorrect matches. TestApp1\\ is **not** the best match when searching for + * namespace TestApp1\\Multi\\Foo if TestApp1\\Multi was explicitly registered. + * + * PSR4Namespace $a; + * $a->namespace = "TestApp1\\"; + * $a->countMatchingNamespaceSegments("TestApp1\\Multi") -> 1, TestApp1 matches. + * + * PSR4Namespace $b; + * $b->namespace = "TestApp1\\Multi"; + * $b->countMatchingNamespaceSegments("TestApp1\\Multi") -> 2, TestApp1\\Multi matches + * + * PSR4Namespace $c; + * $c->namespace = "HaydenPierce\\Foo\\Bar"; + * $c->countMatchingNamespaceSegments("TestApp1\\Multi") -> 0, No matches. + * + * @param string $namespace + * @return int + */ + public function countMatchingNamespaceSegments($namespace) + { + $namespaceFragments = explode('\\', $namespace); + $undefinedNamespaceFragments = array(); + + while($namespaceFragments) { + $possibleNamespace = implode('\\', $namespaceFragments) . '\\'; + + if(strpos($this->namespace, $possibleNamespace) !== false){ + return count(explode('\\', $possibleNamespace)) - 1; + } + + array_unshift($undefinedNamespaceFragments, array_pop($namespaceFragments)); + } + + return 0; + } + + /** + * @param string $namespace + * @return bool + */ + public function isAcceptableNamespace($namespace) + { + $namespaceSegments = count(explode('\\', $this->namespace)) - 1; + $matchingSegments = $this->countMatchingNamespaceSegments($namespace); + return $namespaceSegments === $matchingSegments; + } + + /** + * @param string $namespace + * @return bool + */ + public function isAcceptableNamespaceRecursiveMode($namespace) + { + // Remove prefix backslash (TODO: review if we do this eariler). + $namespace = ltrim($namespace, '\\'); + + return strpos($this->namespace, $namespace) === 0; + } + + /** + * Used to identify subnamespaces. + * + * @return string[] + */ + public function findDirectories() + { + $self = $this; + $directories = array_reduce($this->directories, function($carry, $directory) use ($self){ + $path = $self->normalizePath($directory, ''); + $realDirectory = realpath($path); + if ($realDirectory !== false) { + return array_merge($carry, array($realDirectory)); + } else { + return $carry; + } + }, array()); + + $arraysOfClasses = array_map(function($directory) use ($self) { + $files = scandir($directory); + return array_map(function($file) use ($directory, $self) { + return $self->normalizePath($directory, $file); + }, $files); + }, $directories); + + $potentialDirectories = array_reduce($arraysOfClasses, function($carry, $arrayOfClasses) { + return array_merge($carry, $arrayOfClasses); + }, array()); + + // Remove '.' and '..' directories + $potentialDirectories = array_filter($potentialDirectories, function($potentialDirectory) { + $segments = explode('/', $potentialDirectory); + $lastSegment = array_pop($segments); + + return $lastSegment !== '.' && $lastSegment !== '..'; + }); + + $confirmedDirectories = array_filter($potentialDirectories, function($potentialDirectory) { + return is_dir($potentialDirectory); + }); + + return $confirmedDirectories; + } + + /** + * @param string $namespace + * @param int $options + * @return string[] + */ + public function findClasses($namespace, $options = ClassFinder::STANDARD_MODE) + { + $relativePath = substr($namespace, strlen($this->namespace)); + + $self = $this; + $directories = array_reduce($this->directories, function($carry, $directory) use ($relativePath, $namespace, $self){ + $path = $self->normalizePath($directory, $relativePath); + $realDirectory = realpath($path); + if ($realDirectory !== false) { + return array_merge($carry, array($realDirectory)); + } else { + return $carry; + } + }, array()); + + $arraysOfClasses = array_map(function($directory) { + return scandir($directory); + }, $directories); + + $potentialClassFiles = array_reduce($arraysOfClasses, function($carry, $arrayOfClasses) { + return array_merge($carry, $arrayOfClasses); + }, array()); + + $potentialClasses = array_map(function($file) use ($namespace){ + return $namespace . '\\' . str_replace('.php', '', $file); + }, $potentialClassFiles); + + if ($options == ClassFinder::RECURSIVE_MODE) { + return $this->getClassesFromListRecursively($namespace); + } else { + return array_filter($potentialClasses, function($potentialClass) { + if (function_exists($potentialClass)) { + // For some reason calling class_exists() on a namespace'd function raises a Fatal Error (tested PHP 7.0.8) + // Example: DeepCopy\deep_copy + return false; + } else { + return class_exists($potentialClass); + } + }); + } + } + + /** + * @return string[] + */ + private function getDirectClassesOnly() + { + $self = $this; + $directories = array_reduce($this->directories, function($carry, $directory) use ($self){ + $path = $self->normalizePath($directory, ''); + $realDirectory = realpath($path); + if ($realDirectory !== false) { + return array_merge($carry, array($realDirectory)); + } else { + return $carry; + } + }, array()); + + $arraysOfClasses = array_map(function($directory) { + return scandir($directory); + }, $directories); + + $potentialClassFiles = array_reduce($arraysOfClasses, function($carry, $arrayOfClasses) { + return array_merge($carry, $arrayOfClasses); + }, array()); + + $selfNamespace = $this->namespace; // PHP 5.3 BC + $potentialClasses = array_map(function($file) use ($self, $selfNamespace) { + return $selfNamespace . str_replace('.php', '', $file); + }, $potentialClassFiles); + + return array_filter($potentialClasses, function($potentialClass) { + if (function_exists($potentialClass)) { + // For some reason calling class_exists() on a namespace'd function raises a Fatal Error (tested PHP 7.0.8) + // Example: DeepCopy\deep_copy + return false; + } else { + return class_exists($potentialClass); + } + }); + } + + /** + * @param string $namespace + * @return string[] + */ + public function getClassesFromListRecursively($namespace) + { + $initialClasses = strpos( $this->namespace, $namespace) !== false ? $this->getDirectClassesOnly() : array(); + + return array_reduce($this->getDirectSubnamespaces(), function($carry, PSR4Namespace $subNamespace) use ($namespace) { + return array_merge($carry, $subNamespace->getClassesFromListRecursively($namespace)); + }, $initialClasses); + } + + /** + * Join an absolute path and a relative path in a platform agnostic way. + * + * This method is also extracted so that it can be turned into a vfs:// stream URL for unit testing. + * + * @param string $directory + * @param string $relativePath + * @return mixed + */ + public function normalizePath($directory, $relativePath) + { + $path = str_replace('\\', '/', $directory . '/' . $relativePath); + return $path; + } + + /** + * @return PSR4Namespace[] + */ + public function getDirectSubnamespaces() + { + return $this->directSubnamespaces; + } + + /** + * @param PSR4Namespace[] $directSubnamespaces + */ + public function setDirectSubnamespaces($directSubnamespaces) + { + $this->directSubnamespaces = $directSubnamespaces; + } + + /** + * @return mixed + */ + public function getNamespace() + { + return trim($this->namespace, '\\'); + } +} diff --git a/vendor/haydenpierce/class-finder/src/PSR4/PSR4NamespaceFactory.php b/vendor/haydenpierce/class-finder/src/PSR4/PSR4NamespaceFactory.php new file mode 100644 index 0000000..f74bf53 --- /dev/null +++ b/vendor/haydenpierce/class-finder/src/PSR4/PSR4NamespaceFactory.php @@ -0,0 +1,153 @@ +appConfig = $appConfig; + } + + /** + * @return string[] + */ + public function getPSR4Namespaces() + { + $namespaces = $this->getUserDefinedPSR4Namespaces(); + $vendorNamespaces = require($this->appConfig->getAppRoot() . 'vendor/composer/autoload_psr4.php'); + + $namespaces = array_merge($vendorNamespaces, $namespaces); + + // There's some wackiness going on here for PHP 5.3 compatibility. + $names = array_keys($namespaces); + $directories = array_values($namespaces); + $self = $this; + $namespaces = array_map(function($index) use ($self, $names, $directories) { + return $self->createNamespace($names[$index], $directories[$index]); + },range(0, count($namespaces) - 1)); + + return $namespaces; + } + + /** + * @return string[] + */ + private function getUserDefinedPSR4Namespaces() + { + $appRoot = $this->appConfig->getAppRoot(); + + $composerJsonPath = $appRoot . 'composer.json'; + $composerConfig = json_decode(file_get_contents($composerJsonPath)); + + if (!isset($composerConfig->autoload)) { + return array(); + } + + //Apparently PHP doesn't like hyphens, so we use variable variables instead. + $psr4 = "psr-4"; + return (array)$composerConfig->autoload->$psr4; + } + + /** + * Creates a namespace from composer_psr4.php and composer.json autoload.psr4 items. + * + * @param string $namespace + * @param string[] $directories + * @return PSR4Namespace + * @throws ClassFinderException + */ + public function createNamespace($namespace, $directories) + { + if (is_string($directories)) { + // This is an acceptable format according to composer.json + $directories = array($directories); + } elseif (is_array($directories)) { + // composer_psr4.php seems to put everything in this format + } else { + throw new ClassFinderException('Unknown PSR4 definition.'); + } + + $self = $this; + $appConfig = $this->appConfig; + $directories = array_map(function($directory) use ($self, $appConfig) { + if ($self->isAbsolutePath($directory)) { + return $directory; + } else { + return $appConfig->getAppRoot() . $directory; + } + }, $directories); + + $directories = array_filter(array_map(function($directory) { + return realpath($directory); + }, $directories)); + + $psr4Namespace = new PSR4Namespace($namespace, $directories); + + $subNamespaces = $this->getSubnamespaces($psr4Namespace); + $psr4Namespace->setDirectSubnamespaces($subNamespaces); + + return $psr4Namespace; + } + + /** + * @param PSR4Namespace $psr4Namespace + * @return PSR4Namespace[] + */ + private function getSubnamespaces(PSR4Namespace $psr4Namespace) + { + // Scan it's own directories. + $directories = $psr4Namespace->findDirectories(); + + $self = $this; + $subnamespaces = array_map(function($directory) use ($self, $psr4Namespace){ + $segments = explode('/', $directory); + $subnamespaceSegment = array_pop($segments); + + $namespace = $psr4Namespace->getNamespace() . "\\" . $subnamespaceSegment . "\\"; + return $self->createNamespace($namespace, $directory); + }, $directories); + + return $subnamespaces; + } + + /** + * Check if a path is absolute. + * + * Mostly this answer https://stackoverflow.com/a/38022806/3000068 + * A few changes: Changed exceptions to be ClassFinderExceptions, removed some ctype dependencies, + * updated the root prefix regex to handle Window paths better. + * + * @param string $path + * @return bool + * @throws ClassFinderException + */ + public function isAbsolutePath($path) { + if (!is_string($path)) { + $mess = sprintf('String expected but was given %s', gettype($path)); + throw new ClassFinderException($mess); + } + + // Optional wrapper(s). + $regExp = '%^(?(?:[[:print:]]{2,}://)*)'; + // Optional root prefix. + $regExp .= '(?(?:[[:alpha:]]:[/\\\\]|/)?)'; + // Actual path. + $regExp .= '(?(?:[[:print:]]*))$%'; + $parts = array(); + if (!preg_match($regExp, $path, $parts)) { + $mess = sprintf('Path is NOT valid, was given %s', $path); + throw new ClassFinderException($mess); + } + if ('' !== $parts['root']) { + return true; + } + return false; + } +} diff --git a/vendor/laragraph/utils/.styleci.yml b/vendor/laragraph/utils/.styleci.yml new file mode 100644 index 0000000..135a7af --- /dev/null +++ b/vendor/laragraph/utils/.styleci.yml @@ -0,0 +1,5 @@ +preset: laravel +risky: true +enabled: + - declare_strict_types + - unalign_double_arrow diff --git a/vendor/laragraph/utils/CHANGELOG.md b/vendor/laragraph/utils/CHANGELOG.md new file mode 100644 index 0000000..75b96ae --- /dev/null +++ b/vendor/laragraph/utils/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 1.0.0 + +### Added + +- Add `RequestParser` to convert an incoming HTTP request to one or more `OperationParams` diff --git a/vendor/laragraph/utils/LICENSE b/vendor/laragraph/utils/LICENSE new file mode 100644 index 0000000..c9ff8d8 --- /dev/null +++ b/vendor/laragraph/utils/LICENSE @@ -0,0 +1,16 @@ +The MIT License (MIT) + +Copyright (c) 2019 Benedikt Franke + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/laragraph/utils/README.md b/vendor/laragraph/utils/README.md new file mode 100644 index 0000000..45f9260 --- /dev/null +++ b/vendor/laragraph/utils/README.md @@ -0,0 +1,39 @@ +# laragraph/utils + +[![CI Status](https://github.com/laragraph/utils/workflows/Continuous%20Integration/badge.svg)](https://github.com/laragraph/utils/actions) +[![codecov](https://codecov.io/gh/laragraph/utils/branch/master/graph/badge.svg)](https://codecov.io/gh/laragraph/utils) +[![StyleCI](https://github.styleci.io/repos/228471198/shield?branch=master)](https://github.styleci.io/repos/228471198) + +[![Latest Stable Version](https://poser.pugx.org/laragraph/utils/v/stable)](https://packagist.org/packages/laragraph/utils) +[![Total Downloads](https://poser.pugx.org/laragraph/utils/downloads)](https://packagist.org/packages/laragraph/utils) + +Utilities for using GraphQL with Laravel + +## Installation + +Install through composer + +```bash +composer require laragraph/utils +``` + +## Usage + +This package holds basic utilities that are useful for building a GraphQL server with Laravel. +If you want to build an application, we recommend using a full framework that integrates the +primitives within this package: + +- SDL-first: [Lighthouse](https://github.com/nuwave/lighthouse) +- Code-first: [graphql-laravel](https://github.com/rebing/graphql-laravel) + +## Changelog + +See [`CHANGELOG.md`](CHANGELOG.md). + +## Contributing + +See [`CONTRIBUTING.md`](.github/CONTRIBUTING.md). + +## License + +This package is licensed using the MIT License. diff --git a/vendor/laragraph/utils/composer.json b/vendor/laragraph/utils/composer.json new file mode 100644 index 0000000..036c755 --- /dev/null +++ b/vendor/laragraph/utils/composer.json @@ -0,0 +1,55 @@ +{ + "name": "laragraph/utils", + "type": "library", + "description": "Utilities for using GraphQL with Laravel", + "homepage": "https://github.com/laragraph/utils", + "license": "MIT", + "authors": [ + { + "name": "Benedikt Franke", + "email": "benedikt@franke.tech" + } + ], + "require": { + "php": "^7.2 || ^8.0", + "illuminate/contracts": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/http": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "thecodingmachine/safe": "^1.1", + "webonyx/graphql-php": "^0.13.2 || ^14" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.11", + "infection/infection": "~0.20", + "jangregor/phpstan-prophecy": "^0.8.1", + "orchestra/testbench": "3.6.* || 3.7.* || 3.8.* || 3.9.* || ^4 || ^5 || ^6", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12.57", + "phpstan/phpstan-deprecation-rules": "^0.12.5", + "phpstan/phpstan-strict-rules": "^0.12.5", + "phpunit/phpunit": "^7.5 || ^8.5", + "thecodingmachine/phpstan-safe-rule": "^1.0" + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + }, + "autoload": { + "psr-4": { + "Laragraph\\Utils\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Laragraph\\Utils\\Tests\\": "tests/" + }, + "files": [ + "vendor/symfony/var-dumper/Resources/functions/dump.php" + ] + }, + "minimum-stability": "dev", + "prefer-stable": true, + "support": { + "issues": "https://github.com/laragraph/utils/issues", + "source": "https://github.com/laragraph/utils" + } +} diff --git a/vendor/laragraph/utils/src/RequestParser.php b/vendor/laragraph/utils/src/RequestParser.php new file mode 100644 index 0000000..016e264 --- /dev/null +++ b/vendor/laragraph/utils/src/RequestParser.php @@ -0,0 +1,118 @@ +helper = new Helper(); + } + + /** + * Converts an incoming HTTP request to one or more OperationParams. + * + * @return \GraphQL\Server\OperationParams|array + * + * @throws \GraphQL\Server\RequestError + */ + public function parseRequest(Request $request) + { + $method = $request->getMethod(); + $bodyParams = []; + /** @var array $queryParams */ + $queryParams = $request->query(); + + if ($method === 'POST') { + /** + * Never null, since Symfony defaults to application/x-www-form-urlencoded. + * + * @var string $contentType + */ + $contentType = $request->header('Content-Type'); + + if (stripos($contentType, 'application/json') !== false) { + /** @var string $content */ + $content = $request->getContent(); + $bodyParams = \Safe\json_decode($content, true); + + if (! is_array($bodyParams)) { + throw new RequestError( + 'GraphQL Server expects JSON object or array, but got '. + Utils::printSafeJson($bodyParams) + ); + } + } elseif (stripos($contentType, 'application/graphql') !== false) { + /** @var string $content */ + $content = $request->getContent(); + $bodyParams = ['query' => $content]; + } elseif (stripos($contentType, 'application/x-www-form-urlencoded') !== false) { + /** @var array $bodyParams */ + $bodyParams = $request->post(); + } elseif (stripos($contentType, 'multipart/form-data') !== false) { + $bodyParams = $this->inlineFiles($request); + } else { + throw new RequestError('Unexpected content type: '.Utils::printSafeJson($contentType)); + } + } + + return $this->helper->parseRequestParams($method, $bodyParams, $queryParams); + } + + /** + * Inline file uploads given through a multipart request. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + protected function inlineFiles(Request $request): array + { + /** @var string|null $mapParam */ + $mapParam = $request->post('map'); + if ($mapParam === null) { + throw new RequestError( + 'Could not find a valid map, be sure to conform to GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec' + ); + } + + /** @var string|null $operationsParam */ + $operationsParam = $request->post('operations'); + if ($operationsParam === null) { + throw new RequestError( + 'Could not find valid operations, be sure to conform to GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec' + ); + } + + /** @var array|array> $operations */ + $operations = \Safe\json_decode($operationsParam, true); + + /** @var array> $map */ + $map = \Safe\json_decode($mapParam, true); + + foreach ($map as $fileKey => $operationsPaths) { + /** @var array $operationsPaths */ + $file = $request->file((string) $fileKey); + + /** @var string $operationsPath */ + foreach ($operationsPaths as $operationsPath) { + Arr::set($operations, $operationsPath, $file); + } + } + + return $operations; + } +} diff --git a/vendor/laragraph/utils/tests/Unit/RequestParserTest.php b/vendor/laragraph/utils/tests/Unit/RequestParserTest.php new file mode 100644 index 0000000..d62e7ef --- /dev/null +++ b/vendor/laragraph/utils/tests/Unit/RequestParserTest.php @@ -0,0 +1,253 @@ +makeRequest('GET', ['query' => $query]); + + $parser = new RequestParser(); + /** @var \GraphQL\Server\OperationParams $params */ + $params = $parser->parseRequest($request); + + self::assertSame($query, $params->query); + } + + public function testPostWithJson(): void + { + $query = /** @lang GraphQL */ '{ foo }'; + $request = $this->makeRequest( + 'POST', + [], + [], + ['Content-Type' => 'application/json'], + \Safe\json_encode(['query' => $query]) + ); + + $parser = new RequestParser(); + /** @var \GraphQL\Server\OperationParams $params */ + $params = $parser->parseRequest($request); + + self::assertSame($query, $params->query); + } + + public function testPostWithQueryApplicationGraphQL(): void + { + $query = /** @lang GraphQL */ '{ foo }'; + $request = $this->makeRequest( + 'POST', + [], + [], + ['Content-Type' => 'application/graphql'], + $query + ); + + $parser = new RequestParser(); + /** @var \GraphQL\Server\OperationParams $params */ + $params = $parser->parseRequest($request); + + self::assertSame($query, $params->query); + } + + public function testPostWithRegularForm(): void + { + $query = /** @lang GraphQL */ '{ foo }'; + $request = $this->makeRequest( + 'POST', + ['query' => $query], + [], + ['Content-Type' => 'application/x-www-form-urlencoded'] + ); + + $parser = new RequestParser(); + /** @var \GraphQL\Server\OperationParams $params */ + $params = $parser->parseRequest($request); + + self::assertSame($query, $params->query); + } + + public function testPostDefaultsToRegularForm(): void + { + $query = /** @lang GraphQL */ '{ foo }'; + $request = $this->makeRequest( + 'POST', + ['query' => $query] + ); + + $parser = new RequestParser(); + /** @var \GraphQL\Server\OperationParams $params */ + $params = $parser->parseRequest($request); + + self::assertSame($query, $params->query); + } + + public function testNonSensicalContentType(): void + { + $request = $this->makeRequest( + 'POST', + [], + [], + ['Content-Type' => 'foobar'] + ); + + $parser = new RequestParser(); + $this->expectException(RequestError::class); + $parser->parseRequest($request); + } + + public function testNoQuery(): void + { + $request = $this->makeRequest('GET'); + + $parser = new RequestParser(); + /** @var \GraphQL\Server\OperationParams $params */ + $params = $parser->parseRequest($request); + + self::assertSame(null, $params->query); + } + + public function testInvalidJson(): void + { + $request = $this->makeRequest( + 'POST', + [], + [], + ['Content-Type' => 'application/json'], + 'this is not valid json' + ); + + $parser = new RequestParser(); + $this->expectException(JsonException::class); + $parser->parseRequest($request); + } + + public function testNonArrayJson(): void + { + $request = $this->makeRequest( + 'POST', + [], + [], + ['Content-Type' => 'application/json'], + '"this should be a map with query, variables, etc."' + ); + + $parser = new RequestParser(); + $this->expectException(RequestError::class); + $parser->parseRequest($request); + } + + public function testMultipartFormRequest(): void + { + $file = UploadedFile::fake()->create('image.jpg', 500); + + $request = $this->makeRequest( + 'POST', + [ + 'operations' => /** @lang JSON */ ' + { + "query": "mutation Upload($file: Upload!) { upload(file: $file) }", + "variables": { + "file": null + } + } + ', + 'map' => /** @lang JSON */ ' + { + "0": ["variables.file"] + } + ', + ], + [ + '0' => $file, + ], + [ + 'Content-Type' => 'multipart/form-data', + ] + ); + + $parser = new RequestParser(); + /** @var \GraphQL\Server\OperationParams $params */ + $params = $parser->parseRequest($request); + + self::assertSame('mutation Upload($file: Upload!) { upload(file: $file) }', $params->query); + + $variables = $params->variables; + self::assertNotNull($variables); + /** @var array $variables */ + self::assertSame($file, $variables['file']); + } + + public function testMultipartFormWithoutMap(): void + { + $request = $this->makeRequest( + 'POST', + [], + [], + [ + 'Content-Type' => 'multipart/form-data', + ] + ); + + $parser = new RequestParser(); + $this->expectException(RequestError::class); + $parser->parseRequest($request); + } + + public function testMultipartFormWithoutOperations(): void + { + $request = $this->makeRequest( + 'POST', + [ + 'map' => /** @lang JSON */ ' + { + "0": ["variables.file"] + } + ', + ], + [], + [ + 'Content-Type' => 'multipart/form-data', + ] + ); + + $parser = new RequestParser(); + $this->expectException(RequestError::class); + $parser->parseRequest($request); + } + + /** + * @param string $method + * @param array $parameters + * @param array $files + * @param array $headers + * @param string|resource|null $content + * @return \Illuminate\Http\Request + */ + public function makeRequest(string $method, array $parameters = [], array $files = [], array $headers = [], $content = null): Request + { + $symfonyRequest = SymfonyRequest::create( + 'http://foo.bar/graphql', + $method, + $parameters, + [], + $files, + $this->transformHeadersToServerVars($headers), + $content + ); + + return Request::createFromBase($symfonyRequest); + } +} diff --git a/vendor/nuwave/lighthouse/README.md b/vendor/nuwave/lighthouse/README.md index e66c547..e25b02f 100644 --- a/vendor/nuwave/lighthouse/README.md +++ b/vendor/nuwave/lighthouse/README.md @@ -1,6 +1,6 @@ @@ -8,50 +8,59 @@ # Lighthouse -[![Build Status](https://travis-ci.org/nuwave/lighthouse.svg?branch=master)](https://travis-ci.org/nuwave/lighthouse) -[![codecov](https://codecov.io/gh/nuwave/lighthouse/branch/master/graph/badge.svg)](https://codecov.io/gh/nuwave/lighthouse) +[![Continuous Integration](https://github.com/nuwave/lighthouse/workflows/Continuous%20Integration/badge.svg)](https://github.com/nuwave/lighthouse/actions) +[![Code Coverage](https://codecov.io/gh/nuwave/lighthouse/branch/master/graph/badge.svg)](https://codecov.io/gh/nuwave/lighthouse) [![PHPStan](https://img.shields.io/badge/PHPStan-enabled-brightgreen.svg?style=flat)](https://github.com/phpstan/phpstan) -[![StyleCI](https://github.styleci.io/repos/59965104/shield?branch=master)](https://github.styleci.io/repos/59965104) -[![Packagist](https://img.shields.io/packagist/dt/nuwave/lighthouse.svg)](https://packagist.org/packages/nuwave/lighthouse) -[![GitHub license](https://img.shields.io/github/license/nuwave/lighthouse.svg)](https://github.com/nuwave/lighthouse/blob/master/LICENSE) -[![Get on Slack](https://img.shields.io/badge/slack-join-orange.svg)](https://join.slack.com/t/lighthouse-php/shared_invite/enQtMzc1NzQwNTUxMjk3LWI1ZDQ1YWM1NmM2MmQ0NTU0NGNjZWFkMTJhY2VjMDAwZmMyZDFlZTc1Mjc3ZGY0MWM1Y2Q5MWNjYmJmYWJkYmU) +[![StyleCI](https://github.styleci.io/repos/59965104/shield?branch=master&style=flat)](https://github.styleci.io/repos/59965104) + +[![Packagist](https://img.shields.io/packagist/dt/nuwave/lighthouse.svg)](https://packagist.org/packages/nuwave/lighthouse) +[![Latest Stable Version](https://poser.pugx.org/nuwave/lighthouse/v/stable)](https://packagist.org/packages/nuwave/lighthouse) +[![GitHub license](https://img.shields.io/github/license/nuwave/lighthouse.svg)](https://github.com/nuwave/lighthouse/blob/master/LICENSE) + +[![Ask on Stack Overflow](https://img.shields.io/badge/StackOverflow-ask-orange.svg)](https://stackoverflow.com/questions/tagged/laravel-lighthouse) +[![Get on Slack](https://img.shields.io/badge/Slack-join-blueviolet.svg)](https://join.slack.com/t/lighthouse-php/shared_invite/zt-4sm280w1-wu21r94f3kLRRtBXRbXVfw) + +**A framework for serving GraphQL from Laravel** -**GraphQL Server for Laravel** -Lighthouse is a PHP package that allows you to serve a GraphQL endpoint from your -Laravel application. It greatly reduces the boilerplate required to create a schema, -it integrates well with any Laravel project, and it's highly customizable -giving you full control over your data. +Lighthouse is a GraphQL framework that integrates with your Laravel application. +It takes the best ideas of both and combines them to solve common tasks with ease +and offer flexibility when you need it. -## [Documentation](https://lighthouse-php.com/) +## Documentation The documentation lives at [lighthouse-php.com](https://lighthouse-php.com/). -If you like reading plain markdown, you can also find the source files in the [docs folder](/docs). +The site includes the latest docs for each major version of Lighthouse. +You can find docs for specific versions by looking at the contents of [/docs/master](/docs/master) +at that point in the git history: `https://github.com/nuwave/lighthouse/tree//docs/master`. -## Get started - -If you have an existing Laravel project, all you really need -to get up and running is a few steps: - -1. Install via `composer require nuwave/lighthouse` -2. Publish the default schema `php artisan vendor:publish --provider="Nuwave\Lighthouse\LighthouseServiceProvider" --tag=schema` -3. Use something like [GraphQL Playground](https://github.com/mll-lab/laravel-graphql-playground) to explore your GraphQL endpoint - -Check out [the docs](https://lighthouse-php.com/) to learn more. +A chinese translation is available at [lighthouse-php.cn](http://lighthouse-php.cn/) and is maintained +over at https://github.com/haxibiao/lighthouse. ## Get involved -We welcome contributions of any kind. - -- Have a question? [Use the laravel-lighthouse tag on Stackoverflow](https://stackoverflow.com/questions/tagged/laravel-lighthouse) -- Talk to other users? [Hop into Slack](https://join.slack.com/t/lighthouse-php/shared_invite/enQtMzc1NzQwNTUxMjk3LWI1ZDQ1YWM1NmM2MmQ0NTU0NGNjZWFkMTJhY2VjMDAwZmMyZDFlZTc1Mjc3ZGY0MWM1Y2Q5MWNjYmJmYWJkYmU) +- Have a question? [Use the laravel-lighthouse tag on Stack Overflow](https://stackoverflow.com/questions/tagged/laravel-lighthouse) +- Talk to other users? [Hop into Slack](https://join.slack.com/t/lighthouse-php/shared_invite/zt-4sm280w1-wu21r94f3kLRRtBXRbXVfw) - Found a bug? [Report a bug](https://github.com/nuwave/lighthouse/issues/new?template=bug_report.md) -- Need a feature? [Open a feature request](https://github.com/nuwave/lighthouse/issues/new?template=feature_request.md) -- Want to improve Lighthouse? [Read our contribution guidelines](https://github.com/nuwave/lighthouse/blob/master/.github/CONTRIBUTING.md) +- Have an idea? [Propose a feature](https://github.com/nuwave/lighthouse/issues/new?template=feature_proposal.md) +- Want to improve Lighthouse? [Read our contribution guidelines](https://github.com/nuwave/lighthouse/blob/master/CONTRIBUTING.md) + +## Changelog + +All notable changes to this project are documented in [`CHANGELOG.md`](CHANGELOG.md). + +## Upgrade Guide + +When upgrading between major versions of Lighthouse, consider [`UPGRADE.md`](UPGRADE.md). + +## Contributing + +We welcome contributions of any kind, see how in [`CONTRIBUTING.md`](CONTRIBUTING.md). ## Security Vulnerabilities If you discover a security vulnerability within Lighthouse, -please email Benedikt Franke via [benedikt@franke.tech](mailto:benedikt@franke.tech). +please email Benedikt Franke via [benedikt@franke.tech](mailto:benedikt@franke.tech) +or visit https://tidelift.com/security. diff --git a/vendor/nuwave/lighthouse/_ide_helper.php b/vendor/nuwave/lighthouse/_ide_helper.php new file mode 100644 index 0000000..3c2b6bf --- /dev/null +++ b/vendor/nuwave/lighthouse/_ide_helper.php @@ -0,0 +1,122 @@ += 7.1", + "php": ">= 7.2", "ext-json": "*", - "illuminate/contracts": "5.5.*|5.6.*|5.7.*|5.8.*|^6.0", - "illuminate/http": "5.5.*|5.6.*|5.7.*|5.8.*|^6.0", - "illuminate/pagination": "5.5.*|5.6.*|5.7.*|5.8.*|^6.0", - "illuminate/routing": "5.5.*|5.6.*|5.7.*|5.8.*|^6.0", - "illuminate/support": "5.5.*|5.6.*|5.7.*|5.8.*|^6.0", - "illuminate/validation": "5.5.*|5.6.*|5.7.*|5.8.*|^6.0", - "webonyx/graphql-php": "^0.13.2" + "haydenpierce/class-finder": "^0.4", + "illuminate/auth": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/bus": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/contracts": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/http": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/pagination": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/queue": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/routing": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/support": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/validation": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "laragraph/utils": "^1", + "thecodingmachine/safe": "^1", + "webonyx/graphql-php": "^14.7" }, "require-dev": { - "bensampo/laravel-enum": "^1.22", - "laravel/lumen-framework": "5.5.*|5.6.*|5.7.*|5.8.*|^6.0", - "laravel/scout": "^4.0", - "mll-lab/graphql-php-scalars": "^2.1", - "mockery/mockery": "^1.0", - "orchestra/database": "3.5.*|3.6.*|3.7.*|3.8.*|3.9.*", - "orchestra/testbench": "3.5.*|3.6.*|3.7.*|3.8.*|3.9.*", - "phpbench/phpbench": "@dev", - "pusher/pusher-php-server": "^3.2", - "haydenpierce/class-finder": "^0.3.3" + "bensampo/laravel-enum": "^1.28.3 || ^2 || ^3", + "ergebnis/composer-normalize": "^2.2.2", + "finwe/phpstan-faker": "^0.1.0", + "laravel/framework": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "laravel/legacy-factories": "^1", + "laravel/lumen-framework": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "laravel/scout": "^7 || ^8", + "mll-lab/graphql-php-scalars": "^4", + "mockery/mockery": "^1", + "nunomaduro/larastan": "^0.6 || ^0.7", + "orchestra/testbench": "3.6.* || 3.7.* || 3.8.* || 3.9.* || ^4 || ^5 || ^6", + "phpbench/phpbench": "1.0.0-alpha4", + "phpstan/phpstan": "0.12.89", + "phpstan/phpstan-mockery": "^0.12.5", + "phpstan/phpstan-phpunit": "^0.12.17", + "phpunit/phpunit": "^7.5 || ^8.4 || ^9", + "predis/predis": "^1.1", + "pusher/pusher-php-server": "^4 || ^5", + "rector/rector": "^0.9", + "thecodingmachine/phpstan-safe-rule": "^1", + "vimeo/psalm": "^4.7" }, "suggest": { + "bensampo/laravel-enum": "Convenient enum definitions that can easily be registered in your Schema", "laravel/scout": "Required for the @search directive", - "mll-lab/graphql-php-scalars": "Useful scalar types, required for @whereConstraints", + "mll-lab/graphql-php-scalars": "Useful scalar types, required for @whereConditions", "mll-lab/laravel-graphql-playground": "GraphQL IDE for better development workflow - integrated with Laravel", - "bensampo/laravel-enum": "Convenient enum definitions that can easily be registered in your Schema" + "pusher/pusher-php-server": "Required when using the Pusher Subscriptions driver" + }, + "config": { + "sort-packages": true + }, + "extra": { + "laravel": { + "aliases": { + "graphql": "Nuwave\\Lighthouse\\GraphQL" + }, + "providers": [ + "Nuwave\\Lighthouse\\LighthouseServiceProvider", + "Nuwave\\Lighthouse\\GlobalId\\GlobalIdServiceProvider", + "Nuwave\\Lighthouse\\OrderBy\\OrderByServiceProvider", + "Nuwave\\Lighthouse\\Pagination\\PaginationServiceProvider", + "Nuwave\\Lighthouse\\Scout\\ScoutServiceProvider", + "Nuwave\\Lighthouse\\SoftDeletes\\SoftDeletesServiceProvider", + "Nuwave\\Lighthouse\\Validation\\ValidationServiceProvider" + ] + } }, "autoload": { "psr-4": { @@ -67,24 +99,15 @@ } }, "scripts": { - "test": "phpunit --colors=always", - "test:unit": "phpunit --colors=always --testsuite Unit", - "test:integration": "phpunit --colors=always --testsuite Integration", + "bench": "phpbench run", + "rector": "rector process -v src/ tests/", "stan": "phpstan analyse --memory-limit 2048M", - "bench": "phpbench run" + "test": "phpunit --colors=always", + "test:integration": "phpunit --colors=always --testsuite Integration", + "test:unit": "phpunit --colors=always --testsuite Unit" }, - "extra": { - "laravel": { - "providers": [ - "Nuwave\\Lighthouse\\LighthouseServiceProvider", - "Nuwave\\Lighthouse\\SoftDeletes\\SoftDeletesServiceProvider" - ], - "aliases": { - "graphql": "Nuwave\\Lighthouse\\GraphQL" - } - } - }, - "config": { - "sort-packages": true + "support": { + "issues": "https://github.com/nuwave/lighthouse/issues", + "source": "https://github.com/nuwave/lighthouse" } } diff --git a/vendor/nuwave/lighthouse/config/config.php b/vendor/nuwave/lighthouse/config/config.php deleted file mode 100644 index b8f34fa..0000000 --- a/vendor/nuwave/lighthouse/config/config.php +++ /dev/null @@ -1,240 +0,0 @@ - false, to disable the default route - | registration and take full control. - | - */ - - 'route' => [ - /* - * The URI the endpoint responds to, e.g. mydomain.com/graphql. - */ - 'uri' => 'graphql', - - /* - * Lighthouse creates a named route for convenient URL generation and redirects. - */ - 'name' => 'graphql', - - /* - * - * Beware that middleware defined here runs before the GraphQL execution phase, - * so you have to take extra care to return spec-compliant error responses. - * To apply middleware on a field level, use the @middleware directive. - */ - 'middleware' => [ - \Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class, - ], - ], - - /* - |-------------------------------------------------------------------------- - | Schema Declaration - |-------------------------------------------------------------------------- - | - | This is a path that points to where your GraphQL schema is located - | relative to the app path. You should define your entire GraphQL - | schema in this file (additional files may be imported). - | - */ - - 'schema' => [ - 'register' => base_path('graphql/schema.graphql'), - ], - - /* - |-------------------------------------------------------------------------- - | Schema Cache - |-------------------------------------------------------------------------- - | - | A large part of schema generation consists of parsing and AST manipulation. - | This operation is very expensive, so it is highly recommended to enable - | caching of the final schema to optimize performance of large schemas. - | - */ - - 'cache' => [ - 'enable' => env('LIGHTHOUSE_CACHE_ENABLE', true), - 'key' => env('LIGHTHOUSE_CACHE_KEY', 'lighthouse-schema'), - 'ttl' => env('LIGHTHOUSE_CACHE_TTL', null), - ], - - /* - |-------------------------------------------------------------------------- - | Namespaces - |-------------------------------------------------------------------------- - | - | These are the default namespaces where Lighthouse looks for classes - | that extend functionality of the schema. You may pass either a string - | or an array, they are tried in order and the first match is used. - | - */ - - 'namespaces' => [ - 'models' => ['App', 'App\\Models'], - 'queries' => 'App\\GraphQL\\Queries', - 'mutations' => 'App\\GraphQL\\Mutations', - 'subscriptions' => 'App\\GraphQL\\Subscriptions', - 'interfaces' => 'App\\GraphQL\\Interfaces', - 'unions' => 'App\\GraphQL\\Unions', - 'scalars' => 'App\\GraphQL\\Scalars', - 'directives' => ['App\\GraphQL\\Directives'], - ], - - /* - |-------------------------------------------------------------------------- - | Security - |-------------------------------------------------------------------------- - | - | Control how Lighthouse handles security related query validation. - | This configures the options from http://webonyx.github.io/graphql-php/security/ - | - */ - - 'security' => [ - 'max_query_complexity' => \GraphQL\Validator\Rules\QueryComplexity::DISABLED, - 'max_query_depth' => \GraphQL\Validator\Rules\QueryDepth::DISABLED, - 'disable_introspection' => \GraphQL\Validator\Rules\DisableIntrospection::DISABLED, - ], - - /* - |-------------------------------------------------------------------------- - | Pagination - |-------------------------------------------------------------------------- - | - | Limits the maximum "count" that users may pass as an argument - | to fields that are paginated with the @paginate directive. - | A setting of "null" means the count is unrestricted. - | - */ - - 'paginate_max_count' => null, - - /* - |-------------------------------------------------------------------------- - | Pagination Amount Argument - |-------------------------------------------------------------------------- - | - | Set the name to use for the generated argument on paginated fields - | that controls how many results are returned. - | This setting will be removed in v5. - | - */ - - 'pagination_amount_argument' => 'first', - - /* - |-------------------------------------------------------------------------- - | Debug - |-------------------------------------------------------------------------- - | - | Control the debug level as described in http://webonyx.github.io/graphql-php/error-handling/ - | Debugging is only applied if the global Laravel debug config is set to true. - | - */ - - 'debug' => \GraphQL\Error\Debug::INCLUDE_DEBUG_MESSAGE | \GraphQL\Error\Debug::INCLUDE_TRACE, - - /* - |-------------------------------------------------------------------------- - | Error Handlers - |-------------------------------------------------------------------------- - | - | Register error handlers that receive the Errors that occur during execution - | and handle them. You may use this to log, filter or format the errors. - | The classes must implement \Nuwave\Lighthouse\Execution\ErrorHandler - | - */ - - 'error_handlers' => [ - \Nuwave\Lighthouse\Execution\ExtensionErrorHandler::class, - ], - - /* - |-------------------------------------------------------------------------- - | Global ID - |-------------------------------------------------------------------------- - | - | The name that is used for the global id field on the Node interface. - | When creating a Relay compliant server, this must be named "id". - | - */ - - 'global_id_field' => 'id', - - /* - |-------------------------------------------------------------------------- - | Batched Queries - |-------------------------------------------------------------------------- - | - | GraphQL query batching means sending multiple queries to the server in one request, - | You may set this flag to either process or deny batched queries. - | - */ - - 'batched_queries' => true, - - /* - |-------------------------------------------------------------------------- - | Transactional Mutations - |-------------------------------------------------------------------------- - | - | Sets default setting for transactional mutations. - | You may set this flag to have @create|@update mutations transactional or not. - | - */ - - 'transactional_mutations' => true, - - /* - |-------------------------------------------------------------------------- - | GraphQL Subscriptions - |-------------------------------------------------------------------------- - | - | Here you can define GraphQL subscription "broadcasters" and "storage" drivers - | as well their required configuration options. - | - */ - - 'subscriptions' => [ - /* - * Determines if broadcasts should be queued by default. - */ - 'queue_broadcasts' => env('LIGHTHOUSE_QUEUE_BROADCASTS', true), - - /* - * Default subscription storage. - * - * Any Laravel supported cache driver options are available here. - */ - 'storage' => env('LIGHTHOUSE_SUBSCRIPTION_STORAGE', 'redis'), - - /* - * Default subscription broadcaster. - */ - 'broadcaster' => env('LIGHTHOUSE_BROADCASTER', 'pusher'), - - /* - * Subscription broadcasting drivers with config options. - */ - 'broadcasters' => [ - 'log' => [ - 'driver' => 'log', - ], - 'pusher' => [ - 'driver' => 'pusher', - 'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class.'@pusher', - 'connection' => 'pusher', - ], - ], - ], - -]; diff --git a/vendor/nuwave/lighthouse/rector.php b/vendor/nuwave/lighthouse/rector.php new file mode 100644 index 0000000..0904244 --- /dev/null +++ b/vendor/nuwave/lighthouse/rector.php @@ -0,0 +1,29 @@ +parameters(); + + $parameters->set(Option::SETS, [ + SetList::CODE_QUALITY, + SetList::DEAD_CODE, + SetList::PHPUNIT_EXCEPTION, + SetList::PHPUNIT_SPECIFIC_METHOD, + SetList::PHPUNIT_YIELD_DATA_PROVIDER, + ]); + + $parameters->set(Option::SKIP, [ + // Does not fit autoloading standards + __DIR__.'/tests/database/migrations', + + // Gets stuck on WhereConditionsBaseDirective for some reason + __DIR__.'/src/WhereConditions', + + // Having unused parameters can increase clarity, e.g. in event handlers + RemoveUnusedParameterRector::class, + ]); +}; diff --git a/vendor/nuwave/lighthouse/src/ClientDirectives/ClientDirective.php b/vendor/nuwave/lighthouse/src/ClientDirectives/ClientDirective.php new file mode 100644 index 0000000..618ba97 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/ClientDirectives/ClientDirective.php @@ -0,0 +1,79 @@ +name = $name; + } + + /** + * Get the given values for a client directive. + * + * This returns an array of the given arguments for all field nodes. + * The number of items in the returned result will always be equivalent + * to the number of field nodes, each having one of the following values: + * - When a field node does not have the directive on it: null + * - When the directive is present but has no arguments: [] + * - When the directive is present with arguments: an associative array + * + * @return array|null> + */ + public function forField(ResolveInfo $resolveInfo): array + { + $directive = $this->definition(); + + $arguments = []; + foreach ($resolveInfo->fieldNodes as $fieldNode) { + $arguments [] = Values::getDirectiveValues($directive, $fieldNode, $resolveInfo->variableValues); + } + + return $arguments; + } + + /** + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + protected function definition(): Directive + { + if ($this->definition !== null) { + return $this->definition; + } + + /** @var \Nuwave\Lighthouse\Schema\SchemaBuilder $schemaBuilder */ + $schemaBuilder = app(SchemaBuilder::class); + $schema = $schemaBuilder->schema(); + + $definition = $schema->getDirective($this->name); + if ($definition === null) { + throw new DefinitionException("Missing a schema definition for the client directive $this->name"); + } + + return $this->definition = $definition; + } +} diff --git a/vendor/nuwave/lighthouse/src/Console/CacheCommand.php b/vendor/nuwave/lighthouse/src/Console/CacheCommand.php new file mode 100644 index 0000000..6f7b3d0 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/CacheCommand.php @@ -0,0 +1,20 @@ +documentAST(); + + $this->info('GraphQL schema cache created.'); + } +} diff --git a/vendor/nuwave/lighthouse/src/Console/ClearCacheCommand.php b/vendor/nuwave/lighthouse/src/Console/ClearCacheCommand.php index 2cd7523..55cc71a 100644 --- a/vendor/nuwave/lighthouse/src/Console/ClearCacheCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/ClearCacheCommand.php @@ -3,33 +3,45 @@ namespace Nuwave\Lighthouse\Console; use Illuminate\Console\Command; -use Illuminate\Contracts\Cache\Repository; +use Illuminate\Contracts\Cache\Factory as CacheFactory; +use Illuminate\Contracts\Config\Repository as ConfigRepository; +use Illuminate\Filesystem\Filesystem; +use Nuwave\Lighthouse\Exceptions\UnknownCacheVersionException; class ClearCacheCommand extends Command { /** - * The name and signature of the console command. - * - * @var string + * TODO remove once we require Laravel 6 which allows $this->call(ClearCacheCommand::class). */ - protected $signature = 'lighthouse:clear-cache'; + const NAME = 'lighthouse:clear-cache'; - /** - * The console command description. - * - * @var string - */ - protected $description = 'Clear the cache for the GraphQL AST.'; + protected $name = self::NAME; - /** - * Execute the console command. - * - * @param \Illuminate\Contracts\Cache\Repository $cache - * @return void - */ - public function handle(Repository $cache): void + protected $description = 'Clear the GraphQL schema cache.'; + + public function handle(ConfigRepository $config): void { - $cache->forget(config('lighthouse.cache.key')); + $version = $config->get('lighthouse.cache.version', 1); + switch ($version) { + case 1: + /** @var \Illuminate\Contracts\Cache\Factory $cacheFactory */ + $cacheFactory = app(CacheFactory::class); + + $cacheFactory + ->store($config->get('lighthouse.cache.store')) + ->forget($config->get('lighthouse.cache.key')); + break; + case 2: + /** @var \Illuminate\Filesystem\Filesystem $filesystem */ + $filesystem = app(Filesystem::class); + + $path = $config->get('lighthouse.cache.path') + ?? base_path('bootstrap/cache/lighthouse-schema.php'); + $filesystem->delete($path); + break; + default: + throw new UnknownCacheVersionException($version); + } $this->info('GraphQL AST schema cache deleted.'); } diff --git a/vendor/nuwave/lighthouse/src/Console/DirectiveCommand.php b/vendor/nuwave/lighthouse/src/Console/DirectiveCommand.php new file mode 100644 index 0000000..f81d93d --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/DirectiveCommand.php @@ -0,0 +1,228 @@ + + */ + protected $imports; + + /** + * The implemented interfaces. + * + * @var \Illuminate\Support\Collection + */ + protected $implements; + + /** + * The method stubs. + * + * @var \Illuminate\Support\Collection + */ + protected $methods; + + protected function getNameInput(): string + { + return parent::getNameInput().'Directive'; + } + + protected function namespaceConfigKey(): string + { + return 'directives'; + } + + /** + * @param string $name + * + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + */ + protected function buildClass($name): string + { + $this->imports = new Collection(); + $this->implements = new Collection(); + $this->methods = new Collection(); + + $stub = parent::buildClass($name); + + $forType = $this->option('type'); + $forField = $this->option('field'); + $forArgument = $this->option('argument'); + + if (! $forType && ! $forField && ! $forArgument) { + throw new \Exception('Must specify at least one of: --type, --field or --argument'); + } + + if ($forType) { + $this->askForInterfaces(self::TYPE_INTERFACES); + } + + if ($forField) { + $this->askForInterfaces(self::FIELD_INTERFACES); + } + + if ($forArgument) { + // Arg directives always either implement ArgDirective or ArgDirectiveForArray. + if ($this->confirm('Will your argument directive apply to a list of items?')) { + $this->implementInterface(ArgDirectiveForArray::class); + } else { + $this->implementInterface(ArgDirective::class); + } + + $this->askForInterfaces(self::ARGUMENT_INTERFACES); + } + + $stub = str_replace( + '{{ imports }}', + $this->imports + ->filter() + ->unique() + ->implode("\n"), + $stub + ); + + $stub = str_replace( + '{{ methods }}', + $this->methods->implode("\n"), + $stub + ); + + return str_replace( + '{{ implements }}', + $this->implements->implode(', '), + $stub + ); + } + + /** + * Ask the user if the directive should implement any of the given interfaces. + * + * @param array $interfaces + */ + protected function askForInterfaces(array $interfaces): void + { + foreach ($interfaces as $interface) { + if ($this->confirm("Should the directive implement the {$this->shortName($interface)} middleware?")) { + $this->implementInterface($interface); + } + } + } + + /** + * @param class-string $interface + */ + protected function shortName(string $interface): string + { + return Str::afterLast($interface, '\\'); + } + + /** + * @param class-string $interface + */ + protected function implementInterface(string $interface): void + { + $shortName = $this->shortName($interface); + $this->implements->push($shortName); + + $this->imports->push("use {$interface};"); + if ($imports = $this->interfaceImports($shortName)) { + $imports = explode("\n", $imports); + $this->imports->push(...$imports); + } + + if ($methods = $this->interfaceMethods($shortName)) { + $this->methods->push($methods); + } + } + + protected function getStub(): string + { + return __DIR__.'/stubs/directive.stub'; + } + + protected function interfaceMethods(string $interface): ?string + { + return $this->getFileIfExists( + __DIR__.'/stubs/directives/'.Str::snake($interface).'_methods.stub' + ); + } + + protected function interfaceImports(string $interface): ?string + { + return $this->getFileIfExists( + __DIR__.'/stubs/directives/'.Str::snake($interface).'_imports.stub' + ); + } + + protected function getFileIfExists(string $path): ?string + { + if (! $this->files->exists($path)) { + return null; + } + + return $this->files->get($path); + } + + /** + * @return array> + */ + protected function getOptions(): array + { + return [ + ['type', null, InputOption::VALUE_NONE, 'Create a directive that can be applied to types.'], + ['field', null, InputOption::VALUE_NONE, 'Create a directive that can be applied to fields.'], + ['argument', null, InputOption::VALUE_NONE, 'Create a directive that can be applied to arguments.'], + ]; + } +} diff --git a/vendor/nuwave/lighthouse/src/Console/FieldGeneratorCommand.php b/vendor/nuwave/lighthouse/src/Console/FieldGeneratorCommand.php new file mode 100644 index 0000000..8c61b8b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/FieldGeneratorCommand.php @@ -0,0 +1,27 @@ +option('full') + ? 'field_full' + : 'field_simple'; + + return __DIR__."/stubs/{$stub}.stub"; + } + + /** + * @return array> + */ + protected function getOptions(): array + { + return [ + ['full', 'F', InputOption::VALUE_NONE, 'Include the seldom needed resolver arguments $context and $resolveInfo'], + ]; + } +} diff --git a/vendor/nuwave/lighthouse/src/Console/IdeHelperCommand.php b/vendor/nuwave/lighthouse/src/Console/IdeHelperCommand.php index 547631d..709317a 100644 --- a/vendor/nuwave/lighthouse/src/Console/IdeHelperCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/IdeHelperCommand.php @@ -2,88 +2,91 @@ namespace Nuwave\Lighthouse\Console; -use Illuminate\Console\Command; +use GraphQL\Type\Definition\Type; +use GraphQL\Utils\SchemaPrinter; use HaydenPierce\ClassFinder\ClassFinder; -use Nuwave\Lighthouse\Schema\AST\PartialParser; -use Nuwave\Lighthouse\Schema\DirectiveNamespacer; +use Illuminate\Console\Command; +use Illuminate\Support\Collection; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use Nuwave\Lighthouse\Schema\DirectiveLocator; +use Nuwave\Lighthouse\Schema\TypeRegistry; use Nuwave\Lighthouse\Support\Contracts\Directive; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -use HaydenPierce\ClassFinder\Exception\ClassFinderException; class IdeHelperCommand extends Command { - const GENERATED_NOTICE = <<<'SDL' + public const OPENING_PHP_TAG = /** @lang GraphQL */ "error( - "This command requires haydenpierce/class-finder. Install it by running:\n" - ."\n" - ." composer require --dev haydenpierce/class-finder\n" - ); + $this->schemaDirectiveDefinitions($directiveLocator); + $this->programmaticTypes($typeRegistry); + $this->phpIdeHelper(); - return 1; - } - - $directiveClasses = $this->scanForDirectives( - $directiveNamespaces->gather() - ); - - $schema = $this->buildSchemaString($directiveClasses); - - $filePath = static::filePath(); - file_put_contents($filePath, $schema); - - $this->info("Wrote schema directive definitions to $filePath."); + $this->info("\nIt is recommended to add them to your .gitignore file."); return 0; } + /** + * Create and write schema directive definitions to a file. + */ + protected function schemaDirectiveDefinitions(DirectiveLocator $directiveLocator): void + { + $schema = /** @lang GraphQL */ <<<'GRAPHQL' +""" +Placeholder type for various directives such as `@orderBy`. +Will be replaced by a generated type during schema manipulation. +""" +scalar _ + +GRAPHQL; + + $directiveClasses = $this->scanForDirectives( + $directiveLocator->namespaces() + ); + + foreach ($directiveClasses as $directiveClass) { + $definition = $this->define($directiveClass); + + $schema .= /** @lang GraphQL */ <<info("Wrote schema directive definitions to $filePath."); + } + /** * Scan the given namespaces for directive classes. * - * @param string[] $directiveNamespaces - * @return string[] + * @param array $directiveNamespaces + * @return array> */ protected function scanForDirectives(array $directiveNamespaces): array { $directives = []; foreach ($directiveNamespaces as $directiveNamespace) { - try { - $classesInNamespace = ClassFinder::getClassesInNamespace($directiveNamespace); - } catch (ClassFinderException $classFinderException) { - // TODO remove if https://gitlab.com/hpierce1102/ClassFinder/merge_requests/16 is merged - // The ClassFinder throws if no classes are found. Since we can not know - // in advance if the user has defined custom directives, this behaviour is problematic. - continue; - } + /** @var array $classesInNamespace */ + $classesInNamespace = ClassFinder::getClassesInNamespace($directiveNamespace); foreach ($classesInNamespace as $class) { $reflection = new \ReflectionClass($class); @@ -94,10 +97,7 @@ SDL; if (! is_a($class, Directive::class, true)) { continue; } - - /** @var \Nuwave\Lighthouse\Support\Contracts\Directive $instance */ - $instance = app($class); - $name = $instance->name(); + $name = DirectiveLocator::directiveName($class); // The directive was already found, so we do not add it twice if (isset($directives[$name])) { @@ -112,42 +112,77 @@ SDL; } /** - * @param string[] $directiveClasses - * @return string + * @param class-string<\Nuwave\Lighthouse\Support\Contracts\Directive> $directiveClass + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ - protected function buildSchemaString(array $directiveClasses): string + protected function define(string $directiveClass): string { - $schema = self::GENERATED_NOTICE; + $definition = $directiveClass::definition(); - foreach ($directiveClasses as $name => $directiveClass) { - $definition = $this->define($name, $directiveClass); + // Throws if the definition is invalid + ASTHelper::extractDirectiveDefinition($definition); - $schema .= "\n" - ."# Directive class: $directiveClass\n" - .$definition."\n"; - } - - return $schema; + return trim($definition); } - protected function define(string $name, string $directiveClass): string - { - if (is_a($directiveClass, DefinedDirective::class, true)) { - /** @var DefinedDirective $directiveClass */ - $definition = $directiveClass::definition(); - - // This operation throws if the schema definition is invalid - PartialParser::directiveDefinition($definition); - - return trim($definition); - } else { - return '# Add a proper definition by implementing '.DefinedDirective::class."\n" - ."directive @{$name}"; - } - } - - public static function filePath(): string + public static function schemaDirectivesPath(): string { return base_path().'/schema-directives.graphql'; } + + protected function programmaticTypes(TypeRegistry $typeRegistry): void + { + // Users may register types programmatically, e.g. in service providers + // In order to allow referencing those in the schema, it is useful to print + // those types to a helper schema, excluding types the user defined in the schema + $types = new Collection($typeRegistry->resolvedTypes()); + + $filePath = static::programmaticTypesPath(); + + if ($types->isEmpty() && file_exists($filePath)) { + \Safe\unlink($filePath); + + return; + } + + $schema = $types + ->map(function (Type $type): string { + return SchemaPrinter::printType($type); + }) + ->implode("\n"); + + \Safe\file_put_contents($filePath, self::GENERATED_NOTICE.$schema); + + $this->info("Wrote definitions for programmatically registered types to $filePath."); + } + + public static function programmaticTypesPath(): string + { + return base_path().'/programmatic-types.graphql'; + } + + protected function phpIdeHelper(): void + { + $filePath = static::phpIdeHelperPath(); + $contents = \Safe\file_get_contents(__DIR__.'/../../_ide_helper.php'); + + \Safe\file_put_contents($filePath, $this->withGeneratedNotice($contents)); + + $this->info("Wrote PHP definitions to $filePath."); + } + + public static function phpIdeHelperPath(): string + { + return base_path().'/_lighthouse_ide_helper.php'; + } + + protected function withGeneratedNotice(string $phpContents): string + { + return substr_replace( + $phpContents, + self::OPENING_PHP_TAG.self::GENERATED_NOTICE, + 0, + strlen(self::OPENING_PHP_TAG) + ); + } } diff --git a/vendor/nuwave/lighthouse/src/Console/InterfaceCommand.php b/vendor/nuwave/lighthouse/src/Console/InterfaceCommand.php index 9170a34..7969c23 100644 --- a/vendor/nuwave/lighthouse/src/Console/InterfaceCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/InterfaceCommand.php @@ -4,43 +4,17 @@ namespace Nuwave\Lighthouse\Console; class InterfaceCommand extends LighthouseGeneratorCommand { - /** - * The name of the console command. - * - * @var string - */ protected $name = 'lighthouse:interface'; - /** - * The console command description. - * - * @var string - */ protected $description = 'Create a class for a GraphQL interface type.'; - /** - * The type of class being generated. - * - * @var string - */ protected $type = 'Interface'; - /** - * Get the default namespace for the class. - * - * @param string $rootNamespace - * @return string - */ - protected function getDefaultNamespace($rootNamespace): string + protected function namespaceConfigKey(): string { - return config('lighthouse.namespaces.interfaces'); + return 'interfaces'; } - /** - * Get the stub file for the generator. - * - * @return string - */ protected function getStub(): string { return __DIR__.'/stubs/typeResolver.stub'; diff --git a/vendor/nuwave/lighthouse/src/Console/LighthouseGeneratorCommand.php b/vendor/nuwave/lighthouse/src/Console/LighthouseGeneratorCommand.php index 887f187..d5a3663 100644 --- a/vendor/nuwave/lighthouse/src/Console/LighthouseGeneratorCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/LighthouseGeneratorCommand.php @@ -3,6 +3,7 @@ namespace Nuwave\Lighthouse\Console; use Illuminate\Console\GeneratorCommand; +use InvalidArgumentException; abstract class LighthouseGeneratorCommand extends GeneratorCommand { @@ -12,11 +13,83 @@ abstract class LighthouseGeneratorCommand extends GeneratorCommand * As a typical workflow would be to write the schema first and then copy-paste * a field name to generate a class for it, we uppercase it so the user does * not run into unnecessary errors. You're welcome. - * - * @return string */ protected function getNameInput(): string { - return ucfirst(trim($this->argument('name'))); + $name = $this->argument('name'); + if (! is_string($name)) { + throw new InvalidArgumentException('You must the name for the class to generate.'); + } + + return ucfirst(trim($name)); + } + + /** + * @param string $rootNamespace + */ + protected function getDefaultNamespace($rootNamespace): string + { + $namespaces = config('lighthouse.namespaces.'.$this->namespaceConfigKey()); + + return static::commonNamespace((array) $namespaces); + } + + /** + * Get the config key that holds the default namespaces for the class. + */ + abstract protected function namespaceConfigKey(): string; + + /** + * Find the common namespace of a list of namespaces. + * + * For example, ['App\\Foo\\A', 'App\\Foo\\B'] would return 'App\\Foo'. + * + * @param array $namespaces + */ + public static function commonNamespace(array $namespaces): string + { + if ($namespaces === []) { + throw new InvalidArgumentException( + 'A default namespace is required for code generation.' + ); + } + + if (count($namespaces) === 1) { + return reset($namespaces); + } + + // Save the first namespace + $preferredNamespaceFallback = reset($namespaces); + + // If the strings are sorted, any prefix common to all strings + // will be common to the sorted first and last strings. + // All the strings in the middle can be ignored. + \Safe\sort($namespaces); + + $firstParts = explode('\\', reset($namespaces)); + $lastParts = explode('\\', end($namespaces)); + + $matching = []; + foreach ($firstParts as $i => $part) { + // We ran out of elements to compare, so we reached the maximum common length + if (! isset($lastParts[$i])) { + break; + } + + // We found an element that differs + if ($lastParts[$i] !== $part) { + break; + } + + $matching [] = $part; + } + + // We could not determine a common part of the configured namespaces, + // so we just assume the user will prefer the first one in the list. + if ($matching === []) { + return $preferredNamespaceFallback; + } + + return implode('\\', $matching); } } diff --git a/vendor/nuwave/lighthouse/src/Console/MutationCommand.php b/vendor/nuwave/lighthouse/src/Console/MutationCommand.php index 01207ec..5342d5a 100644 --- a/vendor/nuwave/lighthouse/src/Console/MutationCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/MutationCommand.php @@ -2,47 +2,16 @@ namespace Nuwave\Lighthouse\Console; -class MutationCommand extends LighthouseGeneratorCommand +class MutationCommand extends FieldGeneratorCommand { - /** - * The name of the console command. - * - * @var string - */ protected $name = 'lighthouse:mutation'; - /** - * The console command description. - * - * @var string - */ protected $description = 'Create a class for a single field on the root Mutation type.'; - /** - * The type of class being generated. - * - * @var string - */ protected $type = 'Mutation'; - /** - * Get the default namespace for the class. - * - * @param string $rootNamespace - * @return string - */ - protected function getDefaultNamespace($rootNamespace): string + protected function namespaceConfigKey(): string { - return config('lighthouse.namespaces.mutations'); - } - - /** - * Get the stub file for the generator. - * - * @return string - */ - protected function getStub(): string - { - return __DIR__.'/stubs/field.stub'; + return 'mutations'; } } diff --git a/vendor/nuwave/lighthouse/src/Console/PrintSchemaCommand.php b/vendor/nuwave/lighthouse/src/Console/PrintSchemaCommand.php index e6e28d9..6540da0 100644 --- a/vendor/nuwave/lighthouse/src/Console/PrintSchemaCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/PrintSchemaCommand.php @@ -2,53 +2,62 @@ namespace Nuwave\Lighthouse\Console; -use Nuwave\Lighthouse\GraphQL; -use Illuminate\Console\Command; +use GraphQL\Type\Introspection; +use GraphQL\Type\Schema; use GraphQL\Utils\SchemaPrinter; -use Illuminate\Cache\Repository; +use Illuminate\Console\Command; use Illuminate\Contracts\Filesystem\Filesystem; +use Nuwave\Lighthouse\Schema\SchemaBuilder; class PrintSchemaCommand extends Command { - /** - * The name and signature of the console command. - * - * @var string - */ - protected $signature = ' - lighthouse:print-schema - {--W|write : Write the output to a file} - '; + public const GRAPHQL_FILENAME = 'lighthouse-schema.graphql'; + public const JSON_FILENAME = 'lighthouse-schema.json'; - /** - * The console command description. - * - * @var string - */ - protected $description = 'Compile the final GraphQL schema and print the result.'; + protected $signature = <<<'SIGNATURE' +lighthouse:print-schema +{--W|write : Write the output to a file} +{--json : Output JSON instead of GraphQL SDL} +SIGNATURE; - /** - * Execute the console command. - * - * @param \Illuminate\Cache\Repository $cache - * @param \Illuminate\Contracts\Filesystem\Filesystem $storage - * @param \Nuwave\Lighthouse\GraphQL $graphQL - * @return void - */ - public function handle(Repository $cache, Filesystem $storage, GraphQL $graphQL): void + protected $description = 'Compile the GraphQL schema and print the result.'; + + public function handle(Filesystem $storage, SchemaBuilder $schemaBuilder): void { // Clear the cache so this always gets the current schema - $cache->forget(config('lighthouse.cache.key')); + $this->callSilent(ClearCacheCommand::NAME); - $schema = SchemaPrinter::doPrint( - $graphQL->prepSchema() - ); + $schema = $schemaBuilder->schema(); + if ($this->option('json')) { + $filename = self::JSON_FILENAME; + $schemaString = $this->toJson($schema); + } else { + $filename = self::GRAPHQL_FILENAME; + $schemaString = SchemaPrinter::doPrint($schema); + } if ($this->option('write')) { - $storage->put('lighthouse-schema.graphql', $schema); - $this->info('Wrote schema to the default file storage (usually storage/app) as "lighthouse-schema.graphql".'); + $storage->put($filename, $schemaString); + $this->info('Wrote schema to the default file storage (usually storage/app) as "'.$filename.'".'); } else { - $this->info($schema); + $this->info($schemaString); } } + + protected function toJson(Schema $schema): string + { + $introspectionResult = Introspection::fromSchema($schema); + if ($introspectionResult === null) { + throw new \Exception(<<<'MESSAGE' +Did not receive a valid introspection result. +Check if your schema is correct with: + + php artisan lighthouse:validate-schema + +MESSAGE +); + } + + return \Safe\json_encode($introspectionResult); + } } diff --git a/vendor/nuwave/lighthouse/src/Console/QueryCommand.php b/vendor/nuwave/lighthouse/src/Console/QueryCommand.php index b93de92..fb2c8d0 100644 --- a/vendor/nuwave/lighthouse/src/Console/QueryCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/QueryCommand.php @@ -2,47 +2,16 @@ namespace Nuwave\Lighthouse\Console; -class QueryCommand extends LighthouseGeneratorCommand +class QueryCommand extends FieldGeneratorCommand { - /** - * The name of the console command. - * - * @var string - */ protected $name = 'lighthouse:query'; - /** - * The console command description. - * - * @var string - */ protected $description = 'Create a class for a single field on the root Query type.'; - /** - * The type of class being generated. - * - * @var string - */ protected $type = 'Query'; - /** - * Get the default namespace for the class. - * - * @param string $rootNamespace - * @return string - */ - protected function getDefaultNamespace($rootNamespace): string + protected function namespaceConfigKey(): string { - return config('lighthouse.namespaces.queries'); - } - - /** - * Get the stub file for the generator. - * - * @return string - */ - protected function getStub(): string - { - return __DIR__.'/stubs/field.stub'; + return 'queries'; } } diff --git a/vendor/nuwave/lighthouse/src/Console/ScalarCommand.php b/vendor/nuwave/lighthouse/src/Console/ScalarCommand.php index 45aeb13..dc70547 100644 --- a/vendor/nuwave/lighthouse/src/Console/ScalarCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/ScalarCommand.php @@ -4,43 +4,17 @@ namespace Nuwave\Lighthouse\Console; class ScalarCommand extends LighthouseGeneratorCommand { - /** - * The name of the console command. - * - * @var string - */ protected $name = 'lighthouse:scalar'; - /** - * The console command description. - * - * @var string - */ protected $description = 'Create a class for a GraphQL scalar type.'; - /** - * The type of class being generated. - * - * @var string - */ protected $type = 'Scalar'; - /** - * Get the default namespace for the class. - * - * @param string $rootNamespace - * @return string - */ - protected function getDefaultNamespace($rootNamespace): string + protected function namespaceConfigKey(): string { - return config('lighthouse.namespaces.scalars'); + return 'scalars'; } - /** - * Get the stub file for the generator. - * - * @return string - */ protected function getStub(): string { return __DIR__.'/stubs/scalar.stub'; diff --git a/vendor/nuwave/lighthouse/src/Console/SubscriptionCommand.php b/vendor/nuwave/lighthouse/src/Console/SubscriptionCommand.php index 9ef885e..0ea5eb6 100644 --- a/vendor/nuwave/lighthouse/src/Console/SubscriptionCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/SubscriptionCommand.php @@ -4,43 +4,17 @@ namespace Nuwave\Lighthouse\Console; class SubscriptionCommand extends LighthouseGeneratorCommand { - /** - * The name of the console command. - * - * @var string - */ protected $name = 'lighthouse:subscription'; - /** - * The console command description. - * - * @var string - */ protected $description = 'Create a class for a single field on the root Subscription type.'; - /** - * The type of class being generated. - * - * @var string - */ protected $type = 'Subscription'; - /** - * Get the default namespace for the class. - * - * @param string $rootNamespace - * @return string - */ - protected function getDefaultNamespace($rootNamespace): string + protected function namespaceConfigKey(): string { - return config('lighthouse.namespaces.subscriptions'); + return 'subscriptions'; } - /** - * Get the stub file for the generator. - * - * @return string - */ protected function getStub(): string { return __DIR__.'/stubs/subscription.stub'; diff --git a/vendor/nuwave/lighthouse/src/Console/UnionCommand.php b/vendor/nuwave/lighthouse/src/Console/UnionCommand.php index 53a9232..afc3faf 100644 --- a/vendor/nuwave/lighthouse/src/Console/UnionCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/UnionCommand.php @@ -4,43 +4,17 @@ namespace Nuwave\Lighthouse\Console; class UnionCommand extends LighthouseGeneratorCommand { - /** - * The name of the console command. - * - * @var string - */ protected $name = 'lighthouse:union'; - /** - * The console command description. - * - * @var string - */ protected $description = 'Create a class for a GraphQL union type.'; - /** - * The type of class being generated. - * - * @var string - */ protected $type = 'Union'; - /** - * Get the default namespace for the class. - * - * @param string $rootNamespace - * @return string - */ - protected function getDefaultNamespace($rootNamespace): string + protected function namespaceConfigKey(): string { - return config('lighthouse.namespaces.unions'); + return 'unions'; } - /** - * Get the stub file for the generator. - * - * @return string - */ protected function getStub(): string { return __DIR__.'/stubs/typeResolver.stub'; diff --git a/vendor/nuwave/lighthouse/src/Console/ValidateSchemaCommand.php b/vendor/nuwave/lighthouse/src/Console/ValidateSchemaCommand.php index 4343f9e..bdf31c8 100644 --- a/vendor/nuwave/lighthouse/src/Console/ValidateSchemaCommand.php +++ b/vendor/nuwave/lighthouse/src/Console/ValidateSchemaCommand.php @@ -2,38 +2,52 @@ namespace Nuwave\Lighthouse\Console; -use Nuwave\Lighthouse\GraphQL; +use GraphQL\Type\Schema; use Illuminate\Console\Command; -use Illuminate\Contracts\Cache\Repository; +use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; +use Nuwave\Lighthouse\Events\ValidateSchema; +use Nuwave\Lighthouse\Schema\DirectiveLocator; +use Nuwave\Lighthouse\Schema\Factories\DirectiveFactory; +use Nuwave\Lighthouse\Schema\FallbackTypeNodeConverter; +use Nuwave\Lighthouse\Schema\SchemaBuilder; +use Nuwave\Lighthouse\Schema\TypeRegistry; class ValidateSchemaCommand extends Command { - /** - * The name and signature of the console command. - * - * @var string - */ - protected $signature = 'lighthouse:validate-schema'; - /** - * The console command description. - * - * @var string - */ + protected $name = 'lighthouse:validate-schema'; + protected $description = 'Validate the GraphQL schema definition.'; - /** - * Execute the console command. - * - * @param \Illuminate\Contracts\Cache\Repository $cache - * @param \Nuwave\Lighthouse\GraphQL $graphQL - * @return void - */ - public function handle(Repository $cache, GraphQL $graphQL): void - { + public function handle( + EventsDispatcher $eventsDispatcher, + SchemaBuilder $schemaBuilder, + DirectiveLocator $directiveLocator, + TypeRegistry $typeRegistry + ): void { // Clear the cache so this always validates the current schema - $cache->forget(config('lighthouse.cache.key')); + $this->call(ClearCacheCommand::NAME); - $graphQL->prepSchema()->assertValid(); + $originalSchema = $schemaBuilder->schema(); + $schemaConfig = $originalSchema->getConfig(); + + // We add schema directive definitions only here, since it is very slow + $directiveFactory = new DirectiveFactory( + new FallbackTypeNodeConverter($typeRegistry) + ); + foreach ($directiveLocator->definitions() as $directiveDefinition) { + // TODO consider a solution that feels less hacky + if ($directiveDefinition->name->value !== 'deprecated') { + $schemaConfig->directives [] = $directiveFactory->handle($directiveDefinition); + } + } + + $schema = new Schema($schemaConfig); + $schema->assertValid(); + + // Allow plugins to do their own schema validations + $eventsDispatcher->dispatch( + new ValidateSchema($schema) + ); $this->info('The defined schema is valid.'); } diff --git a/vendor/nuwave/lighthouse/src/Console/ValidatorCommand.php b/vendor/nuwave/lighthouse/src/Console/ValidatorCommand.php new file mode 100644 index 0000000..b8cbe3e --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/ValidatorCommand.php @@ -0,0 +1,40 @@ + $value The slice of arguments that belongs to this nested resolver. + * @return mixed + */ + public function __invoke($root, $value) + { + // TODO implement the arg resolver + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_transformer_directive_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_transformer_directive_methods.stub new file mode 100644 index 0000000..25930ad --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/arg_transformer_directive_methods.stub @@ -0,0 +1,10 @@ + /** + * Apply transformations on the value of an argument given to a field. + * + * @param mixed $argumentValue + * @return mixed + */ + public function transform($argumentValue) + { + // TODO implement the arg transformer + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_imports.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_imports.stub new file mode 100644 index 0000000..7bbfa4c --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_imports.stub @@ -0,0 +1,3 @@ +use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_methods.stub new file mode 100644 index 0000000..8bd4f34 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_manipulator_methods.stub @@ -0,0 +1,15 @@ + /** + * Manipulate the AST based on a field definition. + * + * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST + * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition + * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType + * @return void + */ + public function manipulateFieldDefinition( + DocumentAST &$documentAST, + FieldDefinitionNode &$fieldDefinition, + ObjectTypeDefinitionNode &$parentType + ) { + // TODO implement the field manipulator + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_imports.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_imports.stub new file mode 100644 index 0000000..45caded --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_imports.stub @@ -0,0 +1,2 @@ +use Closure; +use Nuwave\Lighthouse\Schema\Values\FieldValue; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_methods.stub new file mode 100644 index 0000000..4898c92 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_middleware_methods.stub @@ -0,0 +1,11 @@ + /** + * Wrap around the final field resolver. + * + * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue + * @param \Closure $next + * @return \Nuwave\Lighthouse\Schema\Values\FieldValue + */ + public function handleField(FieldValue $fieldValue, Closure $next) + { + // TODO implement the field middleware + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_imports.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_imports.stub new file mode 100644 index 0000000..3f2e335 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_imports.stub @@ -0,0 +1 @@ +use Nuwave\Lighthouse\Schema\Values\FieldValue; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_methods.stub new file mode 100644 index 0000000..a53b634 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/field_resolver_methods.stub @@ -0,0 +1,13 @@ + /** + * Set a field resolver on the FieldValue. + * + * This must call $fieldValue->setResolver() before returning + * the FieldValue. + * + * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue + * @return \Nuwave\Lighthouse\Schema\Values\FieldValue + */ + public function resolveField(FieldValue $fieldValue) + { + // TODO implement the field resolver + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_imports.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_imports.stub new file mode 100644 index 0000000..61a2bd9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_imports.stub @@ -0,0 +1,2 @@ +use GraphQL\Language\AST\TypeExtensionNode; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_methods.stub new file mode 100644 index 0000000..30f4bdf --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_extension_manipulator_methods.stub @@ -0,0 +1,11 @@ + /** + * Apply manipulations from a type extension node. + * + * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST + * @param \GraphQL\Language\AST\TypeExtensionNode $typeExtension + * @return void + */ + public function manipulateTypeExtension(DocumentAST &$documentAST, TypeExtensionNode &$typeExtension) + { + // TODO implement the type extension manipulator + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_imports.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_imports.stub new file mode 100644 index 0000000..72eb52c --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_imports.stub @@ -0,0 +1,2 @@ +use GraphQL\Language\AST\TypeDefinitionNode; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_methods.stub new file mode 100644 index 0000000..8cf2070 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_manipulator_methods.stub @@ -0,0 +1,11 @@ + /** + * Apply manipulations from a type definition node. + * + * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST + * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition + * @return void + */ + public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition) + { + // TODO implement the type manipulator + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_imports.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_imports.stub new file mode 100644 index 0000000..a15879a --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_imports.stub @@ -0,0 +1,2 @@ +use Closure; +use Nuwave\Lighthouse\Schema\Values\TypeValue; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_methods.stub new file mode 100644 index 0000000..cb7a6c5 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_middleware_methods.stub @@ -0,0 +1,11 @@ + /** + * Handle a type AST as it is converted to an executable type. + * + * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $value + * @param \Closure $next + * @return \GraphQL\Type\Definition\Type + */ + public function handleNode(TypeValue $value, Closure $next) + { + // TODO implement the type middleware + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_imports.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_imports.stub new file mode 100644 index 0000000..eef27eb --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_imports.stub @@ -0,0 +1 @@ +use Nuwave\Lighthouse\Schema\Values\TypeValue; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_methods.stub b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_methods.stub new file mode 100644 index 0000000..1914373 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/directives/type_resolver_methods.stub @@ -0,0 +1,10 @@ + /** + * Resolve a type AST to a GraphQL Type. + * + * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $value + * @return \GraphQL\Type\Definition\Type + */ + public function resolveNode(TypeValue $value) + { + // TODO implement the type resolver + } diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/field.stub b/vendor/nuwave/lighthouse/src/Console/stubs/field.stub deleted file mode 100644 index 01e3d03..0000000 --- a/vendor/nuwave/lighthouse/src/Console/stubs/field.stub +++ /dev/null @@ -1,23 +0,0 @@ - $args The field arguments passed by the client. + * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context Shared between all fields. + * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo Metadata for advanced query resolution. + * @return mixed + */ + public function __invoke($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) + { + // TODO implement the resolver + } +} diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/field_simple.stub b/vendor/nuwave/lighthouse/src/Console/stubs/field_simple.stub new file mode 100644 index 0000000..d79c5f6 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/field_simple.stub @@ -0,0 +1,15 @@ + $args + */ + public function __invoke($_, array $args) + { + // TODO implement the resolver + } +} diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/scalar.stub b/vendor/nuwave/lighthouse/src/Console/stubs/scalar.stub index 164f0c5..605f531 100644 --- a/vendor/nuwave/lighthouse/src/Console/stubs/scalar.stub +++ b/vendor/nuwave/lighthouse/src/Console/stubs/scalar.stub @@ -5,7 +5,7 @@ namespace DummyNamespace; use GraphQL\Type\Definition\ScalarType; /** - * Read more about scalars here http://webonyx.github.io/graphql-php/type-system/scalar-types/ + * Read more about scalars here https://webonyx.github.io/graphql-php/type-definitions/scalars */ class DummyClass extends ScalarType { @@ -45,7 +45,7 @@ class DummyClass extends ScalarType * } * * @param \GraphQL\Language\AST\Node $valueNode - * @param mixed[]|null $variables + * @param array|null $variables * @return mixed */ public function parseLiteral($valueNode, ?array $variables = null) diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/typeResolver.stub b/vendor/nuwave/lighthouse/src/Console/stubs/typeResolver.stub index 1fabf19..3ccb087 100644 --- a/vendor/nuwave/lighthouse/src/Console/stubs/typeResolver.stub +++ b/vendor/nuwave/lighthouse/src/Console/stubs/typeResolver.stub @@ -5,6 +5,7 @@ namespace DummyNamespace; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\ResolveInfo; use Nuwave\Lighthouse\Schema\TypeRegistry; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; class DummyClass { @@ -15,12 +16,6 @@ class DummyClass */ protected $typeRegistry; - /** - * Constructor. - * - * @param \Nuwave\Lighthouse\Schema\TypeRegistry $typeRegistry - * @return void - */ public function __construct(TypeRegistry $typeRegistry) { $this->typeRegistry = $typeRegistry; diff --git a/vendor/nuwave/lighthouse/src/Console/stubs/validator.stub b/vendor/nuwave/lighthouse/src/Console/stubs/validator.stub new file mode 100644 index 0000000..c3e4554 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Console/stubs/validator.stub @@ -0,0 +1,20 @@ +> + */ + public function rules(): array + { + return [ + // TODO Add your validation rules + ]; + } +} diff --git a/vendor/nuwave/lighthouse/src/Defer/Defer.php b/vendor/nuwave/lighthouse/src/Defer/Defer.php index 357d8ad..32528f2 100644 --- a/vendor/nuwave/lighthouse/src/Defer/Defer.php +++ b/vendor/nuwave/lighthouse/src/Defer/Defer.php @@ -3,14 +3,13 @@ namespace Nuwave\Lighthouse\Defer; use Closure; +use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Support\Arr; +use Nuwave\Lighthouse\Events\StartExecution; use Nuwave\Lighthouse\GraphQL; -use Nuwave\Lighthouse\Events\ManipulateAST; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; -use Symfony\Component\HttpFoundation\Response; -use Nuwave\Lighthouse\Schema\AST\PartialParser; -use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse; +use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; +use Symfony\Component\HttpFoundation\Response; class Defer implements CreatesResponse { @@ -25,161 +24,134 @@ class Defer implements CreatesResponse protected $graphQL; /** - * @var mixed[] + * @var \Nuwave\Lighthouse\Events\StartExecution */ - protected $result = []; + protected $startExecution; /** - * @var mixed[] + * A map from paths to deferred resolvers. + * + * @var array */ protected $deferred = []; /** - * @var mixed[] + * Paths resolved during the current nesting of defers. + * + * @var array */ protected $resolved = []; /** - * @var bool + * The entire result of resolving the query up until the current nesting. + * + * @var array */ - protected $acceptFurtherDeferring = true; + protected $result = []; /** + * Should further deferring happen? + * + * @var bool + */ + protected $shouldDeferFurther = true; + + /** + * Are we currently streaming deferred results? + * * @var bool */ protected $isStreaming = false; /** - * @var int + * @var float|int */ protected $maxExecutionTime = 0; - /** * @var int */ protected $maxNestedFields = 0; - /** - * @param \Nuwave\Lighthouse\Support\Contracts\CanStreamResponse $stream - * @param \Nuwave\Lighthouse\GraphQL $graphQL - * @return void - */ - public function __construct(CanStreamResponse $stream, GraphQL $graphQL) + public function __construct(CanStreamResponse $stream, GraphQL $graphQL, ConfigRepository $config) { $this->stream = $stream; $this->graphQL = $graphQL; - $this->maxNestedFields = config('lighthouse.defer.max_nested_fields', 0); + + $executionTime = $config->get('lighthouse.defer.max_execution_ms', 0); + if ($executionTime > 0) { + $this->maxExecutionTime = microtime(true) + $executionTime * 1000; + } + + $this->maxNestedFields = $config->get('lighthouse.defer.max_nested_fields', 0); } - /** - * Set the tracing directive on all fields of the query to enable tracing them. - * - * @param \Nuwave\Lighthouse\Events\ManipulateAST $manipulateAST - * @return void - */ - public function handleManipulateAST(ManipulateAST $manipulateAST): void + public function handleStartExecution(StartExecution $startExecution): void { - ASTHelper::attachDirectiveToObjectTypeFields( - $manipulateAST->documentAST, - PartialParser::directive('@deferrable') - ); - - $manipulateAST->documentAST->setDirectiveDefinition( - PartialParser::directiveDefinition(' -""" -Use this directive on expensive or slow fields to resolve them asynchronously. -Must not be placed upon: -- Non-Nullable fields -- Mutation root fields -""" -directive @defer(if: Boolean = true) on FIELD -') - ); - } - - /** - * @return bool - */ - public function isStreaming(): bool - { - return $this->isStreaming; + $this->startExecution = $startExecution; } /** * Register deferred field. * - * @param \Closure $resolver - * @param string $path - * @return mixed + * @param \Closure(): mixed $resolver + * @return mixed The data if it is already available. */ public function defer(Closure $resolver, string $path) { - if ($data = Arr::get($this->result, "data.{$path}")) { + $data = $this->getData($path); + if ($data !== null) { return $data; } - if ($this->isDeferred($path) || ! $this->acceptFurtherDeferring) { + // If we have been here before, now is the time to resolve this field + $deferredResolver = $this->deferred[$path] ?? null; + if ($deferredResolver) { + return $this->resolve($deferredResolver, $path); + } + + if (! $this->shouldDeferFurther) { return $this->resolve($resolver, $path); } $this->deferred[$path] = $resolver; + + return null; } /** - * @param \Closure $originalResolver - * @param string $path - * @return mixed + * @return mixed The data at the path */ - public function findOrResolve(Closure $originalResolver, string $path) + protected function getData(string $path) { - if (! $this->hasData($path)) { - if (isset($this->deferred[$path])) { - unset($this->deferred[$path]); - } - - return $this->resolve($originalResolver, $path); - } - return Arr::get($this->result, "data.{$path}"); } /** - * Resolve field with data or resolver. - * - * @param \Closure $originalResolver - * @param string $path - * @return mixed + * @param \Closure(): mixed $resolver + * @return mixed The loaded data */ - public function resolve(Closure $originalResolver, string $path) + protected function resolve(Closure $resolver, string $path) { - $isDeferred = $this->isDeferred($path); - $resolver = $isDeferred - ? $this->deferred[$path] - : $originalResolver; - - if ($isDeferred) { - $this->resolved[] = $path; - - unset($this->deferred[$path]); - } + unset($this->deferred[$path]); + $this->resolved [] = $path; return $resolver(); } /** - * @param string $path - * @return bool + * @param \Closure(): mixed $originalResolver + * @return mixed The loaded data */ - public function isDeferred(string $path): bool + public function findOrResolve(Closure $originalResolver, string $path) { - return isset($this->deferred[$path]); + if ($this->hasData($path)) { + return $this->getData($path); + } + + return $originalResolver(); } - /** - * @param string $path - * @return bool - */ - public function hasData(string $path): bool + protected function hasData(string $path): bool { return Arr::has($this->result, "data.{$path}"); } @@ -187,30 +159,26 @@ directive @defer(if: Boolean = true) on FIELD /** * Return either a final response or a stream of responses. * - * @param mixed[] $result + * @param array $result * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\StreamedResponse */ public function createResponse(array $result): Response { - if (empty($this->deferred)) { + if (! $this->hasRemainingDeferred()) { return response($result); } + $this->result = $result; + $this->isStreaming = true; + return response()->stream( - function () use ($result): void { + function (): void { + $this->stream(); + $nested = 1; - $this->result = $result; - $this->isStreaming = true; - $this->stream->stream($result, [], empty($this->deferred)); - - if ($executionTime = config('lighthouse.defer.max_execution_ms', 0)) { - $this->maxExecutionTime = microtime(true) + ($executionTime * 1000); - } - - // TODO: Allow nested_levels to be set in config to break out of loop early. while ( - count($this->deferred) - && ! $this->executionTimeExpired() + $this->hasRemainingDeferred() + && ! $this->maxExecutionTimeReached() && ! $this->maxNestedFieldsResolved($nested) ) { $nested++; @@ -218,48 +186,40 @@ directive @defer(if: Boolean = true) on FIELD } // We've hit the max execution time or max nested levels of deferred fields. + $this->shouldDeferFurther = false; + // We process remaining deferred fields, but are no longer allowing additional // fields to be deferred. - if (count($this->deferred)) { - $this->acceptFurtherDeferring = false; + if ($this->hasRemainingDeferred()) { $this->executeDeferred(); } }, 200, [ - // TODO: Allow headers to be set in config 'X-Accel-Buffering' => 'no', 'Content-Type' => 'multipart/mixed; boundary="-"', ] ); } - /** - * @param int $time - * @return void - */ - public function setMaxExecutionTime(int $time): void + protected function hasRemainingDeferred(): bool { - $this->maxExecutionTime = $time; + return count($this->deferred) > 0; + } + + protected function stream(): void + { + $this->stream->stream( + $this->result, + $this->resolved, + ! $this->hasRemainingDeferred() + ); } /** - * Override max nested fields. - * - * @param int $max - * @return void + * Check if we reached the maximum execution time. */ - public function setMaxNestedFields(int $max): void - { - $this->maxNestedFields = $max; - } - - /** - * Check if the maximum execution time has expired. - * - * @return bool - */ - protected function executionTimeExpired(): bool + protected function maxExecutionTimeReached(): bool { if ($this->maxExecutionTime === 0) { return false; @@ -270,9 +230,6 @@ directive @defer(if: Boolean = true) on FIELD /** * Check if the maximum number of nested field has been resolved. - * - * @param int $nested - * @return bool */ protected function maxNestedFieldsResolved(int $nested): bool { @@ -280,26 +237,32 @@ directive @defer(if: Boolean = true) on FIELD return false; } - return $nested >= $this->maxNestedFields; + return $this->maxNestedFields <= $nested; } - /** - * Execute deferred fields. - * - * @return void - */ protected function executeDeferred(): void { - $this->result = app()->call( - [$this->graphQL, 'executeRequest'] + $executionResult = $this->graphQL->executeQuery( + $this->startExecution->query, + $this->startExecution->context, + $this->startExecution->variables, + null, + $this->startExecution->operationName ); - $this->stream->stream( - $this->result, - $this->resolved, - empty($this->deferred) - ); + $this->result = $this->graphQL->serializable($executionResult); + $this->stream(); $this->resolved = []; } + + public function setMaxExecutionTime(float $time): void + { + $this->maxExecutionTime = $time; + } + + public function setMaxNestedFields(int $max): void + { + $this->maxNestedFields = $max; + } } diff --git a/vendor/nuwave/lighthouse/src/Defer/DeferServiceProvider.php b/vendor/nuwave/lighthouse/src/Defer/DeferServiceProvider.php index 3720680..5d483b1 100644 --- a/vendor/nuwave/lighthouse/src/Defer/DeferServiceProvider.php +++ b/vendor/nuwave/lighthouse/src/Defer/DeferServiceProvider.php @@ -2,43 +2,65 @@ namespace Nuwave\Lighthouse\Defer; -use Illuminate\Support\ServiceProvider; +use GraphQL\Language\Parser; use Illuminate\Contracts\Events\Dispatcher; +use Illuminate\Support\ServiceProvider; use Nuwave\Lighthouse\Events\ManipulateAST; -use Nuwave\Lighthouse\Schema\Factories\DirectiveFactory; +use Nuwave\Lighthouse\Events\RegisterDirectiveNamespaces; +use Nuwave\Lighthouse\Events\StartExecution; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; class DeferServiceProvider extends ServiceProvider { - /** - * Bootstrap any application services. - * - * @param \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory $directiveFactory - * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher - * @return void - */ - public function boot(DirectiveFactory $directiveFactory, Dispatcher $dispatcher): void + public function register(): void { - $directiveFactory->addResolved( - DeferrableDirective::NAME, - DeferrableDirective::class + $this->app->singleton(Defer::class); + $this->app->singleton(CreatesResponse::class, Defer::class); + } + + public function boot(Dispatcher $dispatcher): void + { + $dispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } ); $dispatcher->listen( ManipulateAST::class, - Defer::class.'@handleManipulateAST' + function (ManipulateAST $manipulateAST): void { + $this->handleManipulateAST($manipulateAST); + } + ); + + $dispatcher->listen( + StartExecution::class, + Defer::class.'@handleStartExecution' ); } /** - * Register any application services. - * - * @return void + * Set the tracing directive on all fields of the query to enable tracing them. */ - public function register(): void + public function handleManipulateAST(ManipulateAST $manipulateAST): void { - $this->app->singleton(Defer::class); + ASTHelper::attachDirectiveToObjectTypeFields( + $manipulateAST->documentAST, + Parser::constDirective(/** @lang GraphQL */ '@deferrable') + ); - $this->app->singleton(CreatesResponse::class, Defer::class); + $manipulateAST->documentAST->setDirectiveDefinition( + Parser::directiveDefinition(/** @lang GraphQL */ ' +""" +Use this directive on expensive or slow fields to resolve them asynchronously. +Must not be placed upon: +- Non-Nullable fields +- Mutation root fields +""" +directive @defer(if: Boolean = true) on FIELD +') + ); } } diff --git a/vendor/nuwave/lighthouse/src/Defer/DeferrableDirective.php b/vendor/nuwave/lighthouse/src/Defer/DeferrableDirective.php index 744618b..d412ec9 100644 --- a/vendor/nuwave/lighthouse/src/Defer/DeferrableDirective.php +++ b/vendor/nuwave/lighthouse/src/Defer/DeferrableDirective.php @@ -4,31 +4,32 @@ namespace Nuwave\Lighthouse\Defer; use Closure; use GraphQL\Error\Error; -use GraphQL\Language\AST\TypeNode; -use GraphQL\Type\Definition\ResolveInfo; use GraphQL\Language\AST\NonNullTypeNode; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; -use Nuwave\Lighthouse\Schema\Values\FieldValue; +use GraphQL\Language\AST\TypeNode; +use GraphQL\Type\Definition\Directive; +use GraphQL\Type\Definition\ResolveInfo; +use Nuwave\Lighthouse\ClientDirectives\ClientDirective; use Nuwave\Lighthouse\Schema\Directives\BaseDirective; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Schema\RootType; +use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -class DeferrableDirective extends BaseDirective implements DefinedDirective, FieldMiddleware +class DeferrableDirective extends BaseDirective implements FieldMiddleware { - const NAME = 'deferrable'; - const THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_ROOT_MUTATION_FIELD = 'The @defer directive cannot be used on a root mutation field.'; - const THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_NON_NULLABLE_FIELD = 'The @defer directive cannot be used on a Non-Nullable field.'; + public const THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_ROOT_MUTATION_FIELD = 'The @defer directive cannot be used on a root mutation field.'; + public const THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_NON_NULLABLE_FIELD = 'The @defer directive cannot be used on a Non-Nullable field.'; + public const DEFER_DIRECTIVE_NAME = 'defer'; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Do not use this directive directly, it is automatically added to the schema when using the defer extension. """ directive @deferrable on FIELD_DEFINITION -SDL; +GRAPHQL; } /** @@ -36,32 +37,11 @@ SDL; */ protected $defer; - /** - * @param \Nuwave\Lighthouse\Defer\Defer $defer - * @return void - */ public function __construct(Defer $defer) { $this->defer = $defer; } - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return self::NAME; - } - - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { $previousResolver = $fieldValue->getResolver(); @@ -78,9 +58,7 @@ SDL; return $this->defer->defer($wrappedResolver, $path); } - return $this->defer->isStreaming() - ? $this->defer->findOrResolve($wrappedResolver, $path) - : $previousResolver($root, $args, $context, $resolveInfo); + return $this->defer->findOrResolve($wrappedResolver, $path); } ); @@ -90,49 +68,56 @@ SDL; /** * Determine if field should be deferred. * - * @param \GraphQL\Language\AST\TypeNode $fieldType - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return bool - * * @throws \GraphQL\Error\Error */ protected function shouldDefer(TypeNode $fieldType, ResolveInfo $resolveInfo): bool { - foreach ($resolveInfo->fieldNodes as $fieldNode) { - $deferDirective = ASTHelper::directiveDefinition($fieldNode, 'defer'); - if (! $deferDirective) { - return false; - } + $defers = (new ClientDirective(self::DEFER_DIRECTIVE_NAME))->forField($resolveInfo); - if ($resolveInfo->parentType->name === 'Mutation') { + if ($this->anyFieldHasDefer($defers)) { + if ($resolveInfo->parentType->name === RootType::MUTATION) { throw new Error(self::THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_ROOT_MUTATION_FIELD); } - - if (! ASTHelper::directiveArgValue($deferDirective, 'if', true)) { - return false; + if ($fieldType instanceof NonNullTypeNode) { + throw new Error(self::THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_NON_NULLABLE_FIELD); } + } - $skipDirective = ASTHelper::directiveDefinition($fieldNode, 'skip'); - if ( - $skipDirective - && ASTHelper::directiveArgValue($skipDirective, 'if') === true - ) { - return false; - } - - $includeDirective = ASTHelper::directiveDefinition($fieldNode, 'include'); - if ( - $includeDirective - && ASTHelper::directiveArgValue($includeDirective, 'if') === false - ) { + // Following the semantics of Apollo: + // All declarations of a field have to contain @defer for the field to be deferred + foreach ($defers as $defer) { + if ($defer === null || $defer === [Directive::IF_ARGUMENT_NAME => false]) { return false; } } - if ($fieldType instanceof NonNullTypeNode) { - throw new Error(self::THE_DEFER_DIRECTIVE_CANNOT_BE_USED_ON_A_NON_NULLABLE_FIELD); + $skips = (new ClientDirective(Directive::SKIP_NAME))->forField($resolveInfo); + foreach ($skips as $skip) { + if ($skip === [Directive::IF_ARGUMENT_NAME => true]) { + return false; + } } - return true; + $includes = (new ClientDirective(Directive::INCLUDE_NAME))->forField($resolveInfo); + + return ! in_array( + [Directive::IF_ARGUMENT_NAME => false], + $includes, + true + ); + } + + /** + * @param array|null> $defers + */ + protected function anyFieldHasDefer(array $defers): bool + { + foreach ($defers as $defer) { + if ($defer !== null) { + return true; + } + } + + return false; } } diff --git a/vendor/nuwave/lighthouse/src/Events/BuildExtensionsResponse.php b/vendor/nuwave/lighthouse/src/Events/BuildExtensionsResponse.php index cc74002..a353ed2 100644 --- a/vendor/nuwave/lighthouse/src/Events/BuildExtensionsResponse.php +++ b/vendor/nuwave/lighthouse/src/Events/BuildExtensionsResponse.php @@ -5,9 +5,8 @@ namespace Nuwave\Lighthouse\Events; /** * Fires after a query was resolved. * - * Listeners of this event may return an instance of - * @see \Nuwave\Lighthouse\Execution\ExtensionsResponse - * that is then added to the response. + * Listeners may return a @see \Nuwave\Lighthouse\Execution\ExtensionsResponse + * to include in the response. */ class BuildExtensionsResponse { diff --git a/vendor/nuwave/lighthouse/src/Events/BuildSchemaString.php b/vendor/nuwave/lighthouse/src/Events/BuildSchemaString.php index 019cf0a..e38c4e0 100644 --- a/vendor/nuwave/lighthouse/src/Events/BuildSchemaString.php +++ b/vendor/nuwave/lighthouse/src/Events/BuildSchemaString.php @@ -19,12 +19,6 @@ class BuildSchemaString */ public $userSchema; - /** - * BuildSchemaString constructor. - * - * @param string $userSchema - * @return void - */ public function __construct(string $userSchema) { $this->userSchema = $userSchema; diff --git a/vendor/nuwave/lighthouse/src/Events/EndExecution.php b/vendor/nuwave/lighthouse/src/Events/EndExecution.php new file mode 100644 index 0000000..666935b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Events/EndExecution.php @@ -0,0 +1,32 @@ +result = $result; + $this->moment = Carbon::now(); + } +} diff --git a/vendor/nuwave/lighthouse/src/Events/EndOperationOrOperations.php b/vendor/nuwave/lighthouse/src/Events/EndOperationOrOperations.php new file mode 100644 index 0000000..27380cc --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Events/EndOperationOrOperations.php @@ -0,0 +1,24 @@ +|array> + */ + public $resultOrResults; + + /** + * @param array|array> $resultOrResults + */ + public function __construct(array $resultOrResults) + { + $this->resultOrResults = $resultOrResults; + } +} diff --git a/vendor/nuwave/lighthouse/src/Events/EndRequest.php b/vendor/nuwave/lighthouse/src/Events/EndRequest.php new file mode 100644 index 0000000..7291f1a --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Events/EndRequest.php @@ -0,0 +1,37 @@ +response = $response; + $this->moment = Carbon::now(); + } +} diff --git a/vendor/nuwave/lighthouse/src/Events/ManipulateAST.php b/vendor/nuwave/lighthouse/src/Events/ManipulateAST.php index 85e200a..52136d3 100644 --- a/vendor/nuwave/lighthouse/src/Events/ManipulateAST.php +++ b/vendor/nuwave/lighthouse/src/Events/ManipulateAST.php @@ -21,12 +21,6 @@ class ManipulateAST */ public $documentAST; - /** - * BuildSchemaString constructor. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @return void - */ public function __construct(DocumentAST &$documentAST) { $this->documentAST = $documentAST; diff --git a/vendor/nuwave/lighthouse/src/Events/ManipulateResult.php b/vendor/nuwave/lighthouse/src/Events/ManipulateResult.php index 8b7d8fd..6fe46dc 100644 --- a/vendor/nuwave/lighthouse/src/Events/ManipulateResult.php +++ b/vendor/nuwave/lighthouse/src/Events/ManipulateResult.php @@ -19,12 +19,6 @@ class ManipulateResult */ public $result; - /** - * ManipulateResult constructor. - * - * @param \GraphQL\Executor\ExecutionResult $result - * @return void - */ public function __construct(ExecutionResult &$result) { $this->result = $result; diff --git a/vendor/nuwave/lighthouse/src/Events/RegisterDirectiveNamespaces.php b/vendor/nuwave/lighthouse/src/Events/RegisterDirectiveNamespaces.php index 2b341ac..2252067 100644 --- a/vendor/nuwave/lighthouse/src/Events/RegisterDirectiveNamespaces.php +++ b/vendor/nuwave/lighthouse/src/Events/RegisterDirectiveNamespaces.php @@ -8,7 +8,7 @@ namespace Nuwave\Lighthouse\Events; * Listeners may return one or more strings that are used as the base * namespace for locating directives. * - * @see \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory + * @see \Nuwave\Lighthouse\Schema\DirectiveLocator::namespaces() */ class RegisterDirectiveNamespaces { diff --git a/vendor/nuwave/lighthouse/src/Events/StartExecution.php b/vendor/nuwave/lighthouse/src/Events/StartExecution.php index eea796d..30bf7f1 100644 --- a/vendor/nuwave/lighthouse/src/Events/StartExecution.php +++ b/vendor/nuwave/lighthouse/src/Events/StartExecution.php @@ -2,30 +2,61 @@ namespace Nuwave\Lighthouse\Events; -use Carbon\Carbon; +use GraphQL\Language\AST\DocumentNode; +use Illuminate\Support\Carbon; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; /** - * Fires right before resolving an individual query. + * Fires right before resolving a single operation. * - * Might happen multiple times in a single request if - * query batching is used. + * Might happen multiple times in a single request if batching is used. */ class StartExecution { + /** + * The client given parsed query string. + * + * @var \GraphQL\Language\AST\DocumentNode + */ + public $query; + + /** + * The client given variables, neither validated nor transformed. + * + * @var array|null + */ + public $variables; + + /** + * The client given operation name. + * + * @var string|null + */ + public $operationName; + + /** + * The context for the operation. + * + * @var \Nuwave\Lighthouse\Support\Contracts\GraphQLContext + */ + public $context; + /** * The point in time when the query execution started. * - * @var \Carbon\Carbon + * @var \Illuminate\Support\Carbon */ public $moment; /** - * StartRequest constructor. - * - * @return void + * @param array|null $variables */ - public function __construct() + public function __construct(DocumentNode $query, ?array $variables, ?string $operationName, GraphQLContext $context) { + $this->query = $query; + $this->variables = $variables; + $this->operationName = $operationName; + $this->context = $context; $this->moment = Carbon::now(); } } diff --git a/vendor/nuwave/lighthouse/src/Events/StartOperationOrOperations.php b/vendor/nuwave/lighthouse/src/Events/StartOperationOrOperations.php new file mode 100644 index 0000000..2ffe470 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Events/StartOperationOrOperations.php @@ -0,0 +1,24 @@ + + */ + public $operationOrOperations; + + /** + * @param \GraphQL\Server\OperationParams|array $operationOrOperations + */ + public function __construct($operationOrOperations) + { + $this->operationOrOperations = $operationOrOperations; + } +} diff --git a/vendor/nuwave/lighthouse/src/Events/StartRequest.php b/vendor/nuwave/lighthouse/src/Events/StartRequest.php index b79ef58..a4f8224 100644 --- a/vendor/nuwave/lighthouse/src/Events/StartRequest.php +++ b/vendor/nuwave/lighthouse/src/Events/StartRequest.php @@ -2,8 +2,8 @@ namespace Nuwave\Lighthouse\Events; -use Carbon\Carbon; -use Nuwave\Lighthouse\Execution\GraphQLRequest; +use Illuminate\Http\Request; +use Illuminate\Support\Carbon; /** * Fires right after a request reaches the GraphQLController. @@ -16,26 +16,20 @@ use Nuwave\Lighthouse\Execution\GraphQLRequest; class StartRequest { /** - * GraphQL request instance. + * The request sent from the client. * - * @var \Nuwave\Lighthouse\Execution\GraphQLRequest + * @var \Illuminate\Http\Request */ public $request; /** * The point in time when the request started. * - * @var \Carbon\Carbon + * @var \Illuminate\Support\Carbon */ public $moment; - /** - * StartRequest constructor. - * - * @param \Nuwave\Lighthouse\Execution\GraphQLRequest $request - * @return void - */ - public function __construct(GraphQLRequest $request) + public function __construct(Request $request) { $this->request = $request; $this->moment = Carbon::now(); diff --git a/vendor/nuwave/lighthouse/src/Events/ValidateSchema.php b/vendor/nuwave/lighthouse/src/Events/ValidateSchema.php new file mode 100644 index 0000000..7029691 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Events/ValidateSchema.php @@ -0,0 +1,25 @@ +schema = $schema; + } +} diff --git a/vendor/nuwave/lighthouse/src/Exceptions/AuthenticationException.php b/vendor/nuwave/lighthouse/src/Exceptions/AuthenticationException.php index 0bdb645..10218ae 100644 --- a/vendor/nuwave/lighthouse/src/Exceptions/AuthenticationException.php +++ b/vendor/nuwave/lighthouse/src/Exceptions/AuthenticationException.php @@ -6,35 +6,21 @@ use Illuminate\Auth\AuthenticationException as IlluminateAuthenticationException class AuthenticationException extends IlluminateAuthenticationException implements RendersErrorsExtensions { - /** - * Returns true when exception message is safe to be displayed to a client. - * - * @api - * @return bool - */ + public const MESSAGE = 'Unauthenticated.'; + public const CATEGORY = 'authentication'; + public function isClientSafe(): bool { return true; } - /** - * Returns string describing a category of the error. - * - * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it. - * - * @api - * @return string - */ public function getCategory(): string { - return 'authentication'; + return self::CATEGORY; } /** - * Return the content that is put in the "extensions" part - * of the returned error. - * - * @return array + * @return array> */ public function extensionsContent(): array { diff --git a/vendor/nuwave/lighthouse/src/Exceptions/AuthorizationException.php b/vendor/nuwave/lighthouse/src/Exceptions/AuthorizationException.php index 49cfeb2..285870f 100644 --- a/vendor/nuwave/lighthouse/src/Exceptions/AuthorizationException.php +++ b/vendor/nuwave/lighthouse/src/Exceptions/AuthorizationException.php @@ -7,30 +7,13 @@ use Illuminate\Auth\Access\AuthorizationException as IlluminateAuthorizationExce class AuthorizationException extends IlluminateAuthorizationException implements ClientAware { - /** - * @var string - */ - const CATEGORY = 'authorization'; + public const CATEGORY = 'authorization'; - /** - * Returns true when exception message is safe to be displayed to a client. - * - * @api - * @return bool - */ public function isClientSafe(): bool { return true; } - /** - * Returns string describing a category of the error. - * - * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it. - * - * @api - * @return string - */ public function getCategory(): string { return self::CATEGORY; diff --git a/vendor/nuwave/lighthouse/src/Exceptions/DefinitionException.php b/vendor/nuwave/lighthouse/src/Exceptions/DefinitionException.php index fee7dfb..5cff4d8 100644 --- a/vendor/nuwave/lighthouse/src/Exceptions/DefinitionException.php +++ b/vendor/nuwave/lighthouse/src/Exceptions/DefinitionException.php @@ -5,27 +5,18 @@ namespace Nuwave\Lighthouse\Exceptions; use Exception; use GraphQL\Error\ClientAware; +/** + * Thrown when the schema definition or related code is wrong. + * + * This signals a developer error, so we do not show this exception to the user. + */ class DefinitionException extends Exception implements ClientAware { - /** - * Returns true when exception message is safe to be displayed to a client. - * - * @api - * @return bool - */ public function isClientSafe(): bool { return false; } - /** - * Returns string describing a category of the error. - * - * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it. - * - * @api - * @return string - */ public function getCategory(): string { return 'schema'; diff --git a/vendor/nuwave/lighthouse/src/Exceptions/DirectiveException.php b/vendor/nuwave/lighthouse/src/Exceptions/DirectiveException.php index 20b9325..c7dcb90 100644 --- a/vendor/nuwave/lighthouse/src/Exceptions/DirectiveException.php +++ b/vendor/nuwave/lighthouse/src/Exceptions/DirectiveException.php @@ -7,25 +7,11 @@ use GraphQL\Error\ClientAware; class DirectiveException extends Exception implements ClientAware { - /** - * Returns true when exception message is safe to be displayed to a client. - * - * @api - * @return bool - */ public function isClientSafe(): bool { return false; } - /** - * Returns string describing a category of the error. - * - * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it. - * - * @api - * @return string - */ public function getCategory(): string { return 'schema'; diff --git a/vendor/nuwave/lighthouse/src/Exceptions/FederationException.php b/vendor/nuwave/lighthouse/src/Exceptions/FederationException.php new file mode 100644 index 0000000..de28c21 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Exceptions/FederationException.php @@ -0,0 +1,10 @@ + $extensions * @return $this */ - public function setExtensions($extensions): self + public function setExtensions(array $extensions): self { - $this->extensions = (array) $extensions; + $this->extensions = $extensions; return $this; } /** - * Set the category that will be rendered under the "extensions" key of the error response. - * - * @param string $category * @return $this */ public function setCategory(string $category): self diff --git a/vendor/nuwave/lighthouse/src/Exceptions/ParseException.php b/vendor/nuwave/lighthouse/src/Exceptions/ParseException.php index a4602f2..4be8752 100644 --- a/vendor/nuwave/lighthouse/src/Exceptions/ParseException.php +++ b/vendor/nuwave/lighthouse/src/Exceptions/ParseException.php @@ -4,28 +4,31 @@ namespace Nuwave\Lighthouse\Exceptions; use Exception; use GraphQL\Error\ClientAware; +use GraphQL\Error\SyntaxError; +use GraphQL\Language\Source; class ParseException extends Exception implements ClientAware { - /** - * Returns true when exception message is safe to be displayed to a client. - * - * @api - * @return bool - */ + public function __construct(SyntaxError $error) + { + $message = $error->getMessage(); + + $source = $error->getSource(); + $positions = $error->getPositions(); + if ($source instanceof Source && count($positions) > 0) { + $position = $positions[0]; + + $message .= ', near: '.\Safe\substr($source->body, max(0, $position - 50), 100); + } + + parent::__construct($message); + } + public function isClientSafe(): bool { return false; } - /** - * Returns string describing a category of the error. - * - * Value "graphql" is reserved for errors produced by query parsing or validation, do not use it. - * - * @api - * @return string - */ public function getCategory(): string { return 'schema'; diff --git a/vendor/nuwave/lighthouse/src/Exceptions/RateLimitException.php b/vendor/nuwave/lighthouse/src/Exceptions/RateLimitException.php new file mode 100644 index 0000000..2fade1b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Exceptions/RateLimitException.php @@ -0,0 +1,30 @@ + */ public function extensionsContent(): array; } diff --git a/vendor/nuwave/lighthouse/src/Exceptions/SubscriptionException.php b/vendor/nuwave/lighthouse/src/Exceptions/SubscriptionException.php deleted file mode 100644 index 6a9707f..0000000 --- a/vendor/nuwave/lighthouse/src/Exceptions/SubscriptionException.php +++ /dev/null @@ -1,35 +0,0 @@ -validator = $validator; + } + + public static function fromLaravel(LaravelValidationException $laravelException): self + { + return new static( + $laravelException->getMessage(), + $laravelException->validator + ); + } + + /** + * Instantiate from a plain array of messages. + * + * @see \Illuminate\Validation\ValidationException::withMessages() + * + * @param array> $messages + */ + public static function withMessages(array $messages): self + { + return static::fromLaravel( + LaravelValidationException::withMessages($messages) + ); + } + + public function isClientSafe(): bool { return true; } - /** - * Returns string describing a category of the error. - * - * @return string - */ - public function getCategory() + public function getCategory(): string { - return 'validation'; + return self::CATEGORY; } - /** - * Return the content that is put in the "extensions" part - * of the returned error. - * - * @return array - */ public function extensionsContent(): array { - return ['validation' => $this->errors()]; + return [ + self::CATEGORY => $this->validator->errors()->messages(), + ]; } } diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgPartitioner.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgPartitioner.php new file mode 100644 index 0000000..07e8929 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgPartitioner.php @@ -0,0 +1,209 @@ + + */ + public static function nestedArgResolvers(ArgumentSet $argumentSet, $root): array + { + $model = $root instanceof Model + ? new \ReflectionClass($root) + : null; + + foreach ($argumentSet->arguments as $name => $argument) { + static::attachNestedArgResolver($name, $argument, $model); + } + + return static::partition( + $argumentSet, + static function (string $name, Argument $argument): bool { + return $argument->resolver !== null; + } + ); + } + + /** + * Extract all the arguments that correspond to a relation of a certain type on the model. + * + * For example, if the args input looks like this: + * + * [ + * 'name' => 'Ralf', + * 'comments' => + * ['foo' => 'Bar'], + * ] + * + * and the model has a method "comments" that returns a HasMany relationship, + * the result will be: + * [ + * [ + * 'comments' => + * ['foo' => 'Bar'], + * ], + * [ + * 'name' => 'Ralf', + * ] + * ] + * + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $argumentSet + * @return array{0: \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet, 1: \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet} + */ + public static function relationMethods( + ArgumentSet $argumentSet, + Model $model, + string $relationClass + ): array { + $modelReflection = new ReflectionClass($model); + + [$relations, $remaining] = static::partition( + $argumentSet, + static function (string $name) use ($modelReflection, $relationClass): bool { + return static::methodReturnsRelation($modelReflection, $name, $relationClass); + } + ); + + $nonNullRelations = new ArgumentSet(); + $nonNullRelations->arguments = array_filter( + $relations->arguments, + static function (Argument $argument): bool { + return null !== $argument->value; + } + ); + + return [$nonNullRelations, $remaining]; + } + + /** + * Attach a nested argument resolver to an argument. + * + * @param \Nuwave\Lighthouse\Execution\Arguments\Argument $argument + */ + protected static function attachNestedArgResolver(string $name, Argument &$argument, ?ReflectionClass $model): void + { + $resolverDirective = $argument->directives->first( + Utils::instanceofMatcher(ArgResolver::class) + ); + + if ($resolverDirective) { + $argument->resolver = $resolverDirective; + + return; + } + + if (isset($model)) { + $isRelation = static function (string $relationClass) use ($model, $name): bool { + return static::methodReturnsRelation($model, $name, $relationClass); + }; + + if ( + $isRelation(HasOne::class) + || $isRelation(MorphOne::class) + ) { + $argument->resolver = new ResolveNested(new NestedOneToOne($name)); + + return; + } + + if ( + $isRelation(HasMany::class) + || $isRelation(MorphMany::class) + ) { + $argument->resolver = new ResolveNested(new NestedOneToMany($name)); + + return; + } + + if ( + $isRelation(BelongsToMany::class) + || $isRelation(MorphToMany::class) + ) { + $argument->resolver = new ResolveNested(new NestedManyToMany($name)); + + return; + } + } + } + + /** + * Partition arguments based on a predicate. + * + * The predicate will be called for each argument within the ArgumentSet + * with the following parameters: + * 1. The name of the argument + * 2. The argument itself + * + * Returns an array of two new ArgumentSet instances: + * - the first one contains all arguments for which the predicate matched + * - the second one contains all arguments for which the predicate did not match + * + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $argumentSet + * @return array{0: \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet, 1: \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet} + */ + public static function partition(ArgumentSet $argumentSet, \Closure $predicate): array + { + $matched = new ArgumentSet(); + $notMatched = new ArgumentSet(); + + foreach ($argumentSet->arguments as $name => $argument) { + if ($predicate($name, $argument)) { + $matched->arguments[$name] = $argument; + } else { + $notMatched->arguments[$name] = $argument; + } + } + + return [ + $matched, + $notMatched, + ]; + } + + /** + * Does a method on the model return a relation of the given class? + */ + public static function methodReturnsRelation( + ReflectionClass $modelReflection, + string $name, + string $relationClass + ): bool { + if (! $modelReflection->hasMethod($name)) { + return false; + } + + $relationMethodCandidate = $modelReflection->getMethod($name); + + $returnType = $relationMethodCandidate->getReturnType(); + if ($returnType === null) { + return false; + } + + if (! $returnType instanceof ReflectionNamedType) { + return false; + } + + if (! class_exists($returnType->getName())) { + throw new DefinitionException('Class '.$returnType->getName().' does not exist, did you forget to import the Eloquent relation class?'); + } + + return is_a($returnType->getName(), $relationClass, true); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/Argument.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/Argument.php new file mode 100644 index 0000000..4251616 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/Argument.php @@ -0,0 +1,70 @@ +|mixed|array + */ + public $value; + + /** + * The type of the argument. + * + * @var \Nuwave\Lighthouse\Execution\Arguments\ListType|\Nuwave\Lighthouse\Execution\Arguments\NamedType|null + */ + public $type; + + /** + * A list of directives associated with that argument. + * + * @var \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> + */ + public $directives; + + /** + * An argument may have a resolver that handles it's given value. + * + * @var \Nuwave\Lighthouse\Support\Contracts\ArgResolver|null + */ + public $resolver; + + public function __construct() + { + $this->directives = new Collection(); + } + + /** + * Get the plain PHP value of this argument. + * + * @return mixed The plain PHP value. + */ + public function toPlain() + { + return static::toPlainRecursive($this->value); + } + + /** + * Convert the given value to plain PHP values recursively. + * + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet>|mixed|array $value + * @return mixed|array + */ + protected static function toPlainRecursive($value) + { + if ($value instanceof ArgumentSet) { + return $value->toArray(); + } + + if (is_array($value)) { + return array_map([static::class, 'toPlainRecursive'], $value); + } + + return $value; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSet.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSet.php new file mode 100644 index 0000000..760a2be --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSet.php @@ -0,0 +1,275 @@ + + */ + public $arguments = []; + + /** + * An associative array of arguments that were not given. + * + * @var array + */ + public $undefined = []; + + /** + * A list of directives. + * + * This may be coming from + * - the field the arguments are a part of + * - the parent argument when in a tree of nested inputs. + * + * @var \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> + */ + public $directives; + + /** + * Get a plain array representation of this ArgumentSet. + * + * @return array + */ + public function toArray(): array + { + $plainArguments = []; + + foreach ($this->arguments as $name => $argument) { + $plainArguments[$name] = $argument->toPlain(); + } + + return $plainArguments; + } + + /** + * Check if the ArgumentSet has a non-null value with the given key. + */ + public function has(string $key): bool + { + $argument = $this->arguments[$key] ?? null; + + if ($argument === null) { + return false; + } + + return $argument->value !== null; + } + + /** + * Apply the @spread directive and return a new, modified instance. + * + * @noRector \Rector\DeadCode\Rector\ClassMethod\RemoveDeadRecursiveClassMethodRector + */ + public function spread(): self + { + $argumentSet = new self(); + $argumentSet->directives = $this->directives; + + foreach ($this->arguments as $name => $argument) { + $value = $argument->value; + + // In this case, we do not care about argument sets nested within + // lists, spreading only makes sense for single nested inputs. + if ($value instanceof self) { + // Recurse down first, as that resolves the more deeply nested spreads first + $value = $value->spread(); + + if ($argument->directives->contains( + Utils::instanceofMatcher(SpreadDirective::class) + )) { + $argumentSet->arguments += $value->arguments; + continue; + } + } + + $argumentSet->arguments[$name] = $argument; + } + + return $argumentSet; + } + + /** + * Apply the @rename directive and return a new, modified instance. + * + * @noRector \Rector\DeadCode\Rector\ClassMethod\RemoveDeadRecursiveClassMethodRector + */ + public function rename(): self + { + $argumentSet = new self(); + $argumentSet->directives = $this->directives; + + foreach ($this->arguments as $name => $argument) { + // Recursively apply the renaming to nested inputs. + // We look for further ArgumentSet instances, they + // might be contained within an array. + $argument->value = Utils::applyEach( + function ($value) { + if ($value instanceof self) { + return $value->rename(); + } + + return $value; + }, + $argument->value + ); + + /** @var \Nuwave\Lighthouse\Schema\Directives\RenameDirective|null $renameDirective */ + $renameDirective = $argument->directives->first(function ($directive) { + return $directive instanceof RenameDirective; + }); + + if ($renameDirective !== null) { + $argumentSet->arguments[$renameDirective->attributeArgValue()] = $argument; + } else { + $argumentSet->arguments[$name] = $argument; + } + } + + return $argumentSet; + } + + /** + * Apply ArgBuilderDirectives and scopes to the builder. + * + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder + * @param array $scopes + * @param \Closure $directiveFilter + * + * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Laravel\Scout\Builder + */ + public function enhanceBuilder(object $builder, array $scopes, Closure $directiveFilter = null): object + { + $scoutEnhancer = new ScoutEnhancer($this, $builder); + if ($scoutEnhancer->hasSearchArguments()) { + return $scoutEnhancer->enhanceBuilder(); + } + + self::applyArgBuilderDirectives($this, $builder, $directiveFilter); + self::applyFieldBuilderDirectives($this, $builder); + + foreach ($scopes as $scope) { + $builder->{$scope}($this->toArray()); + } + + return $builder; + } + + /** + * Recursively apply the ArgBuilderDirectives onto the builder. + * + * TODO get rid of the reference passing in here. The issue is that @search makes a new builder instance, + * but we must special case that in some way anyhow, as only eq filters can be added on top of search. + * + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $argumentSet + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder + * @param (\Closure(\Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective): bool)|null $directiveFilter + */ + protected static function applyArgBuilderDirectives(self $argumentSet, object &$builder, Closure $directiveFilter = null): void + { + foreach ($argumentSet->arguments as $argument) { + $value = $argument->toPlain(); + + // TODO switch to instanceof when we require bensampo/laravel-enum + // Unbox Enum values to ensure their underlying value is used for queries + if (is_a($value, '\BenSampo\Enum\Enum')) { + $value = $value->value; + } + + $filteredDirectives = $argument + ->directives + ->filter(Utils::instanceofMatcher(ArgBuilderDirective::class)); + + if (null !== $directiveFilter) { + $filteredDirectives = $filteredDirectives->filter($directiveFilter); + } + + $filteredDirectives->each(static function (ArgBuilderDirective $argBuilderDirective) use (&$builder, $value): void { + $builder = $argBuilderDirective->handleBuilder($builder, $value); + }); + + Utils::applyEach( + static function ($value) use (&$builder, $directiveFilter) { + if ($value instanceof self) { + self::applyArgBuilderDirectives($value, $builder, $directiveFilter); + } + }, + $argument->value + ); + } + } + + /** + * Apply the FieldBuilderDirectives onto the builder. + * + * TODO get rid of the reference passing in here. The issue is that @search makes a new builder instance, + * but we must special case that in some way anyhow, as only eq filters can be added on top of search. + * + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $argumentSet + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder + */ + protected static function applyFieldBuilderDirectives(self $argumentSet, object &$builder): void + { + $argumentSet->directives + ->filter(Utils::instanceofMatcher(FieldBuilderDirective::class)) + ->each(static function (FieldBuilderDirective $fieldBuilderDirective) use (&$builder): void { + $builder = $fieldBuilderDirective->handleFieldBuilder($builder); + }); + } + + /** + * Add a value at the dot-separated path. + * + * Works just like @see \Illuminate\Support\Arr::add(). + * + * @param mixed $value Any value to inject. + * @return $this + */ + public function addValue(string $path, $value): self + { + $argumentSet = $this; + $keys = explode('.', $path); + + while (count($keys) > 1) { + $key = array_shift($keys); + + // If the key doesn't exist at this depth, we will just create an empty ArgumentSet + // to hold the next value, allowing us to create the ArgumentSet to hold a final + // value at the correct depth. Then we'll keep digging into the ArgumentSet. + if (! isset($argumentSet->arguments[$key])) { + $argument = new Argument(); + $argument->value = new self(); + $argumentSet->arguments[$key] = $argument; + } + + $argumentSet = $argumentSet->arguments[$key]->value; + } + + $argument = new Argument(); + $argument->value = $value; + $argumentSet->arguments[array_shift($keys)] = $argument; + + return $this; + } + + /** + * The contained arguments, including all that were not passed. + * + * @return array + */ + public function argumentsWithUndefined(): array + { + return array_merge($this->arguments, $this->undefined); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSetFactory.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSetFactory.php new file mode 100644 index 0000000..3b7a59c --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentSetFactory.php @@ -0,0 +1,179 @@ +documentAST = $astBuilder->documentAST(); + $this->argumentTypeNodeConverter = $argumentTypeNodeConverter; + $this->directiveLocator = $directiveLocator; + } + + /** + * Wrap client-given args with type information. + * + * @param array $args + * @return \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet + */ + public function fromResolveInfo(array $args, ResolveInfo $resolveInfo): ArgumentSet + { + /** + * TODO handle programmatic types without an AST gracefully. + * + * @var \GraphQL\Language\AST\FieldDefinitionNode $definition + */ + $definition = $resolveInfo->fieldDefinition->astNode; + + return $this->wrapArgs($definition, $args); + } + + /** + * Wrap client-given args with type information. + * + * @param \GraphQL\Language\AST\FieldDefinitionNode|\GraphQL\Language\AST\InputObjectTypeDefinitionNode $definition + * @param array $args + * @return \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet + */ + public function wrapArgs(Node $definition, array $args): ArgumentSet + { + $argumentSet = new ArgumentSet(); + $argumentSet->directives = $this->directiveLocator->associated($definition); + + if ($definition instanceof FieldDefinitionNode) { + $argDefinitions = $definition->arguments; + } elseif ($definition instanceof InputObjectTypeDefinitionNode) { + $argDefinitions = $definition->fields; + } else { + throw new InvalidArgumentException('Got unexpected node of type '.get_class($definition)); + } + + $argumentDefinitionMap = $this->makeDefinitionMap($argDefinitions); + + foreach ($argumentDefinitionMap as $name => $definition) { + if (array_key_exists($name, $args)) { + $argumentSet->arguments[$name] = $this->wrapInArgument($args[$name], $definition); + } else { + $argumentSet->undefined[$name] = $this->wrapInArgument(null, $definition); + } + } + + return $argumentSet; + } + + /** + * Make a map with the name as keys. + * + * @param iterable<\GraphQL\Language\AST\InputValueDefinitionNode> $argumentDefinitions + * @return array + */ + protected function makeDefinitionMap($argumentDefinitions): array + { + $argumentDefinitionMap = []; + + foreach ($argumentDefinitions as $definition) { + $argumentDefinitionMap[$definition->name->value] = $definition; + } + + return $argumentDefinitionMap; + } + + /** + * Wrap a single client-given argument with type information. + * + * @param mixed $value The client given value. + * @return \Nuwave\Lighthouse\Execution\Arguments\Argument + */ + protected function wrapInArgument($value, InputValueDefinitionNode $definition): Argument + { + $type = $this->argumentTypeNodeConverter->convert($definition->type); + + $argument = new Argument(); + $argument->directives = $this->directiveLocator->associated($definition); + $argument->type = $type; + $argument->value = $this->wrapWithType($value, $type); + + return $argument; + } + + /** + * Wrap a client-given value with information from a type. + * + * @param mixed|array $valueOrValues + * @param \Nuwave\Lighthouse\Execution\Arguments\ListType|\Nuwave\Lighthouse\Execution\Arguments\NamedType $type + * @return array|mixed|\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet + */ + protected function wrapWithType($valueOrValues, $type) + { + // No need to recurse down further if the value is null + if ($valueOrValues === null) { + return null; + } + + // We have to do this conversion as we are resolving a client query + // because the incoming arguments put a bound on recursion depth + if ($type instanceof ListType) { + $typeInList = $type->type; + + $values = []; + foreach ($valueOrValues as $singleValue) { + $values [] = $this->wrapWithType($singleValue, $typeInList); + } + + return $values; + } + + return $this->wrapWithNamedType($valueOrValues, $type); + } + + /** + * Wrap a client-given value with information from a named type. + * + * @param mixed $value The client given value. + * @param \Nuwave\Lighthouse\Execution\Arguments\NamedType $namedType + * @return \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|mixed + */ + protected function wrapWithNamedType($value, NamedType $namedType) + { + // This might be null if the type is + // - created outside of the schema string + // - one of the built in types + $typeDef = $this->documentAST->types[$namedType->name] ?? null; + + // We recurse down only if the type is an Input + if ($typeDef instanceof InputObjectTypeDefinitionNode) { + return $this->wrapArgs($typeDef, $value); + } + + // Otherwise, we just return the value as is and are done with that subtree + return $value; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentTypeNodeConverter.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentTypeNodeConverter.php new file mode 100644 index 0000000..e0ef45c --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/ArgumentTypeNodeConverter.php @@ -0,0 +1,36 @@ +nonNull = true; + + return $type; + } + + /** + * @param \Nuwave\Lighthouse\Execution\Arguments\NamedType $type + * @return \Nuwave\Lighthouse\Execution\Arguments\ListType + */ + protected function listOf($type): object + { + return new ListType($type); + } + + /** + * @return \Nuwave\Lighthouse\Execution\Arguments\NamedType + */ + protected function namedType(string $nodeName): NamedType + { + return new NamedType($nodeName); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/ListType.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/ListType.php new file mode 100644 index 0000000..c41c4c6 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/ListType.php @@ -0,0 +1,28 @@ +type = $type; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/NamedType.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/NamedType.php new file mode 100644 index 0000000..cd6f157 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/NamedType.php @@ -0,0 +1,25 @@ +name = $name; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedBelongsTo.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedBelongsTo.php new file mode 100644 index 0000000..37a4ff7 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedBelongsTo.php @@ -0,0 +1,88 @@ +relation = $relation; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $parent + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($parent, $args): void + { + if ($args->has('create')) { + $saveModel = new ResolveNested(new SaveModel($this->relation)); + + $related = $saveModel( + // @phpstan-ignore-next-line Unrecognized mixin + $this->relation->make(), + $args->arguments['create']->value + ); + $this->relation->associate($related); + } + + if ($args->has('connect')) { + $this->relation->associate($args->arguments['connect']->value); + } + + if ($args->has('update')) { + $updateModel = new ResolveNested(new UpdateModel(new SaveModel($this->relation))); + + $related = $updateModel( + // @phpstan-ignore-next-line Unrecognized mixin + $this->relation->make(), + $args->arguments['update']->value + ); + $this->relation->associate($related); + } + + if ($args->has('upsert')) { + $upsertModel = new ResolveNested(new UpsertModel(new SaveModel($this->relation))); + + $related = $upsertModel( + // @phpstan-ignore-next-line Unrecognized mixin + $this->relation->make(), + $args->arguments['upsert']->value + ); + $this->relation->associate($related); + } + + self::disconnectOrDelete($this->relation, $args); + } + + public static function disconnectOrDelete(BelongsTo $relation, ArgumentSet $args): void + { + // We proceed with disconnecting/deleting only if the given $values is truthy. + // There is no other information to be passed when issuing those operations, + // but GraphQL forces us to pass some value. It would be unintuitive for + // the end user if the given value had no effect on the execution. + if ( + $args->has('disconnect') + && $args->arguments['disconnect']->value + ) { + $relation->dissociate(); + } + + if ( + $args->has('delete') + && $args->arguments['delete']->value + ) { + $relation->dissociate(); + // @phpstan-ignore-next-line Unrecognized mixin + $relation->delete(); + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedManyToMany.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedManyToMany.php new file mode 100644 index 0000000..2faff4f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedManyToMany.php @@ -0,0 +1,99 @@ +relationName = $relationName; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $parent + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($parent, $args): void + { + /** @var \Illuminate\Database\Eloquent\Relations\BelongsToMany|\Illuminate\Database\Eloquent\Relations\MorphToMany $relation */ + $relation = $parent->{$this->relationName}(); + + if ($args->has('sync')) { + $relation->sync( + $this->generateRelationArray($args->arguments['sync']) + ); + } + + if ($args->has('syncWithoutDetaching')) { + $relation->syncWithoutDetaching( + $this->generateRelationArray($args->arguments['syncWithoutDetaching']) + ); + } + + NestedOneToMany::createUpdateUpsert($args, $relation); + + if ($args->has('delete')) { + $ids = $args->arguments['delete']->toPlain(); + + $relation->detach($ids); + $relation->getRelated()::destroy($ids); + } + + if ($args->has('connect')) { + $relation->attach( + $this->generateRelationArray($args->arguments['connect']) + ); + } + + if ($args->has('disconnect')) { + $relation->detach( + $args->arguments['disconnect']->toPlain() + ); + } + } + + /** + * Generate an array for passing into sync, syncWithoutDetaching or connect method. + * + * Those functions natively have the capability of passing additional + * data to store in the pivot table. That array expects passing the id's + * as keys, so we transform the passed arguments to match that. + * + * @param \Nuwave\Lighthouse\Execution\Arguments\Argument $args + * @return array + */ + protected function generateRelationArray(Argument $args): array + { + $values = $args->toPlain(); + + if (empty($values)) { + return []; + } + + // Since GraphQL inputs are monomorphic, we can just look at the first + // given value and can deduce the value of all given args. + $exemplaryValue = $values[0]; + + // We assume that the values contain pivot information + if (is_array($exemplaryValue)) { + $relationArray = []; + foreach ($values as $value) { + $id = Arr::pull($value, 'id'); + $relationArray[$id] = $value; + } + + return $relationArray; + } + + // The default case is simply a flat array of IDs which we don't have to transform + return $values; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedMorphTo.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedMorphTo.php new file mode 100644 index 0000000..8f95cd1 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedMorphTo.php @@ -0,0 +1,44 @@ +relation = $relation; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $parent + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($parent, $args): void + { + // TODO implement create and update once we figure out how to do polymorphic input types https://github.com/nuwave/lighthouse/issues/900 + + if ($args->has('connect')) { + $connectArgs = $args->arguments['connect']->value; + + $morphToModel = $this->relation->createModelByType( + (string) $connectArgs->arguments['type']->value + ); + $morphToModel->setAttribute( + $morphToModel->getKeyName(), + $connectArgs->arguments['id']->value + ); + + $this->relation->associate($morphToModel); + } + + NestedBelongsTo::disconnectOrDelete($this->relation, $args); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToMany.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToMany.php new file mode 100644 index 0000000..75083b6 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToMany.php @@ -0,0 +1,119 @@ +relationName = $relationName; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $parent + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($parent, $args): void + { + /** @var \Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Eloquent\Relations\MorphMany $relation */ + $relation = $parent->{$this->relationName}(); + + static::createUpdateUpsert($args, $relation); + static::connectDisconnect($args, $relation); + + if ($args->has('delete')) { + $relation->getRelated()::destroy( + $args->arguments['delete']->toPlain() + ); + } + } + + /** + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public static function createUpdateUpsert(ArgumentSet $args, Relation $relation): void + { + if ($args->has('create')) { + $saveModel = new ResolveNested(new SaveModel($relation)); + + foreach ($args->arguments['create']->value as $childArgs) { + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $saveModel($relation->make(), $childArgs); + } + } + + if ($args->has('update')) { + $updateModel = new ResolveNested(new UpdateModel(new SaveModel($relation))); + + foreach ($args->arguments['update']->value as $childArgs) { + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $updateModel($relation->make(), $childArgs); + } + } + + if ($args->has('upsert')) { + $upsertModel = new ResolveNested(new UpsertModel(new SaveModel($relation))); + + foreach ($args->arguments['upsert']->value as $childArgs) { + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $upsertModel($relation->make(), $childArgs); + } + } + } + + public static function connectDisconnect(ArgumentSet $args, HasOneOrMany $relation): void + { + if ($args->has('connect')) { + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $children = $relation + ->make() + ->whereIn( + self::getLocalKeyName($relation), + $args->arguments['connect']->value + ) + ->get(); + + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $relation->saveMany($children); + } + + if ($args->has('disconnect')) { + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $relation + ->make() + ->whereIn( + self::getLocalKeyName($relation), + $args->arguments['disconnect']->value + ) + ->update([$relation->getForeignKeyName() => null]); + } + } + + /** + * TODO remove this horrible hack when we no longer support Laravel 5.6. + */ + protected static function getLocalKeyName(HasOneOrMany $relation): string + { + $getLocalKeyName = Closure::bind( + function () { + /** @psalm-suppress InvalidScope */ + // @phpstan-ignore-next-line This is a dirty hack + return $this->localKey; + }, + $relation, + get_class($relation) + ); + + return $getLocalKeyName(); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToOne.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToOne.php new file mode 100644 index 0000000..9a90c6f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/NestedOneToOne.php @@ -0,0 +1,52 @@ +relationName = $relationName; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $parent + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($parent, $args): void + { + /** @var \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation */ + $relation = $parent->{$this->relationName}(); + + if ($args->has('create')) { + $saveModel = new ResolveNested(new SaveModel($relation)); + + $saveModel($relation->make(), $args->arguments['create']->value); + } + + if ($args->has('update')) { + $updateModel = new ResolveNested(new UpdateModel(new SaveModel($relation))); + + $updateModel($relation->make(), $args->arguments['update']->value); + } + + if ($args->has('upsert')) { + $upsertModel = new ResolveNested(new UpsertModel(new SaveModel($relation))); + + $upsertModel($relation->make(), $args->arguments['upsert']->value); + } + + if ($args->has('delete')) { + $relation->getRelated()::destroy( + $args->arguments['delete']->toPlain() + ); + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/ResolveNested.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/ResolveNested.php new file mode 100644 index 0000000..3b9b5c5 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/ResolveNested.php @@ -0,0 +1,47 @@ +previous = $previous; + $this->argPartitioner = $argPartitioner ?? [ArgPartitioner::class, 'nestedArgResolvers']; + } + + /** + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($root, $args) + { + [$nestedArgs, $regularArgs] = ($this->argPartitioner)($args, $root); + + if ($this->previous) { + $root = ($this->previous)($root, $regularArgs); + } + + /** @var \Nuwave\Lighthouse\Execution\Arguments\Argument $nested */ + foreach ($nestedArgs->arguments as $nested) { + // @phpstan-ignore-next-line we know the resolver is there because we partitioned for it + ($nested->resolver)($root, $nested->value); + } + + return $root; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/SaveModel.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/SaveModel.php new file mode 100644 index 0000000..298014d --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/SaveModel.php @@ -0,0 +1,95 @@ +parentRelation = $parentRelation; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $model + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($model, $args): Model + { + // Extract $morphTo first, as MorphTo extends BelongsTo + [$morphTo, $remaining] = ArgPartitioner::relationMethods( + $args, + $model, + MorphTo::class + ); + + [$belongsTo, $remaining] = ArgPartitioner::relationMethods( + $remaining, + $model, + BelongsTo::class + ); + + $argsToFill = $remaining->toArray(); + + // Use all the remaining attributes and fill the model + if (config('lighthouse.force_fill')) { + $model->forceFill($argsToFill); + } else { + $model->fill($argsToFill); + } + + foreach ($belongsTo->arguments as $relationName => $nestedOperations) { + /** @var \Illuminate\Database\Eloquent\Relations\BelongsTo $belongsTo */ + $belongsTo = $model->{$relationName}(); + $belongsToResolver = new ResolveNested(new NestedBelongsTo($belongsTo)); + $belongsToResolver($model, $nestedOperations->value); + } + + foreach ($morphTo->arguments as $relationName => $nestedOperations) { + /** @var \Illuminate\Database\Eloquent\Relations\MorphTo $morphTo */ + $morphTo = $model->{$relationName}(); + $morphToResolver = new ResolveNested(new NestedMorphTo($morphTo)); + $morphToResolver($model, $nestedOperations->value); + } + + if ($this->parentRelation instanceof HasOneOrMany) { + // If we are already resolving a nested create, we might + // already have an instance of the parent relation available. + // In that case, use it to set the current model as a child. + $this->parentRelation->save($model); + + return $model; + } + + $model->save(); + + if ($this->parentRelation instanceof BelongsTo) { + $parentModel = $this->parentRelation->associate($model); + + // If the parent Model does not exist (still to be saved), + // a save could break any pending belongsTo relations that still + // needs to be created and associated with the parent model + if ($parentModel->exists) { + $parentModel->save(); + } + } + + if ($this->parentRelation instanceof BelongsToMany) { + $this->parentRelation->syncWithoutDetaching($model); + } + + return $model; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/UpdateModel.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/UpdateModel.php new file mode 100644 index 0000000..e06136f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/UpdateModel.php @@ -0,0 +1,45 @@ +previous = $previous; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $model + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($model, $args) + { + /** @var \Nuwave\Lighthouse\Execution\Arguments\Argument|null $id */ + $id = Arr::pull($args->arguments, 'id') + ?? Arr::pull($args->arguments, $model->getKeyName()) + ?? null; + + if ($id === null) { + throw new Error(self::MISSING_PRIMARY_KEY_FOR_UPDATE); + } + + $model = $model->newQuery()->findOrFail($id->value); + + return ($this->previous)($model, $args); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Arguments/UpsertModel.php b/vendor/nuwave/lighthouse/src/Execution/Arguments/UpsertModel.php new file mode 100644 index 0000000..6c9705b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Arguments/UpsertModel.php @@ -0,0 +1,45 @@ +previous = $previous; + } + + /** + * @param \Illuminate\Database\Eloquent\Model $model + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $args + */ + public function __invoke($model, $args) + { + // TODO consider Laravel native ->upsert(), available from 8.10 + $id = $args->arguments['id'] + ?? $args->arguments[$model->getKeyName()] + ?? null; + + if ($id !== null) { + $existingModel = $model + ->newQuery() + ->find($id->value); + + if ($existingModel !== null) { + $model = $existingModel; + } + } + + return ($this->previous)($model, $args); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/BaseRequest.php b/vendor/nuwave/lighthouse/src/Execution/BaseRequest.php deleted file mode 100644 index 755de03..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/BaseRequest.php +++ /dev/null @@ -1,98 +0,0 @@ -fieldValue('query'); - } - - /** - * Get the operationName of the current request. - * - * @return string|null - */ - public function operationName(): ?string - { - return $this->fieldValue('operationName'); - } - - /** - * Is the current query a batched query? - * - * @return bool - */ - public function isBatched(): bool - { - return ! is_null($this->batchIndex); - } - - /** - * Get the index of the current batch. - * - * Returns null if we are not resolving a batched query. - * - * @return int|null - */ - public function batchIndex(): ?int - { - return $this->batchIndex; - } - - /** - * Advance the batch index and indicate if there are more batches to process. - * - * @return bool - */ - public function advanceBatchIndex(): bool - { - if ($result = $this->hasMoreBatches()) { - $this->batchIndex++; - } - - return $result; - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/BatchLoader/BatchLoaderRegistry.php b/vendor/nuwave/lighthouse/src/Execution/BatchLoader/BatchLoaderRegistry.php new file mode 100644 index 0000000..7e6aa03 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/BatchLoader/BatchLoaderRegistry.php @@ -0,0 +1,69 @@ + + */ + protected static $instances = []; + + /** + * Return an instance of a BatchLoader for a specific field. + * + * @param array $pathToField Path to the GraphQL field from the root, is used as a key for BatchLoader instances + * @param callable(): object $makeInstance Function to instantiate the instance once + * @return object The result of calling makeInstance + * + * @throws \Exception + */ + public static function instance(array $pathToField, callable $makeInstance): object + { + // The path to the field serves as the unique key for the instance + $instanceKey = static::instanceKey($pathToField); + + if (isset(self::$instances[$instanceKey])) { + return self::$instances[$instanceKey]; + } + + return self::$instances[$instanceKey] = $makeInstance(); + } + + /** + * Remove all stored BatchLoaders. + * + * This is called after Lighthouse has resolved a query, so multiple + * queries can be handled in a single request/session. + */ + public static function forgetInstances(): void + { + self::$instances = []; + } + + /** + * Generate a unique key for the instance, using the path in the query. + * + * @param array $path + */ + protected static function instanceKey(array $path): string + { + $significantPathSegments = array_filter( + $path, + static function ($segment): bool { + // Ignore numeric path entries, as those signify a list of fields. + // Combining the queries for those is the very purpose of the + // batch loader, so they must not be included. + return ! is_numeric($segment); + } + ); + + // Using . as the separator would combine relations in nested fields with + // higher up relations using dot notation, matching the field path. + // We might optimize this in the future to enable batching them anyways, + // but employ this solution for now, as it preserves correctness. + return implode('|', $significantPathSegments); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/BatchLoader/RelationBatchLoader.php b/vendor/nuwave/lighthouse/src/Execution/BatchLoader/RelationBatchLoader.php new file mode 100644 index 0000000..198357a --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/BatchLoader/RelationBatchLoader.php @@ -0,0 +1,85 @@ + + */ + protected $parents = []; + + /** + * Marks when the actual batch loading happened. + * + * @var bool + */ + protected $hasResolved = false; + + public function __construct(ModelsLoader $relationLoader) + { + $this->relationLoader = $relationLoader; + } + + /** + * Schedule loading a relation off of a concrete model. + * + * This returns effectively a promise that will resolve to + * the result of loading the relation. + * + * As a side-effect, the model will then hold the relation. + */ + public function load(Model $model): Deferred + { + $modelKey = ModelKey::build($model); + $this->parents[$modelKey] = $model; + + return new Deferred(function () use ($modelKey) { + if (! $this->hasResolved) { + $this->resolve(); + } + + // When we are deep inside a nested query, we can come across the + // same model in two different paths, so this might be another + // model instance then $model. + $parent = $this->parents[$modelKey]; + + return $this->relationLoader->extract($parent); + }); + } + + public function resolve(): void + { + $parentModels = new EloquentCollection($this->parents); + + // Monomorphize the models to simplify eager loading relations onto them + $parentsGroupedByClass = $parentModels->groupBy( + /** + * @return class-string<\Illuminate\Database\Eloquent\Model> + */ + static function (Model $model): string { + return get_class($model); + }, + true + ); + + foreach ($parentsGroupedByClass as $parentsOfSameClass) { + $this->relationLoader->load($parentsOfSameClass); + } + + $this->hasResolved = true; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Builder.php b/vendor/nuwave/lighthouse/src/Execution/Builder.php deleted file mode 100644 index b8d6a72..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/Builder.php +++ /dev/null @@ -1,79 +0,0 @@ - $value) { - // TODO switch to instanceof when we require bensampo/laravel-enum - // Unbox Enum values to ensure their underlying value is used for queries - if (is_a($value, '\BenSampo\Enum\Enum')) { - $value = $value->value; - } - - /** @var \Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective $builderDirective */ - if ($builderDirective = Arr::get($this->builderDirectives, $key)) { - $builder = $builderDirective->handleBuilder($builder, $value); - } - } - - foreach ($this->scopes as $scope) { - call_user_func([$builder, $scope], $args); - } - - return $builder; - } - - /** - * Add scopes that are then called upon the query with the field arguments. - * - * @param string[] $scopes - * @return $this - */ - public function addScopes(array $scopes): self - { - $this->scopes = array_merge($this->scopes, $scopes); - - return $this; - } - - /** - * Add a query builder directive keyed by the argument name. - * - * @param string $argumentName - * @param \Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective $argBuilderDirective - * @return $this - */ - public function addBuilderDirective(string $argumentName, ArgBuilderDirective $argBuilderDirective): self - { - $this->builderDirectives[$argumentName] = $argBuilderDirective; - - return $this; - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/ContextFactory.php b/vendor/nuwave/lighthouse/src/Execution/ContextFactory.php index 5fdbfa3..59916c9 100644 --- a/vendor/nuwave/lighthouse/src/Execution/ContextFactory.php +++ b/vendor/nuwave/lighthouse/src/Execution/ContextFactory.php @@ -9,12 +9,6 @@ use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; class ContextFactory implements CreatesContext { - /** - * Generate GraphQL context. - * - * @param \Illuminate\Http\Request $request - * @return \Nuwave\Lighthouse\Support\Contracts\GraphQLContext - */ public function generate(Request $request): GraphQLContext { return new Context($request); diff --git a/vendor/nuwave/lighthouse/src/Execution/DataLoader/BatchLoader.php b/vendor/nuwave/lighthouse/src/Execution/DataLoader/BatchLoader.php index 0c60d40..d928db8 100644 --- a/vendor/nuwave/lighthouse/src/Execution/DataLoader/BatchLoader.php +++ b/vendor/nuwave/lighthouse/src/Execution/DataLoader/BatchLoader.php @@ -2,29 +2,32 @@ namespace Nuwave\Lighthouse\Execution\DataLoader; -use Exception; use GraphQL\Deferred; -use Illuminate\Support\Collection; -use Nuwave\Lighthouse\Execution\GraphQLRequest; -use Nuwave\Lighthouse\Support\Traits\HandlesCompositeKey; +/** + * @deprecated implement your own batch loader instead. + * @see \Nuwave\Lighthouse\Execution\BatchLoader\BatchLoaderRegistry to resolve instances. + */ abstract class BatchLoader { - use HandlesCompositeKey; + /** + * Active BatchLoader instances. + * + * @var array + */ + protected static $instances = []; /** - * Keys to resolve. + * Map from keys to metainfo for resolving. * - * @var array + * @var array> */ protected $keys = []; /** - * Map of loaded results. + * Map from keys to resolved values. * - * [key => resolvedValue] - * - * @var mixed[] + * @var array */ protected $results = []; @@ -39,8 +42,8 @@ abstract class BatchLoader * Return an instance of a BatchLoader for a specific field. * * @param string $loaderClass The class name of the concrete BatchLoader to instantiate - * @param mixed[] $pathToField Path to the GraphQL field from the root, is used as a key for BatchLoader instances - * @param mixed[] $constructorArgs Those arguments are passed to the constructor of the new BatchLoader instance + * @param array $pathToField Path to the GraphQL field from the root, is used as a key for BatchLoader instances + * @param array $constructorArgs Those arguments are passed to the constructor of the new BatchLoader instance * @return static * * @throws \Exception @@ -50,60 +53,52 @@ abstract class BatchLoader // The path to the field serves as the unique key for the instance $instanceName = static::instanceKey($pathToField); - // If we are resolving a batched query, we need to assign each - // query a uniquely indexed instance - /** @var \Nuwave\Lighthouse\Execution\GraphQLRequest $graphQLRequest */ - $graphQLRequest = app(GraphQLRequest::class); - if ($graphQLRequest->isBatched()) { - $currentBatchIndex = $graphQLRequest->batchIndex(); - $instanceName = "batch_{$currentBatchIndex}_{$instanceName}"; + if (isset(self::$instances[$instanceName])) { + return self::$instances[$instanceName]; } - // Only register a new instance if it is not already bound - $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 self::$instances[$instanceName] = app()->makeWith($loaderClass, $constructorArgs); } /** * Generate a unique key for the instance, using the path in the query. * - * @param mixed[] $path - * @return string + * @param array $path */ public static function instanceKey(array $path): string { - return (new Collection($path)) - ->filter(function ($path): bool { - // Ignore numeric path entries, as those signify an array of fields. + $significantPathSegments = array_filter( + $path, + function ($path): bool { + // Ignore numeric path entries, as those signify a list of fields. // Combining the queries for those is the very purpose of the // batch loader, so they must not be included. return ! is_numeric($path); - }) - ->implode('_'); + } + ); + $pathIgnoringLists = implode('.', $significantPathSegments); + + return 'nuwave/lighthouse/batchloader/'.$pathIgnoringLists; } /** - * Load object by key. + * Remove all stored BatchLoaders. * - * @param mixed $key - * @param mixed[] $metaInfo - * @return \GraphQL\Deferred + * This is called after Lighthouse has resolved a query, so multiple + * queries can be handled in a single request/session. */ - public function load($key, array $metaInfo = []): Deferred + public static function forgetInstances(): void + { + self::$instances = []; + } + + /** + * Schedule a result to be loaded. + * + * @param array $metaInfo + */ + public function load(string $key, array $metaInfo = []): Deferred { - $key = $this->buildKey($key); $this->keys[$key] = $metaInfo; return new Deferred(function () use ($key) { @@ -116,12 +111,29 @@ abstract class BatchLoader }); } + /** + * Schedule multiple results to be loaded. + * + * @param array $keys + * @param array $metaInfo + * @return array<\GraphQL\Deferred> + */ + public function loadMany(array $keys, array $metaInfo = []): array + { + return array_map( + function ($key) use ($metaInfo): Deferred { + return $this->load($key, $metaInfo); + }, + $keys + ); + } + /** * Resolve the keys. * - * The result has to be an associative array: [key => result] + * The result has to be a map from keys to resolved values. * - * @return mixed[] + * @return array */ abstract public function resolve(): array; } diff --git a/vendor/nuwave/lighthouse/src/Execution/DataLoader/ModelRelationFetcher.php b/vendor/nuwave/lighthouse/src/Execution/DataLoader/ModelRelationFetcher.php deleted file mode 100644 index d14d677..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/DataLoader/ModelRelationFetcher.php +++ /dev/null @@ -1,410 +0,0 @@ -setModels($models); - $this->setRelations($relations); - } - - /** - * Set the relations to be loaded. - * - * @param array $relations - * @return $this - */ - public function setRelations(array $relations): self - { - // Parse and set the relations. - $this->relations = $this->newModelQuery() - ->with($relations) - ->getEagerLoads(); - - return $this; - } - - /** - * Return a fresh instance of a query builder for the underlying model. - * - * @return \Illuminate\Database\Eloquent\Builder - */ - protected function newModelQuery(): EloquentBuilder - { - return $this->models() - ->first() - ->newModelQuery(); - } - - /** - * Get all the underlying models. - * - * @return \Illuminate\Database\Eloquent\Collection<\Illuminate\Database\Eloquent\Model> - */ - public function models(): EloquentCollection - { - return $this->models; - } - - /** - * Set one or more Model instances as an EloquentCollection. - * - * @param mixed $models - * @return $this - */ - protected function setModels($models): self - { - $this->models = $models instanceof EloquentCollection - ? $models - : new EloquentCollection($models); - - return $this; - } - - /** - * Load all the relations of all the models. - * - * @return $this - */ - public function loadRelations(): self - { - $this->models->load($this->relations); - - return $this; - } - - /** - * Load all relations for the model, but constrain the query to the current page. - * - * @param int $perPage - * @param int $page - * @return $this - */ - public function loadRelationsForPage(int $perPage, int $page = 1): self - { - foreach ($this->relations as $name => $constraints) { - $this->loadRelationForPage($perPage, $page, $name, $constraints); - } - - return $this; - } - - /** - * Load only one page of relations of all the models. - * - * The relation will be converted to a `Paginator` instance. - * - * @param int $first - * @param int $page - * @param string $relationName - * @param \Closure $relationConstraints - * @return $this - */ - public function loadRelationForPage(int $first, int $page, string $relationName, Closure $relationConstraints): self - { - // Load the count of relations of models, this will be the `total` argument of `Paginator`. - // Be aware that this will reload all the models entirely with the count of their relations, - // which will bring extra DB queries, always prefer querying without pagination if possible. - $this->reloadModelsWithRelationCount(); - - $relations = $this - ->buildRelationsFromModels($relationName, $relationConstraints) - ->map( - function (Relation $relation) use ($first, $page) { - return $relation->forPage($page, $first); - } - ); - - /** @var \Illuminate\Database\Eloquent\Collection $relationModels */ - $relationModels = $this - ->unionAllRelationQueries($relations) - ->get(); - - $this->hydratePivotRelation($relationName, $relationModels); - - $this->loadDefaultWith($relationModels); - - $this->associateRelationModels($relationName, $relationModels); - - $this->convertRelationToPaginator($first, $page, $relationName); - - return $this; - } - - /** - * Reload the models to get the `{relation}_count` attributes of models set. - * - * @return $this - */ - public function reloadModelsWithRelationCount(): self - { - /** @var \Illuminate\Database\Eloquent\Builder $query */ - $query = $this->models() - ->first() - ->newQuery() - ->withCount($this->relations); - - $ids = $this->getModelIds(); - - $reloadedModels = $query - ->whereKey($ids) - ->get() - ->filter(function (Model $model) use ($ids): bool { - return in_array( - $model->getKey(), - $ids, - true - ); - }); - - return $this->setModels($reloadedModels); - } - - /** - * Extract the primary keys from the underlying models. - * - * @return mixed[] - */ - protected function getModelIds(): array - { - return $this->models - ->map(function (Model $model) { - return $model->getKey(); - }) - ->all(); - } - - /** - * Get queries to fetch relationships. - * - * @param string $relationName - * @param \Closure $relationConstraints - * @return \Illuminate\Support\Collection<\Illuminate\Database\Eloquent\Relations\Relation> - */ - protected function buildRelationsFromModels(string $relationName, Closure $relationConstraints): Collection - { - return $this->models->toBase()->map( - function (Model $model) use ($relationName, $relationConstraints): Relation { - $relation = $this->getRelationInstance($relationName); - - $relation->addEagerConstraints([$model]); - - // Call the constraints - $relationConstraints($relation, $model); - - if (method_exists($relation, 'shouldSelect')) { - $shouldSelect = new ReflectionMethod(get_class($relation), 'shouldSelect'); - $shouldSelect->setAccessible(true); - $select = $shouldSelect->invoke($relation, ['*']); - - $relation->addSelect($select); - } elseif (method_exists($relation, 'getSelectColumns')) { - $getSelectColumns = new ReflectionMethod(get_class($relation), 'getSelectColumns'); - $getSelectColumns->setAccessible(true); - $select = $getSelectColumns->invoke($relation, ['*']); - - $relation->addSelect($select); - } - - $relation->initRelation([$model], $relationName); - - return $relation; - } - ); - } - - /** - * Load default eager loads. - * - * @param \Illuminate\Database\Eloquent\Collection<\Illuminate\Database\Eloquent\Model> $collection - * @return $this - */ - protected function loadDefaultWith(EloquentCollection $collection): self - { - if ($collection->isEmpty()) { - return $this; - } - - $model = $collection->first(); - $reflection = new ReflectionClass($model); - $withProperty = $reflection->getProperty('with'); - $withProperty->setAccessible(true); - - $with = array_filter((array) $withProperty->getValue($model), function ($relation) use ($model): bool { - return ! $model->relationLoaded($relation); - }); - - if (! empty($with)) { - $collection->load($with); - } - - return $this; - } - - /** - * This is the name that Eloquent gives to the attribute that contains the count. - * - * @see \Illuminate\Database\Eloquent\Concerns\QueriesRelationships->withCount() - * - * @param string $relationName - * @return string - */ - public function getRelationCountName(string $relationName): string - { - return Str::snake("{$relationName}_count"); - } - - /** - * Get an associative array of relations, keyed by the models primary key. - * - * @param string $relationName - * @return mixed[] - */ - public function getRelationDictionary(string $relationName): array - { - return $this->models - ->mapWithKeys( - function (Model $model) use ($relationName): array { - return [$this->buildKey($model->getKey()) => $model->getRelation($relationName)]; - } - )->all(); - } - - /** - * Merge all the relation queries into a single query with UNION ALL. - * - * @param \Illuminate\Support\Collection $relations - * @return \Illuminate\Database\Eloquent\Builder - */ - protected function unionAllRelationQueries(Collection $relations): EloquentBuilder - { - return $relations - ->reduce( - function (EloquentBuilder $builder, Relation $relation) { - return $builder->unionAll( - $relation->getQuery() - ); - }, - // Use the first query as the initial starting point - $relations->shift()->getQuery() - ); - } - - /** - * @param int $first - * @param int $page - * @param string $relationName - * @return $this - */ - protected function convertRelationToPaginator(int $first, int $page, string $relationName): self - { - $this->models->each(function (Model $model) use ($page, $first, $relationName): void { - $total = $model->getAttribute( - $this->getRelationCountName($relationName) - ); - - $paginator = app()->makeWith( - LengthAwarePaginator::class, - [ - 'items' => $model->getRelation($relationName), - 'total' => $total, - 'perPage' => $first, - 'currentPage' => $page, - 'options' => [], - ] - ); - - $model->setRelation($relationName, $paginator); - }); - - return $this; - } - - /** - * Associate the collection of all fetched relationModels back with their parents. - * - * @param string $relationName - * @param \Illuminate\Database\Eloquent\Collection $relationModels - * @return $this - */ - protected function associateRelationModels(string $relationName, EloquentCollection $relationModels): self - { - $relation = $this->getRelationInstance($relationName); - - $relation->match( - $this->models->all(), - $relationModels, - $relationName - ); - - return $this; - } - - /** - * Ensure the pivot relation is hydrated too, if it exists. - * - * @param string $relationName - * @param \Illuminate\Database\Eloquent\Collection<\Illuminate\Database\Eloquent\Model> $relationModels - * @return $this - */ - protected function hydratePivotRelation(string $relationName, EloquentCollection $relationModels): self - { - $relation = $this->getRelationInstance($relationName); - - if ($relationModels->isNotEmpty() && method_exists($relation, 'hydratePivotRelation')) { - $hydrationMethod = new ReflectionMethod(get_class($relation), 'hydratePivotRelation'); - $hydrationMethod->setAccessible(true); - $hydrationMethod->invoke($relation, $relationModels->all()); - } - - return $this; - } - - /** - * Use the underlying model to instantiate a relation by name. - * - * @param string $relationName - * @return \Illuminate\Database\Eloquent\Relations\Relation - */ - protected function getRelationInstance(string $relationName): Relation - { - return $this - ->newModelQuery() - ->getRelation($relationName); - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/DataLoader/RelationBatchLoader.php b/vendor/nuwave/lighthouse/src/Execution/DataLoader/RelationBatchLoader.php deleted file mode 100644 index 127d617..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/DataLoader/RelationBatchLoader.php +++ /dev/null @@ -1,122 +0,0 @@ -relationName = $relationName; - $this->args = $args; - $this->scopes = $scopes; - $this->resolveInfo = $resolveInfo; - $this->first = $first; - $this->page = $page; - } - - /** - * Resolve the keys. - * - * @return mixed[] - */ - 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); - } - - /** - * Construct a new instance of a relation fetcher. - * - * @return \Nuwave\Lighthouse\Execution\DataLoader\ModelRelationFetcher - */ - protected function getRelationFetcher(): ModelRelationFetcher - { - return new ModelRelationFetcher( - $this->getParentModels(), - [$this->relationName => function ($query) { - return $this->resolveInfo - ->builder - ->addScopes($this->scopes) - ->apply($query, $this->args); - }] - ); - } - - /** - * Get the parents from the keys that are present on the BatchLoader. - * - * @return \Illuminate\Support\Collection<\Illuminate\Database\Eloquent\Model> - */ - protected function getParentModels(): Collection - { - return (new Collection($this->keys))->pluck('parent'); - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/ErrorBuffer.php b/vendor/nuwave/lighthouse/src/Execution/ErrorBuffer.php deleted file mode 100644 index 7d7df4d..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/ErrorBuffer.php +++ /dev/null @@ -1,159 +0,0 @@ -errorType = $errorType; - $this->exceptionResolver = $exceptionResolver ?? $this->defaultExceptionResolver(); - } - - /** - * Construct a default exception resolver. - * - * @return \Closure - */ - protected function defaultExceptionResolver(): Closure - { - return function (string $errorMessage): GenericException { - return (new GenericException($errorMessage)) - ->setExtensions([$this->errorType => $this->errors]) - ->setCategory($this->errorType); - }; - } - - /** - * Set the Exception resolver. - * - * @param \Closure $exceptionResolver - * @return $this - */ - public function setExceptionResolver(Closure $exceptionResolver): self - { - $this->exceptionResolver = $exceptionResolver; - - return $this; - } - - /** - * Resolve the exception by calling the exception handler with the given args. - * - * @param mixed ...$args - * @return mixed - */ - protected function resolveException(...$args) - { - return ($this->exceptionResolver)(...$args); - } - - /** - * Push an error message into the buffer. - * - * @param string $errorMessage - * @param string|null $key - * @return $this - */ - public function push(string $errorMessage, ?string $key = null): self - { - if ($key === null) { - $this->errors[] = $errorMessage; - } else { - $this->errors[$key][] = $errorMessage; - } - - return $this; - } - - /** - * Flush the errors. - * - * @param string $errorMessage - * @return void - * - * @throws \Exception - */ - public function flush(string $errorMessage): void - { - if (! $this->hasErrors()) { - return; - } - - $exception = $this->resolveException($errorMessage, $this); - - $this->clearErrors(); - - throw $exception; - } - - /** - * Reset the errors to an empty array. - * - * @return void - */ - public function clearErrors(): void - { - $this->errors = []; - } - - /** - * Get the error type. - * - * @return string - */ - public function errorType(): string - { - return $this->errorType; - } - - /** - * Set the error type. - * - * @param string $errorType - * @return $this - */ - public function setErrorType(string $errorType): self - { - $this->errorType = $errorType; - - return $this; - } - - /** - * Have we encountered any errors yet? - * - * @return bool - */ - public function hasErrors(): bool - { - return count($this->errors) > 0; - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/ErrorHandler.php b/vendor/nuwave/lighthouse/src/Execution/ErrorHandler.php index c7bf591..d4e8aef 100644 --- a/vendor/nuwave/lighthouse/src/Execution/ErrorHandler.php +++ b/vendor/nuwave/lighthouse/src/Execution/ErrorHandler.php @@ -5,17 +5,19 @@ namespace Nuwave\Lighthouse\Execution; use Closure; use GraphQL\Error\Error; +/** + * Instantiated through the container, once per query. + */ interface ErrorHandler { /** - * This function receives all GraphQL errors and may alter them or do something else with them. + * Called with each GraphQL error, allows doing anything with them. * - * Always call $next($error) to keep the Pipeline going. Multiple such Handlers may be registered - * as an array in the config. + * Multiple such Handlers may be registered as an array in the config. + * Always call $next($error) to keep the Pipeline going. + * Returning null discards the error. * - * @param \GraphQL\Error\Error $error - * @param \Closure $next - * @return array + * @return array|null */ - public static function handle(Error $error, Closure $next): array; + public function __invoke(?Error $error, Closure $next): ?array; } diff --git a/vendor/nuwave/lighthouse/src/Execution/ErrorPool.php b/vendor/nuwave/lighthouse/src/Execution/ErrorPool.php new file mode 100644 index 0000000..38fca74 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ErrorPool.php @@ -0,0 +1,53 @@ + + */ + protected $throwables = []; + + /** + * Stores an error that will be added to the result. + */ + public function record(Throwable $throwable): void + { + $this->throwables [] = $throwable; + } + + /** + * @return array<\GraphQL\Error\Error> + */ + public function errors(): array + { + return array_map( + function (Throwable $throwable): Error { + if ($throwable instanceof Error) { + return $throwable; + } + + return new Error( + $throwable->getMessage(), + null, + null, + [], + null, + $throwable + ); + }, + $this->throwables + ); + } + + public function clear(): void + { + $this->throwables = []; + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/ExtensionErrorHandler.php b/vendor/nuwave/lighthouse/src/Execution/ExtensionErrorHandler.php index 898ea50..bd19c69 100644 --- a/vendor/nuwave/lighthouse/src/Execution/ExtensionErrorHandler.php +++ b/vendor/nuwave/lighthouse/src/Execution/ExtensionErrorHandler.php @@ -6,32 +6,32 @@ use Closure; use GraphQL\Error\Error; use Nuwave\Lighthouse\Exceptions\RendersErrorsExtensions; +/** + * 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. + */ class ExtensionErrorHandler implements ErrorHandler { - /** - * 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. - * - * @param \GraphQL\Error\Error $error - * @param \Closure $next - * @return array - */ - public static function handle(Error $error, Closure $next): array + public function __invoke(?Error $error, Closure $next): ?array { - $underlyingException = $error->getPrevious(); + if ($error === null) { + return $next(null); + } + $underlyingException = $error->getPrevious(); if ($underlyingException instanceof RendersErrorsExtensions) { // Reconstruct the error, passing in the extensions of the underlying exception - $error = new Error( - $error->message, - $error->nodes, + return $next(new Error( + $error->getMessage(), + // @phpstan-ignore-next-line graphql-php and phpstan disagree with themselves + $error->getNodes(), $error->getSource(), $error->getPositions(), $error->getPath(), $underlyingException, $underlyingException->extensionsContent() - ); + )); } return $next($error); diff --git a/vendor/nuwave/lighthouse/src/Execution/ExtensionsResponse.php b/vendor/nuwave/lighthouse/src/Execution/ExtensionsResponse.php index 0701983..09635c9 100644 --- a/vendor/nuwave/lighthouse/src/Execution/ExtensionsResponse.php +++ b/vendor/nuwave/lighthouse/src/Execution/ExtensionsResponse.php @@ -3,8 +3,7 @@ namespace Nuwave\Lighthouse\Execution; /** - * May be returned from listeners of the event:. - * @see \Nuwave\Lighthouse\Events\BuildExtensionsResponse + * May be returned from listeners of @see \Nuwave\Lighthouse\Events\BuildExtensionsResponse. */ class ExtensionsResponse { @@ -16,18 +15,12 @@ class ExtensionsResponse protected $key; /** - * JSON-encodable content of the extension. - * - * @var mixed + * @var mixed JSON-encodable content of the extension. */ protected $content; /** - * ExtensionsResponse constructor. - * - * @param string $key - * @param mixed $content - * @return void + * @param mixed $content JSON-encodable content */ public function __construct(string $key, $content) { @@ -37,8 +30,6 @@ class ExtensionsResponse /** * Return the key of the extension. - * - * @return string */ public function key(): string { @@ -46,9 +37,7 @@ class ExtensionsResponse } /** - * Return the JSON-encodable content of the extension. - * - * @return mixed + * @return mixed JSON-encodable content of the extension. */ public function content() { diff --git a/vendor/nuwave/lighthouse/src/Execution/GraphQLRequest.php b/vendor/nuwave/lighthouse/src/Execution/GraphQLRequest.php deleted file mode 100644 index 88206d9..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/GraphQLRequest.php +++ /dev/null @@ -1,50 +0,0 @@ -customAttributes, 'root'); - } - - /** - * Get the context that was passed to the field that is being validated. - * - * @return \Nuwave\Lighthouse\Support\Contracts\GraphQLContext - */ - public function getContext(): GraphQLContext - { - return Arr::get($this->customAttributes, 'context'); - } - - /** - * Get the resolve info that was passed to the field that is being validated. - * - * @return \GraphQL\Type\Definition\ResolveInfo - */ - public function getResolveInfo(): ResolveInfo - { - return Arr::get($this->customAttributes, 'resolveInfo'); - } - - /** - * Return the dot separated path of the field that is being validated. - * - * @return string - */ - public function getFieldPath(): string - { - return implode( - '.', - $this->getResolveInfo()->path - ); - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/LighthouseRequest.php b/vendor/nuwave/lighthouse/src/Execution/LighthouseRequest.php deleted file mode 100644 index 27f66d3..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/LighthouseRequest.php +++ /dev/null @@ -1,75 +0,0 @@ -request = $request; - - // If the request has neither a query, nor an operationName, - // we assume we are resolving a batched query. - if (! $request->hasAny('query', 'operationName')) { - $this->batchIndex = 0; - } - } - - /** - * Get the given variables for the query. - * - * @return mixed[] - */ - public function variables(): array - { - $variables = $this->fieldValue('variables'); - - // In case we are resolving a GET request, variables - // are sent as a JSON encoded string - if (is_string($variables)) { - return json_decode($variables, true) ?? []; - } - - // If this is a POST request, Laravel already decoded the input for us - return $variables ?? []; - } - - /** - * Are there more batched queries to process? - * - * @return bool - */ - protected function hasMoreBatches(): bool - { - return count($this->request->input()) - 1 > $this->batchIndex; - } - - /** - * Get the contents of a field by key. - * - * This is expected to take batched requests into consideration. - * - * @param string $key - * @return array|string|null - */ - protected function fieldValue(string $key) - { - return $this->request->input($key) - ?? $this->request->input("{$this->batchIndex}.{$key}"); - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/AggregateModelsLoader.php b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/AggregateModelsLoader.php new file mode 100644 index 0000000..b1b580e --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/AggregateModelsLoader.php @@ -0,0 +1,59 @@ +relation = $relation; + $this->column = $column; + $this->function = $function; + $this->decorateBuilder = $decorateBuilder; + } + + public function load(EloquentCollection $parents): void + { + // @phpstan-ignore-next-line Only present in Laravel 8+ + $parents->loadAggregate([$this->relation => $this->decorateBuilder], $this->column, $this->function); + } + + public function extract(Model $model) + { + /** + * This is the name that Eloquent gives to the attribute that contains the aggregate. + * + * @see \Illuminate\Database\Eloquent\Concerns\QueriesRelationships::withAggregate() + */ + $attribute = Str::snake( + \Safe\preg_replace('/[^[:alnum:][:space:]_]/u', '', "$this->relation $this->function $this->column") + ); + + return $model->getAttribute($attribute); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/CountModelsLoader.php b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/CountModelsLoader.php new file mode 100644 index 0000000..63afee9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/CountModelsLoader.php @@ -0,0 +1,94 @@ +relation = $relation; + $this->decorateBuilder = $decorateBuilder; + } + + public function load(EloquentCollection $parents): void + { + self::loadCount($parents, [$this->relation => $this->decorateBuilder]); + } + + public function extract(Model $model): int + { + return self::extractCount($model, $this->relation); + } + + public static function extractCount(Model $model, string $relationName): int + { + /** + * This is the name that Eloquent gives to the attribute that contains the count. + * + * @see \Illuminate\Database\Eloquent\Concerns\QueriesRelationships::withCount() + */ + $countAttributeName = Str::snake("${relationName}_count"); + + /** + * We just assert this is an int and let PHP run into a type error if not. + * + * @var int $count + */ + $count = $model->getAttribute($countAttributeName); + + return $count; + } + + /** + * Reload the models to get the `{relation}_count` attributes of models set. + * + * @deprecated Laravel 5.7 has native ->loadCount() on EloquentCollection + * @see \Illuminate\Database\Eloquent\Collection::loadCount() + * + * @param array $relations + */ + public static function loadCount(EloquentCollection $parents, array $relations): void + { + if ($parents->isEmpty()) { + return; + } + + $models = $parents->first()->newModelQuery() + ->whereKey($parents->modelKeys()) + ->select($parents->first()->getKeyName()) + ->withCount($relations) + ->get() + ->keyBy($parents->first()->getKeyName()); + + $attributes = Arr::except( + array_keys($models->first()->getAttributes()), + $models->first()->getKeyName() + ); + + foreach ($parents as $model) { + $extraAttributes = Arr::only($models->get($model->getKey())->getAttributes(), $attributes); + + $model->forceFill($extraAttributes); + + foreach ($attributes as $attribute) { + $model->syncOriginalAttribute($attribute); + } + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/ModelsLoader.php b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/ModelsLoader.php new file mode 100644 index 0000000..5b78f3f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/ModelsLoader.php @@ -0,0 +1,21 @@ +relation = $relation; + $this->decorateBuilder = $decorateBuilder; + $this->paginationArgs = $paginationArgs; + } + + public function load(EloquentCollection $parents): void + { + CountModelsLoader::loadCount($parents, [$this->relation => $this->decorateBuilder]); + + $relatedModels = $this->loadRelatedModels($parents); + + $this->hydratePivotRelation($parents, $relatedModels); + $this->loadDefaultWith($relatedModels); + $this->associateRelationModels($parents, $relatedModels); + $this->convertRelationToPaginator($parents); + } + + public function extract(Model $model) + { + return $model->getRelation($this->relation); + } + + protected function loadRelatedModels(EloquentCollection $parents): EloquentCollection + { + $relations = $parents + ->toBase() + ->map(function (Model $model) use ($parents): Relation { + $relation = $this->relationInstance($parents); + + $relation->addEagerConstraints([$model]); + + ($this->decorateBuilder)($relation, $model); + + if ($relation instanceof BelongsToMany || $relation instanceof HasManyThrough) { + $shouldSelect = new ReflectionMethod(get_class($relation), 'shouldSelect'); + $shouldSelect->setAccessible(true); + $select = $shouldSelect->invoke($relation, ['*']); + + // @phpstan-ignore-next-line Builder mixin is not understood + $relation->addSelect($select); + } + + $relation->initRelation([$model], $this->relation); + + // @phpstan-ignore-next-line Builder mixin is not understood + return $relation->forPage($this->paginationArgs->page, $this->paginationArgs->first); + }); + + // Merge all the relation queries into a single query with UNION ALL. + + /** + * Use the first query as the initial starting point. + * + * We can assume this to be non-null because only non-empty lists of parents + * are passed into this loader. + * + * @var \Illuminate\Database\Eloquent\Relations\Relation $firstRelation + */ + $firstRelation = $relations->shift(); + + // We have to make sure to use ->getQuery() in order to respect + // model scopes, such as soft deletes + $mergedRelationQuery = $relations->reduce( + static function (EloquentBuilder $builder, Relation $relation): EloquentBuilder { + return $builder->unionAll( + // @phpstan-ignore-next-line Laravel can deal with an EloquentBuilder just fine + $relation->getQuery() + ); + }, + $firstRelation->getQuery() + ); + + return $mergedRelationQuery->get(); + } + + /** + * Use the underlying model to instantiate a relation by name. + */ + protected function relationInstance(EloquentCollection $parents): Relation + { + return $this + ->newModelQuery($parents) + ->getRelation($this->relation); + } + + /** + * Return a fresh instance of a query builder for the underlying model. + */ + protected function newModelQuery(EloquentCollection $parents): EloquentBuilder + { + /** @var \Illuminate\Database\Eloquent\Model $anyModelInstance */ + $anyModelInstance = $parents->first(); + + /** @var \Illuminate\Database\Eloquent\Builder $newModelQuery */ + $newModelQuery = $anyModelInstance->newModelQuery(); + + return $newModelQuery; + } + + /** + * Ensure the pivot relation is hydrated too, if it exists. + * + * @param \Illuminate\Database\Eloquent\Collection<\Illuminate\Database\Eloquent\Model> $relatedModels + */ + protected function hydratePivotRelation(EloquentCollection $parents, EloquentCollection $relatedModels): void + { + $relation = $this->relationInstance($parents); + + if ($relatedModels->isNotEmpty() && method_exists($relation, 'hydratePivotRelation')) { + $hydrationMethod = new ReflectionMethod(get_class($relation), 'hydratePivotRelation'); + $hydrationMethod->setAccessible(true); + $hydrationMethod->invoke($relation, $relatedModels->all()); + } + } + + protected function loadDefaultWith(EloquentCollection $collection): void + { + /** @var \Illuminate\Database\Eloquent\Model|null $model */ + $model = $collection->first(); + if ($model === null) { + return; + } + + $reflection = new ReflectionClass($model); + $withProperty = $reflection->getProperty('with'); + $withProperty->setAccessible(true); + + $unloadedWiths = array_filter( + (array) $withProperty->getValue($model), + static function (string $relation) use ($model): bool { + return ! $model->relationLoaded($relation); + } + ); + + if (count($unloadedWiths) > 0) { + $collection->load($unloadedWiths); + } + } + + /** + * Associate the collection of all fetched relationModels back with their parents. + */ + protected function associateRelationModels(EloquentCollection $parents, EloquentCollection $relatedModels): void + { + $this + ->relationInstance($parents) + ->match( + $parents->all(), + $relatedModels, + $this->relation + ); + } + + protected function convertRelationToPaginator(EloquentCollection $parents): void + { + foreach ($parents as $model) { + $total = CountModelsLoader::extractCount($model, $this->relation); + + $paginator = app()->makeWith( + LengthAwarePaginator::class, + [ + 'items' => $model->getRelation($this->relation), + 'total' => $total, + 'perPage' => $this->paginationArgs->first, + 'currentPage' => $this->paginationArgs->page, + 'options' => [], + ] + ); + + $model->setRelation($this->relation, $paginator); + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/SimpleModelsLoader.php b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/SimpleModelsLoader.php new file mode 100644 index 0000000..985c210 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ModelsLoader/SimpleModelsLoader.php @@ -0,0 +1,48 @@ +relation = $relation; + $this->decorateBuilder = $decorateBuilder; + } + + public function load(EloquentCollection $parents): void + { + $parents->load([$this->relation => $this->decorateBuilder]); + } + + /** + * Extract the relation that was loaded. + * + * @return mixed The model's relation. + */ + public function extract(Model $model) + { + // Dot notation may be used to eager load nested relations + $parts = explode('.', $this->relation); + + // We just return the first level of relations for now. + // They hold the nested relations in case they are needed. + $firstRelation = $parts[0]; + + return $model->getRelation($firstRelation); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/MultipartFormRequest.php b/vendor/nuwave/lighthouse/src/Execution/MultipartFormRequest.php deleted file mode 100644 index a636779..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/MultipartFormRequest.php +++ /dev/null @@ -1,93 +0,0 @@ -has('map')) { - throw new InvariantViolation( - 'Could not find a valid map, be sure to conform to GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec' - ); - } - - $this->operations = json_decode( - $request->input('operations'), - true - ); - - // If operations is 0-indexed, we assume we are resolving a batched query - if (isset($this->operations[0])) { - $this->batchIndex = 0; - } - - $map = json_decode($request->input('map'), true); - - /** - * @var string - * @var array $operationsPaths - */ - foreach ($map as $fileKey => $operationsPaths) { - $file = $request->file($fileKey); - - /** @var string $operationsPath */ - foreach ($operationsPaths as $operationsPath) { - Arr::set($this->operations, $operationsPath, $file); - } - } - } - - /** - * Get the given variables for the query. - * - * @return mixed[] - */ - public function variables(): array - { - return $this->fieldValue('variables') ?? []; - } - - /** - * If we are dealing with a batched request, this gets the - * contents of the currently resolving batch index. - * - * @param string $key - * @return array|string|null - */ - protected function fieldValue(string $key) - { - return $this->isBatched() - ? Arr::get($this->operations, $this->batchIndex.'.'.$key) - : $this->operations[$key] ?? null; - } - - /** - * Are there more batched queries to process? - * - * @return bool - */ - protected function hasMoreBatches(): bool - { - return count($this->operations) - 1 > $this->batchIndex; - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/MutationExecutor.php b/vendor/nuwave/lighthouse/src/Execution/MutationExecutor.php deleted file mode 100644 index 544ed2f..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/MutationExecutor.php +++ /dev/null @@ -1,426 +0,0 @@ -{$relationName}(); - - if (isset($nestedOperations['create'])) { - self::handleMultiRelationCreate(new Collection($nestedOperations['create']), $relation); - } - }; - $hasMany->each($createOneToMany); - $morphMany->each($createOneToMany); - - $createOneToOne = function (array $nestedOperations, string $relationName) use ($model): void { - /** @var \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation */ - $relation = $model->{$relationName}(); - - if (isset($nestedOperations['create'])) { - self::handleSingleRelationCreate(new Collection($nestedOperations['create']), $relation); - } - }; - $hasOne->each($createOneToOne); - $morphOne->each($createOneToOne); - - $createManyToMany = function (array $nestedOperations, string $relationName) use ($model): void { - /** @var \Illuminate\Database\Eloquent\Relations\BelongsToMany|\Illuminate\Database\Eloquent\Relations\MorphToMany $relation */ - $relation = $model->{$relationName}(); - - if (isset($nestedOperations['sync'])) { - $relation->sync($nestedOperations['sync']); - } - - if (isset($nestedOperations['create'])) { - self::handleMultiRelationCreate(new Collection($nestedOperations['create']), $relation); - } - - if (isset($nestedOperations['update'])) { - (new Collection($nestedOperations['update']))->each(function ($singleValues) use ($relation): void { - self::executeUpdate( - $relation->getModel()->newInstance(), - new Collection($singleValues), - $relation - ); - }); - } - - if (isset($nestedOperations['connect'])) { - $relation->attach($nestedOperations['connect']); - } - }; - $belongsToMany->each($createManyToMany); - $morphToMany->each($createManyToMany); - - return $model; - } - - /** - * Save a model that maybe has a parent. - * - * @param \Illuminate\Database\Eloquent\Model $model - * @param \Illuminate\Support\Collection $args - * @param \Illuminate\Database\Eloquent\Relations\Relation|null $parentRelation - * @return \Illuminate\Database\Eloquent\Model - */ - protected static function saveModelWithPotentialParent(Model $model, Collection $args, ?Relation $parentRelation = null): Model - { - $reflection = new ReflectionClass($model); - - // Extract $morphTo first, as MorphTo extends BelongsTo - [$morphTo, $remaining] = self::partitionArgsByRelationType( - $reflection, - $args, - MorphTo::class - ); - - [$belongsTo, $remaining] = self::partitionArgsByRelationType( - $reflection, - $remaining, - BelongsTo::class - ); - - // Use all the remaining attributes and fill the model - $model->fill( - $remaining->all() - ); - - $belongsTo->each(function (array $nestedOperations, string $relationName) use ($model): void { - /** @var \Illuminate\Database\Eloquent\Relations\BelongsTo $relation */ - $relation = $model->{$relationName}(); - - if (isset($nestedOperations['create'])) { - $belongsToModel = self::executeCreate( - $relation->getModel()->newInstance(), - new Collection($nestedOperations['create']) - ); - $relation->associate($belongsToModel); - } - - if (isset($nestedOperations['connect'])) { - $relation->associate($nestedOperations['connect']); - } - - if (isset($nestedOperations['update'])) { - $belongsToModel = self::executeUpdate( - $relation->getModel()->newInstance(), - new Collection($nestedOperations['update']) - ); - $relation->associate($belongsToModel); - } - - // We proceed with disconnecting/deleting only if the given $values is truthy. - // There is no other information to be passed when issuing those operations, - // but GraphQL forces us to pass some value. It would be unintuitive for - // the end user if the given value had no effect on the execution. - if ($nestedOperations['disconnect'] ?? false) { - $relation->dissociate(); - } - - if ($nestedOperations['delete'] ?? false) { - $relation->delete(); - } - }); - - $morphTo->each(function (array $nestedOperations, string $relationName) use ($model): void { - /** @var \Illuminate\Database\Eloquent\Relations\MorphTo $relation */ - $relation = $model->{$relationName}(); - - // TODO implement create and update once we figure out how to do polymorphic input types https://github.com/nuwave/lighthouse/issues/900 - - if (isset($nestedOperations['connect'])) { - $connectArgs = $nestedOperations['connect']; - - $morphToModel = $relation->createModelByType( - (string) $connectArgs['type'] - ); - $morphToModel->setAttribute( - $morphToModel->getKeyName(), - $connectArgs['id'] - ); - - $relation->associate($morphToModel); - } - - // We proceed with disconnecting/deleting only if the given $values is truthy. - // There is no other information to be passed when issuing those operations, - // but GraphQL forces us to pass some value. It would be unintuitive for - // the end user if the given value had no effect on the execution. - if ($nestedOperations['disconnect'] ?? false) { - $relation->dissociate(); - } - - if ($nestedOperations['delete'] ?? false) { - $relation->delete(); - } - }); - - if ($parentRelation && ! $parentRelation instanceof BelongsToMany) { - // If we are already resolving a nested create, we might - // already have an instance of the parent relation available. - // In that case, use it to set the current model as a child. - $parentRelation->save($model); - - return $model; - } - - $model->save(); - - if ($parentRelation instanceof BelongsToMany) { - $parentRelation->syncWithoutDetaching($model); - } - - return $model; - } - - /** - * Handle the creation with multiple relations. - * - * @param \Illuminate\Support\Collection $multiValues - * @param \Illuminate\Database\Eloquent\Relations\Relation $relation - * @return void - */ - 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 a single relation. - * - * @param \Illuminate\Support\Collection $singleValues - * @param \Illuminate\Database\Eloquent\Relations\Relation $relation - * @return void - */ - protected static function handleSingleRelationCreate(Collection $singleValues, Relation $relation): void - { - self::executeCreate( - $relation->getModel()->newInstance(), - $singleValues, - $relation - ); - } - - /** - * Execute an update mutation. - * - * @param \Illuminate\Database\Eloquent\Model $model - * An empty instance of the model that should be updated - * @param \Illuminate\Support\Collection $args - * The corresponding slice of the input arguments for updating this model - * @param \Illuminate\Database\Eloquent\Relations\Relation|null $parentRelation - * If we are in a nested update, we can use this to associate the new model to its parent - * @return \Illuminate\Database\Eloquent\Model - */ - public static function executeUpdate(Model $model, Collection $args, ?Relation $parentRelation = null): Model - { - $id = $args->pull('id') - ?? $args->pull( - $model->getKeyName() - ); - - $model = $model->newQuery()->findOrFail($id); - - $reflection = new ReflectionClass($model); - - [$hasMany, $remaining] = self::partitionArgsByRelationType($reflection, $args, HasMany::class); - - [$morphMany, $remaining] = self::partitionArgsByRelationType($reflection, $remaining, MorphMany::class); - - [$hasOne, $remaining] = self::partitionArgsByRelationType($reflection, $remaining, HasOne::class); - - [$morphOne, $remaining] = self::partitionArgsByRelationType($reflection, $remaining, MorphOne::class); - - [$belongsToMany, $remaining] = self::partitionArgsByRelationType($reflection, $remaining, BelongsToMany::class); - - [$morphToMany, $remaining] = self::partitionArgsByRelationType($reflection, $remaining, MorphToMany::class); - - $model = self::saveModelWithPotentialParent($model, $remaining, $parentRelation); - - $updateOneToMany = function (array $nestedOperations, string $relationName) use ($model): void { - /** @var \Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Eloquent\Relations\MorphMany $relation */ - $relation = $model->{$relationName}(); - - if (isset($nestedOperations['create'])) { - self::handleMultiRelationCreate(new Collection($nestedOperations['create']), $relation); - } - - if (isset($nestedOperations['update'])) { - (new Collection($nestedOperations['update']))->each(function ($singleValues) use ($relation): void { - self::executeUpdate( - $relation->getModel()->newInstance(), - new Collection($singleValues), - $relation - ); - }); - } - - if (isset($nestedOperations['delete'])) { - $relation->getModel()::destroy($nestedOperations['delete']); - } - }; - $hasMany->each($updateOneToMany); - $morphMany->each($updateOneToMany); - - $updateOneToOne = function (array $nestedOperations, string $relationName) use ($model): void { - /** @var \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne $relation */ - $relation = $model->{$relationName}(); - - if (isset($nestedOperations['create'])) { - self::handleSingleRelationCreate(new Collection($nestedOperations['create']), $relation); - } - - if (isset($nestedOperations['update'])) { - self::executeUpdate( - $relation->getModel()->newInstance(), - new Collection($nestedOperations['update']), - $relation - ); - } - - if (isset($nestedOperations['delete'])) { - $relation->getModel()::destroy($nestedOperations['delete']); - } - }; - $hasOne->each($updateOneToOne); - $morphOne->each($updateOneToOne); - - $updateManyToMany = function (array $nestedOperations, string $relationName) use ($model): void { - /** @var \Illuminate\Database\Eloquent\Relations\BelongsToMany|\Illuminate\Database\Eloquent\Relations\MorphToMany $relation */ - $relation = $model->{$relationName}(); - - if (isset($nestedOperations['sync'])) { - $relation->sync($nestedOperations['sync']); - } - - if (isset($nestedOperations['create'])) { - self::handleMultiRelationCreate(new Collection($nestedOperations['create']), $relation); - } - - if (isset($nestedOperations['update'])) { - (new Collection($nestedOperations['update']))->each(function ($singleValues) use ($relation): void { - self::executeUpdate( - $relation->getModel()->newInstance(), - new Collection($singleValues), - $relation - ); - }); - } - - if (isset($nestedOperations['delete'])) { - $relation->detach($nestedOperations['delete']); - $relation->getModel()::destroy($nestedOperations['delete']); - } - - if (isset($nestedOperations['connect'])) { - $relation->attach($nestedOperations['connect']); - } - - if (isset($nestedOperations['disconnect'])) { - $relation->detach($nestedOperations['disconnect']); - } - }; - $belongsToMany->each($updateManyToMany); - $morphToMany->each($updateManyToMany); - - return $model; - } - - /** - * Extract all the arguments that correspond to a relation of a certain type on the model. - * - * For example, if the args input looks like this: - * - * [ - * 'comments' => - * ['foo' => 'Bar'], - * 'name' => 'Ralf', - * ] - * - * and the model has a method "comments" that returns a HasMany relationship, - * the result will be: - * [ - * [ - * 'comments' => - * ['foo' => 'Bar'], - * ], - * [ - * 'name' => 'Ralf', - * ] - * ] - * - * @param \ReflectionClass $modelReflection - * @param \Illuminate\Support\Collection $args - * @param string $relationClass - * @return \Illuminate\Support\Collection [relationshipArgs, remainingArgs] - */ - 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 is_a($returnType->getName(), $relationClass, true); - } - ); - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/QueryAST.php b/vendor/nuwave/lighthouse/src/Execution/QueryAST.php deleted file mode 100644 index 4b1d168..0000000 --- a/vendor/nuwave/lighthouse/src/Execution/QueryAST.php +++ /dev/null @@ -1,76 +0,0 @@ -definitions = new Collection($documentNode->definitions); - } - - /** - * Create a new instance from a query string. - * - * @param string $query - * @return static - */ - public static function fromSource(string $query): self - { - return new static( - Parser::parse($query) - ); - } - - /** - * Get all operation definitions. - * - * @return \Illuminate\Support\Collection<\GraphQL\Language\AST\OperationDefinitionNode> - */ - public function operationDefinitions(): Collection - { - return $this->definitionsByType(OperationDefinitionNode::class); - } - - /** - * Get all fragment definitions. - * - * @return \Illuminate\Support\Collection<\GraphQL\Language\AST\FragmentDefinitionNode> - */ - public function fragmentDefinitions(): Collection - { - return $this->definitionsByType(FragmentDefinitionNode::class); - } - - /** - * Get all definitions of a given type. - * - * @param string $typeClassName - * @return \Illuminate\Support\Collection - */ - protected function definitionsByType(string $typeClassName): Collection - { - return $this->definitions - ->filter(function (Node $node) use ($typeClassName): bool { - return $node instanceof $typeClassName; - }); - } -} diff --git a/vendor/nuwave/lighthouse/src/Execution/ReportingErrorHandler.php b/vendor/nuwave/lighthouse/src/Execution/ReportingErrorHandler.php new file mode 100644 index 0000000..40d97f7 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ReportingErrorHandler.php @@ -0,0 +1,44 @@ +exceptionHandler = $exceptionHandler; + } + + public function __invoke(?Error $error, Closure $next): ?array + { + if ($error === null) { + return $next(null); + } + + // Client-safe errors are assumed to be something that a client can handle + // or is expected to happen, e.g. wrong syntax, authentication or validation + if ($error->isClientSafe()) { + return $next($error); + } + + $previous = $error->getPrevious(); + if ($previous !== null) { + // @phpstan-ignore-next-line Laravel versions prior to 7 are limited to accepting \Exception + $this->exceptionHandler->report($previous); + } + + return $next($error); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Resolved.php b/vendor/nuwave/lighthouse/src/Execution/Resolved.php new file mode 100644 index 0000000..e78f997 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Resolved.php @@ -0,0 +1,24 @@ +then($handle); + } + + return $handle($resolved); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/SingleResponse.php b/vendor/nuwave/lighthouse/src/Execution/SingleResponse.php index 1eb18e6..b98b628 100644 --- a/vendor/nuwave/lighthouse/src/Execution/SingleResponse.php +++ b/vendor/nuwave/lighthouse/src/Execution/SingleResponse.php @@ -2,17 +2,11 @@ namespace Nuwave\Lighthouse\Execution; -use Symfony\Component\HttpFoundation\Response; use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; +use Symfony\Component\HttpFoundation\Response; class SingleResponse implements CreatesResponse { - /** - * Create a HTTP response from the final result. - * - * @param mixed[] $result - * @return \Symfony\Component\HttpFoundation\Response - */ public function createResponse(array $result): Response { return response($result); diff --git a/vendor/nuwave/lighthouse/src/Execution/Utils/ModelKey.php b/vendor/nuwave/lighthouse/src/Execution/Utils/ModelKey.php new file mode 100644 index 0000000..87d6e25 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/Utils/ModelKey.php @@ -0,0 +1,24 @@ +getKey()) + ) + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/Utils/Subscription.php b/vendor/nuwave/lighthouse/src/Execution/Utils/Subscription.php index 93aa191..527c4c0 100644 --- a/vendor/nuwave/lighthouse/src/Execution/Utils/Subscription.php +++ b/vendor/nuwave/lighthouse/src/Execution/Utils/Subscription.php @@ -2,32 +2,27 @@ namespace Nuwave\Lighthouse\Execution\Utils; -use Throwable; use InvalidArgumentException; -use Nuwave\Lighthouse\GraphQL; -use Nuwave\Lighthouse\Subscriptions\SubscriptionRegistry; +use Nuwave\Lighthouse\Schema\SchemaBuilder; use Nuwave\Lighthouse\Subscriptions\Contracts\BroadcastsSubscriptions; use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionExceptionHandler; +use Nuwave\Lighthouse\Subscriptions\SubscriptionRegistry; +use Throwable; class Subscription { /** * Broadcast subscription to client(s). * - * @param string $subscriptionField - * @param mixed $root - * @param bool|null $shouldQueue - * @return void - * * @throws \InvalidArgumentException */ public static function broadcast(string $subscriptionField, $root, ?bool $shouldQueue = null): void { // Ensure we have a schema and registered subscription fields // in the event we are calling this method in code. - /** @var \Nuwave\Lighthouse\GraphQL $graphQL */ - $graphQL = app(GraphQL::class); - $graphQL->prepSchema(); + /** @var \Nuwave\Lighthouse\Schema\SchemaBuilder $schemaBuilder */ + $schemaBuilder = app(SchemaBuilder::class); + $schemaBuilder->schema(); /** @var \Nuwave\Lighthouse\Subscriptions\SubscriptionRegistry $registry */ $registry = app(SubscriptionRegistry::class); @@ -39,25 +34,22 @@ class Subscription /** @var \Nuwave\Lighthouse\Subscriptions\Contracts\BroadcastsSubscriptions $broadcaster */ $broadcaster = app(BroadcastsSubscriptions::class); - $shouldQueue = $shouldQueue === null - ? config('lighthouse.subscriptions.queue_broadcasts', false) - : $shouldQueue; + // Default to the configuration setting if not specified + if ($shouldQueue === null) { + $shouldQueue = config('lighthouse.subscriptions.queue_broadcasts', false); + } - $method = $shouldQueue - ? 'queueBroadcast' - : 'broadcast'; + $subscription = $registry->subscription($subscriptionField); try { - call_user_func( - [$broadcaster, $method], - $registry->subscription($subscriptionField), - $subscriptionField, - $root - ); + if ($shouldQueue) { + $broadcaster->queueBroadcast($subscription, $subscriptionField, $root); + } else { + $broadcaster->broadcast($subscription, $subscriptionField, $root); + } } catch (Throwable $e) { /** @var \Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionExceptionHandler $exceptionHandler */ $exceptionHandler = app(SubscriptionExceptionHandler::class); - $exceptionHandler->handleBroadcastError($e); } } diff --git a/vendor/nuwave/lighthouse/src/Execution/ValidationErrorHandler.php b/vendor/nuwave/lighthouse/src/Execution/ValidationErrorHandler.php new file mode 100644 index 0000000..1c4ddc5 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ValidationErrorHandler.php @@ -0,0 +1,36 @@ +getPrevious(); + if ($underlyingException instanceof LaravelValidationException) { + return $next(new Error( + $error->getMessage(), + // @phpstan-ignore-next-line graphql-php and phpstan disagree with themselves + $error->getNodes(), + $error->getSource(), + $error->getPositions(), + $error->getPath(), + ValidationException::fromLaravel($underlyingException) + )); + } + + return $next($error); + } +} diff --git a/vendor/nuwave/lighthouse/src/Execution/ValidationRulesProvider.php b/vendor/nuwave/lighthouse/src/Execution/ValidationRulesProvider.php new file mode 100644 index 0000000..d89929d --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Execution/ValidationRulesProvider.php @@ -0,0 +1,32 @@ +configRepository = $configRepository; + } + + public function validationRules(): ?array + { + return [ + QueryComplexity::class => new QueryComplexity($this->configRepository->get('lighthouse.security.max_query_complexity', 0)), + QueryDepth::class => new QueryDepth($this->configRepository->get('lighthouse.security.max_query_depth', 0)), + DisableIntrospection::class => new DisableIntrospection($this->configRepository->get('lighthouse.security.disable_introspection', 0)), + ] + DocumentValidator::defaultRules(); + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/ASTManipulator.php b/vendor/nuwave/lighthouse/src/Federation/ASTManipulator.php new file mode 100644 index 0000000..87b87e8 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/ASTManipulator.php @@ -0,0 +1,100 @@ +documentAST; + + $this->addScalars($documentAST); + $this->addEntityUnion($documentAST); + $this->addRootFields($documentAST); + $this->addServiceType($documentAST); + } + + protected function addScalars(DocumentAST &$documentAST): void + { + $documentAST->setTypeDefinition( + Parser::scalarTypeDefinition(/** @lang GraphQL */ ' + scalar _Any @scalar(class: "Nuwave\\\Lighthouse\\\Federation\\\Types\\\Any") + ') + ); + + $documentAST->setTypeDefinition( + Parser::scalarTypeDefinition(/** @lang GraphQL */ ' + scalar _FieldSet @scalar(class: "Nuwave\\\Lighthouse\\\Federation\\\Types\\\FieldSet") + ') + ); + } + + /** + * Combine object types with `@key` into the _Entity union. + * + * @throws \Nuwave\Lighthouse\Exceptions\FederationException + */ + protected function addEntityUnion(DocumentAST &$documentAST): void + { + /** @var array $entities */ + $entities = []; + + foreach ($documentAST->types as $type) { + if (! $type instanceof ObjectTypeDefinitionNode) { + continue; + } + + /** @var \GraphQL\Language\AST\DirectiveNode $directive */ + foreach ($type->directives as $directive) { + if ($directive->name->value === 'key') { + $entities[] = $type->name->value; + break; + } + } + } + + if (count($entities) === 0) { + throw new FederationException('There must be at least one type using the @key directive when federation is enabled.'); + } + + $entitiesString = implode(' | ', $entities); + $documentAST->setTypeDefinition( + Parser::unionTypeDefinition(/** @lang GraphQL */ " + union _Entity = {$entitiesString} + ") + ); + } + + protected function addRootFields(DocumentAST &$documentAST): void + { + /** @var \GraphQL\Language\AST\ObjectTypeDefinitionNode $queryType */ + $queryType = $documentAST->types['Query']; + + $queryType->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ ' + _entities( + representations: [_Any!]! + ): [_Entity]! @field(resolver: "Nuwave\\\Lighthouse\\\Federation\\\Resolvers\\\Entities") + '); + + $queryType->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ ' + _service: _Service! @field(resolver: "Nuwave\\\Lighthouse\\\Federation\\\Resolvers\\\Service") + '); + } + + protected function addServiceType(DocumentAST &$documentAST): void + { + $documentAST->setTypeDefinition( + Parser::objectTypeDefinition(/** @lang GraphQL */ ' + type _Service { + sdl: String + } + ') + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/Directives/ExtendsDirective.php b/vendor/nuwave/lighthouse/src/Federation/Directives/ExtendsDirective.php new file mode 100644 index 0000000..cde062e --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/Directives/ExtendsDirective.php @@ -0,0 +1,30 @@ +setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { + // The parent might just hold a foreign key to the external object, in which case we just return that. + return is_scalar($root) + ? $root + : (Executor::getDefaultFieldResolver())($root, $args, $context, $resolveInfo); + }); + + return $fieldValue; + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/Directives/KeyDirective.php b/vendor/nuwave/lighthouse/src/Federation/Directives/KeyDirective.php new file mode 100644 index 0000000..a46aaa9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/Directives/KeyDirective.php @@ -0,0 +1,44 @@ +directiveArgValue('fields'); + if (! is_string($fields)) { + throw new DefinitionException('Argument `fields` on the `@key` directive is required.'); + } + + // Grammatically, a field set is a selection set minus the braces. + // https://www.apollographql.com/docs/federation/federation-spec/#scalar-_fieldset + return Parser::selectionSet("{ {$fields} }"); + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/Directives/ProvidesDirective.php b/vendor/nuwave/lighthouse/src/Federation/Directives/ProvidesDirective.php new file mode 100644 index 0000000..83ecac0 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/Directives/ProvidesDirective.php @@ -0,0 +1,44 @@ + + */ + protected $definitions; + + /** + * Maps from __typename to resolver. + * + * @var array): mixed> + */ + protected $resolvers; + + public function __construct(SchemaBuilder $schemaBuilder, DirectiveLocator $directiveLocator, ConfigRepository $configRepository) + { + $this->schema = $schemaBuilder->schema(); + $this->directiveLocator = $directiveLocator; + $this->configRepository = $configRepository; + } + + public static function missingResolver(string $typename): string + { + return "Could not locate a resolver for __typename `{$typename}`."; + } + + public static function unknownTypename(string $typename): string + { + return "Unknown __typename `{$typename}`."; + } + + /** + * @return \Closure(array $representations): mixed + */ + public function resolver(string $typename): Closure + { + if (isset($this->resolvers[$typename])) { + return $this->resolvers[$typename]; + } + + $resolver = $this->resolverFromClass($typename) + ?? $this->resolverFromModel($typename) + ?? null; + + if ($resolver === null) { + throw new Error(self::missingResolver($typename)); + } + + $this->resolvers[$typename] = $resolver; + + return $resolver; + } + + public function typeDefinition(string $typename): ObjectTypeDefinitionNode + { + if (isset($this->definitions[$typename])) { + return $this->definitions[$typename]; + } + + $type = null; + try { + $type = $this->schema->getType($typename); + } catch (DefinitionException $definitionException) { + // Signalizes the type is unknown, handled by the null check below + } + if ($type === null) { + throw new Error(self::unknownTypename($typename)); + } + + /** + * TODO remove when upgrading graphql-php. + * + * @var (\GraphQL\Language\AST\Node&\GraphQL\Language\AST\TypeDefinitionNode)|null $definition + */ + $definition = $type->astNode; + if ($definition === null) { + throw new FederationException("Must provide AST definition for type `{$typename}`."); + } + + if (! $definition instanceof ObjectTypeDefinitionNode) { + throw new Error("Expected __typename `{$typename}` to be ObjectTypeDefinition, got {$definition->kind}."); + } + + $this->definitions[$typename] = $definition; + + return $definition; + } + + protected function resolverFromClass(string $typename): ?Closure + { + $resolverClass = Utils::namespaceClassname( + $typename, + (array) config('lighthouse.federation.entities_resolver_namespace'), + 'class_exists' + ); + + if ($resolverClass === null) { + return null; + } + + return Utils::constructResolver($resolverClass, '__invoke'); + } + + protected function resolverFromModel(string $typeName): ?Closure + { + $definition = $this->typeDefinition($typeName); + + $model = ModelDirective::modelClass($definition) ?? $typeName; + + /** @var class-string<\Illuminate\Database\Eloquent\Model>|null $modelClass */ + $modelClass = Utils::namespaceClassname( + $model, + (array) $this->configRepository->get('lighthouse.namespaces.models'), + static function (string $classCandidate): bool { + return is_subclass_of($classCandidate, Model::class); + } + ); + if ($modelClass === null) { + return null; + } + + $keyFieldsSelections = $this->keyFieldsSelections($definition); + + return function (array $representation) use ($keyFieldsSelections, $modelClass): ?Model { + /** @var \Illuminate\Database\Eloquent\Builder $builder */ + $builder = $modelClass::query(); + $this->constrainKeys($builder, $keyFieldsSelections, $representation); + + $results = $builder->get(); + if ($results->count() > 1) { + throw new Error('The query returned more than one result.'); + } + + return $results->first(); + }; + } + + /** + * @param \Illuminate\Support\Collection<\GraphQL\Language\AST\SelectionSetNode> $keyFieldsSelections + * @param array $representation + */ + protected function constrainKeys(Builder $builder, Collection $keyFieldsSelections, array $representation): void + { + $this->applySatisfiedSelection( + $builder, + $this->firstSatisfiedKeyFields($keyFieldsSelections, $representation), + $representation + ); + } + + /** + * @param array $representation + */ + protected function satisfiesKeyFields(SelectionSetNode $keyFields, array $representation): bool + { + /** + * Fragments or spreads are not allowed in key fields. + * @see \Nuwave\Lighthouse\Federation\SchemaValidator + * + * @var \GraphQL\Language\AST\FieldNode $field + */ + foreach ($keyFields->selections as $field) { + $fieldName = $field->name->value; + $value = $representation[$fieldName] ?? null; + if ($value === null) { + return false; + } + + $subSelection = $field->selectionSet; + if ($subSelection !== null) { + if (! is_array($value)) { + return false; + } + + $subSelectionProvidesKeys = $this->satisfiesKeyFields($subSelection, $value); + if (! $subSelectionProvidesKeys) { + return false; + } + } + } + + return true; + } + + /** + * @param array $representation + */ + protected function applySatisfiedSelection(Builder $builder, SelectionSetNode $keyFields, array $representation): void + { + /** + * Fragments or spreads are not allowed in key fields. + * + * @var \GraphQL\Language\AST\FieldNode $field + */ + foreach ($keyFields->selections as $field) { + $fieldName = $field->name->value; + $value = $representation[$fieldName]; + + $subSelection = $field->selectionSet; + if ($subSelection === null) { + $builder->where($fieldName, $value); + + return; + } + + $this->applySatisfiedSelection($builder, $subSelection, $representation); + } + } + + /** + * @return \Illuminate\Support\Collection<\GraphQL\Language\AST\SelectionSetNode> + */ + public function keyFieldsSelections(ObjectTypeDefinitionNode $definition): Collection + { + return $this->directiveLocator + ->associatedOfType($definition, KeyDirective::class) + ->map(static function (KeyDirective $keyDirective): SelectionSetNode { + return $keyDirective->fields(); + }); + } + + /** + * @param \Illuminate\Support\Collection<\GraphQL\Language\AST\SelectionSetNode> $keyFieldsSelections + * @param array $representation + */ + public function firstSatisfiedKeyFields(Collection $keyFieldsSelections, array $representation): SelectionSetNode + { + $satisfiedKeyFields = $keyFieldsSelections->first( + function (SelectionSetNode $keyFields) use ($representation): bool { + return $this->satisfiesKeyFields($keyFields, $representation); + } + ); + + if ($satisfiedKeyFields === null) { + throw new Error('Representation does not satisfy any set of uniquely identifying keys: '.\Safe\json_encode($representation)); + } + + return $satisfiedKeyFields; + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/FederationPrinter.php b/vendor/nuwave/lighthouse/src/Federation/FederationPrinter.php new file mode 100644 index 0000000..5363c77 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/FederationPrinter.php @@ -0,0 +1,124 @@ +getTypeMap(); + foreach (self::FEDERATION_TYPES as $type) { + unset($types[$type]); + } + + $originalQueryType = Arr::pull($types, 'Query'); + $config->setQuery(new ObjectType([ + 'name' => 'Query', + 'fields' => array_filter( + $originalQueryType->getFields(), + static function (FieldDefinition $field): bool { + return ! in_array($field->name, static::FEDERATION_FIELDS); + } + ), + 'interfaces' => $originalQueryType->getInterfaces(), + ])); + + $config->setMutation(Arr::pull($types, 'Mutation')); + + $config->setSubscription(Arr::pull($types, 'Subscription')); + + $config->setTypes($types); + + $config->setDirectives(array_filter( + $schema->getDirectives(), + static function (Directive $directive): bool { + return ! in_array($directive->name, static::FEDERATION_DIRECTIVES); + } + )); + + $printDirectives = static function ($definition): string { + /** @var Type|EnumValueDefinition|FieldArgument|FieldDefinition|InputObjectField $definition */ + $astNode = $definition->astNode; + if ($astNode === null) { + return ''; + } + + if ($astNode instanceof ObjectTypeDefinitionNode) { + return SchemaPrinter::printDirectives( + Utils::filter( + $astNode->directives, + static function (DirectiveNode $directive): bool { + $name = $directive->name->value; + + return $name === KeyDirective::NAME + || $name === ExtendsDirective::NAME; + } + ) + ); + } elseif ($astNode instanceof FieldDefinitionNode) { + return SchemaPrinter::printDirectives( + Utils::filter( + $astNode->directives, + static function (DirectiveNode $directive): bool { + $name = $directive->name->value; + + return $name === ProvidesDirective::NAME + || $name === RequiresDirective::NAME + || $name === ExternalDirective::NAME; + } + ) + ); + } + + return ''; + }; + + return SchemaPrinter::doPrint( + new Schema($config), + // @phpstan-ignore-next-line We extended the SchemaPrinter to allow for this option + ['printDirectives' => $printDirectives] + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/FederationServiceProvider.php b/vendor/nuwave/lighthouse/src/Federation/FederationServiceProvider.php new file mode 100644 index 0000000..1c15313 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/FederationServiceProvider.php @@ -0,0 +1,30 @@ +app->singleton(EntityResolverProvider::class); + } + + public function boot(EventsDispatcher $eventsDispatcher): void + { + $eventsDispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__.'\\Directives'; + } + ); + + $eventsDispatcher->listen(ManipulateAST::class, ASTManipulator::class); + $eventsDispatcher->listen(ValidateSchema::class, SchemaValidator::class); + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/Resolvers/Entities.php b/vendor/nuwave/lighthouse/src/Federation/Resolvers/Entities.php new file mode 100644 index 0000000..94c6dba --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/Resolvers/Entities.php @@ -0,0 +1,43 @@ +entityResolverProvider = $entityResolverProvider; + } + + /** + * @param array{representations: array} $args + * @return list + */ + public function __invoke($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): array + { + $results = []; + + foreach ($args['representations'] as $representation) { + $typename = $representation['__typename']; + $resolver = $this->entityResolverProvider->resolver($typename); + + $results [] = $resolver($representation); + } + + return $results; + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/Resolvers/Service.php b/vendor/nuwave/lighthouse/src/Federation/Resolvers/Service.php new file mode 100644 index 0000000..d4dbded --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/Resolvers/Service.php @@ -0,0 +1,21 @@ + $args Always empty + * @return array{sdl: string} + */ + public function __invoke($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): array + { + return [ + 'sdl' => FederationPrinter::print($resolveInfo->schema), + ]; + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/SchemaPrinter.php b/vendor/nuwave/lighthouse/src/Federation/SchemaPrinter.php new file mode 100644 index 0000000..6e2582a --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/SchemaPrinter.php @@ -0,0 +1,113 @@ + $options + * @param \GraphQL\Type\Definition\ObjectType|\GraphQL\Type\Definition\InterfaceType $type + */ + protected static function printFields(array $options, $type): string + { + $firstInBlock = true; + + return implode( + "\n", + array_map( + static function (FieldDefinition $f) use (&$firstInBlock, $options): string { + $description = static::printDescription($options, $f, ' ', $firstInBlock) + .' ' + .$f->name + .static::printArgs($options, $f->args, ' ') + .': ' + .(string) $f->getType() + .(isset($options['printDirectives']) + ? $options['printDirectives']($f) + : '') + .static::printDeprecated($f); + + $firstInBlock = false; + + return $description; + }, + $type->getFields() + ) + ); + } + + /** + * @param array $options + */ + protected static function printObject(ObjectType $type, array $options): string + { + return static::printObjectLike('type', $type, $options); + } + + /** + * @param array $options + */ + protected static function printInterface(InterfaceType $type, array $options): string + { + return static::printObjectLike('interface', $type, $options); + } + + /** + * @param \GraphQL\Type\Definition\ObjectType|\GraphQL\Type\Definition\InterfaceType $type + * @param array $options + */ + protected static function printObjectLike(string $kind, Type $type, array $options): string + { + $interfaces = $type->getInterfaces(); + $implementedInterfaces = count($interfaces) > 0 + ? ' implements '.implode( + ' & ', + array_map( + static function (InterfaceType $interface): string { + return $interface->name; + }, + $interfaces + ) + ) + : ''; + + $description = static::printDescription($options, $type); + $directives = isset($options['printDirectives']) + ? $options['printDirectives']($type) + : ''; + $fields = static::printFields($options, $type); + + return <<name}{$implementedInterfaces}{$directives} { +{$fields} +} +GRAPHQL; + } + + /** + * @param array<\GraphQL\Language\AST\DirectiveNode> $directives + */ + public static function printDirectives(array $directives): string + { + if (count($directives) === 0) { + return ''; + } + + return ' ' + .implode( + ' ', + Utils::map($directives, static function (DirectiveNode $directive): string { + return Printer::doPrint($directive); + }) + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/SchemaValidator.php b/vendor/nuwave/lighthouse/src/Federation/SchemaValidator.php new file mode 100644 index 0000000..ff6b5cf --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/SchemaValidator.php @@ -0,0 +1,91 @@ +directiveLocator = $directiveLocator; + } + + public function handle(ValidateSchema $validateSchema): void + { + $schema = $validateSchema->schema; + + foreach ($schema->getTypeMap() as $type) { + if ($type instanceof ObjectType) { + $this->validateObjectType($type); + } + } + } + + protected function validateObjectType(ObjectType $type): void + { + $ast = $type->astNode; + if ($ast !== null) { + $directives = $this->directiveLocator->associated($ast); + + /** @var \Nuwave\Lighthouse\Support\Contracts\Directive $directive */ + foreach ($directives as $directive) { + if ($directive instanceof KeyDirective) { + $this->validateKeySelectionSet($directive->fields(), $type); + } + } + } + } + + /** + * @throws \Nuwave\Lighthouse\Exceptions\FederationException + */ + protected function validateKeySelectionSet(SelectionSetNode $selectionSet, ObjectType $type): void + { + foreach ($selectionSet->selections as $selection) { + if (! $selection instanceof FieldNode) { + throw new FederationException("Must only use field selections in the `fields` argument of @key, got: {$selection->kind}."); + } + + try { + // Throws if the field is not defined + $field = $type->getField($selection->name->value); + } catch (InvariantViolation $i) { + throw new FederationException($i->getMessage(), $i->getCode(), $i); + } + + if ( + ASTHelper::hasDirective($type->astNode, ExtendsDirective::NAME) + && ! ASTHelper::hasDirective($field->astNode, ExternalDirective::NAME) + ) { + throw new FederationException("A @key directive on `{$type->name}` specifies the `{$field->name}` field which has no @external directive."); + } + + $nestedSelection = $selection->selectionSet; + if ($nestedSelection !== null) { + $type = $field->getType(); + if ($type instanceof WrappingType) { + $type = $type->getWrappedType(true); + } + + $this->validateKeySelectionSet($nestedSelection, $type); + } + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/Types/Any.php b/vendor/nuwave/lighthouse/src/Federation/Types/Any.php new file mode 100644 index 0000000..8a4bdd0 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/Types/Any.php @@ -0,0 +1,68 @@ +typeDefinition($typename); + $keyFieldsSelections = $entityResolverProvider->keyFieldsSelections($definition); + $entityResolverProvider->firstSatisfiedKeyFields($keyFieldsSelections, $value); + + // Ensure we actually have a resolver for the type available + $entityResolverProvider->resolver($typename); + + // @phpstan-ignore-next-line type inference is too weak + return $value; + } + + /** + * @return array{__typename: string} + */ + public function parseLiteral($valueNode, ?array $variables = null): array + { + return $this->parseValue( + AST::valueFromASTUntyped($valueNode) + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Federation/Types/FieldSet.php b/vendor/nuwave/lighthouse/src/Federation/Types/FieldSet.php new file mode 100644 index 0000000..36912ae --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Federation/Types/FieldSet.php @@ -0,0 +1,24 @@ +globalId = $globalId; + } + + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Converts between IDs/types and global IDs. + +When used upon a field, it encodes; +when used upon an argument, it decodes. +""" +directive @globalId( + """ + Decoding a global id produces a tuple of `$type` and `$id`. + This setting controls which of those is passed along. + """ + decode: GlobalIdDecode = ARRAY +) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION + +""" +Options for the `decode` argument of `@globalId`. +""" +enum GlobalIdDecode { + """ + Return an array of `[$type, $id]`. + """ + ARRAY + + """ + Return just `$type`. + """ + TYPE + + """ + Return just `$id`. + """ + ID +} +GRAPHQL; + } + + public function handleField(FieldValue $fieldValue, Closure $next): FieldValue + { + $type = $fieldValue->getParentName(); + + $fieldValue->resultHandler(function ($result) use ($type) { + if (null === $result) { + return null; + } + + return $this->globalId->encode($type, $result); + }); + + return $next($fieldValue); + } + + /** + * Decodes a global id given as an argument. + * + * @param string|null $argumentValue + * @return string|array{0: string, 1: string}|null + */ + public function sanitize($argumentValue) + { + if (null === $argumentValue) { + return null; + } + + $decode = $this->directiveArgValue('decode'); + if (null !== $decode) { + switch ($decode) { + case 'TYPE': + return $this->globalId->decodeType($argumentValue); + case 'ID': + return $this->globalId->decodeID($argumentValue); + case 'ARRAY': + return $this->globalId->decode($argumentValue); + default: + throw new DefinitionException( + "The decode argument of the @globalId directive can only be TYPE, ARRAY or ID, got {$decode}" + ); + } + } + + return $this->globalId->decode($argumentValue); + } +} diff --git a/vendor/nuwave/lighthouse/src/GlobalId/GlobalIdException.php b/vendor/nuwave/lighthouse/src/GlobalId/GlobalIdException.php new file mode 100644 index 0000000..d144c3a --- /dev/null +++ b/vendor/nuwave/lighthouse/src/GlobalId/GlobalIdException.php @@ -0,0 +1,18 @@ +app->bind(GlobalIdContract::class, GlobalId::class); + $this->app->singleton(NodeRegistry::class); + } + + public function boot(Dispatcher $dispatcher): void + { + $dispatcher->listen( + ManipulateAST::class, + function (ManipulateAST $manipulateAST): void { + $documentAST = $manipulateAST->documentAST; + $this->addNodeSupport($documentAST); + } + ); + + $dispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } + ); + } + + /** + * Inject the Node interface and a node field into the Query type. + */ + protected function addNodeSupport(DocumentAST $documentAST): void + { + // Only add the node type and node field if a type actually implements them + // Otherwise, a validation error is thrown + if (! $this->hasTypeImplementingInterface($documentAST, 'Node')) { + return; + } + + $globalId = config('lighthouse.global_id_field'); + // Double slashes to escape the slashes in the namespace. + $documentAST->setTypeDefinition( + Parser::interfaceTypeDefinition(/** @lang GraphQL */ <<types[RootType::QUERY]; + $queryType->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ ' + node(id: ID! @globalId): Node @field(resolver: "Nuwave\\\Lighthouse\\\GlobalId\\\NodeRegistry@resolve") + '); + } + + /** + * Returns whether or not the given interface is used within the defined types. + */ + protected function hasTypeImplementingInterface(DocumentAST $documentAST, string $interfaceName): bool + { + foreach ($documentAST->types as $typeDefinition) { + if ( + $typeDefinition instanceof ObjectTypeDefinitionNode + && ASTHelper::typeImplementsInterface($typeDefinition, $interfaceName) + ) { + return true; + } + } + + return false; + } +} diff --git a/vendor/nuwave/lighthouse/src/GlobalId/NodeDirective.php b/vendor/nuwave/lighthouse/src/GlobalId/NodeDirective.php new file mode 100644 index 0000000..fdcff6e --- /dev/null +++ b/vendor/nuwave/lighthouse/src/GlobalId/NodeDirective.php @@ -0,0 +1,100 @@ +nodeRegistry = $nodeRegistry; + } + + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Register a type for Relay's global object identification. + +When used without any arguments, Lighthouse will attempt +to resolve the type through a model with the same name. +""" +directive @node( + """ + Reference to a function that receives the decoded `id` and returns a result. + Consists of two parts: a class name and a method name, seperated by an `@` symbol. + If you pass only a class name, the method name defaults to `__invoke`. + + Mutually exclusive with the `model` argument. + """ + resolver: String + + """ + Specify the class name of the model to use. + This is only needed when the default model detection does not work. + + Mutually exclusive with the `model` argument. + """ + model: String +) on OBJECT +GRAPHQL; + } + + public function handleNode(TypeValue $value, Closure $next): Type + { + if ($this->directiveHasArgument('resolver')) { + $resolver = $this->getResolverFromArgument('resolver'); + } else { + $resolver = function ($id): ?Model { + /** @var \Illuminate\Database\Eloquent\Model|null $model */ + $model = $this->getModelClass()::find($id); + + return $model; + }; + } + + $this->nodeRegistry->registerNode( + $value->getTypeDefinitionName(), + $resolver + ); + + return $next($value); + } + + /** + * @param \GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node $typeDefinition + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition): void + { + if (! $typeDefinition instanceof ObjectTypeDefinitionNode) { + throw new DefinitionException( + "The {$this->name()} directive must only be used on object type definitions, not on {$typeDefinition->kind} {$typeDefinition->name->value}." + ); + } + + /** @var \GraphQL\Language\AST\NamedTypeNode $namedTypeNode */ + $namedTypeNode = Parser::parseType('Node', ['noLocation' => true]); + $typeDefinition->interfaces [] = $namedTypeNode; + + $globalIdFieldName = config('lighthouse.global_id_field'); + $typeDefinition->fields [] = Parser::fieldDefinition(/** @lang GraphQL */ "{$globalIdFieldName}: ID! @globalId"); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/NodeRegistry.php b/vendor/nuwave/lighthouse/src/GlobalId/NodeRegistry.php similarity index 68% rename from vendor/nuwave/lighthouse/src/Schema/NodeRegistry.php rename to vendor/nuwave/lighthouse/src/GlobalId/NodeRegistry.php index c22e18a..8a6e7a1 100644 --- a/vendor/nuwave/lighthouse/src/Schema/NodeRegistry.php +++ b/vendor/nuwave/lighthouse/src/GlobalId/NodeRegistry.php @@ -1,13 +1,13 @@ */ protected $nodeResolver = []; @@ -35,12 +35,6 @@ class NodeRegistry */ protected $currentType; - /** - * NodeRegistry constructor. - * - * @param \Nuwave\Lighthouse\Schema\TypeRegistry $typeRegistry - * @return void - */ public function __construct(TypeRegistry $typeRegistry) { $this->typeRegistry = $typeRegistry; @@ -70,37 +64,26 @@ class NodeRegistry return $this; } - /** - * Register an Eloquent model that can be resolved as a Node. - * - * @param string $typeName - * @param string $modelName - * @return $this - */ - public function registerModel(string $typeName, string $modelName): self - { - $this->nodeResolver[$typeName] = function ($id) use ($modelName): ?Model { - return $modelName::find($id); - }; - - return $this; - } - /** * Get the appropriate resolver for the node and call it with the decoded id. * - * @param mixed|null $rootValue - * @param mixed[] $args - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return mixed + * @param array $args + * @return mixed The result of calling the resolver. * * @throws \GraphQL\Error\Error */ - public function resolve($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) + public function resolve($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { [$decodedType, $decodedId] = $args['id']; + // This check forces Lighthouse to eagerly load the type, which might not have + // happened if the client only references it indirectly through an interface. + // Loading the type in turn causes the TypeMiddleware to run and thus register + // the type in the NodeRegistry. + if (! $this->typeRegistry->has($decodedType)) { + throw new Error("[{$decodedType}] is not a type and cannot be resolved."); + } + // Check if we have a resolver registered for the given type if (! $resolver = Arr::get($this->nodeResolver, $decodedType)) { throw new Error("[{$decodedType}] is not a registered node and cannot be resolved."); @@ -114,8 +97,6 @@ class NodeRegistry /** * Get the Type for the stashed type. - * - * @return \GraphQL\Type\Definition\Type */ public function resolveType(): Type { diff --git a/vendor/nuwave/lighthouse/src/GraphQL.php b/vendor/nuwave/lighthouse/src/GraphQL.php index b1fd388..4e01543 100644 --- a/vendor/nuwave/lighthouse/src/GraphQL.php +++ b/vendor/nuwave/lighthouse/src/GraphQL.php @@ -2,153 +2,180 @@ namespace Nuwave\Lighthouse; +use GraphQL\Error\DebugFlag; use GraphQL\Error\Error; -use GraphQL\Type\Schema; -use GraphQL\GraphQL as GraphQLBase; +use GraphQL\Error\SyntaxError; use GraphQL\Executor\ExecutionResult; -use GraphQL\Validator\Rules\QueryDepth; -use Nuwave\Lighthouse\Support\Pipeline; -use GraphQL\Validator\DocumentValidator; -use Nuwave\Lighthouse\Schema\SchemaBuilder; -use GraphQL\Validator\Rules\QueryComplexity; -use Nuwave\Lighthouse\Events\StartExecution; -use Nuwave\Lighthouse\Schema\AST\ASTBuilder; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; -use Nuwave\Lighthouse\Events\ManipulateResult; -use Nuwave\Lighthouse\Execution\GraphQLRequest; -use GraphQL\Validator\Rules\DisableIntrospection; -use Nuwave\Lighthouse\Events\BuildExtensionsResponse; -use Nuwave\Lighthouse\Support\Contracts\CreatesContext; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use GraphQL\GraphQL as GraphQLBase; +use GraphQL\Language\Parser; +use GraphQL\Server\Helper as GraphQLHelper; +use GraphQL\Server\OperationParams; +use GraphQL\Server\RequestError; +use GraphQL\Type\Schema; +use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Contracts\Events\Dispatcher as EventDispatcher; +use Illuminate\Pipeline\Pipeline; +use Illuminate\Support\Collection; +use Nuwave\Lighthouse\Events\BuildExtensionsResponse; +use Nuwave\Lighthouse\Events\EndExecution; +use Nuwave\Lighthouse\Events\EndOperationOrOperations; +use Nuwave\Lighthouse\Events\ManipulateResult; +use Nuwave\Lighthouse\Events\StartExecution; +use Nuwave\Lighthouse\Events\StartOperationOrOperations; +use Nuwave\Lighthouse\Execution\BatchLoader\BatchLoaderRegistry; +use Nuwave\Lighthouse\Execution\DataLoader\BatchLoader; +use Nuwave\Lighthouse\Execution\ErrorPool; +use Nuwave\Lighthouse\Schema\SchemaBuilder; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Support\Contracts\ProvidesValidationRules; +use Nuwave\Lighthouse\Support\Utils as LighthouseUtils; +/** + * The main entrypoint to start and end GraphQL execution. + */ class GraphQL { /** - * The executable schema. - * - * @var \GraphQL\Type\Schema - */ - protected $executableSchema; - - /** - * The parsed schema AST. - * - * @var \Nuwave\Lighthouse\Schema\AST\DocumentAST - */ - protected $documentAST; - - /** - * The schema builder. - * * @var \Nuwave\Lighthouse\Schema\SchemaBuilder */ protected $schemaBuilder; /** - * The pipeline. - * - * @var \Nuwave\Lighthouse\Support\Pipeline + * @var \Illuminate\Pipeline\Pipeline */ protected $pipeline; /** - * The event dispatcher. - * * @var \Illuminate\Contracts\Events\Dispatcher */ protected $eventDispatcher; /** - * The AST builder. - * - * @var \Nuwave\Lighthouse\Schema\AST\ASTBuilder + * @var \Nuwave\Lighthouse\Execution\ErrorPool */ - protected $astBuilder; + protected $errorPool; /** - * The context factory. - * - * @var \Nuwave\Lighthouse\Support\Contracts\CreatesContext + * @var \Nuwave\Lighthouse\Support\Contracts\ProvidesValidationRules */ - protected $createsContext; + protected $providesValidationRules; /** - * GraphQL constructor. - * - * @param \Nuwave\Lighthouse\Schema\SchemaBuilder $schemaBuilder - * @param \Nuwave\Lighthouse\Support\Pipeline $pipeline - * @param \Illuminate\Contracts\Events\Dispatcher $eventDispatcher - * @param \Nuwave\Lighthouse\Schema\AST\ASTBuilder $astBuilder - * @param \Nuwave\Lighthouse\Support\Contracts\CreatesContext $createsContext - * @return void + * @var \GraphQL\Server\Helper */ + protected $graphQLHelper; + + /** + * @var \Illuminate\Contracts\Config\Repository + */ + protected $configRepository; + + /** + * Lazily initialized. + * + * @var \Closure( + * array<\GraphQL\Error\Error> $errors, + * callable(\GraphQL\Error\Error $error): ?array + * ): array + */ + protected $errorsHandler; + public function __construct( SchemaBuilder $schemaBuilder, Pipeline $pipeline, EventDispatcher $eventDispatcher, - ASTBuilder $astBuilder, - CreatesContext $createsContext + ErrorPool $errorPool, + ProvidesValidationRules $providesValidationRules, + GraphQLHelper $graphQLHelper, + ConfigRepository $configRepository ) { $this->schemaBuilder = $schemaBuilder; $this->pipeline = $pipeline; $this->eventDispatcher = $eventDispatcher; - $this->astBuilder = $astBuilder; - $this->createsContext = $createsContext; + $this->errorPool = $errorPool; + $this->providesValidationRules = $providesValidationRules; + $this->graphQLHelper = $graphQLHelper; + $this->configRepository = $configRepository; } /** - * Execute a set of batched queries on the lighthouse schema and return a - * collection of ExecutionResults. + * Run one ore more GraphQL operations against the schema. * - * @param \Nuwave\Lighthouse\Execution\GraphQLRequest $request - * @return mixed[] + * @param \GraphQL\Server\OperationParams|array $operationOrOperations + * @return array|array> */ - public function executeRequest(GraphQLRequest $request): array + public function executeOperationOrOperations($operationOrOperations, GraphQLContext $context): array { + $this->eventDispatcher->dispatch( + new StartOperationOrOperations($operationOrOperations) + ); + + $resultOrResults = LighthouseUtils::applyEach( + /** + * @return array + */ + function (OperationParams $operationParams) use ($context): array { + return $this->executeOperation($operationParams, $context); + }, + $operationOrOperations + ); + + $this->eventDispatcher->dispatch( + new EndOperationOrOperations($resultOrResults) + ); + + return $resultOrResults; + } + + /** + * Run a single GraphQL operation against the schema and get a result. + * + * @return array + */ + public function executeOperation(OperationParams $params, GraphQLContext $context): array + { + $errors = $this->graphQLHelper->validateOperationParams($params); + + $query = $params->query; + if (! is_string($query) || $query === '') { + $errors[] = new RequestError( + 'GraphQL Request parameter "query" is required and must not be empty.' + ); + } + + if (count($errors) > 0) { + $errors = array_map( + static function (RequestError $err): Error { + return Error::createLocatedError($err); + }, + $errors + ); + + return $this->serializable( + new ExecutionResult(null, $errors) + ); + } + /** @var string $query Otherwise we would have bailed with an error */ $result = $this->executeQuery( - $request->query(), - $this->createsContext->generate( - app('request') - ), - $request->variables(), + $query, + $context, + $params->variables, null, - $request->operationName() + $params->operation ); - return $this->applyDebugSettings($result); + return $this->serializable($result); } /** - * Apply the debug settings from the config and get the result as an array. + * Execute a GraphQL query on the Lighthouse schema and return the raw result. * - * @param \GraphQL\Executor\ExecutionResult $result - * @return mixed[] - */ - public function applyDebugSettings(ExecutionResult $result): array - { - // If debugging is set to false globally, do not add GraphQL specific - // debugging info either. If it is true, then we fetch the debug - // level from the Lighthouse configuration. - return $result->toArray( - config('app.debug') - ? config('lighthouse.debug') - : false - ); - } - - /** - * Execute a GraphQL query on the Lighthouse schema and return the raw ExecutionResult. - * - * To render the ExecutionResult, you will probably want to call `->toArray($debug)` on it, - * with $debug being a combination of flags in \GraphQL\Error\Debug + * To render the @see ExecutionResult, you will probably want to call `->toArray($debug)` on it, + * with $debug being a combination of flags in @see \GraphQL\Error\DebugFlag * * @param string|\GraphQL\Language\AST\DocumentNode $query - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @param mixed[] $variables + * @param array|null $variables * @param mixed|null $rootValue - * @param string|null $operationName - * @return \GraphQL\Executor\ExecutionResult */ public function executeQuery( $query, @@ -157,115 +184,141 @@ class GraphQL $rootValue = null, ?string $operationName = null ): ExecutionResult { + // TODO make executeQuery require a DocumentNode and move this parsing out of here + if (is_string($query)) { + try { + $query = Parser::parse($query); + } catch (SyntaxError $syntaxError) { + return new ExecutionResult(null, [$syntaxError]); + } + } + // Building the executable schema might take a while to do, // so we do it before we fire the StartExecution event. // This allows tracking the time for batched queries independently. - $this->prepSchema(); + $schema = $this->schemaBuilder->schema(); $this->eventDispatcher->dispatch( - new StartExecution + new StartExecution($query, $variables, $operationName, $context) ); $result = GraphQLBase::executeQuery( - $this->executableSchema, + $schema, $query, $rootValue, $context, $variables, $operationName, null, - $this->getValidationRules() + DocumentValidator::defaultRules() + $this->providesValidationRules->validationRules() ); - /** @var \Nuwave\Lighthouse\Execution\ExtensionsResponse[] $extensionsResponses */ + /** @var array<\Nuwave\Lighthouse\Execution\ExtensionsResponse|null> $extensionsResponses */ $extensionsResponses = (array) $this->eventDispatcher->dispatch( new BuildExtensionsResponse ); foreach ($extensionsResponses as $extensionsResponse) { - if ($extensionsResponse) { + if ($extensionsResponse !== null) { $result->extensions[$extensionsResponse->key()] = $extensionsResponse->content(); } } - $result->setErrorsHandler( - function (array $errors, callable $formatter): array { - // User defined error handlers, implementing \Nuwave\Lighthouse\Execution\ErrorHandler - // This allows the user to register multiple handlers and pipe the errors through. - $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 - ); - } - ); + foreach ($this->errorPool->errors() as $error) { + $result->errors [] = $error; + } // Allow listeners to manipulate the result after each resolved query $this->eventDispatcher->dispatch( new ManipulateResult($result) ); + $this->eventDispatcher->dispatch( + new EndExecution($result) + ); + + $this->cleanUpAfterExecution(); + return $result; } + protected function cleanUpAfterExecution(): void + { + BatchLoaderRegistry::forgetInstances(); + $this->errorPool->clear(); + + // TODO remove in v6 + BatchLoader::forgetInstances(); + } + + /** + * Convert the result to a serializable array. + * + * @return array + */ + public function serializable(ExecutionResult $result): array + { + $result->setErrorsHandler($this->errorsHandler()); + + return $result->toArray($this->debugFlag()); + } + + /** + * @return \Closure( + * array<\GraphQL\Error\Error> $errors, + * callable(\GraphQL\Error\Error $error): ?array + * ): array + */ + protected function errorsHandler(): \Closure + { + if (! isset($this->errorsHandler)) { + $this->errorsHandler = function (array $errors, callable $formatter): array { + // User defined error handlers, implementing \Nuwave\Lighthouse\Execution\ErrorHandler + // This allows the user to register multiple handlers and pipe the errors through. + $handlers = []; + foreach ($this->configRepository->get('lighthouse.error_handlers', []) as $handlerClass) { + $handlers [] = app($handlerClass); + } + + return (new Collection($errors)) + ->map(function (Error $error) use ($handlers, $formatter): ?array { + return $this->pipeline + ->send($error) + ->through($handlers) + ->then(function (?Error $error) use ($formatter): ?array { + if ($error === null) { + return null; + } + + return $formatter($error); + }); + }) + ->filter() + ->all(); + }; + } + + return $this->errorsHandler; + } + + protected function debugFlag(): int + { + // If debugging is set to false globally, do not add GraphQL specific + // debugging info either. If it is true, then we fetch the debug + // level from the Lighthouse configuration. + return $this->configRepository->get('app.debug') + ? (int) $this->configRepository->get('lighthouse.debug') + : DebugFlag::NONE; + } + /** * Ensure an executable GraphQL schema is present. * - * @return \GraphQL\Type\Schema + * @deprecated + * @see \Nuwave\Lighthouse\Schema\SchemaBuilder::schema() */ public function prepSchema(): Schema { - if (empty($this->executableSchema)) { - $this->executableSchema = $this->schemaBuilder->build( - $this->documentAST() - ); - } - - return $this->executableSchema; - } - - /** - * Construct the validation rules with values given in the config. - * - * @return \GraphQL\Validator\Rules\ValidationRule[] - */ - 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)), - ]; - } - - /** - * Get instance of DocumentAST. - * - * @return \Nuwave\Lighthouse\Schema\AST\DocumentAST - */ - public function documentAST(): DocumentAST - { - if (empty($this->documentAST)) { - $this->documentAST = config('lighthouse.cache.enable') - ? app('cache') - ->remember( - config('lighthouse.cache.key'), - config('lighthouse.cache.ttl'), - function (): DocumentAST { - return $this->astBuilder->build(); - } - ) - : $this->astBuilder->build(); - } - - return $this->documentAST; + return $this->schemaBuilder->schema(); } } diff --git a/vendor/nuwave/lighthouse/src/LighthouseServiceProvider.php b/vendor/nuwave/lighthouse/src/LighthouseServiceProvider.php index 5919fa3..4fbbcc5 100644 --- a/vendor/nuwave/lighthouse/src/LighthouseServiceProvider.php +++ b/vendor/nuwave/lighthouse/src/LighthouseServiceProvider.php @@ -4,158 +4,117 @@ namespace Nuwave\Lighthouse; use Closure; use Exception; -use Illuminate\Support\Arr; -use Illuminate\Support\Str; -use Illuminate\Routing\Router; -use Illuminate\Validation\Validator; -use Illuminate\Support\ServiceProvider; -use Nuwave\Lighthouse\Schema\NodeRegistry; -use Nuwave\Lighthouse\Schema\TypeRegistry; -use Nuwave\Lighthouse\Console\QueryCommand; -use Nuwave\Lighthouse\Console\UnionCommand; -use Nuwave\Lighthouse\Console\ScalarCommand; +use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Contracts\Container\Container; -use Nuwave\Lighthouse\Console\MutationCommand; -use Nuwave\Lighthouse\Schema\ResolverProvider; +use Illuminate\Foundation\Application as LaravelApplication; +use Illuminate\Routing\Router; +use Illuminate\Support\ServiceProvider; +use Laravel\Lumen\Application as LumenApplication; +use Nuwave\Lighthouse\Console\CacheCommand; +use Nuwave\Lighthouse\Console\ClearCacheCommand; +use Nuwave\Lighthouse\Console\DirectiveCommand; use Nuwave\Lighthouse\Console\IdeHelperCommand; use Nuwave\Lighthouse\Console\InterfaceCommand; -use Nuwave\Lighthouse\Execution\ContextFactory; -use Nuwave\Lighthouse\Execution\GraphQLRequest; -use Nuwave\Lighthouse\Execution\SingleResponse; -use Nuwave\Lighthouse\Execution\Utils\GlobalId; -use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Console\ClearCacheCommand; +use Nuwave\Lighthouse\Console\MutationCommand; use Nuwave\Lighthouse\Console\PrintSchemaCommand; -use Nuwave\Lighthouse\Execution\GraphQLValidator; -use Laravel\Lumen\Application as LumenApplication; +use Nuwave\Lighthouse\Console\QueryCommand; +use Nuwave\Lighthouse\Console\ScalarCommand; use Nuwave\Lighthouse\Console\SubscriptionCommand; -use Nuwave\Lighthouse\Execution\LighthouseRequest; -use Nuwave\Lighthouse\Schema\Source\SchemaStitcher; +use Nuwave\Lighthouse\Console\UnionCommand; use Nuwave\Lighthouse\Console\ValidateSchemaCommand; -use Nuwave\Lighthouse\Execution\MultipartFormRequest; -use Illuminate\Validation\Factory as ValidationFactory; -use Nuwave\Lighthouse\Support\Contracts\CreatesContext; -use Nuwave\Lighthouse\Schema\Factories\DirectiveFactory; -use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; +use Nuwave\Lighthouse\Console\ValidatorCommand; +use Nuwave\Lighthouse\Execution\ContextFactory; +use Nuwave\Lighthouse\Execution\ErrorPool; +use Nuwave\Lighthouse\Execution\SingleResponse; +use Nuwave\Lighthouse\Execution\ValidationRulesProvider; +use Nuwave\Lighthouse\Schema\AST\ASTBuilder; +use Nuwave\Lighthouse\Schema\DirectiveLocator; +use Nuwave\Lighthouse\Schema\ResolverProvider; +use Nuwave\Lighthouse\Schema\SchemaBuilder; use Nuwave\Lighthouse\Schema\Source\SchemaSourceProvider; -use Nuwave\Lighthouse\Support\Contracts\ProvidesResolver; -use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse; -use Illuminate\Foundation\Application as LaravelApplication; -use Nuwave\Lighthouse\Support\Http\Responses\ResponseStream; -use Nuwave\Lighthouse\Support\Compatibility\MiddlewareAdapter; -use Illuminate\Contracts\Config\Repository as ConfigRepository; -use Nuwave\Lighthouse\Support\Compatibility\LumenMiddlewareAdapter; +use Nuwave\Lighthouse\Schema\Source\SchemaStitcher; +use Nuwave\Lighthouse\Schema\TypeRegistry; +use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Nuwave\Lighthouse\Support\AppVersion; use Nuwave\Lighthouse\Support\Compatibility\LaravelMiddlewareAdapter; -use Nuwave\Lighthouse\Support\Contracts\GlobalId as GlobalIdContract; +use Nuwave\Lighthouse\Support\Compatibility\LumenMiddlewareAdapter; +use Nuwave\Lighthouse\Support\Compatibility\MiddlewareAdapter; +use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse; +use Nuwave\Lighthouse\Support\Contracts\CreatesContext; +use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; +use Nuwave\Lighthouse\Support\Contracts\ProvidesResolver; use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver; +use Nuwave\Lighthouse\Support\Contracts\ProvidesValidationRules; +use Nuwave\Lighthouse\Support\Http\Responses\ResponseStream; +use Nuwave\Lighthouse\Testing\TestingServiceProvider; class LighthouseServiceProvider extends ServiceProvider { /** - * Bootstrap any application services. - * - * @param \Illuminate\Validation\Factory $validationFactory - * @param \Illuminate\Contracts\Config\Repository $configRepository - * @return void + * @var array */ - public function boot(ValidationFactory $validationFactory, ConfigRepository $configRepository): void - { - $this->publishes([ - __DIR__.'/../config/config.php' => $this->app->make('path.config').DIRECTORY_SEPARATOR.'lighthouse.php', - ], 'config'); + const COMMANDS = [ + CacheCommand::class, + ClearCacheCommand::class, + DirectiveCommand::class, + IdeHelperCommand::class, + InterfaceCommand::class, + MutationCommand::class, + PrintSchemaCommand::class, + QueryCommand::class, + ScalarCommand::class, + SubscriptionCommand::class, + UnionCommand::class, + ValidateSchemaCommand::class, + ValidatorCommand::class, + ]; - $this->publishes([ - __DIR__.'/../assets/default-schema.graphql' => $configRepository->get('lighthouse.schema.register'), - ], 'schema'); - - $this->loadRoutesFrom(__DIR__.'/Support/Http/routes.php'); - - $validationFactory->resolver( - function ($translator, array $data, array $rules, array $messages, array $customAttributes): Validator { - // This determines whether we are resolving a GraphQL field - return Arr::has($customAttributes, ['root', 'context', 'resolveInfo']) - ? new GraphQLValidator($translator, $data, $rules, $messages, $customAttributes) - : new Validator($translator, $data, $rules, $messages, $customAttributes); - } - ); - } - - /** - * Load routes from provided path. - * - * @param string $path - * @return void - */ - protected function loadRoutesFrom($path): void - { - if (Str::contains($this->app->version(), 'Lumen')) { - require realpath($path); - - return; - } - - parent::loadRoutesFrom($path); - } - - /** - * Register any application services. - * - * @return void - */ public function register(): void { - $this->mergeConfigFrom(__DIR__.'/../config/config.php', 'lighthouse'); + $this->mergeConfigFrom(__DIR__.'/lighthouse.php', 'lighthouse'); $this->app->singleton(GraphQL::class); - - $this->app->singleton(DirectiveFactory::class); - $this->app->singleton(NodeRegistry::class); + $this->app->singleton(ASTBuilder::class); + $this->app->singleton(SchemaBuilder::class); + $this->app->singleton(DirectiveLocator::class); $this->app->singleton(TypeRegistry::class); + $this->app->singleton(ErrorPool::class); $this->app->singleton(CreatesContext::class, ContextFactory::class); $this->app->singleton(CanStreamResponse::class, ResponseStream::class); $this->app->bind(CreatesResponse::class, SingleResponse::class); - $this->app->bind(GlobalIdContract::class, GlobalId::class); - - $this->app->singleton(GraphQLRequest::class, function (Container $app): GraphQLRequest { - /** @var \Illuminate\Http\Request $request */ - $request = $app->make('request'); - - return Str::startsWith( - $request->header('Content-Type'), - 'multipart/form-data' - ) - ? new MultipartFormRequest($request) - : new LighthouseRequest($request); - }); - - $this->app->singleton(SchemaSourceProvider::class, function (): SchemaStitcher { + $this->app->singleton(SchemaSourceProvider::class, static function (): SchemaStitcher { return new SchemaStitcher( config('lighthouse.schema.register', '') ); }); $this->app->bind(ProvidesResolver::class, ResolverProvider::class); - $this->app->bind(ProvidesSubscriptionResolver::class, function (): ProvidesSubscriptionResolver { - return new class implements ProvidesSubscriptionResolver { + $this->app->bind(ProvidesSubscriptionResolver::class, static function (): ProvidesSubscriptionResolver { + return new class implements ProvidesSubscriptionResolver + { public function provideSubscriptionResolver(FieldValue $fieldValue): Closure { throw new Exception( - 'Add the SubscriptionServiceProvider to your config/app.php to enable subscriptions.' - ); + 'Add the SubscriptionServiceProvider to your config/app.php to enable subscriptions.' + ); } }; }); - $this->app->singleton(MiddlewareAdapter::class, function (Container $app): MiddlewareAdapter { + $this->app->bind(ProvidesValidationRules::class, ValidationRulesProvider::class); + + $this->app->singleton(MiddlewareAdapter::class, static function (Container $app): MiddlewareAdapter { // prefer using fully-qualified class names here when referring to Laravel-only or Lumen-only classes if ($app instanceof LaravelApplication) { return new LaravelMiddlewareAdapter( $app->get(Router::class) ); - } elseif ($app instanceof LumenApplication) { - return new LumenMiddlewareAdapter($app); + } + + if ($app instanceof LumenApplication) { + return new LumenMiddlewareAdapter(); } throw new Exception( @@ -164,18 +123,35 @@ class LighthouseServiceProvider extends ServiceProvider }); if ($this->app->runningInConsole()) { - $this->commands([ - ClearCacheCommand::class, - IdeHelperCommand::class, - InterfaceCommand::class, - MutationCommand::class, - PrintSchemaCommand::class, - QueryCommand::class, - ScalarCommand::class, - SubscriptionCommand::class, - UnionCommand::class, - ValidateSchemaCommand::class, - ]); + $this->commands(self::COMMANDS); + } + + if ($this->app->runningUnitTests()) { + $this->app->register(TestingServiceProvider::class); } } + + public function boot(ConfigRepository $configRepository): void + { + $this->publishes([ + __DIR__.'/lighthouse.php' => $this->app->configPath().'/lighthouse.php', + ], 'lighthouse-config'); + + $this->publishes([ + __DIR__.'/default-schema.graphql' => $configRepository->get('lighthouse.schema.register'), + ], 'lighthouse-schema'); + + $this->loadRoutesFrom(__DIR__.'/Support/Http/routes.php'); + } + + protected function loadRoutesFrom($path): void + { + if (AppVersion::isLumen()) { + require \Safe\realpath($path); + + return; + } + + parent::loadRoutesFrom($path); + } } diff --git a/vendor/nuwave/lighthouse/src/OrderBy/OrderByDirective.php b/vendor/nuwave/lighthouse/src/OrderBy/OrderByDirective.php new file mode 100644 index 0000000..d29d9da --- /dev/null +++ b/vendor/nuwave/lighthouse/src/OrderBy/OrderByDirective.php @@ -0,0 +1,121 @@ + $value + */ + public function handleBuilder($builder, $value): object + { + foreach ($value as $orderByClause) { + $builder->orderBy( + $orderByClause['column'], + $orderByClause['order'] + ); + } + + return $builder; + } + + public function manipulateArgDefinition( + DocumentAST &$documentAST, + InputValueDefinitionNode &$argDefinition, + FieldDefinitionNode &$parentField, + ObjectTypeDefinitionNode &$parentType + ): void { + if ($this->hasAllowedColumns()) { + $restrictedOrderByName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType).'OrderByClause'; + $argDefinition->type = Parser::typeReference("[$restrictedOrderByName!]"); + $allowedColumnsEnumName = $this->generateColumnsEnum($documentAST, $argDefinition, $parentField, $parentType); + + $documentAST + ->setTypeDefinition( + OrderByServiceProvider::createOrderByClauseInput( + $restrictedOrderByName, + "Order by clause for the `{$argDefinition->name->value}` argument on the query `{$parentField->name->value}`.", + $allowedColumnsEnumName + ) + ); + } else { + $argDefinition->type = Parser::typeReference('['.OrderByServiceProvider::DEFAULT_ORDER_BY_CLAUSE.'!]'); + } + } + + public function handleFieldBuilder(object $builder): object + { + return $builder->orderBy( + $this->directiveArgValue('column'), + $this->directiveArgValue('direction', 'ASC') + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/OrderBy/OrderByServiceProvider.php b/vendor/nuwave/lighthouse/src/OrderBy/OrderByServiceProvider.php new file mode 100644 index 0000000..ab7f703 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/OrderBy/OrderByServiceProvider.php @@ -0,0 +1,70 @@ +listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } + ); + + $dispatcher->listen( + ManipulateAST::class, + function (ManipulateAST $manipulateAST): void { + $documentAST = $manipulateAST->documentAST; + $documentAST->setTypeDefinition( + Parser::enumTypeDefinition(/** @lang GraphQL */ ' + "The available directions for ordering a list of records." + enum SortOrder { + "Sort records in ascending order." + ASC + + "Sort records in descending order." + DESC + } + ' + ) + ); + $documentAST->setTypeDefinition( + static::createOrderByClauseInput( + static::DEFAULT_ORDER_BY_CLAUSE, + 'Allows ordering a list of records.', + 'String' + ) + ); + } + ); + } + + public static function createOrderByClauseInput(string $name, string $description, string $columnType): InputObjectTypeDefinitionNode + { + return Parser::inputObjectTypeDefinition(/** @lang GraphQL */ << */ public function pageInfoResolver(LengthAwarePaginator $paginator): array { + /** @var int|null $firstItem Laravel type-hints are inaccurate here */ + $firstItem = $paginator->firstItem(); + /** @var int|null $lastItem Laravel type-hints are inaccurate here */ + $lastItem = $paginator->lastItem(); + return [ + 'hasNextPage' => $paginator->hasMorePages(), + 'hasPreviousPage' => $paginator->currentPage() > 1, + 'startCursor' => $firstItem !== null + ? Cursor::encode($firstItem) + : null, + 'endCursor' => $lastItem !== null + ? Cursor::encode($lastItem) + : null, '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 edges for connection. * - * @param \Illuminate\Contracts\Pagination\LengthAwarePaginator $paginator - * @param array $args - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @param GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return \Illuminate\Support\Collection + * @param \Illuminate\Pagination\LengthAwarePaginator $paginator + * @param array $args */ - public function edgeResolver(LengthAwarePaginator $paginator, $args, GraphQLContext $context, ResolveInfo $resolveInfo): Collection + public function edgeResolver(LengthAwarePaginator $paginator, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Collection { - $returnTypeFields = $resolveInfo - ->returnType - ->ofType - ->getFields(); + // We know those types because we manipulated them during PaginationManipulator + /** @var \GraphQL\Type\Definition\NonNull $nonNullList */ + $nonNullList = $resolveInfo->returnType; + /** @var \GraphQL\Type\Definition\ObjectType|\GraphQL\Type\Definition\InterfaceType $objectLikeType */ + $objectLikeType = $nonNullList->getWrappedType(true); + + $returnTypeFields = $objectLikeType->getFields(); + + /** @var int|null $firstItem Laravel type-hints are inaccurate here */ $firstItem = $paginator->firstItem(); return $paginator ->values() - ->map(function ($item, $index) use ($firstItem, $returnTypeFields): array { + ->map(function ($item, int $index) use ($returnTypeFields, $firstItem): array { $data = []; foreach ($returnTypeFields as $field) { switch ($field->name) { case 'cursor': - $data['cursor'] = Cursor::encode($firstItem + $index); + $data['cursor'] = Cursor::encode((int) $firstItem + $index); break; case 'node': diff --git a/vendor/nuwave/lighthouse/src/Pagination/Cursor.php b/vendor/nuwave/lighthouse/src/Pagination/Cursor.php index 4472b37..fd1e01d 100644 --- a/vendor/nuwave/lighthouse/src/Pagination/Cursor.php +++ b/vendor/nuwave/lighthouse/src/Pagination/Cursor.php @@ -22,13 +22,12 @@ class Cursor * this will return 0. That will effectively reset pagination, so the user gets the * first slice. * - * @param array $args - * @return int + * @param array $args */ public static function decode(array $args): int { if ($cursor = Arr::get($args, 'after')) { - return (int) base64_decode($cursor); + return (int) \Safe\base64_decode($cursor); } return 0; @@ -36,12 +35,9 @@ class Cursor /** * Encode the given offset to make the implementation opaque. - * - * @param int $offset - * @return string */ public static function encode(int $offset): string { - return base64_encode($offset); + return base64_encode((string) $offset); } } diff --git a/vendor/nuwave/lighthouse/src/Pagination/PaginateDirective.php b/vendor/nuwave/lighthouse/src/Pagination/PaginateDirective.php new file mode 100644 index 0000000..f2e884b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Pagination/PaginateDirective.php @@ -0,0 +1,148 @@ +directiveHasArgument('builder')) { + // This is done only for validation + $this->getResolverFromArgument('builder'); + } else { + $paginationManipulator->setModelClass( + $this->getModelClass() + ); + } + + $paginationManipulator->transformToPaginatedField( + $this->paginationType(), + $fieldDefinition, + $parentType, + $this->defaultCount(), + $this->paginateMaxCount() + ); + } + + public function resolveField(FieldValue $fieldValue): FieldValue + { + return $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Paginator { + if ($this->directiveHasArgument('builder')) { + $builderResolver = $this->getResolverFromArgument('builder'); + + $query = $builderResolver($root, $args, $context, $resolveInfo); + } else { + $query = $this->getModelClass()::query(); + } + + $query = $resolveInfo + ->argumentSet + ->enhanceBuilder( + $query, + $this->directiveArgValue('scopes', []) + ); + + return PaginationArgs + ::extractArgs($args, $this->paginationType(), $this->paginateMaxCount()) + ->applyToBuilder($query); + } + ); + } + + protected function paginationType(): PaginationType + { + return new PaginationType( + $this->directiveArgValue('type', PaginationType::PAGINATOR) + ); + } + + protected function defaultCount(): ?int + { + return $this->directiveArgValue('defaultCount') + ?? config('lighthouse.pagination.default_count'); + } + + protected function paginateMaxCount(): ?int + { + return $this->directiveArgValue('maxCount') + ?? config('lighthouse.pagination.max_count'); + } +} diff --git a/vendor/nuwave/lighthouse/src/Pagination/PaginationArgs.php b/vendor/nuwave/lighthouse/src/Pagination/PaginationArgs.php new file mode 100644 index 0000000..2da27de --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Pagination/PaginationArgs.php @@ -0,0 +1,111 @@ + $args + * @param \Nuwave\Lighthouse\Pagination\PaginationType $paginationType + * @return static + * + * @throws \GraphQL\Error\Error + */ + public static function extractArgs(array $args, PaginationType $paginationType, ?int $paginateMaxCount): self + { + $instance = new static(); + + $instance->type = $paginationType; + + if ($paginationType->isConnection()) { + $instance->first = $args['first']; + $instance->page = self::calculateCurrentPage( + $instance->first, + Cursor::decode($args) + ); + } else { + // Handles cases "paginate" and "simple", which both take the same args. + $instance->first = $args['first']; + $instance->page = Arr::get($args, 'page', 1); + } + + if ($instance->first <= 0) { + throw new Error( + self::requestedZeroOrLessItems($instance->first) + ); + } + + // Make sure the maximum pagination count is not exceeded + if ( + $paginateMaxCount !== null + && $instance->first > $paginateMaxCount + ) { + throw new Error( + self::requestedTooManyItems($paginateMaxCount, $instance->first) + ); + } + + return $instance; + } + + public static function requestedZeroOrLessItems(int $amount): string + { + return "Requested pagination amount must be more than 0, got {$amount}."; + } + + public static function requestedTooManyItems(int $maxCount, int $actualCount): string + { + return "Maximum number of {$maxCount} requested items exceeded, got {$actualCount}. Fetch smaller chunks."; + } + + /** + * Calculate the current page to inform the user about the pagination state. + */ + protected static function calculateCurrentPage(int $first, int $after, int $defaultPage = 1): int + { + return $first && $after + ? (int) floor(($first + $after) / $first) + : $defaultPage; + } + + /** + * Apply the args to a builder, constructing a paginator. + * + * @param \Illuminate\Database\Query\Builder|\Laravel\Scout\Builder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation $builder + */ + public function applyToBuilder(object $builder): Paginator + { + $methodName = $this->type->isSimple() + ? 'simplePaginate' + : 'paginate'; + + if ($builder instanceof ScoutBuilder) { + return $builder->{$methodName}($this->first, 'page', $this->page); + } + + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + return $builder->{$methodName}($this->first, ['*'], 'page', $this->page); + } +} diff --git a/vendor/nuwave/lighthouse/src/Pagination/PaginationManipulator.php b/vendor/nuwave/lighthouse/src/Pagination/PaginationManipulator.php index 99a444a..44308c1 100644 --- a/vendor/nuwave/lighthouse/src/Pagination/PaginationManipulator.php +++ b/vendor/nuwave/lighthouse/src/Pagination/PaginationManipulator.php @@ -2,15 +2,53 @@ namespace Nuwave\Lighthouse\Pagination; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; -use Nuwave\Lighthouse\Schema\AST\PartialParser; use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Language\AST\TypeNode; +use GraphQL\Language\Parser; +use Illuminate\Container\Container; +use Illuminate\Contracts\Config\Repository as ConfigRepository; use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; +use Nuwave\Lighthouse\Schema\Directives\ModelDirective; class PaginationManipulator { + /** + * @var \Nuwave\Lighthouse\Schema\AST\DocumentAST + */ + protected $documentAST; + + /** + * The class name of the model that is returned from the field. + * + * Might not be present if we are creating a paginated field + * for a relation, as the model is not required for resolving + * that directive and the user may choose a different type. + * + * @var class-string<\Illuminate\Database\Eloquent\Model>|null + */ + protected $modelClass; + + public function __construct(DocumentAST $documentAST) + { + $this->documentAST = $documentAST; + } + + /** + * Set the model class to use for code generation. + * + * @param class-string<\Illuminate\Database\Eloquent\Model> $modelClass + * @return $this + */ + public function setModelClass(string $modelClass): self + { + $this->modelClass = $modelClass; + + return $this; + } + /** * Transform the definition for a field to a field with pagination. * @@ -18,53 +56,34 @@ class PaginationManipulator * The types in between are automatically generated and applied to the schema. * * @param \Nuwave\Lighthouse\Pagination\PaginationType $paginationType - * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param int|null $defaultCount - * @param int|null $maxCount - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|null $edgeType - * @return void */ - public static function transformToPaginatedField( + public function transformToPaginatedField( PaginationType $paginationType, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType, - DocumentAST &$documentAST, ?int $defaultCount = null, ?int $maxCount = null, ?ObjectTypeDefinitionNode $edgeType = null ): void { if ($paginationType->isConnection()) { - self::registerConnection($fieldDefinition, $parentType, $documentAST, $defaultCount, $maxCount, $edgeType); + $this->registerConnection($fieldDefinition, $parentType, $defaultCount, $maxCount, $edgeType); + } elseif ($paginationType->isSimple()) { + $this->registerSimplePaginator($fieldDefinition, $parentType, $defaultCount, $maxCount); } else { - self::registerPaginator($fieldDefinition, $parentType, $documentAST, $defaultCount, $maxCount); + $this->registerPaginator($fieldDefinition, $parentType, $defaultCount, $maxCount); } } - /** - * Register connection w/ schema. - * - * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param int|null $defaultCount - * @param int|null $maxCount - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|null $edgeType - * @return void - * @throws DefinitionException - */ - public static function registerConnection( + protected function registerConnection( FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType, - DocumentAST &$documentAST, ?int $defaultCount = null, ?int $maxCount = null, ?ObjectTypeDefinitionNode $edgeType = null ): void { $fieldTypeName = ASTHelper::getUnderlyingTypeName($fieldDefinition); - if ($edgeType) { + if ($edgeType !== null) { $connectionEdgeName = $edgeType->name->value; $connectionTypeName = "{$connectionEdgeName}Connection"; } else { @@ -74,51 +93,76 @@ class PaginationManipulator $connectionFieldName = addslashes(ConnectionField::class); - $connectionType = PartialParser::objectTypeDefinition(" - type $connectionTypeName { - pageInfo: PageInfo! @field(resolver: \"{$connectionFieldName}@pageInfoResolver\") - edges: [$connectionEdgeName] @field(resolver: \"{$connectionFieldName}@edgeResolver\") + $connectionType = Parser::objectTypeDefinition(/** @lang GraphQL */ <<addPaginationWrapperType($connectionType); $connectionEdge = $edgeType - ?? $documentAST->types[$connectionEdgeName] - ?? PartialParser::objectTypeDefinition(" + ?? $this->documentAST->types[$connectionEdgeName] + ?? Parser::objectTypeDefinition(/** @lang GraphQL */ <<documentAST->setTypeDefinition($connectionEdge); - $inputValueDefinitions = [ - self::countArgument('first', $defaultCount, $maxCount), - "\"A cursor after which elements are returned.\"\nafter: String", - ]; + $fieldDefinition->arguments [] = Parser::inputValueDefinition( + self::countArgument($defaultCount, $maxCount) + ); + $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' +"A cursor after which elements are returned." +after: String +GRAPHQL + ); - $connectionArguments = PartialParser::inputValueDefinitions($inputValueDefinitions); - - $fieldDefinition->arguments = ASTHelper::mergeNodeList($fieldDefinition->arguments, $connectionArguments); - $fieldDefinition->type = PartialParser::namedType($connectionTypeName); - $parentType->fields = ASTHelper::mergeNodeList($parentType->fields, [$fieldDefinition]); - - $documentAST->setTypeDefinition($connectionType); - $documentAST->setTypeDefinition($connectionEdge); + $fieldDefinition->type = $this->paginationResultType($connectionTypeName); + $parentType->fields = ASTHelper::mergeUniqueNodeList($parentType->fields, [$fieldDefinition], true); } - /** - * Register paginator w/ schema. - * - * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param int|null $defaultCount - * @param int|null $maxCount - * @return void - */ - public static function registerPaginator( + protected function addPaginationWrapperType(ObjectTypeDefinitionNode $objectType): void + { + $typeName = $objectType->name->value; + + // Reuse existing types to preserve directives or other modifications made to it + $existingType = $this->documentAST->types[$typeName] ?? null; + if ($existingType !== null) { + if (! $existingType instanceof ObjectTypeDefinitionNode) { + throw new DefinitionException( + "Expected object type for pagination wrapper {$typeName}, found {$objectType->kind} instead." + ); + } + + $objectType = $existingType; + } + + if ( + $this->modelClass + && ! ASTHelper::hasDirective($objectType, ModelDirective::NAME) + ) { + $objectType->directives [] = Parser::constDirective(/** @lang GraphQL */'@model(class: "'.addslashes($this->modelClass).'")'); + } + + $this->documentAST->setTypeDefinition($objectType); + } + + protected function registerPaginator( FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType, - DocumentAST &$documentAST, ?int $defaultCount = null, ?int $maxCount = null ): void { @@ -126,44 +170,80 @@ class PaginationManipulator $paginatorTypeName = "{$fieldTypeName}Paginator"; $paginatorFieldClassName = addslashes(PaginatorField::class); - $paginatorType = PartialParser::objectTypeDefinition(" - type $paginatorTypeName { - paginatorInfo: PaginatorInfo! @field(resolver: \"{$paginatorFieldClassName}@paginatorInfoResolver\") - data: [$fieldTypeName!]! @field(resolver: \"{$paginatorFieldClassName}@dataResolver\") + $paginatorType = Parser::objectTypeDefinition(/** @lang GraphQL */ <<addPaginationWrapperType($paginatorType); - $inputValueDefinitions = [ - self::countArgument(config('lighthouse.pagination_amount_argument'), $defaultCount, $maxCount), - "\"The offset from which elements are returned.\"\npage: Int", - ]; + $fieldDefinition->arguments [] = Parser::inputValueDefinition( + self::countArgument($defaultCount, $maxCount) + ); + $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' +"The offset from which items are returned." +page: Int +GRAPHQL +); - $paginationArguments = PartialParser::inputValueDefinitions($inputValueDefinitions); + $fieldDefinition->type = $this->paginationResultType($paginatorTypeName); + $parentType->fields = ASTHelper::mergeUniqueNodeList($parentType->fields, [$fieldDefinition], true); + } - $fieldDefinition->arguments = ASTHelper::mergeNodeList($fieldDefinition->arguments, $paginationArguments); - $fieldDefinition->type = PartialParser::namedType($paginatorTypeName); - $parentType->fields = ASTHelper::mergeNodeList($parentType->fields, [$fieldDefinition]); + protected function registerSimplePaginator( + FieldDefinitionNode &$fieldDefinition, + ObjectTypeDefinitionNode &$parentType, + ?int $defaultCount = null, + ?int $maxCount = null + ): void { + $fieldTypeName = ASTHelper::getUnderlyingTypeName($fieldDefinition); + $paginatorTypeName = "{$fieldTypeName}SimplePaginator"; + $paginatorFieldClassName = addslashes(SimplePaginatorField::class); - $documentAST->setTypeDefinition($paginatorType); + $paginatorType = Parser::objectTypeDefinition(/** @lang GraphQL */ <<addPaginationWrapperType($paginatorType); + + $fieldDefinition->arguments [] = Parser::inputValueDefinition( + self::countArgument($defaultCount, $maxCount) + ); + $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' +"The offset from which items are returned." +page: Int +GRAPHQL + ); + + $fieldDefinition->type = $this->paginationResultType($paginatorTypeName); + $parentType->fields = ASTHelper::mergeUniqueNodeList($parentType->fields, [$fieldDefinition], true); } /** * Build the count argument definition string, considering default and max values. - * - * @param string $argumentName - * @param int|null $defaultCount - * @param int|null $maxCount - * @return string */ - protected static function countArgument(string $argumentName, ?int $defaultCount = null, ?int $maxCount = null): string + protected static function countArgument(?int $defaultCount = null, ?int $maxCount = null): string { - $description = '"Limits number of fetched elements.'; + $description = '"Limits number of fetched items.'; if ($maxCount) { $description .= ' Maximum allowed value: '.$maxCount.'.'; } $description .= "\"\n"; - $definition = $argumentName.': Int' + $definition = 'first: Int' .($defaultCount ? ' = '.$defaultCount : '!' @@ -171,4 +251,25 @@ class PaginationManipulator return $description.$definition; } + + /** + * @return \GraphQL\Language\AST\NamedTypeNode|\GraphQL\Language\AST\NonNullTypeNode + */ + protected function paginationResultType(string $typeName): TypeNode + { + /** @var \Illuminate\Contracts\Config\Repository $config */ + $config = Container::getInstance()->make(ConfigRepository::class); + $nonNull = $config->get('lighthouse.non_null_pagination_results') + ? '!' + : ''; + + /** + * We do not wrap the typename in [], so this will never be a ListOfTypeNode. + * + * @var \GraphQL\Language\AST\NamedTypeNode|\GraphQL\Language\AST\NonNullTypeNode $nonNullTypeNode + */ + $nonNullTypeNode = Parser::typeReference(/** @lang GraphQL */ "{$typeName}{$nonNull}"); + + return $nonNullTypeNode; + } } diff --git a/vendor/nuwave/lighthouse/src/Pagination/PaginationServiceProvider.php b/vendor/nuwave/lighthouse/src/Pagination/PaginationServiceProvider.php new file mode 100644 index 0000000..cabfb9f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Pagination/PaginationServiceProvider.php @@ -0,0 +1,120 @@ +listen( + ManipulateAST::class, + function (ManipulateAST $manipulateAST): void { + $documentAST = $manipulateAST->documentAST; + $documentAST->setTypeDefinition(self::paginatorInfo()); + $documentAST->setTypeDefinition(self::simplePaginatorInfo()); + $documentAST->setTypeDefinition(self::pageInfo()); + } + ); + + $dispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } + ); + } + + protected static function paginatorInfo(): ObjectTypeDefinitionNode + { + return Parser::objectTypeDefinition(/** @lang GraphQL */ ' + "Information about pagination using a fully featured paginator." + type PaginatorInfo { + "Number of items in the current page." + count: Int! + + "Index of the current page." + currentPage: Int! + + "Index of the first item in the current page." + firstItem: Int + + "Are there more pages after this one?" + hasMorePages: Boolean! + + "Index of the last item in the current page." + lastItem: Int + + "Index of the last available page." + lastPage: Int! + + "Number of items per page." + perPage: Int! + + "Number of total available items." + total: Int! + } + '); + } + + protected static function simplePaginatorInfo(): ObjectTypeDefinitionNode + { + return Parser::objectTypeDefinition(/** @lang GraphQL */ ' + "Information about pagination using a simple paginator." + type SimplePaginatorInfo { + "Number of items in the current page." + count: Int! + + "Index of the current page." + currentPage: Int! + + "Index of the first item in the current page." + firstItem: Int + + "Index of the last item in the current page." + lastItem: Int + + "Number of items per page." + perPage: Int! + } + '); + } + + protected static function pageInfo(): ObjectTypeDefinitionNode + { + return Parser::objectTypeDefinition(/** @lang GraphQL */ ' + "Information about pagination using a Relay style cursor connection." + type PageInfo { + "When paginating forwards, are there more items?" + hasNextPage: Boolean! + + "When paginating backwards, are there more items?" + hasPreviousPage: Boolean! + + "The cursor to continue paginating backwards." + startCursor: String + + "The cursor to continue paginating forwards." + endCursor: String + + "Total number of nodes in the paginated connection." + total: Int! + + "Number of nodes in the current page." + count: Int! + + "Index of the current page." + currentPage: Int! + + "Index of the last available page." + lastPage: Int! + } + '); + } +} diff --git a/vendor/nuwave/lighthouse/src/Pagination/PaginationType.php b/vendor/nuwave/lighthouse/src/Pagination/PaginationType.php index 66fd093..3ec7e98 100644 --- a/vendor/nuwave/lighthouse/src/Pagination/PaginationType.php +++ b/vendor/nuwave/lighthouse/src/Pagination/PaginationType.php @@ -9,32 +9,32 @@ use Nuwave\Lighthouse\Exceptions\DefinitionException; */ class PaginationType { - const TYPE_PAGINATOR = 'paginator'; - const PAGINATION_TYPE_CONNECTION = 'connection'; + public const PAGINATOR = 'PAGINATOR'; + public const SIMPLE = 'SIMPLE'; + public const CONNECTION = 'CONNECTION'; /** - * @var string PAGINATION_TYPE_PAGINATOR|PAGINATION_TYPE_CONNECTION + * @var string One of the constant values in this class */ protected $type; /** - * PaginationType constructor. - * - * @param string $paginationType - * @return void - * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ public function __construct(string $paginationType) { - switch ($paginationType) { + // TODO remove lowercase and alternate options in v6 + switch (strtolower($paginationType)) { case 'default': case 'paginator': - $this->type = self::TYPE_PAGINATOR; + $this->type = self::PAGINATOR; break; case 'connection': case 'relay': - $this->type = self::PAGINATION_TYPE_CONNECTION; + $this->type = self::CONNECTION; + break; + case 'simple': + $this->type = self::SIMPLE; break; default: throw new DefinitionException( @@ -45,11 +45,16 @@ class PaginationType public function isPaginator(): bool { - return $this->type === self::TYPE_PAGINATOR; + return $this->type === self::PAGINATOR; } public function isConnection(): bool { - return $this->type === self::PAGINATION_TYPE_CONNECTION; + return $this->type === self::CONNECTION; + } + + public function isSimple(): bool + { + return $this->type === self::SIMPLE; } } diff --git a/vendor/nuwave/lighthouse/src/Pagination/PaginationUtils.php b/vendor/nuwave/lighthouse/src/Pagination/PaginationUtils.php deleted file mode 100644 index 705d12e..0000000 --- a/vendor/nuwave/lighthouse/src/Pagination/PaginationUtils.php +++ /dev/null @@ -1,66 +0,0 @@ -isConnection()) { - /** @var int $first */ - $first = $args['first']; - $page = self::calculateCurrentPage( - $first, - Cursor::decode($args) - ); - } else { - /** @var int $first */ - $first = $args[config('lighthouse.pagination_amount_argument')]; - $page = Arr::get($args, 'page', 1); - } - - if ($first <= 0) { - throw new Error( - "Requested pagination amount must be more than 0, got $first" - ); - } - - // Make sure the maximum pagination count is not exceeded - if ( - $paginateMaxCount !== null - && $first > $paginateMaxCount - ) { - throw new Error( - "Maximum number of {$paginateMaxCount} requested items exceeded. Fetch smaller chunks." - ); - } - - return [$first, $page]; - } -} diff --git a/vendor/nuwave/lighthouse/src/Pagination/PaginatorField.php b/vendor/nuwave/lighthouse/src/Pagination/PaginatorField.php index 92de29a..08843d2 100644 --- a/vendor/nuwave/lighthouse/src/Pagination/PaginatorField.php +++ b/vendor/nuwave/lighthouse/src/Pagination/PaginatorField.php @@ -2,16 +2,16 @@ namespace Nuwave\Lighthouse\Pagination; -use Illuminate\Support\Collection; use Illuminate\Contracts\Pagination\LengthAwarePaginator; +use Illuminate\Support\Collection; class PaginatorField { /** * Resolve paginator info for connection. * - * @param \Illuminate\Contracts\Pagination\LengthAwarePaginator $root - * @return array + * @param \Illuminate\Pagination\LengthAwarePaginator $root + * @return array */ public function paginatorInfoResolver(LengthAwarePaginator $root): array { @@ -30,11 +30,12 @@ class PaginatorField /** * Resolve data for connection. * - * @param \Illuminate\Contracts\Pagination\LengthAwarePaginator $root - * @return \Illuminate\Support\Collection + * @param \Illuminate\Pagination\LengthAwarePaginator $root + * @return \Illuminate\Support\Collection */ public function dataResolver(LengthAwarePaginator $root): Collection { + // @phpstan-ignore-next-line static refers to the wrong class because it is a proxied method call return $root->values(); } } diff --git a/vendor/nuwave/lighthouse/src/Pagination/SimplePaginatorField.php b/vendor/nuwave/lighthouse/src/Pagination/SimplePaginatorField.php new file mode 100644 index 0000000..8fd0b6b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Pagination/SimplePaginatorField.php @@ -0,0 +1,38 @@ + $root + * @return array + */ + public function paginatorInfoResolver(Paginator $root): array + { + return [ + 'count' => $root->count(), + 'currentPage' => $root->currentPage(), + 'firstItem' => $root->firstItem(), + 'lastItem' => $root->lastItem(), + 'perPage' => $root->perPage(), + ]; + } + + /** + * Resolve data for connection. + * + * @param \Illuminate\Pagination\Paginator $root + * @return \Illuminate\Support\Collection + */ + public function dataResolver(Paginator $root): Collection + { + // @phpstan-ignore-next-line static refers to the wrong class because it is a proxied method call + return $root->values(); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/AST/ASTBuilder.php b/vendor/nuwave/lighthouse/src/Schema/AST/ASTBuilder.php index 79b46e1..4f013ac 100644 --- a/vendor/nuwave/lighthouse/src/Schema/AST/ASTBuilder.php +++ b/vendor/nuwave/lighthouse/src/Schema/AST/ASTBuilder.php @@ -2,80 +2,141 @@ namespace Nuwave\Lighthouse\Schema\AST; -use Illuminate\Support\Arr; -use Nuwave\Lighthouse\Events\ManipulateAST; -use Nuwave\Lighthouse\Events\BuildSchemaString; -use GraphQL\Language\AST\ObjectTypeExtensionNode; +use GraphQL\Language\AST\EnumTypeDefinitionNode; +use GraphQL\Language\AST\EnumTypeExtensionNode; +use GraphQL\Language\AST\InputObjectTypeDefinitionNode; +use GraphQL\Language\AST\InputObjectTypeExtensionNode; +use GraphQL\Language\AST\InterfaceTypeDefinitionNode; +use GraphQL\Language\AST\InterfaceTypeExtensionNode; use GraphQL\Language\AST\ObjectTypeDefinitionNode; -use Nuwave\Lighthouse\Support\Contracts\ArgManipulator; -use Nuwave\Lighthouse\Schema\Factories\DirectiveFactory; -use Nuwave\Lighthouse\Support\Contracts\TypeManipulator; +use GraphQL\Language\AST\ObjectTypeExtensionNode; +use GraphQL\Language\AST\TypeDefinitionNode; +use GraphQL\Language\AST\TypeExtensionNode; +use GraphQL\Language\Parser; +use Illuminate\Contracts\Cache\Factory as CacheFactory; +use Illuminate\Contracts\Config\Repository as ConfigRepository; +use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; +use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Arr; +use Nuwave\Lighthouse\Events\BuildSchemaString; +use Nuwave\Lighthouse\Events\ManipulateAST; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Exceptions\UnknownCacheVersionException; +use Nuwave\Lighthouse\Schema\DirectiveLocator; +use Nuwave\Lighthouse\Schema\RootType; use Nuwave\Lighthouse\Schema\Source\SchemaSourceProvider; +use Nuwave\Lighthouse\Support\Contracts\ArgManipulator; use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; -use Illuminate\Contracts\Events\Dispatcher as EventDispatcher; use Nuwave\Lighthouse\Support\Contracts\TypeExtensionManipulator; +use Nuwave\Lighthouse\Support\Contracts\TypeManipulator; class ASTBuilder { - /** - * The directive factory. - * - * @var \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory - */ - protected $directiveFactory; + public const EXTENSION_TO_DEFINITION_CLASS = [ + ObjectTypeExtensionNode::class => ObjectTypeDefinitionNode::class, + InputObjectTypeExtensionNode::class => InputObjectTypeDefinitionNode::class, + InterfaceTypeExtensionNode::class => InterfaceTypeDefinitionNode::class, + EnumTypeExtensionNode::class => EnumTypeDefinitionNode::class, + ]; /** - * The event dispatcher. - * - * @var \Illuminate\Contracts\Events\Dispatcher + * @var \Nuwave\Lighthouse\Schema\DirectiveLocator */ - protected $eventDispatcher; + protected $directiveLocator; /** - * The schema source provider. - * * @var \Nuwave\Lighthouse\Schema\Source\SchemaSourceProvider */ protected $schemaSourceProvider; /** - * The document AST. + * @var \Illuminate\Contracts\Events\Dispatcher + */ + protected $eventsDispatcher; + + /** + * @var \Illuminate\Contracts\Config\Repository + */ + protected $configRepository; + + /** + * Initialized lazily in $this->documentAST(). * * @var \Nuwave\Lighthouse\Schema\AST\DocumentAST */ protected $documentAST; - /** - * ASTBuilder constructor. - * - * @param \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory $directiveFactory - * @param \Illuminate\Contracts\Events\Dispatcher $eventDispatcher - * @param \Nuwave\Lighthouse\Schema\Source\SchemaSourceProvider $schemaSourceProvider - * @return void - */ public function __construct( - DirectiveFactory $directiveFactory, - EventDispatcher $eventDispatcher, - SchemaSourceProvider $schemaSourceProvider + DirectiveLocator $directiveLocator, + SchemaSourceProvider $schemaSourceProvider, + EventsDispatcher $eventsDispatcher, + ConfigRepository $configRepository ) { - $this->directiveFactory = $directiveFactory; - $this->eventDispatcher = $eventDispatcher; + $this->directiveLocator = $directiveLocator; $this->schemaSourceProvider = $schemaSourceProvider; + $this->eventsDispatcher = $eventsDispatcher; + $this->configRepository = $configRepository; + } + + public function documentAST(): DocumentAST + { + if (! isset($this->documentAST)) { + $cacheConfig = $this->configRepository->get('lighthouse.cache'); + + $this->documentAST = $cacheConfig['enable'] + ? $this->fromCacheOrBuild($cacheConfig) + : $this->build(); + } + + return $this->documentAST; } /** - * Get the schema string and build an AST out of it. - * - * @return \Nuwave\Lighthouse\Schema\AST\DocumentAST + * @param array $cacheConfig */ - public function build(): DocumentAST + protected function fromCacheOrBuild(array $cacheConfig): DocumentAST + { + $version = $cacheConfig['version'] ?? 1; + switch ($version) { + case 1: + /** @var \Illuminate\Contracts\Cache\Factory $cacheFactory */ + $cacheFactory = app(CacheFactory::class); + $cache = $cacheFactory->store($cacheConfig['store'] ?? null); + + return $cache->remember( + $cacheConfig['key'], + $cacheConfig['ttl'], + function (): DocumentAST { + return $this->build(); + } + ); + case 2: + /** @var \Illuminate\Filesystem\Filesystem $filesystem */ + $filesystem = app(Filesystem::class); + $path = $cacheConfig['path'] ?? base_path('bootstrap/cache/lighthouse-schema.php'); + + if ($filesystem->exists($path)) { + return DocumentAST::fromArray(require $path); + } + + $documentAST = $this->build(); + $variable = var_export($documentAST->toArray(), true); + $filesystem->put($path, /** @lang PHP */ "schemaSourceProvider->getSchemaString(); // Allow to register listeners that add in additional schema definitions. // This can be used by plugins to hook into the schema building process // while still allowing the user to add in their schema as usual. - $additionalSchemas = (array) $this->eventDispatcher->dispatch( + $additionalSchemas = (array) $this->eventsDispatcher->dispatch( new BuildSchemaString($schemaString) ); @@ -92,14 +153,10 @@ class ASTBuilder $this->applyFieldManipulators(); $this->applyArgManipulators(); - $this->addPaginationInfoTypes(); - $this->addNodeSupport(); - $this->addOrderByTypes(); - // Listeners may manipulate the DocumentAST that is passed by reference // into the ManipulateAST event. This can be useful for extensions // that want to programmatically change the schema. - $this->eventDispatcher->dispatch( + $this->eventsDispatcher->dispatch( new ManipulateAST($this->documentAST) ); @@ -108,15 +165,13 @@ class ASTBuilder /** * Apply directives on type definitions that can manipulate the AST. - * - * @return void */ protected function applyTypeDefinitionManipulators(): void { foreach ($this->documentAST->types as $typeDefinition) { /** @var \Nuwave\Lighthouse\Support\Contracts\TypeManipulator $typeDefinitionManipulator */ foreach ( - $this->directiveFactory->createAssociatedDirectivesOfType($typeDefinition, TypeManipulator::class) + $this->directiveLocator->associatedOfType($typeDefinition, TypeManipulator::class) as $typeDefinitionManipulator ) { $typeDefinitionManipulator->manipulateTypeDefinition($this->documentAST, $typeDefinition); @@ -126,40 +181,120 @@ class ASTBuilder /** * Apply directives on type extensions that can manipulate the AST. - * - * @return void */ protected function applyTypeExtensionManipulators(): void { foreach ($this->documentAST->typeExtensions as $typeName => $typeExtensionsList) { - /** @var \GraphQL\Language\AST\TypeExtensionNode $typeExtension */ foreach ($typeExtensionsList as $typeExtension) { + // Before we actually extend the types, we apply the manipulator directives + // that are defined on type extensions themselves /** @var \Nuwave\Lighthouse\Support\Contracts\TypeExtensionManipulator $typeExtensionManipulator */ foreach ( - $this->directiveFactory->createAssociatedDirectivesOfType($typeExtension, TypeExtensionManipulator::class) + $this->directiveLocator->associatedOfType($typeExtension, TypeExtensionManipulator::class) as $typeExtensionManipulator ) { - $typeExtensionManipulator->manipulatetypeExtension($this->documentAST, $typeExtension); + $typeExtensionManipulator->manipulateTypeExtension($this->documentAST, $typeExtension); } // After manipulation on the type extension has been done, - // we can merge its fields with the original type - if ($typeExtension instanceof ObjectTypeExtensionNode) { - $relatedObjectType = $this->documentAST->types[$typeName]; - - $relatedObjectType->fields = ASTHelper::mergeUniqueNodeList( - $relatedObjectType->fields, - $typeExtension->fields - ); + // we can merge them with the original type + if ( + $typeExtension instanceof ObjectTypeExtensionNode + || $typeExtension instanceof InputObjectTypeExtensionNode + || $typeExtension instanceof InterfaceTypeExtensionNode + ) { + $this->extendObjectLikeType($typeName, $typeExtension); + } elseif ($typeExtension instanceof EnumTypeExtensionNode) { + $this->extendEnumType($typeName, $typeExtension); } } } } /** - * Apply directives on fields that can manipulate the AST. + * @param \GraphQL\Language\AST\ObjectTypeExtensionNode|\GraphQL\Language\AST\InputObjectTypeExtensionNode|\GraphQL\Language\AST\InterfaceTypeExtensionNode $typeExtension + */ + protected function extendObjectLikeType(string $typeName, TypeExtensionNode $typeExtension): void + { + /** @var \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\InputObjectTypeDefinitionNode|\GraphQL\Language\AST\InterfaceTypeDefinitionNode|null $extendedObjectLikeType */ + $extendedObjectLikeType = $this->documentAST->types[$typeName] ?? null; + if ($extendedObjectLikeType === null) { + if (RootType::isRootType($typeName)) { + $extendedObjectLikeType = Parser::objectTypeDefinition(/** @lang GraphQL */ "type {$typeName}"); + $this->documentAST->setTypeDefinition($extendedObjectLikeType); + } else { + throw new DefinitionException( + $this->missingBaseDefinition($typeName, $typeExtension) + ); + } + } + + $this->assertExtensionMatchesDefinition($typeExtension, $extendedObjectLikeType); + + // @phpstan-ignore-next-line we know the types of fields will match because we passed assertExtensionMatchesDefinition(). + $extendedObjectLikeType->fields = ASTHelper::mergeUniqueNodeList( + // @phpstan-ignore-next-line + $extendedObjectLikeType->fields, + // @phpstan-ignore-next-line + $typeExtension->fields + ); + + if ($extendedObjectLikeType instanceof ObjectTypeDefinitionNode) { + /** + * We know this because we passed assertExtensionMatchesDefinition(). + * + * @var \GraphQL\Language\AST\ObjectTypeExtensionNode $typeExtension + */ + $extendedObjectLikeType->interfaces = ASTHelper::mergeUniqueNodeList( + $extendedObjectLikeType->interfaces, + $typeExtension->interfaces + ); + } + } + + protected function extendEnumType(string $typeName, EnumTypeExtensionNode $typeExtension): void + { + /** @var \GraphQL\Language\AST\EnumTypeDefinitionNode|null $extendedEnum */ + $extendedEnum = $this->documentAST->types[$typeName] ?? null; + if ($extendedEnum === null) { + throw new DefinitionException( + $this->missingBaseDefinition($typeName, $typeExtension) + ); + } + + $this->assertExtensionMatchesDefinition($typeExtension, $extendedEnum); + + $extendedEnum->values = ASTHelper::mergeUniqueNodeList( + $extendedEnum->values, + $typeExtension->values + ); + } + + /** + * @param \GraphQL\Language\AST\ObjectTypeExtensionNode|\GraphQL\Language\AST\InputObjectTypeExtensionNode|\GraphQL\Language\AST\InterfaceTypeExtensionNode|\GraphQL\Language\AST\EnumTypeExtensionNode $typeExtension + */ + protected function missingBaseDefinition(string $typeName, TypeExtensionNode $typeExtension): string + { + return "Could not find a base definition {$typeName} of kind {$typeExtension->kind} to extend."; + } + + /** + * @param \GraphQL\Language\AST\ObjectTypeExtensionNode|\GraphQL\Language\AST\InputObjectTypeExtensionNode|\GraphQL\Language\AST\InterfaceTypeExtensionNode|\GraphQL\Language\AST\EnumTypeExtensionNode $extension + * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\InputObjectTypeDefinitionNode|\GraphQL\Language\AST\InterfaceTypeDefinitionNode|\GraphQL\Language\AST\EnumTypeDefinitionNode $definition * - * @return void + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + protected function assertExtensionMatchesDefinition(TypeExtensionNode $extension, TypeDefinitionNode $definition): void + { + if (static::EXTENSION_TO_DEFINITION_CLASS[get_class($extension)] !== get_class($definition)) { + throw new DefinitionException( + "The type extension {$extension->name->value} of kind {$extension->kind} can not extend a definition of kind {$definition->kind}." + ); + } + } + + /** + * Apply directives on fields that can manipulate the AST. */ protected function applyFieldManipulators(): void { @@ -168,7 +303,7 @@ class ASTBuilder foreach ($typeDefinition->fields as $fieldDefinition) { /** @var \Nuwave\Lighthouse\Support\Contracts\FieldManipulator $fieldManipulator */ foreach ( - $this->directiveFactory->createAssociatedDirectivesOfType($fieldDefinition, FieldManipulator::class) + $this->directiveLocator->associatedOfType($fieldDefinition, FieldManipulator::class) as $fieldManipulator ) { $fieldManipulator->manipulateFieldDefinition($this->documentAST, $fieldDefinition, $typeDefinition); @@ -180,8 +315,6 @@ class ASTBuilder /** * Apply directives on args that can manipulate the AST. - * - * @return void */ protected function applyArgManipulators(): void { @@ -191,7 +324,7 @@ class ASTBuilder foreach ($fieldDefinition->arguments as $argumentDefinition) { /** @var \Nuwave\Lighthouse\Support\Contracts\ArgManipulator $argManipulator */ foreach ( - $this->directiveFactory->createAssociatedDirectivesOfType($argumentDefinition, ArgManipulator::class) + $this->directiveLocator->associatedOfType($argumentDefinition, ArgManipulator::class) as $argManipulator ) { $argManipulator->manipulateArgDefinition( @@ -206,159 +339,4 @@ class ASTBuilder } } } - - /** - * Add the types required for pagination. - * - * @return void - */ - protected function addPaginationInfoTypes(): void - { - $this->documentAST->setTypeDefinition( - PartialParser::objectTypeDefinition(' - type PaginatorInfo { - "Total count of available items in the page." - count: Int! - - "Current pagination page." - currentPage: Int! - - "Index of first item in the current page." - firstItem: Int - - "If collection has more pages." - hasMorePages: Boolean! - - "Index of last item in the current page." - lastItem: Int - - "Last page number of the collection." - lastPage: Int! - - "Number of items per page in the collection." - perPage: Int! - - "Total items available in the collection." - total: Int! - } - ') - ); - - $this->documentAST->setTypeDefinition( - PartialParser::objectTypeDefinition(' - type PageInfo { - "When paginating forwards, are there more items?" - hasNextPage: Boolean! - - "When paginating backwards, are there more items?" - hasPreviousPage: Boolean! - - "When paginating backwards, the cursor to continue." - startCursor: String - - "When paginating forwards, the cursor to continue." - endCursor: String - - "Total number of node in connection." - total: Int - - "Count of nodes in current request." - count: Int - - "Current page of request." - currentPage: Int - - "Last page in connection." - lastPage: Int - } - ') - ); - } - - /** - * Returns whether or not the given interface is used within the defined types. - * - * @param string $interfaceName - * - * @return bool - */ - protected function hasTypeImplementingInterface(string $interfaceName): bool - { - foreach ($this->documentAST->types as $typeDefinition) { - if ($typeDefinition instanceof ObjectTypeDefinitionNode) { - if (ASTHelper::typeImplementsInterface($typeDefinition, $interfaceName)) { - return true; - } - } - } - - return false; - } - - /** - * Inject the Node interface and a node field into the Query type. - * - * @return void - */ - protected function addNodeSupport(): void - { - // Only add the node type and node field if a type actually implements them - // Otherwise, a validation error is thrown - if (! $this->hasTypeImplementingInterface('Node')) { - return; - } - - $globalId = config('lighthouse.global_id_field'); - // Double slashes to escape the slashes in the namespace. - $this->documentAST->setTypeDefinition( - PartialParser::interfaceTypeDefinition(<<documentAST->types['Query']; - $queryType->fields = ASTHelper::mergeNodeList( - $queryType->fields, - [ - PartialParser::fieldDefinition(' - node(id: ID! @globalId): Node @field(resolver: "Nuwave\\\Lighthouse\\\Schema\\\NodeRegistry@resolve") - '), - ] - ); - } - - /** - * Add types that are used for the @orderBy directive. - * - * @see \Nuwave\Lighthouse\Schema\Directives\OrderByDirective - * - * @return void - */ - protected function addOrderByTypes(): void - { - $this->documentAST->setTypeDefinition( - PartialParser::enumTypeDefinition(' - enum SortOrder { - ASC - DESC - } - ' - ) - ); - - $this->documentAST->setTypeDefinition( - PartialParser::inputObjectTypeDefinition(' - input OrderByClause { - field: String! - order: SortOrder! - } - ') - ); - } } diff --git a/vendor/nuwave/lighthouse/src/Schema/AST/ASTHelper.php b/vendor/nuwave/lighthouse/src/Schema/AST/ASTHelper.php index b7d6b13..6d990cf 100644 --- a/vendor/nuwave/lighthouse/src/Schema/AST/ASTHelper.php +++ b/vendor/nuwave/lighthouse/src/Schema/AST/ASTHelper.php @@ -2,56 +2,44 @@ namespace Nuwave\Lighthouse\Schema\AST; -use GraphQL\Utils\AST; -use GraphQL\Language\Parser; -use GraphQL\Language\AST\Node; -use GraphQL\Type\Definition\Type; -use GraphQL\Language\AST\NodeList; -use Illuminate\Support\Collection; -use GraphQL\Language\AST\ValueNode; -use GraphQL\Type\Definition\EnumType; -use GraphQL\Language\AST\ArgumentNode; -use GraphQL\Language\AST\ListTypeNode; +use Exception; +use GraphQL\Error\SyntaxError; +use GraphQL\Executor\Values; +use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DirectiveNode; +use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\InputValueDefinitionNode; +use GraphQL\Language\AST\InterfaceTypeDefinitionNode; use GraphQL\Language\AST\NamedTypeNode; -use GraphQL\Language\AST\NonNullTypeNode; +use GraphQL\Language\AST\Node; +use GraphQL\Language\AST\NodeList; use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Language\AST\ObjectTypeExtensionNode; +use GraphQL\Language\AST\ValueNode; +use GraphQL\Language\Parser; +use GraphQL\Type\Definition\Directive; +use GraphQL\Type\Definition\EnumType; +use GraphQL\Type\Definition\Type; +use GraphQL\Utils\AST; +use Illuminate\Container\Container; +use Illuminate\Support\Collection; +use Illuminate\Support\Str; use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\DirectiveLocator; +use Nuwave\Lighthouse\Schema\Directives\ModelDirective; use Nuwave\Lighthouse\Schema\Directives\NamespaceDirective; class ASTHelper { /** - * This function exists as a workaround for an issue within webonyx/graphql-php. + * Merge two lists of AST nodes. * - * The problem is that lists of definitions are usually NodeList objects - except - * when the list is empty, then it is []. This function corrects that inconsistency - * and allows the rest of our code to not worry about it until it is fixed. - * - * This issue is brought up here https://github.com/webonyx/graphql-php/issues/285 - * Remove this method (and possibly the entire class) once it is resolved. - * - * @param \GraphQL\Language\AST\NodeList|array $original - * @param \GraphQL\Language\AST\NodeList|array $addition - * @return \GraphQL\Language\AST\NodeList - */ - public static function mergeNodeList($original, $addition): NodeList - { - if (! $original instanceof NodeList) { - $original = new NodeList($original); - } - - return $original->merge($addition); - } - - /** - * This function will merge two lists uniquely by name. - * - * @param \GraphQL\Language\AST\NodeList|array $original - * @param \GraphQL\Language\AST\NodeList|array $addition - * @param bool $overwriteDuplicates By default this throws if a collision occurs. If - * this is set to true, the fields of the original list will be overwritten. - * @return \GraphQL\Language\AST\NodeList + * @template TNode of \GraphQL\Language\AST\Node + * @param \GraphQL\Language\AST\NodeList|array $original + * @param \GraphQL\Language\AST\NodeList|array $addition + * @param bool $overwriteDuplicates By default this function throws if a collision occurs. + * If set to true, the fields of the original list will be overwritten. + * @return \GraphQL\Language\AST\NodeList */ public static function mergeUniqueNodeList($original, $addition, bool $overwriteDuplicates = false): NodeList { @@ -63,14 +51,11 @@ class ASTHelper $remainingDefinitions = (new Collection($original)) ->reject(function ($definition) use ($newNames, $overwriteDuplicates): bool { $oldName = $definition->name->value; - $collisionOccurred = in_array( - $oldName, - $newNames - ); + $collisionOccurred = in_array($oldName, $newNames); if ($collisionOccurred && ! $overwriteDuplicates) { throw new DefinitionException( - "Duplicate definition {$oldName} found when merging." + static::duplicateDefinition($oldName) ); } @@ -79,26 +64,44 @@ class ASTHelper ->values() ->all(); - return self::mergeNodeList($remainingDefinitions, $addition); + /** + * Since we did not modify the passed in lists, the types did not change. + * + * @var \GraphQL\Language\AST\NodeList $merged + */ + $merged = (new NodeList($remainingDefinitions))->merge($addition); + + return $merged; } /** - * @param \GraphQL\Language\AST\Node $definition - * @return string + * @template TNode of \GraphQL\Language\AST\Node + * @param \GraphQL\Language\AST\NodeList $nodeList + * @param TNode $node + * @return \GraphQL\Language\AST\NodeList + */ + public static function prepend(NodeList $nodeList, Node $node): NodeList + { + return (new NodeList([$node]))->merge($nodeList); + } + + public static function duplicateDefinition(string $oldName): string + { + return "Duplicate definition {$oldName} found when merging."; + } + + /** + * Unwrap lists and non-nulls and get the name of the contained type. */ public static function getUnderlyingTypeName(Node $definition): string { - $type = $definition->type; - if ($type instanceof ListTypeNode || $type instanceof NonNullTypeNode) { - $type = self::getUnderlyingNamedTypeNode($type); - } + $namedType = self::getUnderlyingNamedTypeNode($definition); - return $type->name->value; + return $namedType->name->value; } /** - * @param \GraphQL\Language\AST\Node $node - * @return \GraphQL\Language\AST\NamedTypeNode + * Unwrap lists and non-nulls and get the named type within. * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ @@ -120,108 +123,99 @@ class ASTHelper } /** - * Does the given directive have an argument of the given name? + * Extract a named argument from a given directive node. * - * @param \GraphQL\Language\AST\DirectiveNode $directiveDefinition - * @param string $name - * @return bool - */ - 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; - }); - } - - /** - * @param \GraphQL\Language\AST\DirectiveNode $directive - * @param string $name - * @param mixed|null $default - * @return mixed|null + * @param mixed $default Is returned if the directive does not have the argument. + * @return mixed The value given to the directive. */ public static function directiveArgValue(DirectiveNode $directive, string $name, $default = null) { - $arg = (new Collection($directive->arguments)) - ->first(function (ArgumentNode $argumentNode) use ($name): bool { - return $argumentNode->name->value === $name; - }); + /** @var \GraphQL\Language\AST\ArgumentNode|null $arg */ + $arg = self::firstByName($directive->arguments, $name); - return $arg - ? self::argValue($arg, $default) + return $arg !== null + ? AST::valueFromASTUntyped($arg->value) : $default; } - /** - * Get argument's value. - * - * @param \GraphQL\Language\AST\ArgumentNode $arg - * @param mixed $default - * @return mixed - */ - public static function argValue(ArgumentNode $arg, $default = null) - { - $valueNode = $arg->value; - - if (! $valueNode) { - return $default; - } - - return AST::valueFromASTUntyped($valueNode); - } - /** * Return the PHP internal value of an arguments default value. * - * @param \GraphQL\Language\AST\ValueNode $defaultValue - * @param \GraphQL\Type\Definition\Type $argumentType - * @return mixed + * @param \GraphQL\Language\AST\ValueNode&\GraphQL\Language\AST\Node $defaultValue + * @param \GraphQL\Type\Definition\Type&\GraphQL\Type\Definition\InputType $argumentType + * @return mixed The plain PHP value. */ public static function defaultValueForArgument(ValueNode $defaultValue, Type $argumentType) { // webonyx/graphql-php expects the internal value here, whereas the // SDL uses the ENUM's name, so we run the conversion here if ($argumentType instanceof EnumType) { - return $argumentType - ->getValue( - $defaultValue->value - ) - ->value; + /** @var \GraphQL\Language\AST\EnumValueNode $defaultValue */ + + /** @var \GraphQL\Type\Definition\EnumValueDefinition $internalValue */ + $internalValue = $argumentType->getValue($defaultValue->value); + + return $internalValue->value; } + // @phpstan-ignore-next-line any ValueNode is fine return AST::valueFromAST($defaultValue, $argumentType); } /** - * This can be at most one directive, since directives can only be used once per location. + * Get a directive with the given name if it is defined upon the node. * - * @param \GraphQL\Language\AST\Node $definitionNode - * @param string $name - * @return \GraphQL\Language\AST\DirectiveNode|null + * As of now, directives may only be used once per location. */ 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; - }); + if (! property_exists($definitionNode, 'directives')) { + throw new Exception('Expected Node class with property `directives`, got: '.get_class($definitionNode)); + } + /** @var \GraphQL\Language\AST\NodeList<\GraphQL\Language\AST\DirectiveNode> $directives */ + $directives = $definitionNode->directives; + + return self::firstByName($directives, $name); + } + + /** + * Check if a node has a directive with the given name on it. + */ + public static function hasDirective(Node $definitionNode, string $name): bool + { + return self::directiveDefinition($definitionNode, $name) !== null; + } + + /** + * Out of a list of nodes, get the first that matches the given name. + * + * @template TNode of \GraphQL\Language\AST\Node + * @param iterable $nodes + * @return TNode|null + */ + public static function firstByName($nodes, string $name): ?Node + { + foreach ($nodes as $node) { + if (! property_exists($node, 'name')) { + throw new Exception('Expected a Node with a name property, got: '.get_class($node)); + } + + if ($node->name->value === $name) { + return $node; + } + } + + return null; } /** * Directives might have an additional namespace associated with them, set via the "@namespace" directive. - * - * @param \GraphQL\Language\AST\Node $definitionNode - * @param string $directiveName - * @return string */ public static function getNamespaceForDirective(Node $definitionNode, string $directiveName): string { - $namespaceDirective = static::directiveDefinition( - $definitionNode, - NamespaceDirective::NAME - ); + $namespaceDirective = static::directiveDefinition($definitionNode, NamespaceDirective::NAME); - return $namespaceDirective + return $namespaceDirective !== null // The namespace directive can contain an argument with the name of the // current directive, in which case it applies here ? static::directiveArgValue($namespaceDirective, $directiveName, '') @@ -233,62 +227,176 @@ class ASTHelper * Attach directive to all registered object type fields. * * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\DirectiveNode $directive - * @return void */ public static function attachDirectiveToObjectTypeFields(DocumentAST $documentAST, DirectiveNode $directive): void { foreach ($documentAST->types as $typeDefinition) { if ($typeDefinition instanceof ObjectTypeDefinitionNode) { - foreach ($typeDefinition->fields as $fieldDefinition) { - $fieldDefinition->directives = $fieldDefinition->directives->merge([$directive]); + /** @var iterable<\GraphQL\Language\AST\FieldDefinitionNode> $fieldDefinitions */ + $fieldDefinitions = $typeDefinition->fields; + foreach ($fieldDefinitions as $fieldDefinition) { + $fieldDefinition->directives = static::prepend($fieldDefinition->directives, $directive); } } } } - /** - * Add the "Node" interface and a global ID field to an object type. - * - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $objectType - * @return \GraphQL\Language\AST\ObjectTypeDefinitionNode - */ - public static function attachNodeInterfaceToObjectType(ObjectTypeDefinitionNode $objectType): ObjectTypeDefinitionNode - { - $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 $objectType; - } - /** * Checks the given type to see whether it implements the given interface. - * - * @param ObjectTypeDefinitionNode $type - * @param string $interfaceName - * - * @return bool */ public static function typeImplementsInterface(ObjectTypeDefinitionNode $type, string $interfaceName): bool { - foreach ($type->interfaces as $interface) { - if ($interface->name->value === $interfaceName) { - return true; + return self::firstByName($type->interfaces, $interfaceName) !== null; + } + + /** + * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\ObjectTypeExtensionNode|mixed $objectType + * + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + public static function addDirectiveToFields(DirectiveNode $directiveNode, &$objectType): void + { + $name = $directiveNode->name->value; + + if ( + ! $objectType instanceof ObjectTypeDefinitionNode + && ! $objectType instanceof ObjectTypeExtensionNode + ) { + throw new DefinitionException( + "The @{$name} directive may only be placed on fields or object types." + ); + } + + /** @var \Nuwave\Lighthouse\Schema\DirectiveLocator $directiveLocator */ + $directiveLocator = Container::getInstance()->make(DirectiveLocator::class); + $directive = $directiveLocator->resolve($name); + $directiveDefinition = self::extractDirectiveDefinition($directive::definition()); + + /** @var iterable<\GraphQL\Language\AST\FieldDefinitionNode> $fieldDefinitions */ + $fieldDefinitions = $objectType->fields; + foreach ($fieldDefinitions as $fieldDefinition) { + // If the field already has the same directive defined, and it is not + // a repeatable directive, skip over it. + // Field directives are more specific than those defined on a type. + if ( + self::hasDirective($fieldDefinition, $name) + && ! $directiveDefinition->repeatable + ) { + continue; + } + + $fieldDefinition->directives = static::prepend($fieldDefinition->directives, $directiveNode); + } + } + + /** + * Create a fully qualified base for a generated name that belongs to an argument. + * + * We have to make sure it is unique in the schema. Even though + * this name becomes a bit verbose, it is also very unlikely to collide + * with a random user defined type. + * + * @example ParentNameFieldNameArgName + */ + public static function qualifiedArgType( + InputValueDefinitionNode &$argDefinition, + FieldDefinitionNode &$parentField, + ObjectTypeDefinitionNode &$parentType + ): string { + return Str::studly($parentType->name->value) + .Str::studly($parentField->name->value) + .Str::studly($argDefinition->name->value); + } + + /** + * Given a collection of directives, returns the string value for the deprecation reason. + * + * @param \GraphQL\Language\AST\EnumValueDefinitionNode|\GraphQL\Language\AST\FieldDefinitionNode $node + * @return string + */ + public static function deprecationReason(Node $node): ?string + { + $deprecated = Values::getDirectiveValues( + Directive::deprecatedDirective(), + $node + ); + + return $deprecated['reason'] ?? null; + } + + /** + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + public static function extractDirectiveDefinition(string $definitionString): DirectiveDefinitionNode + { + try { + $document = Parser::parse($definitionString); + } catch (SyntaxError $error) { + throw new DefinitionException( + "Encountered syntax error while parsing this directive definition::\n\n{$definitionString}", + $error->getCode(), + $error + ); + } + + /** @var \GraphQL\Language\AST\DirectiveDefinitionNode|null $directive */ + $directive = null; + foreach ($document->definitions as $definitionNode) { + if ($definitionNode instanceof DirectiveDefinitionNode) { + if ($directive !== null) { + throw new DefinitionException( + "Found multiple directives while trying to extract a single directive from this definition:\n\n{$definitionString}" + ); + } + + $directive = $definitionNode; } } - return false; + if ($directive === null) { + throw new DefinitionException( + "Found no directive while trying to extract a single directive from this definition:\n\n{$definitionString}" + ); + } + + return $directive; + } + + /** + * @return \GraphQL\Language\AST\Node&\GraphQL\Language\AST\TypeDefinitionNode + */ + public static function underlyingType(FieldDefinitionNode $field): Node + { + $typeName = static::getUnderlyingTypeName($field); + + /** @var \Nuwave\Lighthouse\Schema\AST\ASTBuilder $astBuilder */ + $astBuilder = app(ASTBuilder::class); + $documentAST = $astBuilder->documentAST(); + + $type = $documentAST->types[$typeName] ?? null; + if ($type === null) { + throw new DefinitionException( + "Type '$typeName' on '{$field->name->value}' can not be found in the schema.'" + ); + } + + return $type; + } + + /** + * Take a guess at the name of the model associated with the given node. + */ + public static function modelName(Node $definitionNode): ?string + { + if ($definitionNode instanceof FieldDefinitionNode) { + $definitionNode = static::underlyingType($definitionNode); + } + + if ($definitionNode instanceof ObjectTypeDefinitionNode || $definitionNode instanceof InterfaceTypeDefinitionNode) { + return ModelDirective::modelClass($definitionNode) + ?? $definitionNode->name->value; + } + + return null; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/AST/DocumentAST.php b/vendor/nuwave/lighthouse/src/Schema/AST/DocumentAST.php index 9458d30..b40999e 100644 --- a/vendor/nuwave/lighthouse/src/Schema/AST/DocumentAST.php +++ b/vendor/nuwave/lighthouse/src/Schema/AST/DocumentAST.php @@ -3,24 +3,32 @@ namespace Nuwave\Lighthouse\Schema\AST; use Exception; -use Serializable; -use GraphQL\Language\Parser; use GraphQL\Error\SyntaxError; +use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeList; -use GraphQL\Language\AST\TypeExtensionNode; use GraphQL\Language\AST\TypeDefinitionNode; +use GraphQL\Language\AST\TypeExtensionNode; +use GraphQL\Language\Parser; +use Illuminate\Contracts\Support\Arrayable; use Nuwave\Lighthouse\Exceptions\ParseException; -use GraphQL\Language\AST\DirectiveDefinitionNode; +use Serializable; -class DocumentAST implements Serializable +/** + * Represents the AST of the entire GraphQL schema document. + * + * Explicitly implementing Serializable provides performance gains by: + * - stripping unnecessary data + * - leveraging lazy instantiation of schema types + */ +class DocumentAST implements Serializable, Arrayable { /** * The types within the schema. * * ['foo' => FooType]. * - * @var NodeList + * @var \GraphQL\Language\AST\NodeList<\GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node>|array */ public $types = []; @@ -30,9 +38,7 @@ class DocumentAST implements Serializable * Will NOT be kept after unserialization, as the type * extensions are merged with the types before. * - * ['foo' => [0 => FooExtension, 1 => FooExtension]]. - * - * @var NodeList[] + * @var array> */ public $typeExtensions = []; @@ -41,14 +47,13 @@ class DocumentAST implements Serializable * * ['foo' => FooDirective]. * - * @var NodeList + * @var \GraphQL\Language\AST\NodeList<\GraphQL\Language\AST\DirectiveDefinitionNode>|array */ public $directives = []; /** * Create a new DocumentAST instance from a schema. * - * @param string $schema * @return static * * @throws \Nuwave\Lighthouse\Exceptions\ParseException @@ -64,12 +69,10 @@ class DocumentAST implements Serializable } catch (SyntaxError $syntaxError) { // Throw our own error class instead, since otherwise a schema definition // error would get rendered to the Client. - throw new ParseException( - $syntaxError->getMessage() - ); + throw new ParseException($syntaxError); } - $instance = new self; + $instance = new static; foreach ($documentNode->definitions as $definition) { if ($definition instanceof TypeDefinitionNode) { @@ -90,50 +93,13 @@ class DocumentAST implements Serializable return $instance; } - /** - * Serialize the final AST. - * - * We exclude the type extensions stored in $typeExtensions, - * as they are merged with the actual types at this point. - * - * @return string - */ - public function serialize(): string - { - $nodeToArray = function (Node $node): array { - return $node->toArray(true); - }; - - return serialize([ - 'types' => array_map($nodeToArray, $this->types), - 'directives' => array_map($nodeToArray, $this->directives), - ]); - } - - /** - * Unserialize the AST. - * - * @param string $serialized - */ - public function unserialize($serialized): void - { - [ - 'types' => $types, - 'directives' => $directives, - ] = unserialize($serialized); - - // Utilize the NodeList for lazy unserialization for performance gains. - // Until they are accessed by name, they are kept in their array form. - $this->types = new NodeList($types); - $this->directives = new NodeList($directives); - } - /** * Set a type definition in the AST. * * This operation will overwrite existing definitions with the same name. * - * @param \GraphQL\Language\AST\TypeDefinitionNode $type + * @param \GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node $type + * * @return $this */ public function setTypeDefinition(TypeDefinitionNode $type): self @@ -148,7 +114,8 @@ class DocumentAST implements Serializable * * This operation will overwrite existing definitions with the same name. * - * @param \GraphQL\Language\AST\DirectiveDefinitionNode $directive + * @param \GraphQL\Language\AST\DirectiveDefinitionNode&\GraphQL\Language\AST\Node $directive + * * @return $this */ public function setDirectiveDefinition(DirectiveDefinitionNode $directive): self @@ -157,4 +124,67 @@ class DocumentAST implements Serializable return $this; } + + /** + * Convert to a serializable array. + * + * We exclude the type extensions stored in $typeExtensions, + * as they are merged with the actual types at this point. + * + * @return array + */ + public function toArray(): array + { + $nodeToArray = function (Node $node): array { + return $node->toArray(true); + }; + + return [ + // @phpstan-ignore-next-line Before serialization, those are arrays + 'types' => array_map($nodeToArray, $this->types), + // @phpstan-ignore-next-line Before serialization, those are arrays + 'directives' => array_map($nodeToArray, $this->directives), + ]; + } + + /** + * Instantiate from a serialized array. + * + * @param array $ast + */ + public static function fromArray(array $ast): DocumentAST + { + $documentAST = new static(); + $documentAST->hydrateFromArray($ast); + + return $documentAST; + } + + public function serialize(): string + { + return serialize($this->toArray()); + } + + public function unserialize($data): void + { + $this->hydrateFromArray(unserialize($data)); + } + + /** + * @param array $ast + */ + protected function hydrateFromArray(array $ast): void + { + [ + 'types' => $types, + 'directives' => $directives, + ] = $ast; + + // Utilize the NodeList for lazy unserialization for performance gains. + // Until they are accessed by name, they are kept in their array form. + // @phpstan-ignore-next-line TODO fixed in https://github.com/webonyx/graphql-php/pull/777 + $this->types = new NodeList($types); + // @phpstan-ignore-next-line TODO fixed in https://github.com/webonyx/graphql-php/pull/777 + $this->directives = new NodeList($directives); + } } diff --git a/vendor/nuwave/lighthouse/src/Schema/AST/PartialParser.php b/vendor/nuwave/lighthouse/src/Schema/AST/PartialParser.php deleted file mode 100644 index d57d815..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/AST/PartialParser.php +++ /dev/null @@ -1,323 +0,0 @@ -definitions, - ObjectTypeDefinitionNode::class - ); - } - - /** - * @param string $inputValueDefinition - * @return \GraphQL\Language\AST\InputValueDefinitionNode - */ - public static function inputValueDefinition(string $inputValueDefinition): InputValueDefinitionNode - { - return self::getFirstAndValidateType( - self::fieldDefinition("field($inputValueDefinition): String")->arguments, - InputValueDefinitionNode::class - ); - } - - /** - * @param string[] $inputValueDefinitions - * @return \GraphQL\Language\AST\InputValueDefinitionNode[] - */ - public static function inputValueDefinitions(array $inputValueDefinitions): array - { - return array_map( - function (string $inputValueDefinition): InputValueDefinitionNode { - return self::inputValueDefinition($inputValueDefinition); - }, - $inputValueDefinitions - ); - } - - /** - * @param string $argumentDefinition - * @return \GraphQL\Language\AST\ArgumentNode - */ - public static function argument(string $argumentDefinition): ArgumentNode - { - return self::getFirstAndValidateType( - self::field("field($argumentDefinition)")->arguments, - ArgumentNode::class - ); - } - - /** - * @param string[] $argumentDefinitions - * @return \GraphQL\Language\AST\ArgumentNode[] - */ - public static function arguments(array $argumentDefinitions): array - { - return array_map( - function (string $argumentDefinition): ArgumentNode { - return self::argument($argumentDefinition); - }, - $argumentDefinitions - ); - } - - /** - * @param string $field - * @return \GraphQL\Language\AST\FieldNode - */ - public static function field(string $field): FieldNode - { - return self::getFirstAndValidateType( - self::operationDefinition("{ $field }")->selectionSet->selections, - FieldNode::class - ); - } - - /** - * @param string $operation - * @return \GraphQL\Language\AST\OperationDefinitionNode - */ - public static function operationDefinition(string $operation): OperationDefinitionNode - { - return self::getFirstAndValidateType( - self::parse($operation)->definitions, - OperationDefinitionNode::class - ); - } - - /** - * @param string $fieldDefinition - * @return \GraphQL\Language\AST\FieldDefinitionNode - */ - public static function fieldDefinition(string $fieldDefinition): FieldDefinitionNode - { - return self::getFirstAndValidateType( - self::objectTypeDefinition("type Dummy { $fieldDefinition }")->fields, - FieldDefinitionNode::class - ); - } - - /** - * @param string $directive - * @return \GraphQL\Language\AST\DirectiveNode - */ - public static function directive(string $directive): DirectiveNode - { - return self::getFirstAndValidateType( - self::objectTypeDefinition(" - type Dummy $directive { - dummy: Int - } - ")->directives, - DirectiveNode::class - ); - } - - /** - * @param string[] $directives - * @return \GraphQL\Language\AST\DirectiveNode[] - */ - public static function directives(array $directives): array - { - return array_map( - function (string $directive): DirectiveNode { - return self::directive($directive); - }, - $directives - ); - } - - /** - * @param string $directiveDefinition - * @return \GraphQL\Language\AST\DirectiveDefinitionNode - */ - public static function directiveDefinition(string $directiveDefinition): DirectiveDefinitionNode - { - return self::getFirstAndValidateType( - self::parse($directiveDefinition)->definitions, - DirectiveDefinitionNode::class - ); - } - - /** - * @param string[] $directiveDefinitions - * @return \GraphQL\Language\AST\DirectiveDefinitionNode[] - */ - public static function directiveDefinitions(array $directiveDefinitions): array - { - return array_map( - function (string $directiveDefinition): DirectiveDefinitionNode { - return self::directiveDefinition($directiveDefinition); - }, - $directiveDefinitions - ); - } - - /** - * @param string $interfaceDefinition - * @return \GraphQL\Language\AST\InterfaceTypeDefinitionNode - */ - public static function interfaceTypeDefinition(string $interfaceDefinition): InterfaceTypeDefinitionNode - { - return self::getFirstAndValidateType( - self::parse($interfaceDefinition)->definitions, - InterfaceTypeDefinitionNode::class - ); - } - - /** - * @param string $unionDefinition - * @return \GraphQL\Language\AST\UnionTypeDefinitionNode - */ - public static function unionTypeDefinition(string $unionDefinition): UnionTypeDefinitionNode - { - return self::getFirstAndValidateType( - self::parse($unionDefinition)->definitions, - UnionTypeDefinitionNode::class - ); - } - - /** - * @param string $inputTypeDefinition - * @return \GraphQL\Language\AST\InputObjectTypeDefinitionNode - */ - public static function inputObjectTypeDefinition(string $inputTypeDefinition): InputObjectTypeDefinitionNode - { - return self::getFirstAndValidateType( - self::parse($inputTypeDefinition)->definitions, - InputObjectTypeDefinitionNode::class - ); - } - - /** - * @param string $scalarDefinition - * @return \GraphQL\Language\AST\ScalarTypeDefinitionNode - */ - public static function scalarTypeDefinition(string $scalarDefinition): ScalarTypeDefinitionNode - { - return self::getFirstAndValidateType( - self::parse($scalarDefinition)->definitions, - ScalarTypeDefinitionNode::class - ); - } - - /** - * @param string $enumDefinition - * @return \GraphQL\Language\AST\EnumTypeDefinitionNode - */ - public static function enumTypeDefinition(string $enumDefinition): EnumTypeDefinitionNode - { - return self::getFirstAndValidateType( - self::parse($enumDefinition)->definitions, - EnumTypeDefinitionNode::class - ); - } - - /** - * @param string $typeName - * @return \GraphQL\Language\AST\NamedTypeNode - * - * @throws \Nuwave\Lighthouse\Exceptions\ParseException - */ - public static function namedType(string $typeName): NamedTypeNode - { - return self::validateType( - self::parseType($typeName), - NamedTypeNode::class - ); - } - - /** - * @param string $definition - * @return \GraphQL\Language\AST\DocumentNode - */ - protected static function parse(string $definition): DocumentNode - { - // Ignore location since it only bloats the AST - return Parser::parse($definition, ['noLocation' => true]); - } - - /** - * @param string $definition - * @return \GraphQL\Language\AST\Node - */ - protected static function parseType(string $definition): Node - { - // Ignore location since it only bloats the AST - return Parser::parseType($definition, ['noLocation' => true]); - } - - /** - * Get the first Node from a given NodeList and validate it. - * - * @param \GraphQL\Language\AST\NodeList $list - * @param string $expectedType - * @return \GraphQL\Language\AST\Node - * - * @throws \Nuwave\Lighthouse\Exceptions\ParseException - */ - 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); - } - - /** - * @param \GraphQL\Language\AST\Node $node - * @param string $expectedType - * @return \GraphQL\Language\AST\Node - * - * @throws \Nuwave\Lighthouse\Exceptions\ParseException - */ - protected static function validateType(Node $node, string $expectedType): Node - { - if (! $node instanceof $expectedType) { - throw new ParseException("The given definition was not of type: $expectedType"); - } - - return $node; - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/AST/TypeNodeConverter.php b/vendor/nuwave/lighthouse/src/Schema/AST/TypeNodeConverter.php new file mode 100644 index 0000000..d281aff --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/AST/TypeNodeConverter.php @@ -0,0 +1,85 @@ +convertWrappedTypeNode($node); + } + + /** + * Convert an AST type and apply wrapping types. + * + * @param \GraphQL\Language\AST\TypeNode&\GraphQL\Language\AST\Node $node + * @param array $wrappers + * @return mixed The wrapped type. + */ + protected function convertWrappedTypeNode(TypeNode $node, array $wrappers = []) + { + // Recursively unwrap the type and save the wrappers + $nodeKind = $node->kind; + if (in_array($nodeKind, [NodeKind::NON_NULL_TYPE, NodeKind::LIST_TYPE])) { + /** @var \GraphQL\Language\AST\NonNullTypeNode|\GraphQL\Language\AST\ListTypeNode $node */ + $wrappers[] = $nodeKind; + + return $this->convertWrappedTypeNode( + $node->type, + $wrappers + ); + } + /** @var \GraphQL\Language\AST\NamedTypeNode $node */ + + // Re-wrap the type by applying the wrappers in the reversed order + return (new Collection($wrappers)) + ->reverse() + ->reduce( + function ($type, string $kind) { + if ($kind === NodeKind::NON_NULL_TYPE) { + return $this->nonNull($type); + } + + if ($kind === NodeKind::LIST_TYPE) { + return $this->listOf($type); + } + + return $type; + }, + $this->namedType($node->name->value) + ); + } + + /** + * Wrap or mark the type as non-null. + * + * @param mixed $type The type to wrap. + * @return mixed The type wrapped with non-null. + */ + abstract protected function nonNull($type); + + /** + * Wrap or mark the type as a list. + * + * @param mixed $type The type to wrap. + * @return mixed The type wrapped as a list. + */ + abstract protected function listOf($type); + + /** + * Get the named type for the given node name. + * + * @return mixed Representation of the type with the given name. + */ + abstract protected function namedType(string $nodeName); +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Context.php b/vendor/nuwave/lighthouse/src/Schema/Context.php index 289ecf9..676a755 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Context.php +++ b/vendor/nuwave/lighthouse/src/Schema/Context.php @@ -21,16 +21,10 @@ class Context implements GraphQLContext */ public $user; - /** - * Create new context. - * - * @param \Illuminate\Http\Request $request - * @return void - */ public function __construct(Request $request) { $this->request = $request; - $this->user = $request->user(); + $this->user = $request->user(config('lighthouse.guard')); } /** @@ -45,11 +39,6 @@ class Context implements GraphQLContext return $this->user; } - /** - * Get instance of request. - * - * @return \Illuminate\Http\Request - */ public function request(): Request { return $this->request; diff --git a/vendor/nuwave/lighthouse/src/Schema/Conversion/DefinitionNodeConverter.php b/vendor/nuwave/lighthouse/src/Schema/Conversion/DefinitionNodeConverter.php deleted file mode 100644 index cca4a3d..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Conversion/DefinitionNodeConverter.php +++ /dev/null @@ -1,100 +0,0 @@ -typeRegistry = $typeRegistry; - } - - /** - * Convert a definition node to an executable Type. - * - * @param mixed $node - * @return \GraphQL\Type\Definition\Type - */ - public function toType($node): Type - { - return $this->convertWrappedDefinitionNode($node); - } - - /** - * Unwrap the node if needed and convert to type. - * - * @param mixed $node - * @param string[] $wrappers - * @return \GraphQL\Type\Definition\Type - */ - protected function convertWrappedDefinitionNode($node, array $wrappers = []): Type - { - // Recursively unwrap the type and save the wrappers - if ($node->kind === NodeKind::NON_NULL_TYPE || $node->kind === NodeKind::LIST_TYPE) { - $wrappers[] = $node->kind; - - return $this->convertWrappedDefinitionNode( - $node->type, - $wrappers - ); - } - - // Re-wrap the type by applying the wrappers in the reversed order - return (new Collection($wrappers)) - ->reverse() - ->reduce( - function (Type $type, string $kind): Type { - if ($kind === NodeKind::NON_NULL_TYPE) { - return Type::nonNull($type); - } - - if ($kind === NodeKind::LIST_TYPE) { - return Type::listOf($type); - } - - return $type; - }, - $this->convertNamedTypeNode($node) - ); - } - - /** - * Converted named node to type. - * - * @param \GraphQL\Language\AST\NamedTypeNode $node - * @return \GraphQL\Type\Definition\Type - */ - protected function convertNamedTypeNode(NamedTypeNode $node): Type - { - $nodeName = $node->name->value; - switch ($nodeName) { - case 'ID': - return Type::id(); - case 'Int': - return Type::int(); - case 'Boolean': - return Type::boolean(); - case 'Float': - return Type::float(); - case 'String': - return Type::string(); - default: - return $this->typeRegistry->get($nodeName); - } - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/DirectiveLocator.php b/vendor/nuwave/lighthouse/src/Schema/DirectiveLocator.php new file mode 100644 index 0000000..9b1aed8 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/DirectiveLocator.php @@ -0,0 +1,279 @@ + + */ + protected $directiveNamespaces; + + /** + * A map from short directive names to full class names. + * + * E.g. + * [ + * 'create' => 'Nuwave\Lighthouse\Schema\Directives\CreateDirective', + * 'custom' => 'App\GraphQL\Directives\CustomDirective', + * ] + * + * @var array> + */ + protected $resolvedClassnames = []; + + /** + * @var \Illuminate\Contracts\Events\Dispatcher + */ + protected $eventsDispatcher; + + public function __construct(EventsDispatcher $eventsDispatcher) + { + $this->eventsDispatcher = $eventsDispatcher; + } + + /** + * A list of namespaces with directives in descending priority. + * + * @return array + */ + public function namespaces(): array + { + if ($this->directiveNamespaces === null) { + $this->directiveNamespaces = + // When looking for a directive by name, the namespaces are tried in order + (new Collection([ + // User defined directives (top priority) + config('lighthouse.namespaces.directives'), + + // Plugin developers defined directives + $this->eventsDispatcher->dispatch(new RegisterDirectiveNamespaces), + + // Lighthouse defined directives + 'Nuwave\\Lighthouse\\Schema\\Directives', + ])) + ->flatten() + ->filter() + ->all(); + } + + return $this->directiveNamespaces; + } + + /** + * Scan the namespaces for directive classes. + * + * @return array> + */ + public function classes(): array + { + $directives = []; + + foreach ($this->namespaces() as $directiveNamespace) { + /** @var array $classesInNamespace */ + $classesInNamespace = ClassFinder::getClassesInNamespace($directiveNamespace); + + foreach ($classesInNamespace as $class) { + $reflection = new \ReflectionClass($class); + if (! $reflection->isInstantiable()) { + continue; + } + + if (! is_a($class, Directive::class, true)) { + continue; + } + $name = self::directiveName($class); + + // The directive was already found, so we do not add it twice + if (isset($directives[$name])) { + continue; + } + + $directives[$name] = $class; + } + } + + return $directives; + } + + /** + * Return the parsed definitions for all directive classes. + * + * @return list<\GraphQL\Language\AST\DirectiveDefinitionNode> + */ + public function definitions(): array + { + $definitions = []; + + foreach ($this->classes() as $directiveClass) { + $definitions [] = ASTHelper::extractDirectiveDefinition($directiveClass::definition()); + } + + return $definitions; + } + + /** + * Create a directive by the given directive name. + */ + public function create(string $directiveName): Directive + { + $directiveClass = $this->resolve($directiveName); + + return app($directiveClass); + } + + /** + * Resolve the class for a given directive name. + * + * @return class-string<\Nuwave\Lighthouse\Support\Contracts\Directive> + * + * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + */ + public function resolve(string $directiveName): string + { + // Bail to respect the priority of namespaces, the first resolved directive is kept + if (array_key_exists($directiveName, $this->resolvedClassnames)) { + return $this->resolvedClassnames[$directiveName]; + } + + foreach ($this->namespaces() as $baseNamespace) { + $directiveClass = $baseNamespace.'\\'.static::className($directiveName); + + if (class_exists($directiveClass)) { + if (! is_a($directiveClass, Directive::class, true)) { + throw new DirectiveException("Class $directiveClass must implement the interface ".Directive::class); + } + $this->resolvedClassnames[$directiveName] = $directiveClass; + + return $directiveClass; + } + } + + throw new DirectiveException("No directive found for `{$directiveName}`"); + } + + /** + * Returns the expected class name for a directive name. + */ + protected static function className(string $directiveName): string + { + return Str::studly($directiveName).'Directive'; + } + + /** + * Returns the expected directive name for a class name. + */ + public static function directiveName(string $className): string + { + $baseName = basename(str_replace('\\', '/', $className)); + + return lcfirst( + Str::before($baseName, 'Directive') + ); + } + + /** + * @param class-string<\Nuwave\Lighthouse\Support\Contracts\Directive> $directiveClass + * @return $this + */ + public function setResolved(string $directiveName, string $directiveClass): self + { + $this->resolvedClassnames[$directiveName] = $directiveClass; + + return $this; + } + + /** + * Get all directives that are associated with an AST node. + * + * @return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> + */ + public function associated(Node $node): Collection + { + if (! property_exists($node, 'directives')) { + throw new Exception('Expected Node class with property `directives`, got: '.get_class($node)); + } + + return (new Collection($node->directives)) + ->map(function (DirectiveNode $directiveNode) use ($node): Directive { + $directive = $this->create($directiveNode->name->value); + + if ($directive instanceof BaseDirective) { + // @phpstan-ignore-next-line If there were directives on the given Node, it must be of an allowed type + $directive->hydrate($directiveNode, $node); + } + + return $directive; + }); + } + + /** + * Get all directives of a certain type that are associated with an AST node. + * + * @return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> of type <$directiveClass> + */ + public function associatedOfType(Node $node, string $directiveClass): Collection + { + return $this + ->associated($node) + ->filter(Utils::instanceofMatcher($directiveClass)); + } + + /** + * Get a single directive of a type that belongs to an AST node. + * + * Use this for directives types that can only occur once, such as field resolvers. + * This throws if more than one such directive is found. + * + * @param class-string<\Nuwave\Lighthouse\Support\Contracts\Directive> $directiveClass + * + * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + */ + public function exclusiveOfType(Node $node, string $directiveClass): ?Directive + { + $directives = $this->associatedOfType($node, $directiveClass); + + if ($directives->count() > 1) { + $directiveNames = $directives + ->map(function (Directive $directive): string { + $definition = ASTHelper::extractDirectiveDefinition( + $directive::definition() + ); + + return '@'.$definition->name->value; + }) + ->implode(', '); + + if (! property_exists($node, 'name')) { + throw new Exception('Expected Node class with property `name`, got: '.get_class($node)); + } + + throw new DirectiveException( + "Node {$node->name->value} can only have one directive of type {$directiveClass} but found [{$directiveNames}]." + ); + } + + return $directives->first(); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/DirectiveNamespacer.php b/vendor/nuwave/lighthouse/src/Schema/DirectiveNamespacer.php deleted file mode 100644 index 61e94f7..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/DirectiveNamespacer.php +++ /dev/null @@ -1,50 +0,0 @@ -dispatcher = $dispatcher; - } - - /** - * A list of namespaces with directives in descending priority. - * - * @return string[] - */ - public function gather(): array - { - // When looking for a directive by name, the namespaces are tried in order - return ( - new Collection([ - // User defined directives (top priority) - config('lighthouse.namespaces.directives'), - - // Plugin developers defined directives - $this->dispatcher->dispatch(new RegisterDirectiveNamespaces), - - // Lighthouse defined directives - 'Nuwave\\Lighthouse\\Schema\\Directives', - ])) - ->flatten() - ->filter() - ->all(); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/AggregateDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/AggregateDirective.php new file mode 100644 index 0000000..9ef9336 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/AggregateDirective.php @@ -0,0 +1,147 @@ +directiveArgValue('model'); + if (is_string($modelArg)) { + return $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($modelArg) { + /** @var Builder $query */ + $query = $this + ->namespaceModelClass($modelArg) + ::query(); + + $this->makeBuilderDecorator($resolveInfo)($query); + + return $query->{$this->function()}($this->column()); + } + ); + } + + $relation = $this->directiveArgValue('relation'); + if (is_string($relation)) { + $fieldValue->setResolver( + function (Model $parent, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { + /** @var \Nuwave\Lighthouse\Execution\BatchLoader\RelationBatchLoader $relationBatchLoader */ + $relationBatchLoader = BatchLoaderRegistry::instance( + array_merge( + $this->qualifyPath($args, $resolveInfo), + [$this->function(), $this->column()] + ), + function () use ($resolveInfo): RelationBatchLoader { + return new RelationBatchLoader( + new AggregateModelsLoader( + $this->relation(), + $this->column(), + $this->function(), + $this->makeBuilderDecorator($resolveInfo) + ) + ); + } + ); + + return $relationBatchLoader->load($parent); + } + ); + + return $fieldValue; + } + + throw new DefinitionException( + "A `model` or `relation` argument must be assigned to the '{$this->name()}' directive on '{$this->nodeName()}'." + ); + } + + protected function function(): string + { + return strtolower( + $this->directiveArgValue('function') + ); + } + + protected function column(): string + { + return $this->directiveArgValue('column'); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/AllDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/AllDirective.php index b2cab2e..45a8dcb 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/AllDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/AllDirective.php @@ -7,60 +7,54 @@ use Illuminate\Database\Eloquent\Collection; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class AllDirective extends BaseDirective implements DefinedDirective, FieldResolver +class AllDirective extends BaseDirective implements FieldResolver { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'all'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Fetch all Eloquent models and return the collection as the result. +""" directive @all( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String + """ + Point to a function that provides a Query Builder instance. + This replaces the use of a model. + """ + builder: String + """ Apply scopes to the underlying query. """ scopes: [String!] ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function resolveField(FieldValue $fieldValue): FieldValue { return $fieldValue->setResolver( function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Collection { - /** @var \Illuminate\Database\Eloquent\Model $modelClass */ - $modelClass = $this->getModelClass(); + if ($this->directiveHasArgument('builder')) { + $builderResolver = $this->getResolverFromArgument('builder'); + + $query = $builderResolver($root, $args, $context, $resolveInfo); + } else { + $query = $this->getModelClass()::query(); + } return $resolveInfo - ->builder - ->addScopes( + ->argumentSet + ->enhanceBuilder( + $query, $this->directiveArgValue('scopes', []) ) - ->apply( - $modelClass::query(), - $args - ) ->get(); } ); diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/ArgTraversalDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/ArgTraversalDirective.php new file mode 100644 index 0000000..f643c2d --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/ArgTraversalDirective.php @@ -0,0 +1,86 @@ +getResolver(); + + return $next( + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver) { + $resolveInfo->argumentSet = $this->transformRecursively($resolveInfo->argumentSet); + + return $resolver( + $root, + $resolveInfo->argumentSet->toArray(), + $context, + $resolveInfo + ); + } + ) + ); + } + + public function transformRecursively(ArgumentSet $argumentSet): ArgumentSet + { + foreach ($argumentSet->arguments as $argument) { + $directivesForArray = $argument->directives->filter( + Utils::instanceofMatcher(ArgDirectiveForArray::class) + ); + $argument->value = $this->transform($argument->value, $directivesForArray); + + $directivesForArgument = $argument->directives->filter( + Utils::instanceofMatcher(ArgDirective::class) + ); + + $argument->value = Utils::applyEach( + function ($value) use ($directivesForArgument) { + if ($value instanceof ArgumentSet) { + $value = $this->transform($value, $directivesForArgument); + + return $this->transformRecursively($value); + } else { + return $this->transform($value, $directivesForArgument); + } + }, + $argument->value + ); + } + + return $argumentSet; + } + + /** + * @param mixed $value The client given value + * @return mixed The transformed value + */ + protected function transform($value, Collection $directivesForArgument) + { + foreach ($directivesForArgument as $directive) { + $value = $this->applyDirective($directive, $value); + } + + return $value; + } + + /** + * @param mixed $value The client given value + * @return mixed The transformed value + */ + abstract protected function applyDirective(Directive $directive, $value); +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/AuthDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/AuthDirective.php index 6f4ad61..408e8a2 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/AuthDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/AuthDirective.php @@ -3,67 +3,46 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Illuminate\Contracts\Auth\Authenticatable; -use Nuwave\Lighthouse\Schema\Values\FieldValue; use Illuminate\Contracts\Auth\Factory as AuthFactory; +use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class AuthDirective extends BaseDirective implements DefinedDirective, FieldResolver +class AuthDirective extends BaseDirective implements FieldResolver { /** * @var \Illuminate\Contracts\Auth\Factory */ protected $authFactory; - /** - * AuthDirective constructor. - * - * @param \Illuminate\Contracts\Auth\Factory $authFactory - * @return void - */ public function __construct(AuthFactory $authFactory) { $this->authFactory = $authFactory; } - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'auth'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Return the currently authenticated user as the result of a query. """ directive @auth( """ - Use a particular guard to retreive the user. + Specify which guard to use, e.g. "api". + When not defined, the default from `lighthouse.php` is used. """ guard: String ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function resolveField(FieldValue $fieldValue): FieldValue { - /** @var string|null $guard */ - $guard = $this->directiveArgValue('guard'); - return $fieldValue->setResolver( - function () use ($guard): ?Authenticatable { + function (): ?Authenticatable { + /** @var string|null $guard */ + $guard = $this->directiveArgValue('guard', config('lighthouse.guard')); + + // @phpstan-ignore-next-line phpstan does not know about App\User, which implements Authenticatable return $this ->authFactory ->guard($guard) diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/BaseDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/BaseDirective.php index 17a67c0..fab9886 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/BaseDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/BaseDirective.php @@ -3,86 +3,77 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Closure; -use GraphQL\Language\AST\Node; -use Nuwave\Lighthouse\Support\Utils; use GraphQL\Language\AST\DirectiveNode; -use Illuminate\Database\Eloquent\Model; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use GraphQL\Language\AST\EnumTypeDefinitionNode; +use GraphQL\Language\AST\EnumValueDefinitionNode; use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\InputObjectTypeDefinitionNode; +use GraphQL\Language\AST\InputValueDefinitionNode; +use GraphQL\Language\AST\InterfaceTypeDefinitionNode; +use GraphQL\Language\AST\Node; use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Language\AST\ScalarTypeDefinitionNode; +use GraphQL\Language\AST\UnionTypeDefinitionNode; +use GraphQL\Utils\AST; +use Illuminate\Database\Eloquent\Model; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; use Nuwave\Lighthouse\Support\Contracts\Directive; -use Nuwave\Lighthouse\Exceptions\DirectiveException; +use Nuwave\Lighthouse\Support\Utils; abstract class BaseDirective implements Directive { + /** + * The AST node of the directive. + * + * @var \GraphQL\Language\AST\DirectiveNode + */ + protected $directiveNode; + /** * The node the directive is defined on. * - * @var \GraphQL\Language\AST\Node + * @see \GraphQL\Language\DirectiveLocation + * + * Intentionally leaving out the request definitions and the 'SCHEMA' location. + * + * @var ScalarTypeDefinitionNode|ObjectTypeDefinitionNode|FieldDefinitionNode|InputValueDefinitionNode|InterfaceTypeDefinitionNode|UnionTypeDefinitionNode|EnumTypeDefinitionNode|EnumValueDefinitionNode|InputObjectTypeDefinitionNode */ protected $definitionNode; + /** + * Cached directive arguments. + * + * Lazily initialized. + * + * @var array + */ + protected $directiveArgs; + + /** + * Returns the name of the used directive. + */ + public function name(): string + { + return $this->directiveNode->name->value; + } + /** * The hydrate function is called when retrieving a directive from the directive registry. * - * @param \GraphQL\Language\AST\Node $definitionNode + * @param ScalarTypeDefinitionNode|ObjectTypeDefinitionNode|FieldDefinitionNode|InputValueDefinitionNode|InterfaceTypeDefinitionNode|UnionTypeDefinitionNode|EnumTypeDefinitionNode|EnumValueDefinitionNode|InputObjectTypeDefinitionNode $definitionNode * @return $this */ - public function hydrate(Node $definitionNode): self + public function hydrate(DirectiveNode $directiveNode, Node $definitionNode): self { + $this->directiveNode = $directiveNode; $this->definitionNode = $definitionNode; return $this; } - /** - * Get the directive definition associated with the current directive. - * - * @return \GraphQL\Language\AST\DirectiveNode - */ - protected function directiveDefinition(): DirectiveNode - { - return ASTHelper::directiveDefinition( - $this->definitionNode, - static::name() - ); - } - - /** - * Get directive argument value. - * - * @param string $name - * @param mixed|null $default - * @return mixed|null - */ - protected function directiveArgValue(string $name, $default = null) - { - return ASTHelper::directiveArgValue( - $this->directiveDefinition(), - $name, - $default - ); - } - - /** - * Does the current directive have an argument with the given name? - * - * @param string $name - * @return bool - */ - public function directiveHasArgument(string $name): bool - { - return ASTHelper::directiveHasArgument( - $this->directiveDefinition(), - $name - ); - } - /** * Get a Closure that is defined through an argument on the directive. - * - * @param string $argumentName - * @return \Closure */ public function getResolverFromArgument(string $argumentName): Closure { @@ -93,30 +84,75 @@ abstract class BaseDirective implements Directive return Utils::constructResolver($namespacedClassName, $methodName); } + /** + * Loads directive argument values from AST and caches them in $directiveArgs. + */ + protected function loadArgValues(): void + { + $this->directiveArgs = []; + foreach ($this->directiveNode->arguments as $node) { + if (array_key_exists($node->name->value, $this->directiveArgs)) { + throw new DefinitionException("Directive {$this->directiveNode->name->value} has two arguments with the same name {$node->name->value}"); + } + + $this->directiveArgs[$node->name->value] = AST::valueFromASTUntyped($node->value); + } + } + + /** + * Does the current directive have an argument with the given name? + * TODO change to protected in v6. + */ + public function directiveHasArgument(string $name): bool + { + if (! isset($this->directiveArgs)) { + $this->loadArgValues(); + } + + return array_key_exists($name, $this->directiveArgs); + } + + /** + * Get the value of an argument on the directive. + * + * @param mixed|null $default + * @return mixed|null + */ + protected function directiveArgValue(string $name, $default = null) + { + if (! isset($this->directiveArgs)) { + $this->loadArgValues(); + } + + return array_key_exists($name, $this->directiveArgs) + ? $this->directiveArgs[$name] + : $default; + } + + /** + * The name of the node the directive is defined upon. + */ + protected function nodeName(): string + { + return $this->definitionNode->name->value; + } + /** * Get the model class from the `model` argument of the field. * * @param string $argumentName The default argument name "model" may be overwritten - * @return string + * @return class-string<\Illuminate\Database\Eloquent\Model> * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ protected function getModelClass(string $argumentName = 'model'): string { - $model = $this->directiveArgValue($argumentName); - - // Fallback to using information from the schema definition as the model name - if (! $model) { - if ($this->definitionNode instanceof FieldDefinitionNode) { - $model = ASTHelper::getUnderlyingTypeName($this->definitionNode); - } elseif ($this->definitionNode instanceof ObjectTypeDefinitionNode) { - $model = $this->definitionNode->name->value; - } - } + $model = $this->directiveArgValue($argumentName) + ?? ASTHelper::modelName($this->definitionNode); if (! $model) { - throw new DirectiveException( - "A `model` argument must be assigned to the '{$this->name()}'directive on '{$this->definitionNode->name->value}" + throw new DefinitionException( + "A `model` argument must be assigned to the '@{$this->name()}' directive on '{$this->nodeName()}." ); } @@ -124,21 +160,26 @@ abstract class BaseDirective implements Directive } /** - * @param string $classCandidate - * @param string[] $namespacesToTry - * @param callable $determineMatch - * @return string + * Find a class name in a set of given namespaces. * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * @param array $namespacesToTry + * @param callable(string $className): bool $determineMatch + * + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + * + * @return class-string */ - protected function namespaceClassName(string $classCandidate, array $namespacesToTry = [], callable $determineMatch = null): string - { + protected function namespaceClassName( + string $classCandidate, + array $namespacesToTry = [], + callable $determineMatch = null + ): string { // Always try the explicitly set namespace first array_unshift( $namespacesToTry, ASTHelper::getNamespaceForDirective( $this->definitionNode, - static::name() + $this->name() ) ); @@ -153,8 +194,8 @@ abstract class BaseDirective implements Directive ); if (! $className) { - throw new DirectiveException( - "No class '{$classCandidate}' was found for directive '{$this->name()}'" + throw new DefinitionException( + "No class `{$classCandidate}` was found for directive `@{$this->name()}`" ); } @@ -168,10 +209,9 @@ abstract class BaseDirective implements Directive * e.g. "App\My\Class@methodName" * This validates that exactly two parts are given and are not empty. * - * @param string $argumentName - * @return string[] Contains two entries: [string $className, string $methodName] + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * @return array{0: string, 1: string} Contains two entries: [string $className, string $methodName] */ protected function getMethodArgumentParts(string $argumentName): array { @@ -184,14 +224,15 @@ abstract class BaseDirective implements Directive count($argumentParts) > 2 || empty($argumentParts[0]) ) { - throw new DirectiveException( + throw new DefinitionException( "Directive '{$this->name()}' must have an argument '{$argumentName}' in the form 'ClassName@methodName' or 'ClassName'" ); } - + /** @var array{0: string, 1?: string} $argumentParts */ if (empty($argumentParts[1])) { $argumentParts[1] = '__invoke'; } + /** @var array{0: string, 1: string} $argumentParts */ return $argumentParts; } @@ -199,17 +240,23 @@ abstract class BaseDirective implements Directive /** * Try adding the default model namespace and ensure the given class is a model. * - * @param string $modelClassCandidate - * @return string + * @return class-string<\Illuminate\Database\Eloquent\Model> */ protected function namespaceModelClass(string $modelClassCandidate): string { - return $this->namespaceClassName( + /** + * The callback ensures this holds true. + * + * @var class-string<\Illuminate\Database\Eloquent\Model> $modelClass + */ + $modelClass = $this->namespaceClassName( $modelClassCandidate, (array) config('lighthouse.namespaces.models'), - function (string $classCandidate): bool { + static function (string $classCandidate): bool { return is_subclass_of($classCandidate, Model::class); } ); + + return $modelClass; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/BcryptDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/BcryptDirective.php deleted file mode 100644 index 40db2c1..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/BcryptDirective.php +++ /dev/null @@ -1,42 +0,0 @@ -getResolver(); - - return $fieldValue->setResolver(function () use ($resolver) { - $resolved = call_user_func_array($resolver, func_get_args()); - - $subscriptionField = $this->directiveArgValue('subscription'); - $shouldQueue = $this->directiveArgValue('shouldQueue'); - - if ($resolved instanceof Deferred) { - $resolved->then(function ($root) use ($subscriptionField, $shouldQueue): void { - Subscription::broadcast($subscriptionField, $root, $shouldQueue); - }); - } else { - Subscription::broadcast($subscriptionField, $resolved, $shouldQueue); - } - - return $resolved; - }); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/BuilderDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/BuilderDirective.php index 294cba4..7e04d90 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/BuilderDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/BuilderDirective.php @@ -2,52 +2,71 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Laravel\Scout\Builder as ScoutBuilder; +use Nuwave\Lighthouse\Scout\ScoutBuilderDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; +use Nuwave\Lighthouse\Support\Contracts\FieldBuilderDirective; -class BuilderDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class BuilderDirective extends BaseDirective implements ArgBuilderDirective, ScoutBuilderDirective, FieldBuilderDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'builder'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Use an argument to modify the query builder for a field. +Manipulate the query builder with a method. """ directive @builder( """ Reference a method that is passed the query builder. - Consists of two parts: a class name and a method name, seperated by an `@` symbol. + Consists of two parts: a class name and a method name, separated by an `@` symbol. If you pass only a class name, the method name defaults to `__invoke`. """ method: String! -) on FIELD_DEFINITION -SDL; + + """ + Pass a value to the method as the second argument after the query builder. + Only used when the directive is added on a field. + """ + value: BuilderValue +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | FIELD_DEFINITION + +""" +Any constant literal value: https://graphql.github.io/graphql-spec/draft/#sec-Input-Values +""" +scalar BuilderValue +GRAPHQL; } - /** - * Dynamically call a user-defined method to enhance the builder. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $value - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $value) + public function handleBuilder($builder, $value): object { - return call_user_func( - $this->getResolverFromArgument('method'), - $builder, - $value, - $this->definitionNode - ); + $resolver = $this->resolver(); + + return $resolver($builder, $value, $this->definitionNode); + } + + public function handleScoutBuilder(ScoutBuilder $builder, $value): ScoutBuilder + { + $resolver = $this->resolver(); + + return $resolver($builder, $value, $this->definitionNode); + } + + public function handleFieldBuilder(object $builder): object + { + $resolver = $this->resolver(); + + if ($this->directiveHasArgument('value')) { + return $resolver( + $builder, + $this->directiveArgValue('value') + ); + } + + return $resolver($builder); + } + + protected function resolver(): \Closure + { + return $this->getResolverFromArgument('method'); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/CacheDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/CacheDirective.php index fdcade2..577f00e 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/CacheDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/CacheDirective.php @@ -3,50 +3,36 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Closure; -use Carbon\Carbon; -use GraphQL\Deferred; -use Illuminate\Cache\CacheManager; -use Illuminate\Support\Collection; -use GraphQL\Language\AST\DirectiveNode; use GraphQL\Language\AST\NamedTypeNode; -use GraphQL\Type\Definition\ResolveInfo; use GraphQL\Language\AST\NonNullTypeNode; -use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\Values\TypeValue; +use GraphQL\Type\Definition\ResolveInfo; +use Illuminate\Contracts\Cache\Repository as CacheRepository; +use Illuminate\Support\Carbon; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Execution\Resolved; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use Nuwave\Lighthouse\Schema\RootType; use Nuwave\Lighthouse\Schema\Values\CacheValue; use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Exceptions\DirectiveException; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Schema\Values\TypeValue; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -class CacheDirective extends BaseDirective implements FieldMiddleware, DefinedDirective +class CacheDirective extends BaseDirective implements FieldMiddleware { - /** @var \Illuminate\Cache\CacheManager */ - protected $cacheManager; - /** - * @param \Illuminate\Cache\CacheManager $cacheManager - * @return void + * @var \Illuminate\Contracts\Cache\Repository */ - public function __construct(CacheManager $cacheManager) - { - $this->cacheManager = $cacheManager; - } + protected $cacheRepository; - /** - * Name of the directive. - * - * @return string - */ - public function name(): string + public function __construct(CacheRepository $cacheRepository) { - return 'cache'; + $this->cacheRepository = $cacheRepository; } public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Cache the result of a resolver. """ @@ -64,16 +50,9 @@ directive @cache( """ private: Boolean = false ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { $this->setCacheKeyOnParent( @@ -83,74 +62,90 @@ SDL; // Ensure we run this after all other field middleware $fieldValue = $next($fieldValue); + $shouldUseTags = $this->shouldUseTags(); $resolver = $fieldValue->getResolver(); - $maxAge = $this->directiveArgValue('maxAge'); $isPrivate = $this->directiveArgValue('private', false); - return $fieldValue->setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($fieldValue, $resolver, $maxAge, $isPrivate) { - $cacheValue = new CacheValue([ - 'field_value' => $fieldValue, - 'root' => $root, - 'args' => $args, - 'context' => $context, - 'resolve_info' => $resolveInfo, - 'is_private' => $isPrivate, - ]); + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($fieldValue, $shouldUseTags, $resolver, $maxAge, $isPrivate) { + $cacheValue = new CacheValue( + $root, + $args, + $context, + $resolveInfo, + $fieldValue, + $isPrivate + ); - $cacheKey = $cacheValue->getKey(); + $cacheKey = $cacheValue->getKey(); - /** @var \Illuminate\Cache\Repository|\Illuminate\Cache\TaggedCache $repository */ - $cache = $this->shouldUseTags() - ? $this->cacheManager->tags($cacheValue->getTags()) - : $this->cacheManager; + /** @var \Illuminate\Cache\TaggedCache|\Illuminate\Contracts\Cache\Repository $cache */ + $cache = $shouldUseTags + ? $this->cacheRepository->tags($cacheValue->getTags()) + : $this->cacheRepository; - $cacheHasKey = $cache->has($cacheKey); - - // We found a matching value in the cache, so we can just return early - // without actually running the query - if ($cacheHasKey) { - return $cache->get($cacheKey); - } - - $resolvedValue = $resolver($root, $args, $context, $resolveInfo); - - $storeInCache = $maxAge - ? function ($value) use ($cacheKey, $maxAge, $cache) { - $cache->put($cacheKey, $value, Carbon::now()->addSeconds($maxAge)); + // We found a matching value in the cache, so we can just return early + // without actually running the query + $value = $cache->get($cacheKey); + if ($value !== null) { + return $value; } - : function ($value) use ($cacheKey, $cache) { - $cache->forever($cacheKey, $value); - }; + // In Laravel cache, null is considered as "non-existant" value. As mentioned in laravel documentation, + // https://laravel.com/docs/8.x/cache#checking-for-item-existence + // > The `has` method [...] will also return false if the item exists but its value is null. + // + // If caching `null` value becomes something worthwhile, one possible way to achieve it is to + // encapsulate the `$result` at writing time : + // + // $storeInCache = static function ($result) use ($cacheKey, $maxAge, $cache): void { + // $value = ['rawValue' => $result]; + // $maxAge + // ? $cache->put($cacheKey, $value, Carbon::now()->addSeconds($maxAge)) + // : $cache->forever($cacheKey, $value); + // }; + // + // and restoring original value back at reading : + // + // if (is_array($value) && array_key_exists('rawValue', $value)) { // don't use isset ! + // return $value['rawValue']; + // } + // + // Such a change would introduce some potential BC, if for instance cached value was already containing + // an object with a `rawValue` key prior the implementation change. A possible workaround is to choose a + // less collision-probable key instead of `rawValue` (eg. "com.lighthouse-php:rawValue" ?) - ($resolvedValue instanceof Deferred) - ? $resolvedValue->then(function ($result) use ($storeInCache): void { - $storeInCache($result); - }) - : $storeInCache($resolvedValue); + $resolved = $resolver($root, $args, $context, $resolveInfo); - return $resolvedValue; - }); + $storeInCache = $maxAge + ? static function ($result) use ($cacheKey, $maxAge, $cache): void { + $cache->put($cacheKey, $result, Carbon::now()->addSeconds($maxAge)); + } + : static function ($result) use ($cacheKey, $cache): void { + $cache->forever($cacheKey, $result); + }; + + Resolved::handle($resolved, $storeInCache); + + return $resolved; + }); + + return $fieldValue; } /** * Check if tags should be used and are available. - * - * @return bool */ protected function shouldUseTags(): bool { return config('lighthouse.cache.tags', false) - && method_exists($this->cacheManager->store(), 'tags'); + && method_exists($this->cacheRepository->getStore(), 'tags'); } /** * Set node's cache key. * - * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $typeValue - * @return void - * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ protected function setCacheKeyOnParent(TypeValue $typeValue): void { @@ -158,7 +153,7 @@ SDL; // The cache key was already set, so we do not have to look again $typeValue->getCacheKey() // The Query type is exempt from requiring a cache key - || $typeValue->getTypeDefinitionName() === 'Query' + || $typeValue->getTypeDefinitionName() === RootType::QUERY ) { return; } @@ -166,40 +161,32 @@ SDL; /** @var \GraphQL\Language\AST\ObjectTypeDefinitionNode $typeDefinition */ $typeDefinition = $typeValue->getTypeDefinition(); - // First priority: Look for a field with the @cacheKey directive - /** @var FieldDefinitionNode $field */ - foreach ($typeDefinition->fields as $field) { - $hasCacheKey = (new Collection($field->directives)) - ->contains(function (DirectiveNode $directive): bool { - return $directive->name->value === 'cacheKey'; - }); + /** @var iterable<\GraphQL\Language\AST\FieldDefinitionNode> $fieldDefinitions */ + $fieldDefinitions = $typeDefinition->fields; - if ($hasCacheKey) { - $typeValue->setCacheKey( - $field->name->value - ); + // First priority: Look for a field with the @cacheKey directive + foreach ($fieldDefinitions as $field) { + if (ASTHelper::hasDirective($field, CacheKeyDirective::NAME)) { + $typeValue->setCacheKey($field->name->value); return; } } // Second priority: Look for a Non-Null field with the ID type - /** @var FieldDefinitionNode $field */ - foreach ($typeDefinition->fields as $field) { + foreach ($fieldDefinitions as $field) { if ( $field->type instanceof NonNullTypeNode && $field->type->type instanceof NamedTypeNode && $field->type->type->name->value === 'ID' ) { - $typeValue->setCacheKey( - $field->name->value - ); + $typeValue->setCacheKey($field->name->value); return; } } - throw new DirectiveException( + throw new DefinitionException( "No @cacheKey or ID field defined on {$typeValue->getTypeDefinitionName()}" ); } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/CacheKeyDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/CacheKeyDirective.php index c70581e..1ac8d73 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/CacheKeyDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/CacheKeyDirective.php @@ -3,27 +3,18 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Nuwave\Lighthouse\Support\Contracts\Directive; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class CacheKeyDirective implements Directive, DefinedDirective +class CacheKeyDirective extends BaseDirective implements Directive { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'cacheKey'; - } + public const NAME = 'cacheKey'; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Specify the field to use as a key when creating a cache. """ directive @cacheKey on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/CanDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/CanDirective.php index 6dd33d4..21a9ff0 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/CanDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/CanDirective.php @@ -3,140 +3,228 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Closure; -use Illuminate\Database\Eloquent\Model; +use GraphQL\Error\Error; use GraphQL\Type\Definition\ResolveInfo; use Illuminate\Contracts\Auth\Access\Gate; -use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Support\Arr; use Nuwave\Lighthouse\Exceptions\AuthorizationException; +use Nuwave\Lighthouse\Execution\Arguments\ArgumentSet; +use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Nuwave\Lighthouse\SoftDeletes\ForceDeleteDirective; +use Nuwave\Lighthouse\SoftDeletes\RestoreDirective; +use Nuwave\Lighthouse\SoftDeletes\TrashedDirective; +use Nuwave\Lighthouse\Support\AppVersion; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Support\Utils; -class CanDirective extends BaseDirective implements FieldMiddleware, DefinedDirective +class CanDirective extends BaseDirective implements FieldMiddleware { /** * @var \Illuminate\Contracts\Auth\Access\Gate */ protected $gate; - /** - * CanDirective constructor. - * @param \Illuminate\Contracts\Auth\Access\Gate $gate - * @return void - */ public function __construct(Gate $gate) { $this->gate = $gate; } - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'can'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Check a Laravel Policy to ensure the current user is authorized to access a field. + +When `injectArgs` and `args` are used together, the client given +arguments will be passed before the static args. """ directive @can( """ The ability to check permissions for. """ ability: String! - + """ - The name of the argument that is used to find a specific model - instance against which the permissions should be checked. + If your policy checks against specific model instances, specify + the name of the field argument that contains its primary key(s). + + You may pass the string in dot notation to use nested inputs. """ find: String - + """ - Additional arguments that are passed to `Gate::check`. + Specify the class name of the model to use. + This is only needed when the default model detection does not work. """ - args: [String!] -) on FIELD_DEFINITION -SDL; + model: String + + """ + Pass along the client given input data as arguments to `Gate::check`. + """ + injectArgs: Boolean = false + + """ + Statically defined arguments that are passed to `Gate::check`. + + You may pass pass arbitrary GraphQL literals, + e.g.: [1, 2, 3] or { foo: "bar" } + """ + args: CanArgs +) repeatable on FIELD_DEFINITION + +""" +Any constant literal value: https://graphql.github.io/graphql-spec/draft/#sec-Input-Values +""" +scalar CanArgs +GRAPHQL; } /** * Ensure the user is authorized to access this field. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue */ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { $previousResolver = $fieldValue->getResolver(); + $ability = $this->directiveArgValue('ability'); - return $next( - $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($previousResolver) { - $modelClass = $this->getModelClass(); + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($ability, $previousResolver) { + $gate = $this->gate->forUser($context->user()); + $checkArguments = $this->buildCheckArguments($args); - if ($find = $this->directiveArgValue('find')) { - $modelOrModels = $modelClass::findOrFail($args[$find]); - - if ($modelOrModels instanceof Model) { - $modelOrModels = [$modelOrModels]; - } - - /** @var \Illuminate\Database\Eloquent\Model $model */ - foreach ($modelOrModels as $model) { - $this->authorize($context->user(), $model); - } - } else { - $this->authorize($context->user(), $modelClass); - } - - return call_user_func_array($previousResolver, func_get_args()); + foreach ($this->modelsToCheck($resolveInfo->argumentSet, $args) as $model) { + $this->authorize($gate, $ability, $model, $checkArguments); } - ) + + return $previousResolver($root, $args, $context, $resolveInfo); + } ); + + return $next($fieldValue); } /** - * @param \Illuminate\Contracts\Auth\Authenticatable|null $user + * @param array $args + * @return iterable<\Illuminate\Database\Eloquent\Model|string> + * + * @throws \GraphQL\Error\Error + */ + protected function modelsToCheck(ArgumentSet $argumentSet, array $args): iterable + { + if ($find = $this->directiveArgValue('find')) { + $findValue = Arr::get($args, $find); + if ($findValue === null) { + throw new Error(self::missingKeyToFindModel($find)); + } + + $queryBuilder = $this->getModelClass()::query(); + + $directivesContainsForceDelete = $argumentSet->directives->contains( + Utils::instanceofMatcher(ForceDeleteDirective::class) + ); + if ($directivesContainsForceDelete) { + /** @see \Illuminate\Database\Eloquent\SoftDeletes */ + // @phpstan-ignore-next-line because it involves mixins + $queryBuilder->withTrashed(); + } + + $directivesContainsRestore = $argumentSet->directives->contains( + Utils::instanceofMatcher(RestoreDirective::class) + ); + if ($directivesContainsRestore) { + /** @see \Illuminate\Database\Eloquent\SoftDeletes */ + // @phpstan-ignore-next-line because it involves mixins + $queryBuilder->onlyTrashed(); + } + + try { + /** + * TODO use generics. + * @var \Illuminate\Database\Eloquent\Builder $enhancedBuilder + */ + $enhancedBuilder = $argumentSet->enhanceBuilder( + $queryBuilder, + [], + Utils::instanceofMatcher(TrashedDirective::class) + ); + + $modelOrModels = $enhancedBuilder->findOrFail($findValue); + } catch (ModelNotFoundException $exception) { + throw new Error($exception->getMessage()); + } + + if ($modelOrModels instanceof Model) { + $modelOrModels = [$modelOrModels]; + } + + return $modelOrModels; + } + + return [$this->getModelClass()]; + } + + public static function missingKeyToFindModel(string $find): string + { + return "Got no key to find a model at the expected input path: ${find}."; + } + + /** + * @param string|array $ability * @param string|\Illuminate\Database\Eloquent\Model $model - * @return void + * @param array $arguments * * @throws \Nuwave\Lighthouse\Exceptions\AuthorizationException */ - protected function authorize($user, $model): void + protected function authorize(Gate $gate, $ability, $model, array $arguments): void { // The signature of the second argument `$arguments` of `Gate::check` // should be [modelClassName, additionalArg, additionalArg...] - $arguments = $this->getAdditionalArguments(); array_unshift($arguments, $model); - $can = $this->gate - ->forUser($user) - ->check( - $this->directiveArgValue('ability'), - $arguments - ); + // Gate responses were introduced in Laravel 6 + // TODO remove with Laravel < 6 support + if (AppVersion::atLeast(6.0)) { + Utils::applyEach( + function ($ability) use ($gate, $arguments) { + $response = $gate->inspect($ability, $arguments); - if (! $can) { - throw new AuthorizationException( - "You are not authorized to access {$this->definitionNode->name->value}" + if ($response->denied()) { + throw new AuthorizationException($response->message(), $response->code()); + } + }, + $ability ); + } else { + if (! $gate->check($ability, $arguments)) { + throw new AuthorizationException( + "You are not authorized to access {$this->nodeName()}" + ); + } } } /** * Additional arguments that are passed to `Gate::check`. * - * @return mixed[] + * @param array $args + * @return array */ - protected function getAdditionalArguments(): array + protected function buildCheckArguments(array $args): array { - return (array) $this->directiveArgValue('args'); + $checkArguments = []; + + // The injected args come before the static args + if ($this->directiveArgValue('injectArgs')) { + $checkArguments [] = $args; + } + + if ($this->directiveHasArgument('args')) { + $checkArguments [] = $this->directiveArgValue('args'); + } + + return $checkArguments; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/ComplexityDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/ComplexityDirective.php index 1783473..2af1765 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/ComplexityDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/ComplexityDirective.php @@ -3,27 +3,15 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Closure; -use Illuminate\Support\Arr; -use Nuwave\Lighthouse\Support\Utils; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Utils; -class ComplexityDirective extends BaseDirective implements FieldMiddleware, DefinedDirective +class ComplexityDirective extends BaseDirective implements FieldMiddleware { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'complexity'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Customize the calculation of a fields complexity score before execution. """ @@ -35,41 +23,31 @@ directive @complexity( """ resolver: String ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldFieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function handleField(FieldValue $fieldFieldValue, Closure $next): FieldValue + public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { if ($this->directiveHasArgument('resolver')) { [$className, $methodName] = $this->getMethodArgumentParts('resolver'); $namespacedClassName = $this->namespaceClassName( $className, - $fieldFieldValue->defaultNamespacesForParent() + $fieldValue->defaultNamespacesForParent() ); $resolver = Utils::constructResolver($namespacedClassName, $methodName); } else { - $resolver = function (int $childrenComplexity, array $args): int { - $complexity = Arr::get( - $args, - 'first', - Arr::get($args, config('lighthouse.pagination_amount_argument'), 1) - ); + $resolver = static function (int $childrenComplexity, array $args): int { + /** @var int $complexity */ + $complexity = $args['first'] ?? 1; return $childrenComplexity * $complexity; }; } - return $next( - $fieldFieldValue->setComplexity($resolver) - ); + $fieldValue->setComplexity($resolver); + + return $next($fieldValue); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/CountDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/CountDirective.php new file mode 100644 index 0000000..a946f72 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/CountDirective.php @@ -0,0 +1,93 @@ +directiveArgValue('model'); + if (is_string($modelArg)) { + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($modelArg): int { + $query = $this + ->namespaceModelClass($modelArg) + ::query(); + + $this->makeBuilderDecorator($resolveInfo)($query); + + return $query->count(); + } + ); + + return $fieldValue; + } + + $relation = $this->directiveArgValue('relation'); + if (is_string($relation)) { + $fieldValue->setResolver( + function (Model $parent, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { + /** @var \Nuwave\Lighthouse\Execution\BatchLoader\RelationBatchLoader $relationBatchLoader */ + $relationBatchLoader = BatchLoaderRegistry::instance( + array_merge( + $this->qualifyPath($args, $resolveInfo), + ['count'] + ), + function () use ($resolveInfo): RelationBatchLoader { + return new RelationBatchLoader( + new CountModelsLoader($this->relation(), $this->makeBuilderDecorator($resolveInfo)) + ); + } + ); + + return $relationBatchLoader->load($parent); + } + ); + + return $fieldValue; + } + + throw new DefinitionException( + "A `model` or `relation` argument must be assigned to the '{$this->name()}' directive on '{$this->nodeName()}'." + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/CreateDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/CreateDirective.php index 54fcacf..442987e 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/CreateDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/CreateDirective.php @@ -2,80 +2,36 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Illuminate\Support\Collection; -use Illuminate\Database\Eloquent\Model; -use GraphQL\Type\Definition\ResolveInfo; -use Illuminate\Database\DatabaseManager; -use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Execution\MutationExecutor; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Illuminate\Database\Eloquent\Relations\Relation; +use Nuwave\Lighthouse\Execution\Arguments\SaveModel; -class CreateDirective extends BaseDirective implements FieldResolver, DefinedDirective +class CreateDirective extends MutationExecutorDirective { - /** - * @var \Illuminate\Database\DatabaseManager - */ - protected $databaseManager; - - /** - * @param \Illuminate\Database\DatabaseManager $databaseManager - * @return void - */ - public function __construct(DatabaseManager $databaseManager) - { - $this->databaseManager = $databaseManager; - } - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'create'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Create a new Eloquent model with the given arguments. """ -directive @create( +directive @create( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String -) on FIELD_DEFINITION -SDL; + + """ + Specify the name of the relation on the parent model. + This is only needed when using this directive as a nested arg + resolver and if the name of the relation is not the arg name. + """ + relation: String +) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function resolveField(FieldValue $fieldValue): FieldValue + protected function makeExecutionFunction(?Relation $parentRelation = null): callable { - return $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Model { - $modelClassName = $this->getModelClass(); - /** @var \Illuminate\Database\Eloquent\Model $model */ - $model = new $modelClassName; - - $executeMutation = function () use ($model, $args): Model { - return MutationExecutor::executeCreate($model, new Collection($args))->refresh(); - }; - - return config('lighthouse.transactional_mutations', true) - ? $this->databaseManager->connection($model->getConnectionName())->transaction($executeMutation) - : $executeMutation(); - } - ); + return new SaveModel($parentRelation); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/DeleteDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/DeleteDirective.php index e6d01c7..af7edcc 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/DeleteDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/DeleteDirective.php @@ -2,30 +2,31 @@ namespace Nuwave\Lighthouse\Schema\Directives; +use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\InputValueDefinitionNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; use Illuminate\Database\Eloquent\Model; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasOne; +use Illuminate\Database\Eloquent\Relations\MorphOne; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; +use Nuwave\Lighthouse\Support\Contracts\ArgManipulator; +use Nuwave\Lighthouse\Support\Contracts\ArgResolver; -class DeleteDirective extends ModifyModelExistenceDirective implements DefinedDirective +class DeleteDirective extends ModifyModelExistenceDirective implements ArgResolver, ArgManipulator { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'delete'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Delete one or more models by their ID. The field must have a single non-null argument that may be a list. """ directive @delete( """ + DEPRECATED use @globalId, will be removed in v6 + Set to `true` to use global ids for finding the model. If set to `false`, regular non-global ids are used. """ @@ -33,33 +34,83 @@ directive @delete( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String -) on FIELD_DEFINITION -SDL; + + """ + Specify the name of the relation on the parent model. + This is only needed when using this directive as a nested arg + resolver and if the name of the relation is not the arg name. + """ + relation: String +) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Find one or more models by id. - * - * @param string|\Illuminate\Database\Eloquent\Model $modelClass - * @param string|int|string[]|int[] $idOrIds - * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection - */ protected function find(string $modelClass, $idOrIds) { return $modelClass::find($idOrIds); } - /** - * Bring a model in or out of existence. - * - * @param \Illuminate\Database\Eloquent\Model $model - * @return void - */ - protected function modifyExistence(Model $model): void + protected function modifyExistence(Model $model): bool { - $model->delete(); + return (bool) $model->delete(); + } + + /** + * Delete on ore more related models. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @param mixed|array $idOrIds + */ + public function __invoke($parent, $idOrIds): void + { + $relationName = $this->directiveArgValue('relation') + // Use the name of the argument if no explicit relation name is given + ?? $this->nodeName(); + /** @var \Illuminate\Database\Eloquent\Relations\Relation $relation */ + $relation = $parent->{$relationName}(); + + // Those types of relations may only have one related model attached to + // it, so we don't need to use an ID to know which model to delete. + $relationIsHasOneLike = $relation instanceof HasOne || $relation instanceof MorphOne; + // This includes MorphTo, which is a subclass of BelongsTo + $relationIsBelongsToLike = $relation instanceof BelongsTo; + + if ($relationIsHasOneLike || $relationIsBelongsToLike) { + /** @var \Illuminate\Database\Eloquent\Relations\HasOne|\Illuminate\Database\Eloquent\Relations\MorphOne|\Illuminate\Database\Eloquent\Relations\BelongsTo $relation */ + // Only delete if the given value is truthy, since + // the client might use a variable and always pass the argument. + // Deleting when `false` is given seems wrong. + if ($idOrIds) { + if ($relationIsBelongsToLike) { + /** @var \Illuminate\Database\Eloquent\Relations\BelongsTo $relation */ + $relation->dissociate(); + $relation->getParent()->save(); + } + + // @phpstan-ignore-next-line Builder mixin is not understood + $relation->delete(); + } + } else { + /** @var \Illuminate\Database\Eloquent\Model $related */ + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $related = $relation->make(); + $related::destroy($idOrIds); + } + } + + public function manipulateArgDefinition( + DocumentAST &$documentAST, + InputValueDefinitionNode &$argDefinition, + FieldDefinitionNode &$parentField, + ObjectTypeDefinitionNode &$parentType + ) { + if (! $this->directiveArgValue('relation')) { + throw new DefinitionException( + 'The @delete directive requires the "relation" to be set when used as an argument resolver.' + ); + } } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/DeprecatedDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/DeprecatedDirective.php index 5b7f247..0b1b82c 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/DeprecatedDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/DeprecatedDirective.php @@ -2,54 +2,24 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Closure; -use GraphQL\Type\Definition\Directive; -use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Contracts\Directive; -class DeprecatedDirective extends BaseDirective implements FieldMiddleware, DefinedDirective +class DeprecatedDirective implements Directive { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'deprecated'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Marks an element of a GraphQL schema as no longer supported. """ -directive @deprecated( +directive @deprecated( """ Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted in [Markdown](https://daringfireball.net/projects/markdown/). """ reason: String = "No longer supported" -) on FIELD_DEFINITION -SDL; - } - - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function handleField(FieldValue $fieldValue, Closure $next): FieldValue - { - $reason = $this->directiveArgValue('reason', Directive::DEFAULT_DEPRECATION_REASON); - - $fieldValue->setDeprecationReason($reason); - - return $next($fieldValue); +) on FIELD_DEFINITION | ENUM_VALUE +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/EnumDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/EnumDirective.php new file mode 100644 index 0000000..85baeb9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/EnumDirective.php @@ -0,0 +1,38 @@ +directiveArgValue('value'); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/EqDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/EqDirective.php index e3ef884..3b1d959 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/EqDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/EqDirective.php @@ -2,46 +2,79 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use Laravel\Scout\Builder as ScoutBuilder; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; +use Nuwave\Lighthouse\Scout\ScoutBuilderDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; +use Nuwave\Lighthouse\Support\Contracts\FieldBuilderDirective; +use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; -class EqDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class EqDirective extends BaseDirective implements ArgBuilderDirective, ScoutBuilderDirective, FieldBuilderDirective, FieldManipulator { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'eq'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' -directive @eq( + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Add an equal conditional to a database query. +""" +directive @eq( """ - Specify the database column to compare. - Only required if database column has a different name than the attribute in your schema. + Specify the database column to compare. + Required if the directive is: + - used on an argument and the database column has a different name + - used on a field """ key: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; + + """ + Provide a value to compare against. + Only required when this directive is used on a field. + """ + value: EqValue +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | FIELD_DEFINITION + +""" +Any constant literal value: https://graphql.github.io/graphql-spec/draft/#sec-Input-Values +""" +scalar EqValue +GRAPHQL; } - /** - * Apply a "WHERE = $value" clause. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $value - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $value) + public function handleBuilder($builder, $value): object { return $builder->where( - $this->directiveArgValue('key', $this->definitionNode->name->value), + $this->directiveArgValue('key') ?? $this->nodeName(), $value ); } + + public function handleScoutBuilder(ScoutBuilder $builder, $value): ScoutBuilder + { + return $builder->where( + $this->directiveArgValue('key') ?? $this->nodeName(), + $value + ); + } + + public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType) + { + if (! $this->directiveHasArgument('value')) { + throw new DefinitionException("Must provide the argument `value` when using {$this->name()} on field `{$parentType->name->value}.{$fieldDefinition->name->value}`."); + } + + if (! $this->directiveHasArgument('key')) { + throw new DefinitionException("Must provide the argument `key` when using {$this->name()} on field `{$parentType->name->value}.{$fieldDefinition->name->value}`."); + } + } + + public function handleFieldBuilder(object $builder): object + { + return $this->handleBuilder( + $builder, + $this->directiveArgValue('value') + ); + } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/EventDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/EventDirective.php index b1d9725..56e08f9 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/EventDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/EventDirective.php @@ -3,81 +3,54 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Closure; +use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; -class EventDirective extends BaseDirective implements FieldMiddleware, DefinedDirective +class EventDirective extends BaseDirective implements FieldMiddleware { /** * @var \Illuminate\Contracts\Events\Dispatcher */ protected $eventsDispatcher; - /** - * Construct EventDirective. - * - * @param \Illuminate\Contracts\Events\Dispatcher $eventsDispatcher - * @return void - */ public function __construct(EventsDispatcher $eventsDispatcher) { $this->eventsDispatcher = $eventsDispatcher; } - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'event'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Fire an event after a mutation has taken place. -It requires the `dispatch` argument that should be -the class name of the event you want to fire. +Dispatch an event after the resolution of a field. + +The event constructor will be called with a single argument: +the resolved value of the field. """ -directive @event( +directive @event( """ Specify the fully qualified class name (FQCN) of the event to dispatch. """ dispatch: String! -) on FIELD_DEFINITION -SDL; +) repeatable on FIELD_DEFINITION +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { - $eventBaseName = $this->directiveArgValue('dispatch'); - $eventClassName = $this->namespaceClassName($eventBaseName); - $previousResolver = $fieldValue->getResolver(); - - return $next( - $fieldValue->setResolver( - function () use ($previousResolver, $eventClassName) { - $result = call_user_func_array($previousResolver, func_get_args()); - - $this->eventsDispatcher->dispatch( - new $eventClassName($result) - ); - - return $result; - } - ) + $eventClassName = $this->namespaceClassName( + $this->directiveArgValue('dispatch') ); + + $fieldValue->resultHandler(function ($result) use ($eventClassName) { + $this->eventsDispatcher->dispatch( + new $eventClassName($result) + ); + + return $result; + }); + + return $next($fieldValue); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/FieldDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/FieldDirective.php index b3fa485..9f0be5c 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/FieldDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/FieldDirective.php @@ -2,28 +2,17 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Utils; use GraphQL\Type\Definition\ResolveInfo; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Utils; -class FieldDirective extends BaseDirective implements FieldResolver, DefinedDirective +class FieldDirective extends BaseDirective implements FieldResolver { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'field'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Assign a resolver function to a field. """ @@ -40,15 +29,9 @@ directive @field( """ args: [String!] ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function resolveField(FieldValue $fieldValue): FieldValue { [$className, $methodName] = $this->getMethodArgumentParts('resolver'); diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/FindDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/FindDirective.php index 30ed5ea..b491aee 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/FindDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/FindDirective.php @@ -3,35 +3,24 @@ namespace Nuwave\Lighthouse\Schema\Directives; use GraphQL\Error\Error; -use Illuminate\Database\Eloquent\Model; use GraphQL\Type\Definition\ResolveInfo; +use Illuminate\Database\Eloquent\Model; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class FindDirective extends BaseDirective implements FieldResolver, DefinedDirective +class FindDirective extends BaseDirective implements FieldResolver { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'find'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Find a model based on the arguments provided. """ -directive @find( +directive @find( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String @@ -40,31 +29,19 @@ directive @find( """ scopes: [String!] ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function resolveField(FieldValue $fieldValue): FieldValue { - /** @var \Illuminate\Database\Eloquent\Model $model */ - $model = $this->getModelClass(); - return $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($model): ?Model { + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): ?Model { $results = $resolveInfo - ->builder - ->addScopes( + ->argumentSet + ->enhanceBuilder( + $this->getModelClass()::query(), $this->directiveArgValue('scopes', []) ) - ->apply( - $model::query(), - $args - ) ->get(); if ($results->count() > 1) { diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/FirstDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/FirstDirective.php index db80b3e..fe9426d 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/FirstDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/FirstDirective.php @@ -2,35 +2,24 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Illuminate\Database\Eloquent\Model; use GraphQL\Type\Definition\ResolveInfo; +use Illuminate\Database\Eloquent\Model; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class FirstDirective extends BaseDirective implements FieldResolver, DefinedDirective +class FirstDirective extends BaseDirective implements FieldResolver { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'first'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Get the first query result from a collection of Eloquent models. """ -directive @first( +directive @first( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String @@ -39,31 +28,19 @@ directive @first( """ scopes: [String!] ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function resolveField(FieldValue $fieldValue): FieldValue { - /** @var \Illuminate\Database\Eloquent\Model $model */ - $model = $this->getModelClass(); - return $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($model): ?Model { + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): ?Model { return $resolveInfo - ->builder - ->addScopes( + ->argumentSet + ->enhanceBuilder( + $this->getModelClass()::query(), $this->directiveArgValue('scopes', []) ) - ->apply( - $model::query(), - $args - ) ->first(); } ); diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/GlobalIdDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/GlobalIdDirective.php deleted file mode 100644 index a68e607..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/GlobalIdDirective.php +++ /dev/null @@ -1,113 +0,0 @@ -globalId = $globalId; - } - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'globalId'; - } - - public static function definition(): string - { - return /* @lang GraphQL */ <<<'SDL' -""" -Converts between IDs/types and global IDs. -When used upon a field, it encodes, -when used upon an argument, it decodes. -""" -directive @globalId( - """ - By default, an array of `[$type, $id]` is returned when decoding. - You may limit this to returning just one of both. - Allowed values: "ARRAY", "TYPE", "ID" - """ - decode: String = "ARRAY" -) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION -SDL; - } - - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function handleField(FieldValue $fieldValue, Closure $next): FieldValue - { - $type = $fieldValue->getParentName(); - $resolver = $fieldValue->getResolver(); - - return $next( - $fieldValue->setResolver( - function () use ($type, $resolver): string { - $resolvedValue = call_user_func_array($resolver, func_get_args()); - - return $this->globalId->encode( - $type, - $resolvedValue - ); - } - ) - ); - } - - /** - * Decodes a global id given as an argument. - * - * @param string $argumentValue - * @return string|string[] - */ - public function transform($argumentValue) - { - if ($decode = $this->directiveArgValue('decode')) { - switch ($decode) { - case 'TYPE': - return $this->globalId->decodeType($argumentValue); - case 'ID': - return $this->globalId->decodeID($argumentValue); - case 'ARRAY': - return $this->globalId->decode($argumentValue); - default: - throw new DefinitionException( - "The only argument of the @globalId directive can only be ID or TYPE, got {$decode}" - ); - } - } - - return $this->globalId->decode($argumentValue); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/GuardDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/GuardDirective.php new file mode 100644 index 0000000..835c1b2 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/GuardDirective.php @@ -0,0 +1,114 @@ +auth = $auth; + } + + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Run authentication through one or more guards. +This is run per field and may allow unauthenticated +users to still receive partial results. +""" +directive @guard( + """ + Specify which guards to use, e.g. ["api"]. + When not defined, the default from `lighthouse.php` is used. + """ + with: [String!] +) on FIELD_DEFINITION | OBJECT +GRAPHQL; + } + + public function handleField(FieldValue $fieldValue, Closure $next): FieldValue + { + $previousResolver = $fieldValue->getResolver(); + // TODO remove cast in v6 + $with = (array) ( + $this->directiveArgValue('with') + ?? [config('lighthouse.guard')] + ); + + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($with, $previousResolver) { + $this->authenticate($with); + + return $previousResolver($root, $args, $context, $resolveInfo); + } + ); + + return $next($fieldValue); + } + + /** + * Determine if the user is logged in to any of the given guards. + * + * @param array $guards + * + * @throws \Illuminate\Auth\AuthenticationException + */ + protected function authenticate(array $guards): void + { + foreach ($guards as $guard) { + if ($this->auth->guard($guard)->check()) { + $this->auth->shouldUse($guard); + + return; + } + } + + $this->unauthenticated($guards); + } + + /** + * Handle an unauthenticated user. + * + * @param array $guards + */ + protected function unauthenticated(array $guards): void + { + throw new AuthenticationException( + AuthenticationException::MESSAGE, + $guards + ); + } + + public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition): void + { + ASTHelper::addDirectiveToFields($this->directiveNode, $typeDefinition); + } + + public function manipulateTypeExtension(DocumentAST &$documentAST, TypeExtensionNode &$typeExtension): void + { + ASTHelper::addDirectiveToFields($this->directiveNode, $typeExtension); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/HasManyDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/HasManyDirective.php index f3eaa88..dc966c0 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/HasManyDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/HasManyDirective.php @@ -2,25 +2,13 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; -class HasManyDirective extends RelationDirective implements FieldResolver, FieldManipulator, DefinedDirective +class HasManyDirective extends RelationDirective implements FieldManipulator { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'hasMany'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Corresponds to [the Eloquent relationship HasMany](https://laravel.com/docs/eloquent-relationships#one-to-many). """ @@ -30,30 +18,30 @@ directive @hasMany( if it is named different from the field in the schema. """ relation: String - + """ Apply scopes to the underlying query. """ scopes: [String!] """ - ALlows to resolve the relation as a paginated list. - Allowed values: paginator, connection. + Allows to resolve the relation as a paginated list. + Allowed values: `paginator`, `connection`. """ - type: String + type: HasManyType """ - Specify the default quantity of elements to be returned. - Only applies when using pagination. + Allow clients to query paginated lists without specifying the amount of items. + Overrules the `pagination.default_count` setting from `lighthouse.php`. """ defaultCount: Int - + """ - Specify the maximum quantity of elements to be returned. - Only applies when using pagination. + Limit the maximum amount of items that clients can request from paginated lists. + Overrules the `pagination.max_count` setting from `lighthouse.php`. """ maxCount: Int - + """ Specify a custom type that implements the Edge interface to extend edge object. @@ -61,6 +49,26 @@ directive @hasMany( """ edgeType: String ) on FIELD_DEFINITION -SDL; + +""" +Options for the `type` argument of `@hasMany`. +""" +enum HasManyType { + """ + Offset-based pagination, similar to the Laravel default. + """ + PAGINATOR + + """ + Offset-based pagination like the Laravel "Simple Pagination", which does not count the total number of records. + """ + SIMPLE + + """ + Cursor-based pagination, compatible with the Relay specification. + """ + CONNECTION +} +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/HasOneDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/HasOneDirective.php index 7a9d69c..a9c07a4 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/HasOneDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/HasOneDirective.php @@ -2,39 +2,26 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; - -class HasOneDirective extends RelationDirective implements FieldResolver, DefinedDirective +class HasOneDirective extends RelationDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'hasOne'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Corresponds to [the Eloquent relationship HasOne](https://laravel.com/docs/eloquent-relationships#one-to-one). """ -directive @hasOne( +directive @hasOne( """ Specify the relationship method name in the model class, if it is named different from the field in the schema. """ relation: String - + """ Apply scopes to the underlying query. """ scopes: [String!] ) on FIELD_DEFINITION -SDL; +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/HashDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/HashDirective.php new file mode 100644 index 0000000..ab84bac --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/HashDirective.php @@ -0,0 +1,41 @@ +hasher = $hasher; + } + + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Use Laravel hashing to transform an argument value. + +Useful for hashing passwords before inserting them into the database. +This uses the default hashing driver defined in `config/hashing.php`. +""" +directive @hash on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; + } + + /** + * @param string $argumentValue + */ + public function transform($argumentValue): string + { + return $this->hasher->make($argumentValue); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/InDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/InDirective.php index f28c277..f8a5018 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/InDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/InDirective.php @@ -2,46 +2,31 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class InDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class InDirective extends BaseDirective implements ArgBuilderDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'in'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' -directive @in( + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Use the client given list value to add an IN conditional to a database query. +""" +directive @in( """ - Specify the database column to compare. + Specify the database column to compare. Only required if database column has a different name than the attribute in your schema. """ key: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Apply a simple "WHERE IN $values" clause. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $values - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $values) + public function handleBuilder($builder, $value): object { return $builder->whereIn( - $this->directiveArgValue('key', $this->definitionNode->name->value), - $values + $this->directiveArgValue('key', $this->nodeName()), + $value ); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/InjectDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/InjectDirective.php index 2280be9..5d0f959 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/InjectDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/InjectDirective.php @@ -3,30 +3,21 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Closure; -use Illuminate\Support\Arr; use GraphQL\Type\Definition\ResolveInfo; +use Nuwave\Lighthouse\Exceptions\DefinitionException; use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Exceptions\DirectiveException; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -class InjectDirective extends BaseDirective implements FieldMiddleware, DefinedDirective +class InjectDirective extends BaseDirective implements FieldMiddleware { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'inject'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' -directive @inject( + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Inject a value from the context object into the arguments. +""" +directive @inject( """ A path to the property of the context that will be injected. If the value is nested within the context, you may use dot notation @@ -40,31 +31,25 @@ directive @inject( within the incoming argument. """ name: String! -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on FIELD_DEFINITION +GRAPHQL; } /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { $contextAttributeName = $this->directiveArgValue('context'); if (! $contextAttributeName) { - throw new DirectiveException( + throw new DefinitionException( "The `inject` directive on {$fieldValue->getParentName()} [{$fieldValue->getFieldName()}] must have a `context` argument" ); } $argumentName = $this->directiveArgValue('name'); if (! $argumentName) { - throw new DirectiveException( + throw new DefinitionException( "The `inject` directive on {$fieldValue->getParentName()} [{$fieldValue->getFieldName()}] must have a `name` argument" ); } @@ -74,9 +59,13 @@ SDL; return $next( $fieldValue->setResolver( function ($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($contextAttributeName, $argumentName, $previousResolver) { + $valueFromContext = data_get($context, $contextAttributeName); + + $resolveInfo->argumentSet->addValue($argumentName, $valueFromContext); + return $previousResolver( $rootValue, - Arr::add($args, $argumentName, data_get($context, $contextAttributeName)), + $resolveInfo->argumentSet->toArray(), $context, $resolveInfo ); diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/InterfaceDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/InterfaceDirective.php index db44f62..c3d170b 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/InterfaceDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/InterfaceDirective.php @@ -2,27 +2,15 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; - -class InterfaceDirective extends BaseDirective implements DefinedDirective +class InterfaceDirective extends BaseDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'interface'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Use a custom resolver to determine the concrete type of an interface. """ -directive @interface( +directive @interface( """ Reference to a custom type-resolver function. Consists of two parts: a class name and a method name, seperated by an `@` symbol. @@ -30,6 +18,6 @@ directive @interface( """ resolveType: String! ) on INTERFACE -SDL; +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/LazyLoadDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/LazyLoadDirective.php index 986a5e9..5aafff8 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/LazyLoadDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/LazyLoadDirective.php @@ -3,71 +3,61 @@ namespace Nuwave\Lighthouse\Schema\Directives; use Closure; -use GraphQL\Deferred; -use GraphQL\Type\Definition\ResolveInfo; +use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Pagination\LengthAwarePaginator; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class LazyLoadDirective extends BaseDirective implements DefinedDirective, FieldMiddleware +class LazyLoadDirective extends BaseDirective implements FieldMiddleware, FieldManipulator { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'lazyLoad'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Perform a [lazy eager load](https://laravel.com/docs/eloquent-relationships#lazy-eager-loading) on the relations of a list of models. """ directive @lazyLoad( - """ - The names of the relationship methods to load. - """ - relations: [String!]! -) on FIELD_DEFINITION -SDL; + """ + The names of the relationship methods to load. + """ + relations: [String!]! +) repeatable on FIELD_DEFINITION +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { - $relations = $this->directiveArgValue('relations', []); - $resolver = $fieldValue->getResolver(); + $relations = $this->directiveArgValue('relations'); - return $next( - $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver, $relations) { - /** @var \GraphQL\Deferred|\Illuminate\Database\Eloquent\Model $result */ - $result = $resolver($root, $args, $context, $resolveInfo); + $fieldValue->resultHandler( + /** + * @param Collection|LengthAwarePaginator $items + * + * @return Collection|LengthAwarePaginator + */ + static function ($items) use ($relations) { + $items->load($relations); - ($result instanceof Deferred) - ? $result->then(function (Collection &$items) use ($relations): Collection { - $items->load($relations); - - return $items; - }) - : $result->load($relations); - - return $result; - } - ) + return $items; + } ); + + return $next($fieldValue); + } + + public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType) + { + $relations = $this->directiveArgValue('relations'); + if (! is_array($relations) || count($relations) === 0) { + throw new DefinitionException( + "Must specify non-empty list of relations in `@{$this->name()}` directive on `{$parentType->name->value}.{$fieldDefinition->name->value}`." + ); + } } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/LikeDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/LikeDirective.php new file mode 100644 index 0000000..57c7deb --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/LikeDirective.php @@ -0,0 +1,93 @@ +directiveArgValue('template'); + if (is_string($template)) { + $value = $this->fillTemplate($template, $value); + } + + return $builder->where( + $this->directiveArgValue('key', $this->nodeName()), + 'LIKE', + $value + ); + } + + public function handleFieldBuilder(object $builder): object + { + return $this->handleBuilder( + $builder, + $this->directiveArgValue('value') + ); + } + + protected function fillTemplate(string $wildcardsTemplate, string $value): string + { + return str_replace( + self::PLACEHOLDER, + $this->escapeWildcards($value), + $wildcardsTemplate + ); + } + + protected function escapeWildcards(string $value): string + { + return str_replace( + [self::ESCAPE, self::PERCENTAGE, self::UNDERSCORE], + [self::ESCAPE.self::ESCAPE, self::ESCAPE.self::PERCENTAGE, self::ESCAPE.self::UNDERSCORE], + $value + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/LimitDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/LimitDirective.php new file mode 100644 index 0000000..148576b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/LimitDirective.php @@ -0,0 +1,90 @@ +type); + if ($argType !== Type::INT) { + throw new DefinitionException( + "The {$this->name()} directive must only be used on arguments of type ".Type::INT + .", got {$argType} on {$parentField->name->value}.{$this->nodeName()}." + ); + } + + $parentField->directives [] = $this->directiveNode; + } + + public function handleField(FieldValue $fieldValue, Closure $next) + { + $fieldValue->resultHandler(static function (?iterable $result, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): ?iterable { + if ($result === null) { + return null; + } + + $limit = null; + foreach ($resolveInfo->argumentSet->arguments as $argument) { + $argumentIsUsedToLimit = $argument->directives->contains( + Utils::instanceofMatcher(self::class) + ); + + if ($argumentIsUsedToLimit) { + $limit = $argument->value; + break; + } + } + + // Do not apply a limit if the client passes null explicitly + if (! is_int($limit)) { + return $result; + } + + $limited = []; + + foreach ($result as $value) { + if ($limit === 0) { + break; + } + $limit--; + + $limited [] = $value; + } + + return $limited; + }); + + return $next($fieldValue); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/MethodDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/MethodDirective.php index b20b1fb..54a4df9 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/MethodDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/MethodDirective.php @@ -2,57 +2,53 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use GraphQL\Type\Definition\ResolveInfo; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class MethodDirective extends BaseDirective implements FieldResolver, DefinedDirective +class MethodDirective extends BaseDirective implements FieldResolver { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'method'; - } + /** @var \GraphQL\Language\AST\FieldDefinitionNode */ + protected $definitionNode; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Call a method with a given `name` on the class that represents a type to resolve a field. -Use this if the data is not accessible as an attribute (e.g. `$model->myData`). +Resolve a field by calling a method on the parent object. + +Use this if the data is not accessible through simple property access or if you +want to pass argument to the method. """ -directive @method( +directive @method( """ Specify the method of which to fetch the data from. + Defaults to the name of the field if not given. """ name: String ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function resolveField(FieldValue $fieldValue): FieldValue { - /** @var string $method */ - $method = $this->directiveArgValue( - 'name', - $this->definitionNode->name->value - ); - return $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($method) { - return call_user_func([$root, $method], $root, $args, $context, $resolveInfo); + /** + * @param array $args + * @return mixed Really anything + */ + function ($root, array $args) { + /** @var string $method */ + $method = $this->directiveArgValue( + 'name', + $this->nodeName() + ); + + $orderedArgs = []; + foreach ($this->definitionNode->arguments as $argDefinition) { + $orderedArgs [] = $args[$argDefinition->name->value] ?? null; + } + + return $root->{$method}(...$orderedArgs); } ); } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/MiddlewareDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/MiddlewareDirective.php deleted file mode 100644 index 7219a78..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/MiddlewareDirective.php +++ /dev/null @@ -1,201 +0,0 @@ -pipeline = $pipeline; - $this->createsContext = $createsContext; - $this->middlewareAdapter = $middlewareAdapter; - } - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return self::NAME; - } - - public static function definition(): string - { - return /* @lang GraphQL */ <<<'SDL' -directive @middleware( - """ - Specify which middleware to run. - Pass in either a fully qualified class name, an alias or - a middleware group - or any combination of them. - """ - checks: [String!] -) on FIELD_DEFINITION -SDL; - } - - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function handleField(FieldValue $fieldValue, Closure $next): FieldValue - { - $middleware = $this->getQualifiedMiddlewareNames( - $this->directiveArgValue('checks') - ); - $resolver = $fieldValue->getResolver(); - - return $next( - $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver, $middleware) { - return $this->pipeline - ->send($context->request()) - ->through($middleware) - ->then(function (Request $request) use ($resolver, $root, $args, $resolveInfo) { - return $resolver( - $root, - $args, - $this->createsContext->generate($request), - $resolveInfo - ); - }); - } - ) - ); - } - - /** - * @param string|string[] $middlewareArgValue - * @return \Illuminate\Support\Collection - */ - protected function getQualifiedMiddlewareNames($middlewareArgValue): Collection - { - $middleware = $this->middlewareAdapter->getMiddleware(); - $middlewareGroups = $this->middlewareAdapter->getMiddlewareGroups(); - - return (new Collection($middlewareArgValue)) - ->map(function (string $name) use ($middleware, $middlewareGroups): array { - return (array) MiddlewareNameResolver::resolve($name, $middleware, $middlewareGroups); - }) - ->flatten(); - } - - /** - * Apply manipulations from a type definition node. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition - * @return void - */ - public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition): void - { - self::addMiddlewareDirectiveToFields($typeDefinition); - } - - /** - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\ObjectTypeExtensionNode $objectType - * @return void - * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException - */ - public function addMiddlewareDirectiveToFields(&$objectType): void - { - if ( - ! $objectType instanceof ObjectTypeDefinitionNode - && ! $objectType instanceof ObjectTypeExtensionNode - ) { - throw new DirectiveException( - 'The '.self::NAME.' directive may only be placed on fields or object types.' - ); - } - - $middlewareArgValue = (new Collection($this->directiveArgValue('checks'))) - ->map(function (string $middleware) : string { - // Add slashes, as re-parsing of the values removes a level of slashes - return addslashes($middleware); - }) - ->implode('", "'); - - $middlewareDirective = PartialParser::directive("@middleware(checks: [\"$middlewareArgValue\"])"); - - /** @var FieldDefinitionNode $fieldDefinition */ - foreach ($objectType->fields as $fieldDefinition) { - // If the field already has middleware defined, skip over it - // Field middleware are more specific then those defined on a type - if (ASTHelper::directiveDefinition($fieldDefinition, self::NAME)) { - return; - } - - $fieldDefinition->directives = $fieldDefinition->directives->merge([$middlewareDirective]); - } - } - - /** - * Apply manipulations from a type definition node. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeExtensionNode $typeExtension - * @return void - */ - public function manipulateTypeExtension(DocumentAST &$documentAST, TypeExtensionNode &$typeExtension): void - { - self::addMiddlewareDirectiveToFields($typeExtension); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/ModelDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/ModelDirective.php index 275cd13..37af1ad 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/ModelDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/ModelDirective.php @@ -2,80 +2,40 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Closure; -use GraphQL\Type\Definition\Type; -use Nuwave\Lighthouse\Schema\NodeRegistry; +use GraphQL\Language\AST\Node; use Nuwave\Lighthouse\Schema\AST\ASTHelper; -use GraphQL\Language\AST\TypeDefinitionNode; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; -use Nuwave\Lighthouse\Schema\Values\TypeValue; -use Nuwave\Lighthouse\Support\Contracts\TypeMiddleware; -use Nuwave\Lighthouse\Support\Contracts\TypeManipulator; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class ModelDirective extends BaseDirective implements TypeMiddleware, TypeManipulator, DefinedDirective +class ModelDirective extends BaseDirective { - /** - * @var \Nuwave\Lighthouse\Schema\NodeRegistry - */ - protected $nodeRegistry; - - /** - * @param \Nuwave\Lighthouse\Schema\NodeRegistry $nodeRegistry - * @return void - */ - public function __construct(NodeRegistry $nodeRegistry) - { - $this->nodeRegistry = $nodeRegistry; - } - - /** - * Directive name. - * - * @return string - */ - public function name(): string - { - return 'model'; - } + const NAME = 'model'; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Map a model class to an object type. +This can be used when the name of the model differs from the name of the type. """ -Enable fetching an Eloquent model by its global id through the `node` query. -""" -directive @model on OBJECT -SDL; +directive @model( + """ + The class name of the corresponding model. + """ + class: String! +) on OBJECT +GRAPHQL; } /** - * Handle type construction. - * - * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $value - * @param \Closure $next - * @return \GraphQL\Type\Definition\Type + * Attempt to get the model class name from this directive. */ - public function handleNode(TypeValue $value, Closure $next): Type + public static function modelClass(Node $node): ?string { - $this->nodeRegistry->registerModel( - $value->getTypeDefinitionName(), - $this->getModelClass('class') - ); + $modelDirective = ASTHelper::directiveDefinition($node, self::NAME); + if ($modelDirective !== null) { + return ASTHelper::directiveArgValue($modelDirective, 'class'); + } - return $next($value); - } - - /** - * Apply manipulations from a type definition node. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition - * @return void - */ - public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition): void - { - ASTHelper::attachNodeInterfaceToObjectType($typeDefinition); + return null; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/ModifyModelExistenceDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/ModifyModelExistenceDirective.php index 83b3afe..cc084a8 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/ModifyModelExistenceDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/ModifyModelExistenceDirective.php @@ -2,65 +2,55 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use GraphQL\Language\AST\ListTypeNode; -use Illuminate\Database\Eloquent\Model; -use GraphQL\Language\AST\NonNullTypeNode; -use Illuminate\Database\Eloquent\Collection; +use GraphQL\Error\Error; use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\ListTypeNode; +use GraphQL\Language\AST\NonNullTypeNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\Model; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Execution\ErrorPool; use Nuwave\Lighthouse\Schema\AST\DocumentAST; use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Support\Contracts\GlobalId; -use GraphQL\Language\AST\ObjectTypeDefinitionNode; -use Nuwave\Lighthouse\Exceptions\DirectiveException; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; +use Nuwave\Lighthouse\Support\Contracts\FieldResolver; +use Nuwave\Lighthouse\Support\Contracts\GlobalId; -abstract class ModifyModelExistenceDirective extends BaseDirective implements FieldResolver, FieldManipulator, DefinedDirective +abstract class ModifyModelExistenceDirective extends BaseDirective implements FieldResolver, FieldManipulator { /** - * The GlobalId resolver. - * * @var \Nuwave\Lighthouse\Support\Contracts\GlobalId */ protected $globalId; /** - * DeleteDirective constructor. - * - * @param \Nuwave\Lighthouse\Support\Contracts\GlobalId $globalId - * @return void + * @var \Nuwave\Lighthouse\Execution\ErrorPool */ - public function __construct(GlobalId $globalId) + protected $errorPool; + + public function __construct(GlobalId $globalId, ErrorPool $errorPool) { $this->globalId = $globalId; + $this->errorPool = $errorPool; + } + + public static function couldNotModify(Model $user): string + { + return 'Could not modify model '.get_class($user).' with ID '.$user->getKey().'.'; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function resolveField(FieldValue $fieldValue): FieldValue { return $fieldValue->setResolver( function ($root, array $args) { - /** @var string|int|string[]|int[] $idOrIds */ + /** @var string|int|array|array $idOrIds */ $idOrIds = reset($args); - if ($this->directiveArgValue('globalId', false)) { - // At this point we know the type is at least wrapped in a NonNull type, so we go one deeper - if ($this->idArgument()->type instanceof ListTypeNode) { - $idOrIds = array_map( - function (string $id): string { - return $this->globalId->decodeID($id); - }, - $idOrIds - ); - } else { - $idOrIds = $this->globalId->decodeID($idOrIds); - } + // TODO remove in v6 + if ($this->directiveArgValue('globalId') ?? false) { + // @phpstan-ignore-next-line We know that global ids must be strings + $idOrIds = $this->decodeIdOrIds($idOrIds); } $modelOrModels = $this->find( @@ -68,17 +58,25 @@ abstract class ModifyModelExistenceDirective extends BaseDirective implements Fi $idOrIds ); - if (! $modelOrModels) { - return; + if ($modelOrModels === null) { + return null; } + $modifyModelExistence = function (Model $model): void { + if (! $this->modifyExistence($model)) { + $this->errorPool->record( + new Error( + self::couldNotModify($model) + ) + ); + } + }; + if ($modelOrModels instanceof Model) { - $this->modifyExistence($modelOrModels); - } - - if ($modelOrModels instanceof Collection) { + $modifyModelExistence($modelOrModels); + } elseif ($modelOrModels instanceof Collection) { foreach ($modelOrModels as $model) { - $this->modifyExistence($model); + $modifyModelExistence($model); } } @@ -91,22 +89,20 @@ abstract class ModifyModelExistenceDirective extends BaseDirective implements Fi * Get the type of the id argument. * * Not using an actual type hint, as the manipulateFieldDefinition function - * validates the type during schema build time.f + * validates the type during schema build time. * - * @return \GraphQL\Language\AST\NonNullTypeNode + * @return mixed but should be a \GraphQL\Language\AST\NonNullTypeNode */ protected function idArgument() { - return $this->definitionNode->arguments[0]->type; + /** @var \GraphQL\Language\AST\FieldDefinitionNode $fieldNode */ + $fieldNode = $this->definitionNode; + + return $fieldNode->arguments[0]->type; } /** - * @param DocumentAST $documentAST - * @param FieldDefinitionNode $fieldDefinition - * @param ObjectTypeDefinitionNode $parentType - * @return void - * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ public function manipulateFieldDefinition( DocumentAST &$documentAST, @@ -114,33 +110,53 @@ abstract class ModifyModelExistenceDirective extends BaseDirective implements Fi ObjectTypeDefinitionNode &$parentType ): void { // Ensure there is only a single argument defined on the field. - if (count($this->definitionNode->arguments) !== 1) { - throw new DirectiveException( - 'The @'.static::name()." directive requires the field {$this->definitionNode->name->value} to only contain a single argument." + if (count($fieldDefinition->arguments) !== 1) { + throw new DefinitionException( + 'The @'.$this->name()." directive requires the field {$this->nodeName()} to only contain a single argument." ); } if (! $this->idArgument() instanceof NonNullTypeNode) { - throw new DirectiveException( - 'The @'.static::name()." directive requires the field {$this->definitionNode->name->value} to have a NonNull argument. Mark it with !" + throw new DefinitionException( + 'The @'.$this->name()." directive requires the field {$this->nodeName()} to have a NonNull argument. Mark it with !" ); } } + /** + * @param string|array $idOrIds + * @return string|array + */ + protected function decodeIdOrIds($idOrIds) + { + // At this point we know the type is at least wrapped in a NonNull type, so we go one deeper + if ($this->idArgument()->type instanceof ListTypeNode) { + /** @var array $idOrIds */ + return array_map( + function (string $id): string { + return $this->globalId->decodeID($id); + }, + $idOrIds + ); + } else { + /** @var string $idOrIds */ + return $this->globalId->decodeID($idOrIds); + } + } + /** * Find one or more models by id. * - * @param string|\Illuminate\Database\Eloquent\Model $modelClass - * @param string|int|string[]|int[] $idOrIds - * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection + * @param class-string<\Illuminate\Database\Eloquent\Model> $modelClass + * @param string|int|array|array $idOrIds + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection<\Illuminate\Database\Eloquent\Model>|null */ abstract protected function find(string $modelClass, $idOrIds); /** * Bring a model in or out of existence. * - * @param \Illuminate\Database\Eloquent\Model $model - * @return void + * The return value indicates if the operation was successful. */ - abstract protected function modifyExistence(Model $model): void; + abstract protected function modifyExistence(Model $model): bool; } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/MorphManyDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphManyDirective.php index 9e7a979..4ee5615 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/MorphManyDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphManyDirective.php @@ -2,32 +2,15 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; -class MorphManyDirective extends RelationDirective implements FieldResolver, FieldManipulator, DefinedDirective +class MorphManyDirective extends RelationDirective implements FieldManipulator { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string + public static function definition(): string { - return 'morphMany'; - } - - /** - * SDL definition of the directive. - * - * @return string - */ - public static function definition() - { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Corresponds to [Eloquent's MorphMany-Relationship](https://laravel.com/docs/5.8/eloquent-relationships#one-to-one-polymorphic-relations). +Corresponds to [Eloquent's MorphMany-Relationship](https://laravel.com/docs/eloquent-relationships#one-to-many-polymorphic-relations). """ directive @morphMany( """ @@ -35,30 +18,29 @@ directive @morphMany( if it is named different from the field in the schema. """ relation: String - + """ Apply scopes to the underlying query. """ scopes: [String!] """ - ALlows to resolve the relation as a paginated list. - Allowed values: paginator, connection. + Allows to resolve the relation as a paginated list. """ - type: String + type: MorphManyType """ - Specify the default quantity of elements to be returned. - Only applies when using pagination. + Allow clients to query paginated lists without specifying the amount of items. + Overrules the `pagination.default_count` setting from `lighthouse.php`. """ defaultCount: Int - + """ - Specify the maximum quantity of elements to be returned. - Only applies when using pagination. + Limit the maximum amount of items that clients can request from paginated lists. + Overrules the `pagination.max_count` setting from `lighthouse.php`. """ maxCount: Int - + """ Specify a custom type that implements the Edge interface to extend edge object. @@ -66,6 +48,26 @@ directive @morphMany( """ edgeType: String ) on FIELD_DEFINITION -SDL; + +""" +Options for the `type` argument of `@morphMany`. +""" +enum MorphManyType { + """ + Offset-based pagination, similar to the Laravel default. + """ + PAGINATOR + + """ + Offset-based pagination like the Laravel "Simple Pagination", which does not count the total number of records. + """ + SIMPLE + + """ + Cursor-based pagination, compatible with the Relay specification. + """ + CONNECTION +} +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/MorphOneDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphOneDirective.php index de9f667..321519c 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/MorphOneDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphOneDirective.php @@ -2,44 +2,26 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; - -class MorphOneDirective extends RelationDirective implements FieldResolver, DefinedDirective +class MorphOneDirective extends RelationDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string + public static function definition(): string { - return 'morphOne'; - } - - /** - * SDL definition of the directive. - * - * @return string - */ - public static function definition() - { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Corresponds to [Eloquent's MorphOne-Relationship](https://laravel.com/docs/5.8/eloquent-relationships#one-to-one-polymorphic-relations). +Corresponds to [Eloquent's MorphOne-Relationship](https://laravel.com/docs/eloquent-relationships#one-to-one-polymorphic-relations). """ -directive @morphOne( +directive @morphOne( """ Specify the relationship method name in the model class, if it is named different from the field in the schema. """ relation: String - + """ Apply scopes to the underlying query. """ scopes: [String!] ) on FIELD_DEFINITION -SDL; +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/MorphToDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphToDirective.php index 0a6b946..80e8cae 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/MorphToDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphToDirective.php @@ -2,44 +2,26 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; - -class MorphToDirective extends RelationDirective implements FieldResolver, DefinedDirective +class MorphToDirective extends RelationDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string + public static function definition(): string { - return 'morphTo'; - } - - /** - * SDL definition of the directive. - * - * @return string - */ - public static function definition() - { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Corresponds to [Eloquent's MorphTo-Relationship](https://laravel.com/docs/5.8/eloquent-relationships#one-to-one-polymorphic-relations). +Corresponds to [Eloquent's MorphTo-Relationship](https://laravel.com/docs/eloquent-relationships#one-to-one-polymorphic-relations). """ -directive @morphTo( +directive @morphTo( """ Specify the relationship method name in the model class, if it is named different from the field in the schema. """ relation: String - + """ Apply scopes to the underlying query. """ scopes: [String!] ) on FIELD_DEFINITION -SDL; +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/MorphToManyDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphToManyDirective.php new file mode 100644 index 0000000..4541ade --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/MorphToManyDirective.php @@ -0,0 +1,29 @@ +databaseManager = $databaseManager; + } + + public function resolveField(FieldValue $fieldValue): FieldValue + { + return $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Model { + $modelClass = $this->getModelClass(); + $model = new $modelClass; + + $executeMutation = function () use ($model, $resolveInfo): Model { + /** @var \Illuminate\Database\Eloquent\Model $mutated */ + $mutated = $this->executeMutation( + $model, + $resolveInfo->argumentSet + ); + + return $mutated->refresh(); + }; + + return config('lighthouse.transactional_mutations', true) + ? $this + ->databaseManager + ->connection( + $model->getConnectionName() + ) + ->transaction($executeMutation) + : $executeMutation(); + } + ); + } + + /** + * @param \Illuminate\Database\Eloquent\Model $parent + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $args + * @return \Illuminate\Database\Eloquent\Model|array<\Illuminate\Database\Eloquent\Model> + */ + public function __invoke($parent, $args) + { + $relationName = $this->directiveArgValue('relation') + // Use the name of the argument if no explicit relation name is given + ?? $this->nodeName(); + + /** @var \Illuminate\Database\Eloquent\Relations\Relation $relation */ + $relation = $parent->{$relationName}(); + + /** @var \Illuminate\Database\Eloquent\Model $related */ + // @phpstan-ignore-next-line Relation&Builder mixin not recognized + $related = $relation->make(); + + return $this->executeMutation($related, $args, $relation); + } + + /** + * @param \Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|array<\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet> $args + * @return \Illuminate\Database\Eloquent\Model|array<\Illuminate\Database\Eloquent\Model> + */ + protected function executeMutation(Model $model, $args, ?Relation $parentRelation = null) + { + $update = new ResolveNested($this->makeExecutionFunction($parentRelation)); + + return Utils::applyEach( + static function (ArgumentSet $argumentSet) use ($update, $model) { + return $update($model->newInstance(), $argumentSet); + }, + $args + ); + } + + /** + * Prepare the execution function for a mutation on a model. + */ + abstract protected function makeExecutionFunction(?Relation $parentRelation = null): callable; +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/NamespaceDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/NamespaceDirective.php index 46648f8..29ddbf0 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/NamespaceDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/NamespaceDirective.php @@ -2,15 +2,14 @@ namespace Nuwave\Lighthouse\Schema\Directives; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Language\AST\ObjectTypeExtensionNode; +use GraphQL\Language\AST\TypeDefinitionNode; use GraphQL\Language\AST\TypeExtensionNode; use Nuwave\Lighthouse\Schema\AST\ASTHelper; -use GraphQL\Language\AST\TypeDefinitionNode; use Nuwave\Lighthouse\Schema\AST\DocumentAST; -use GraphQL\Language\AST\ObjectTypeExtensionNode; -use GraphQL\Language\AST\ObjectTypeDefinitionNode; -use Nuwave\Lighthouse\Support\Contracts\TypeManipulator; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\TypeExtensionManipulator; +use Nuwave\Lighthouse\Support\Contracts\TypeManipulator; /** * Redefine the default namespaces used in other directives. @@ -19,59 +18,41 @@ use Nuwave\Lighthouse\Support\Contracts\TypeExtensionManipulator; * For example `@namespace(field: "App\\GraphQL")` applies the namespace * `App\GraphQL` to the `@field` directive. */ -class NamespaceDirective extends BaseDirective implements TypeManipulator, TypeExtensionManipulator, DefinedDirective +class NamespaceDirective extends BaseDirective implements TypeManipulator, TypeExtensionManipulator { - const NAME = 'namespace'; - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return self::NAME; - } + public const NAME = 'namespace'; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Redefine the default namespaces used in other directives. The arguments are a map from directive names to namespaces. """ directive @namespace on FIELD_DEFINITION | OBJECT -SDL; +GRAPHQL; } /** * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\ObjectTypeExtensionNode $objectType - * @return void */ protected function addNamespacesToFields(&$objectType): void { - $namespaceDirective = $this->directiveDefinition(); + /** @var \GraphQL\Language\AST\DirectiveNode $namespaceDirective */ + $namespaceDirective = $this->directiveNode->cloneDeep(); foreach ($objectType->fields as $fieldDefinition) { - if ( - $existingNamespaces = ASTHelper::directiveDefinition( - $fieldDefinition, - self::NAME - ) - ) { + $existingNamespaces = ASTHelper::directiveDefinition($fieldDefinition, self::NAME); + if ($existingNamespaces !== null) { $namespaceDirective->arguments = $namespaceDirective->arguments->merge($existingNamespaces->arguments); } - $fieldDefinition->directives = $fieldDefinition->directives->merge([$namespaceDirective]); + $fieldDefinition->directives [] = $namespaceDirective; } } /** * Apply manipulations from a type definition node. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition - * @return void */ public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition): void { @@ -82,10 +63,6 @@ SDL; /** * Apply manipulations from a type definition node. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeExtensionNode $typeExtension - * @return void */ public function manipulateTypeExtension(DocumentAST &$documentAST, TypeExtensionNode &$typeExtension): void { diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/NeqDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/NeqDirective.php index 8d9a405..6abc05e 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/NeqDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/NeqDirective.php @@ -2,48 +2,30 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class NeqDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class NeqDirective extends BaseDirective implements ArgBuilderDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'neq'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Place a not equals operator `!=` on an Eloquent query. +Use the client given value to add an not-equal conditional to a database query. """ -directive @neq( +directive @neq( """ - Specify the database column to compare. - Only required if database column has a different name than the attribute in your schema. + Specify the database column to compare. + Only required if database column has a different name than the attribute in your schema. """ key: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Apply a "WHERE <> $value" clause. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $value - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $value) + public function handleBuilder($builder, $value): object { return $builder->where( - $this->directiveArgValue('key', $this->definitionNode->name->value), + $this->directiveArgValue('key', $this->nodeName()), '<>', $value ); diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/NestDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/NestDirective.php new file mode 100644 index 0000000..49ea8c0 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/NestDirective.php @@ -0,0 +1,40 @@ + $args The slice of arguments that belongs to this nested resolver. + */ + public function __invoke($root, $args) + { + $resolveNested = new ResolveNested(); + + return Utils::applyEach( + static function (ArgumentSet $argumentSet) use ($resolveNested, $root) { + return $resolveNested($root, $argumentSet); + }, + $args + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/NodeDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/NodeDirective.php deleted file mode 100644 index b41d7bb..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/NodeDirective.php +++ /dev/null @@ -1,87 +0,0 @@ -nodeRegistry = $nodeRegistry; - } - - /** - * Directive name. - * - * @return string - */ - public function name(): string - { - return 'node'; - } - - public static function definition(): string - { - return /* @lang GraphQL */ <<<'SDL' -""" -Register a type for relay global object identification. -""" -directive @node( - """ - Reference to resolver function. - Consists of two parts: a class name and a method name, seperated by an `@` symbol. - If you pass only a class name, the method name defaults to `__invoke`. - """ - resolver: String! -) on FIELD_DEFINITION -SDL; - } - - /** - * Handle type construction. - * - * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $value - * @param \Closure $next - * @return \GraphQL\Type\Definition\Type - */ - public function handleNode(TypeValue $value, Closure $next): Type - { - $this->nodeRegistry->registerNode( - $value->getTypeDefinitionName(), - $this->getResolverFromArgument('resolver') - ); - - return $next($value); - } - - /** - * Apply manipulations from a type definition node. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition - * @return void - */ - public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition): void - { - ASTHelper::attachNodeInterfaceToObjectType($typeDefinition); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/NotInDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/NotInDirective.php index a16b9d2..8839c16 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/NotInDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/NotInDirective.php @@ -2,49 +2,31 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class NotInDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class NotInDirective extends BaseDirective implements ArgBuilderDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'notIn'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Filter a column by an array using a `whereNotIn` clause. +Use the client given value to add a NOT IN conditional to a database query. """ -directive @notIn( +directive @notIn( """ - Specify the name of the column. - Only required if it differs from the name of the argument. + Specify the database column to compare. + Only required if database column has a different name than the attribute in your schema. """ key: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Apply a simple "WHERE NOT IN $values" clause. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $values - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $values) + public function handleBuilder($builder, $value): object { return $builder->whereNotIn( - $this->directiveArgValue('key', $this->definitionNode->name->value), - $values + $this->directiveArgValue('key', $this->nodeName()), + $value ); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/OrderByDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/OrderByDirective.php deleted file mode 100644 index 909569e..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/OrderByDirective.php +++ /dev/null @@ -1,98 +0,0 @@ -orderBy( - $orderByClause['field'], - $orderByClause['order'] - ); - } - - return $builder; - } - - /** - * Validate the input argument definition. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\InputValueDefinitionNode $argDefinition - * @param \GraphQL\Language\AST\FieldDefinitionNode $parentField - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @return void - * - * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException - */ - public function manipulateArgDefinition( - DocumentAST &$documentAST, - InputValueDefinitionNode &$argDefinition, - FieldDefinitionNode &$parentField, - ObjectTypeDefinitionNode &$parentType - ): void { - // Users may define this as NonNull if they want - // Because we need to validate the structure regardless, - // we unwrap it by one level if it is - $expectedOrderByClause = $argDefinition->type instanceof NonNullTypeNode - ? $argDefinition->type - : $argDefinition; - - if ( - data_get( - $expectedOrderByClause, - // Must be a list - 'type' - // of non-nullable - .'.type' - // input objects - .'.type.name.value' - // that are exactly of type - ) !== 'OrderByClause' - ) { - throw new DefinitionException( - "Must define the argument type of {$argDefinition->name->value} on field {$parentField->name->value} as [OrderByClause!]." - ); - } - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/PaginateDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/PaginateDirective.php deleted file mode 100644 index 27e6a94..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/PaginateDirective.php +++ /dev/null @@ -1,192 +0,0 @@ -paginationType(), - $fieldDefinition, - $parentType, - $documentAST, - $this->directiveArgValue('defaultCount'), - $this->paginateMaxCount() - ); - } - - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function resolveField(FieldValue $fieldValue): FieldValue - { - return $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): LengthAwarePaginator { - /** @var int $first */ - /** @var int $page */ - [$first, $page] = PaginationUtils::extractArgs($args, $this->paginationType(), $this->paginateMaxCount()); - - if ($this->directiveHasArgument('builder')) { - $query = call_user_func( - $this->getResolverFromArgument('builder'), - $root, - $args, - $context, - $resolveInfo - ); - } else { - /** @var \Illuminate\Database\Eloquent\Model $model */ - $model = $this->getPaginatorModel(); - $query = $model::query(); - } - - $query = $resolveInfo - ->builder - ->addScopes( - $this->directiveArgValue('scopes', []) - ) - ->apply( - $query, - $args - ); - - if ($query instanceof ScoutBuilder) { - return $query->paginate($first, 'page', $page); - } - - return $query->paginate($first, ['*'], 'page', $page); - } - ); - } - - protected function paginationType(): PaginationType - { - return new PaginationType( - $this->directiveArgValue('type', PaginationType::TYPE_PAGINATOR) - ); - } - - /** - * Get either the specific max or the global setting. - * - * @return int|null - */ - protected function paginateMaxCount(): ?int - { - return $this->directiveArgValue('maxCount') - ?? config('lighthouse.paginate_max_count'); - } - - /** - * Get the model class from the `model` argument of the field. - * - * This works differently as in other directives, so we define a separate function for it. - * - * @return string - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException - */ - protected function getPaginatorModel(): string - { - $model = $this->directiveArgValue('model'); - - // Fallback to using information from the schema definition as the model name - if (! $model) { - $model = ASTHelper::getUnderlyingTypeName($this->definitionNode); - - // Cut the added type suffix to get the base model class name - $model = Str::before($model, 'Paginator'); - $model = Str::before($model, 'Connection'); - } - - if (! $model) { - throw new DirectiveException( - "A `model` argument must be assigned to the '{$this->name()}' directive on '{$this->definitionNode->name->value}" - ); - } - - return $this->namespaceModelClass($model); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirective.php index 2697bac..51e6887 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirective.php @@ -2,130 +2,139 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use GraphQL\Deferred; -use Illuminate\Database\Eloquent\Model; -use GraphQL\Type\Definition\ResolveInfo; use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Type\Definition\ResolveInfo; +use Illuminate\Database\Eloquent\Model; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Execution\BatchLoader\BatchLoaderRegistry; +use Nuwave\Lighthouse\Execution\BatchLoader\RelationBatchLoader; +use Nuwave\Lighthouse\Execution\ModelsLoader\PaginatedModelsLoader; +use Nuwave\Lighthouse\Execution\ModelsLoader\SimpleModelsLoader; +use Nuwave\Lighthouse\Pagination\PaginationArgs; +use Nuwave\Lighthouse\Pagination\PaginationManipulator; +use Nuwave\Lighthouse\Pagination\PaginationType; use Nuwave\Lighthouse\Schema\AST\DocumentAST; use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Pagination\PaginationType; -use Nuwave\Lighthouse\Pagination\PaginationUtils; -use GraphQL\Language\AST\ObjectTypeDefinitionNode; -use Nuwave\Lighthouse\Exceptions\DirectiveException; -use Nuwave\Lighthouse\Execution\DataLoader\BatchLoader; -use Nuwave\Lighthouse\Pagination\PaginationManipulator; +use Nuwave\Lighthouse\Support\Contracts\FieldResolver; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Execution\DataLoader\RelationBatchLoader; -abstract class RelationDirective extends BaseDirective +abstract class RelationDirective extends BaseDirective implements FieldResolver { - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $value - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function resolveField(FieldValue $value): FieldValue + use RelationDirectiveHelpers; + + public function resolveField(FieldValue $fieldValue): FieldValue { - return $value->setResolver( - function (Model $parent, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Deferred { - $constructorArgs = [ - 'relationName' => $this->directiveArgValue('relation', $this->definitionNode->name->value), - 'args' => $args, - 'scopes' => $this->directiveArgValue('scopes', []), - 'resolveInfo' => $resolveInfo, - ]; + $fieldValue->setResolver( + function (Model $parent, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { + $relationName = $this->relation(); - if ($paginationType = $this->paginationType()) { - /** @var int $first */ - /** @var int $page */ - [$first, $page] = PaginationUtils::extractArgs($args, $paginationType, $this->paginateMaxCount()); + $decorateBuilder = $this->makeBuilderDecorator($resolveInfo); + $paginationArgs = $this->paginationArgs($args); - $constructorArgs += [ - 'first' => $first, - 'page' => $page, - ]; + if (config('lighthouse.batchload_relations')) { + /** @var \Nuwave\Lighthouse\Execution\BatchLoader\RelationBatchLoader $relationBatchLoader */ + $relationBatchLoader = BatchLoaderRegistry::instance( + $this->qualifyPath($args, $resolveInfo), + function () use ($relationName, $decorateBuilder, $paginationArgs): RelationBatchLoader { + $modelsLoader = $paginationArgs !== null + ? new PaginatedModelsLoader($relationName, $decorateBuilder, $paginationArgs) + : new SimpleModelsLoader($relationName, $decorateBuilder); + + return new RelationBatchLoader($modelsLoader); + } + ); + + return $relationBatchLoader->load($parent); } - return BatchLoader - ::instance( - RelationBatchLoader::class, - $resolveInfo->path, - $constructorArgs - ) - ->load( - $parent->getKey(), - ['parent' => $parent] - ); + /** @var \Illuminate\Database\Eloquent\Relations\Relation $relation */ + $relation = $parent->{$relationName}(); + + $decorateBuilder($relation); + + return $paginationArgs !== null + ? $paginationArgs->applyToBuilder($relation) + : $relation->getResults(); } ); + + return $fieldValue; } - /** - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @return void - */ - public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType): void - { + public function manipulateFieldDefinition( + DocumentAST &$documentAST, + FieldDefinitionNode &$fieldDefinition, + ObjectTypeDefinitionNode &$parentType + ): void { $paginationType = $this->paginationType(); // We default to not changing the field if no pagination type is set explicitly. // This makes sense for relations, as there should not be too many entries. - if (! $paginationType) { + if ($paginationType === null) { return; } - PaginationManipulator::transformToPaginatedField( + $paginationManipulator = new PaginationManipulator($documentAST); + $paginationManipulator->transformToPaginatedField( $paginationType, $fieldDefinition, $parentType, - $documentAST, - $this->directiveArgValue('defaultCount'), - $this->paginateMaxCount(), + $this->paginationDefaultCount(), + $this->paginationMaxCount(), $this->edgeType($documentAST) ); } - protected function paginationType(): ?PaginationType - { - if ($paginationType = $this->directiveArgValue('type')) { - return new PaginationType($paginationType); - } - - return null; - } - /** - * @param Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @return GraphQL\Language\AST\ObjectTypeDefinitionNode|null - * - * @throws Nuwave\Lighthouse\Exceptions\DirectiveException + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ protected function edgeType(DocumentAST $documentAST): ?ObjectTypeDefinitionNode { - if ($edgeType = $this->directiveArgValue('edgeType')) { - if (! isset($documentAST->types[$edgeType])) { - throw new DirectiveException( - 'The edgeType argument on '.$this->definitionNode->name->value.' must reference an existing type definition' + if ($edgeTypeName = $this->directiveArgValue('edgeType')) { + $edgeType = $documentAST->types[$edgeTypeName] ?? null; + if (! $edgeType instanceof ObjectTypeDefinitionNode) { + throw new DefinitionException( + "The edgeType argument on {$this->nodeName()} must reference an existing object type definition." ); } - return $documentAST->types[$edgeType]; + return $edgeType; } return null; } /** - * Get either the specific max or the global setting. - * - * @return int|null + * @param array $args */ - protected function paginateMaxCount(): ?int + protected function paginationArgs(array $args): ?PaginationArgs + { + $paginationType = $this->paginationType(); + + return $paginationType !== null + ? PaginationArgs::extractArgs($args, $paginationType, $this->paginationMaxCount()) + : null; + } + + protected function paginationType(): ?PaginationType + { + $type = $this->directiveArgValue('type'); + + return $type !== null + ? new PaginationType($type) + : null; + } + + protected function paginationMaxCount(): ?int { return $this->directiveArgValue('maxCount') - ?? config('lighthouse.paginate_max_count'); + ?? config('lighthouse.pagination.max_count'); + } + + protected function paginationDefaultCount(): ?int + { + return $this->directiveArgValue('defaultCount') + ?? config('lighthouse.pagination.default_count'); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirectiveHelpers.php b/vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirectiveHelpers.php new file mode 100644 index 0000000..3c51585 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/RelationDirectiveHelpers.php @@ -0,0 +1,67 @@ + + */ + protected function scopes(): array + { + return $this->directiveArgValue('scopes') + ?? []; + } + + protected function relation(): string + { + return $this->directiveArgValue('relation') + ?? $this->nodeName(); + } + + /** + * @return \Closure(object): void + */ + protected function makeBuilderDecorator(ResolveInfo $resolveInfo): Closure + { + return function (object $builder) use ($resolveInfo) { + if ($builder instanceof Relation) { + $builder = $builder->getQuery(); + } + + $resolveInfo->argumentSet->enhanceBuilder( + $builder, + $this->scopes() + ); + }; + } + + /** + * @param array $args + * @return array + */ + protected function qualifyPath(array $args, ResolveInfo $resolveInfo): array + { + // Includes the field we are loading the relation for + $path = $resolveInfo->path; + + // In case we have no args, we can combine eager loads that are the same + if ($args === []) { + array_pop($path); + } + + // Each relation must be loaded separately + $path [] = $this->relation(); + + // Scopes influence the result of the query + return array_merge($path, $this->scopes()); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/RenameArgsDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/RenameArgsDirective.php new file mode 100644 index 0000000..1882ef9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/RenameArgsDirective.php @@ -0,0 +1,42 @@ +getResolver(); + + return $next( + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver) { + $resolveInfo->argumentSet = $resolveInfo->argumentSet->rename(); + + return $resolver( + $root, + $resolveInfo->argumentSet->toArray(), + $context, + $resolveInfo + ); + } + ) + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/RenameDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/RenameDirective.php index 2fe9a32..c8ec6bd 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/RenameDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/RenameDirective.php @@ -2,53 +2,32 @@ namespace Nuwave\Lighthouse\Schema\Directives; +use Nuwave\Lighthouse\Exceptions\DefinitionException; use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Exceptions\DirectiveException; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -class RenameDirective extends BaseDirective implements FieldResolver, DefinedDirective +class RenameDirective extends BaseDirective implements FieldResolver { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'rename'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Change the internally used name of a field or argument. + +This does not change the schema from a client perspective. +""" directive @rename( """ - Specify the original name of the property/key that the field - value can be retrieved from. + The internal name of an attribute/property/key. """ attribute: String! -) on FIELD_DEFINITION -SDL; +) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException - */ public function resolveField(FieldValue $fieldValue): FieldValue { - $attribute = $this->directiveArgValue('attribute'); - - if (! $attribute) { - throw new DirectiveException( - "The [{$this->name()}] directive requires an `attribute` argument." - ); - } + $attribute = $this->attributeArgValue(); return $fieldValue->setResolver( function ($rootValue) use ($attribute) { @@ -56,4 +35,22 @@ SDL; } ); } + + /** + * Retrieves the attribute argument for the directive. + * + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + public function attributeArgValue(): string + { + $attribute = $this->directiveArgValue('attribute'); + + if (! $attribute) { + throw new DefinitionException( + "The @{$this->name()} directive requires an `attribute` argument." + ); + } + + return $attribute; + } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/RulesDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/RulesDirective.php deleted file mode 100644 index da90cda..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/RulesDirective.php +++ /dev/null @@ -1,82 +0,0 @@ -directiveArgValue('apply'); - - // Custom rules may be referenced through their fully qualified class name. - // The Laravel validator expects a class instance to be passed, so we - // resolve any given rule where a corresponding class exists. - foreach ($rules as $key => $rule) { - if (class_exists($rule)) { - $rules[$key] = resolve($rule); - } - } - - return [$this->argumentPathAsDotNotation() => $rules]; - } - - /** - * @return string[] - */ - public function messages(): array - { - return (new Collection($this->directiveArgValue('messages'))) - ->mapWithKeys(function (string $message, string $rule): array { - $argumentPath = $this->argumentPathAsDotNotation(); - - return ["{$argumentPath}.{$rule}" => $message]; - }) - ->all(); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/RulesForArrayDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/RulesForArrayDirective.php deleted file mode 100644 index dd1e3b4..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/RulesForArrayDirective.php +++ /dev/null @@ -1,87 +0,0 @@ -directiveArgValue('apply'); - - if (! in_array('array', $rules)) { - $rules = Arr::prepend($rules, 'array'); - } - - // Custom rules may be referenced through their fully qualified class name. - // The Laravel validator expects a class instance to be passed, so we - // resolve any given rule where a corresponding class exists. - foreach ($rules as $key => $rule) { - if (class_exists($rule)) { - $rules[$key] = resolve($rule); - } - } - - return [$this->argumentPathAsDotNotation() => $rules]; - } - - /** - * @return string[] - */ - public function messages(): array - { - return (new Collection($this->directiveArgValue('messages'))) - ->mapWithKeys(function (string $message, string $rule): array { - $argumentPath = $this->argumentPathAsDotNotation(); - - return ["{$argumentPath}.{$rule}" => $message]; - }) - ->all(); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/SanitizeDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/SanitizeDirective.php new file mode 100644 index 0000000..42e1ced --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/SanitizeDirective.php @@ -0,0 +1,28 @@ +sanitize($value); + } + + return $value; + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/ScalarDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/ScalarDirective.php index a90d731..d00429f 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/ScalarDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/ScalarDirective.php @@ -2,23 +2,11 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; - -class ScalarDirective extends BaseDirective implements DefinedDirective +class ScalarDirective extends BaseDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'scalar'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Reference a class implementing a scalar definition. """ @@ -28,6 +16,6 @@ directive @scalar( """ class: String! ) on SCALAR -SDL; +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/ScopeDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/ScopeDirective.php new file mode 100644 index 0000000..0505e7b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/ScopeDirective.php @@ -0,0 +1,46 @@ +directiveArgValue('name'); + + try { + return $builder->{$scope}($value); + // @phpstan-ignore-next-line PHPStan thinks this exception does not occur - but it does. Magic. + } catch (BadMethodCallException $exception) { + throw new DefinitionException( + $exception->getMessage()." in @{$this->name()} directive on {$this->nodeName()} argument.", + $exception->getCode(), + $exception->getPrevious() + ); + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/SearchDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/SearchDirective.php deleted file mode 100644 index 0056aff..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/SearchDirective.php +++ /dev/null @@ -1,58 +0,0 @@ -getModel() - ); - - /** @var \Laravel\Scout\Builder $builder */ - $builder = $modelClass::search($value); - - if ($within = $this->directiveArgValue('within')) { - $builder->within($within); - } - - return $builder; - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/SpreadDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/SpreadDirective.php index eac7801..5327fa3 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/SpreadDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/SpreadDirective.php @@ -2,28 +2,42 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\ArgDirective; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Closure; +use GraphQL\Type\Definition\ResolveInfo; +use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -class SpreadDirective implements ArgDirective, DefinedDirective +class SpreadDirective extends BaseDirective implements FieldMiddleware { - /** - * Directive name. - * - * @return string - */ - public function name(): string - { - return 'spread'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Spread out the nested values of an argument of type input object into it\'s parent. +Merge the fields of a nested input object into the arguments of its parent +when processing the field arguments given by a client. """ -directive @spread on ARGUMENT_DEFINITION -SDL; +directive @spread on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; + } + + public function handleField(FieldValue $fieldValue, Closure $next) + { + $resolver = $fieldValue->getResolver(); + + return $next( + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver) { + $resolveInfo->argumentSet = $resolveInfo->argumentSet->spread(); + + return $resolver( + $root, + $resolveInfo->argumentSet->toArray(), + $context, + $resolveInfo + ); + } + ) + ); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/ThrottleDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/ThrottleDirective.php new file mode 100644 index 0000000..bf8118f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/ThrottleDirective.php @@ -0,0 +1,159 @@ +limiter = $limiter; + $this->request = $request; + } + + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Sets rate limit to access the field. Does the same as ThrottleRequests Laravel Middleware. +""" +directive @throttle( + """ + Named preconfigured rate limiter. Requires Laravel 8.x or later. + """ + name: String + + """ + Maximum number of attempts in a specified time interval. + """ + maxAttempts: Int = 60 + + """ + Time in minutes to reset attempts. + """ + decayMinutes: Float = 1.0 + + """ + Prefix to distinguish several field groups. + """ + prefix: String +) on FIELD_DEFINITION +GRAPHQL; + } + + public function handleField(FieldValue $fieldValue, Closure $next): FieldValue + { + /** @var array $limits */ + $limits = []; + + $name = $this->directiveArgValue('name'); + if ($name !== null) { + // @phpstan-ignore-next-line won't be executed on Laravel < 8 + $limiter = $this->limiter->limiter($name); + + $limiterResponse = $limiter($this->request); + /** + * @psalm-suppress UndefinedClass + */ + // @phpstan-ignore-next-line won't be executed on Laravel < 8 + if ($limiterResponse instanceof Unlimited) { + return $next($fieldValue); + } + + if ($limiterResponse instanceof Response) { + throw new DirectiveException( + "Expected named limiter {$name} to return an array, got instance of ".get_class($limiterResponse) + ); + } + + foreach (Arr::wrap($limiterResponse) as $limit) { + $limits[] = [ + 'key' => sha1($name.$limit->key), + 'maxAttempts' => $limit->maxAttempts, + 'decayMinutes' => $limit->decayMinutes, + ]; + } + } else { + $limits[] = [ + 'key' => sha1($this->directiveArgValue('prefix', '').$this->request->ip()), + 'maxAttempts' => $this->directiveArgValue('maxAttempts') ?? 60, + 'decayMinutes' => $this->directiveArgValue('decayMinutes') ?? 1.0, + ]; + } + + $resolver = $fieldValue->getResolver(); + + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver, $limits) { + foreach ($limits as $limit) { + $this->handleLimit( + $limit['key'], + $limit['maxAttempts'], + $limit['decayMinutes'] + ); + } + + return $resolver($root, $args, $context, $resolveInfo); + } + ); + + return $next($fieldValue); + } + + public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType): void + { + $name = $this->directiveArgValue('name'); + if ($name !== null) { + if (AppVersion::below(8.0)) { + throw new DefinitionException('Named limiter requires Laravel 8.x or later'); + } + + // @phpstan-ignore-next-line won't be executed on Laravel < 8 + $limiter = $this->limiter->limiter($name); + // @phpstan-ignore-next-line $limiter may be null although it's not specified in limiter() PHPDoc + if (is_null($limiter)) { + throw new DefinitionException("Named limiter {$name} is not found."); + } + } + } + + /** + * Checks throttling limit. + */ + protected function handleLimit(string $key, int $maxAttempts, float $decayMinutes): void + { + if ($this->limiter->tooManyAttempts($key, $maxAttempts)) { + throw new RateLimitException(); + } + + $this->limiter->hit($key, (int) ($decayMinutes * 60)); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/TransformArgsDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/TransformArgsDirective.php new file mode 100644 index 0000000..c2a5fa9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/TransformArgsDirective.php @@ -0,0 +1,28 @@ +transform($value); + } + + return $value; + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/TrimDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/TrimDirective.php index de586e6..962e438 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/TrimDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/TrimDirective.php @@ -2,39 +2,86 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -use Nuwave\Lighthouse\Support\Contracts\ArgTransformerDirective; +use Closure; +use GraphQL\Type\Definition\ResolveInfo; +use Nuwave\Lighthouse\Execution\Arguments\ArgumentSet; +use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Nuwave\Lighthouse\Support\Contracts\ArgDirective; +use Nuwave\Lighthouse\Support\Contracts\ArgSanitizerDirective; +use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Support\Utils; -class TrimDirective implements ArgTransformerDirective, DefinedDirective +class TrimDirective extends BaseDirective implements ArgSanitizerDirective, ArgDirective, FieldMiddleware { - /** - * Directive name. - * - * @return string - */ - public function name(): string - { - return 'trim'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Run the `trim` function on an input value. +Remove whitespace from the beginning and end of a given input. + +This can be used on: +- a single argument or input field to sanitize that subtree +- a field to trim all strings """ -directive @trim on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +directive @trim on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | FIELD_DEFINITION +GRAPHQL; } /** * Remove whitespace from the beginning and end of a given input. - * - * @param string $argumentValue - * @return string */ - public function transform($argumentValue): string + public function sanitize($argumentValue) { - return trim($argumentValue); + return Utils::applyEach( + function ($value) { + return $value instanceof ArgumentSet + ? $this->transformArgumentSet($value) + : $this->transformLeaf($value); + }, + $argumentValue + ); + } + + public function handleField(FieldValue $fieldValue, Closure $next): FieldValue + { + $resolver = $fieldValue->getResolver(); + + return $next( + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver) { + $resolveInfo->argumentSet = $this->transformArgumentSet($resolveInfo->argumentSet); + + return $resolver( + $root, + $resolveInfo->argumentSet->toArray(), + $context, + $resolveInfo + ); + } + ) + ); + } + + protected function transformArgumentSet(ArgumentSet $argumentSet): ArgumentSet + { + foreach ($argumentSet->arguments as $argument) { + $argument->value = $this->sanitize($argument->value); + } + + return $argumentSet; + } + + /** + * @param mixed $value The client given value + * @return mixed The transformed value + */ + protected function transformLeaf($value) + { + if (is_string($value)) { + return trim($value); + } + + return $value; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/UnionDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/UnionDirective.php index a382308..dc68ad4 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/UnionDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/UnionDirective.php @@ -2,23 +2,11 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; - -class UnionDirective extends BaseDirective implements DefinedDirective +class UnionDirective extends BaseDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'union'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Use a custom function to determine the concrete type of unions. """ @@ -30,6 +18,6 @@ directive @union( """ resolveType: String! ) on UNION -SDL; +GRAPHQL; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/UpdateDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/UpdateDirective.php index c95c12d..e37c57b 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/UpdateDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/UpdateDirective.php @@ -2,100 +2,37 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Illuminate\Support\Collection; -use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\DatabaseManager; -use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Execution\MutationExecutor; -use Nuwave\Lighthouse\Support\Contracts\GlobalId; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Illuminate\Database\Eloquent\Relations\Relation; +use Nuwave\Lighthouse\Execution\Arguments\SaveModel; +use Nuwave\Lighthouse\Execution\Arguments\UpdateModel; -class UpdateDirective extends BaseDirective implements FieldResolver, DefinedDirective +class UpdateDirective extends MutationExecutorDirective { - /** - * @var \Illuminate\Database\DatabaseManager - */ - protected $databaseManager; - - /** - * The GlobalId resolver. - * - * @var \Nuwave\Lighthouse\Support\Contracts\GlobalId - */ - protected $globalId; - - /** - * UpdateDirective constructor. - * - * @param \Illuminate\Database\DatabaseManager $databaseManager - * @param \Nuwave\Lighthouse\Support\Contracts\GlobalId $globalId - * @return void - */ - public function __construct(DatabaseManager $databaseManager, GlobalId $globalId) - { - $this->databaseManager = $databaseManager; - $this->globalId = $globalId; - } - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'update'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Update an Eloquent model with the input values of the field. """ directive @update( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String """ - Set to `true` to use global ids for finding the model. - If set to `false`, regular non-global ids are used. + Specify the name of the relation on the parent model. + This is only needed when using this directive as a nested arg + resolver and if the name of the relation is not the arg name. """ - globalId: Boolean = false -) on FIELD_DEFINITION -SDL; + relation: String +) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function resolveField(FieldValue $fieldValue): FieldValue + protected function makeExecutionFunction(?Relation $parentRelation = null): callable { - return $fieldValue->setResolver( - function ($root, array $args): Model { - $modelClassName = $this->getModelClass(); - /** @var \Illuminate\Database\Eloquent\Model $model */ - $model = new $modelClassName; - - if ($this->directiveArgValue('globalId', false)) { - $args['id'] = $this->globalId->decodeId($args['id']); - } - - $executeMutation = function () use ($model, $args): Model { - return MutationExecutor::executeUpdate($model, new Collection($args))->refresh(); - }; - - return config('lighthouse.transactional_mutations', true) - ? $this->databaseManager->connection($model->getConnectionName())->transaction($executeMutation) - : $executeMutation(); - } - ); + return new UpdateModel(new SaveModel($parentRelation)); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/UpsertDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/UpsertDirective.php new file mode 100644 index 0000000..cf9e373 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/UpsertDirective.php @@ -0,0 +1,46 @@ +validationFactory = $validationFactory; - } - - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - public function handleField(FieldValue $fieldValue, Closure $next): FieldValue - { - $resolver = $fieldValue->getResolver(); - - return $next( - $fieldValue->setResolver( - function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver) { - $this->setResolverArguments($root, $args, $context, $resolveInfo); - - $validator = $this->validationFactory - ->make( - $args, - $this->rules(), - $this->messages(), - // The presence of those custom attributes ensures we get a GraphQLValidator - [ - 'root' => $root, - 'context' => $context, - 'resolveInfo' => $resolveInfo, - ] - ); - - if ($validator->fails()) { - throw new ValidationException($validator); - } - - return $resolver($root, $args, $context, $resolveInfo); - } - ) - ); - } - - /** - * Return custom messages for the rules. - * - * @return array - */ - public function messages(): array - { - return []; - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereAuthDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereAuthDirective.php new file mode 100644 index 0000000..9833408 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereAuthDirective.php @@ -0,0 +1,59 @@ +authFactory = $authFactory; + } + + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Filter a type to only return instances owned by the current user. +""" +directive @whereAuth( + """ + Name of the relationship that links to the user model. + """ + relation: String! + + """ + Specify which guard to use, e.g. "api". + When not defined, the default from `lighthouse.php` is used. + """ + guard: String +) on FIELD_DEFINITION +GRAPHQL; + } + + public function handleFieldBuilder(object $builder): object + { + // @phpstan-ignore-next-line Mixins are magic + return $builder->whereHas( + $this->directiveArgValue('relation'), + function ($query): void { + $guard = $this->directiveArgValue('guard') + ?? config('lighthouse.guard'); + + $userId = $this + ->authFactory + ->guard($guard) + ->id(); + + $query->whereKey($userId); + } + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereBetweenDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereBetweenDirective.php index c7936da..8b6a832 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereBetweenDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereBetweenDirective.php @@ -2,53 +2,34 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class WhereBetweenDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class WhereBetweenDirective extends BaseDirective implements ArgBuilderDirective { - const NAME = 'whereBetween'; - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return self::NAME; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Verify that a column\'s value is between two values. +Verify that a column's value is between two values. + The type of the input value this is defined upon should be an `input` object with two fields. """ directive @whereBetween( """ - Specify the database column to compare. + Specify the database column to compare. Only required if database column has a different name than the attribute in your schema. """ key: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Apply a "WHERE BETWEEN" clause. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $values - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $values) + public function handleBuilder($builder, $value): object { return $builder->whereBetween( - $this->directiveArgValue('key', $this->definitionNode->name->value), - $values + $this->directiveArgValue('key', $this->nodeName()), + $value ); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereDirective.php index 85e70fe..90ec2ea 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereDirective.php @@ -2,24 +2,13 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class WhereDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class WhereDirective extends BaseDirective implements ArgBuilderDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'where'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Use an input value as a [where filter](https://laravel.com/docs/queries#where-clauses). """ @@ -30,34 +19,27 @@ directive @where( operator: String = "=" """ - Specify the database column to compare. + Specify the database column to compare. Only required if database column has a different name than the attribute in your schema. """ key: String """ - Use Laravel\'s where clauses upon the query builder. + Use Laravel's where clauses upon the query builder. """ clause: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Add any "WHERE" clause to the builder. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $value - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $value) + public function handleBuilder($builder, $value): object { // Allow users to overwrite the default "where" clause, e.g. "whereYear" $clause = $this->directiveArgValue('clause', 'where'); return $builder->{$clause}( - $this->directiveArgValue('key', $this->definitionNode->name->value), - $operator = $this->directiveArgValue('operator', '='), + $this->directiveArgValue('key', $this->nodeName()), + $this->directiveArgValue('operator', '='), $value ); } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereJsonContainsDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereJsonContainsDirective.php index 3e6a9e1..9dd3b05 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereJsonContainsDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereJsonContainsDirective.php @@ -2,48 +2,30 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class WhereJsonContainsDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class WhereJsonContainsDirective extends BaseDirective implements ArgBuilderDirective { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'whereJsonContains'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Use an input value as a [whereJsonContains filter](https://laravel.com/docs/queries#json-where-clauses). """ directive @whereJsonContains( """ - Specify the database column and path inside the JSON to compare. + Specify the database column and path inside the JSON to compare. Only required if database column has a different name than the attribute in your schema. """ key: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Add a "WHERE JSON_CONTAINS()" clause to the builder. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $value - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $value) + public function handleBuilder($builder, $value): object { return $builder->whereJsonContains( - $this->directiveArgValue('key', $this->definitionNode->name->value), + $this->directiveArgValue('key', $this->nodeName()), $value ); } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereNotBetweenDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereNotBetweenDirective.php index e885251..9b2e1de 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/WhereNotBetweenDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WhereNotBetweenDirective.php @@ -2,53 +2,34 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class WhereNotBetweenDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class WhereNotBetweenDirective extends BaseDirective implements ArgBuilderDirective { - const NAME = 'whereNotBetween'; - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return self::NAME; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Verify that a column\'s value lies outside of two values. +Verify that a column's value lies outside of two values. + The type of the input value this is defined upon should be an `input` object with two fields. """ directive @whereNotBetween( """ - Specify the database column to compare. + Specify the database column to compare. Only required if database column has a different name than the attribute in your schema. """ key: String -) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +) repeatable on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION +GRAPHQL; } - /** - * Apply a "WHERE NOT BETWEEN" clause. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $values - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $values) + public function handleBuilder($builder, $value): object { return $builder->whereNotBetween( - $this->directiveArgValue('key', $this->definitionNode->name->value), - $values + $this->directiveArgValue('key', $this->nodeName()), + $value ); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WithCountDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WithCountDirective.php new file mode 100644 index 0000000..c6890d5 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WithCountDirective.php @@ -0,0 +1,63 @@ +name->value)) { + throw new DefinitionException("Can not use @{$this->name()} on fields of a root type."); + } + + $relation = $this->directiveArgValue('relation'); + if (! is_string($relation)) { + throw new DefinitionException("You must specify the argument relation in the {$this->name()} directive on {$this->definitionNode->name->value}."); + } + } + + /** + * @return CountModelsLoader + */ + protected function relationLoader(ResolveInfo $resolveInfo): ModelsLoader + { + return new CountModelsLoader( + $this->relation(), + $this->makeBuilderDecorator($resolveInfo) + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WithDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WithDirective.php index d3c2dd6..755c734 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/WithDirective.php +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WithDirective.php @@ -2,32 +2,21 @@ namespace Nuwave\Lighthouse\Schema\Directives; -use Closure; -use GraphQL\Deferred; -use Illuminate\Database\Eloquent\Model; +use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; use GraphQL\Type\Definition\ResolveInfo; -use Nuwave\Lighthouse\Schema\Values\FieldValue; -use Nuwave\Lighthouse\Execution\DataLoader\BatchLoader; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -use Nuwave\Lighthouse\Execution\DataLoader\RelationBatchLoader; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Execution\ModelsLoader\ModelsLoader; +use Nuwave\Lighthouse\Execution\ModelsLoader\SimpleModelsLoader; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; +use Nuwave\Lighthouse\Schema\RootType; +use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; -class WithDirective extends RelationDirective implements FieldMiddleware, DefinedDirective +class WithDirective extends WithRelationDirective implements FieldManipulator { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'with'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Eager-load an Eloquent relation. """ @@ -42,49 +31,25 @@ directive @with( Apply scopes to the underlying query. """ scopes: [String!] -) on FIELD_DEFINITION -SDL; +) repeatable on FIELD_DEFINITION +GRAPHQL; + } + + public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType) + { + if (RootType::isRootType($parentType->name->value)) { + throw new DefinitionException("Can not use @{$this->name()} on fields of a root type."); + } } /** - * Eager load a relation on the parent instance. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue + * @return \Nuwave\Lighthouse\Execution\ModelsLoader\SimpleModelsLoader */ - public function handleField(FieldValue $fieldValue, Closure $next): FieldValue + protected function relationLoader(ResolveInfo $resolveInfo): ModelsLoader { - $resolver = $fieldValue->getResolver(); - - return $next( - $fieldValue->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); - } - ); - }); - } - ) + return new SimpleModelsLoader( + $this->relation(), + $this->makeBuilderDecorator($resolveInfo) ); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/WithRelationDirective.php b/vendor/nuwave/lighthouse/src/Schema/Directives/WithRelationDirective.php new file mode 100644 index 0000000..43f1256 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Directives/WithRelationDirective.php @@ -0,0 +1,54 @@ +getResolver(); + + $fieldValue->setResolver( + function (Model $parent, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($previousResolver) { + return $this + ->loadRelation($parent, $args, $resolveInfo) + ->then(function () use ($previousResolver, $parent, $args, $context, $resolveInfo) { + return $previousResolver($parent, $args, $context, $resolveInfo); + }); + } + ); + + return $next($fieldValue); + } + + /** + * @param array $args + */ + protected function loadRelation(Model $parent, array $args, ResolveInfo $resolveInfo): Deferred + { + /** @var \Nuwave\Lighthouse\Execution\BatchLoader\RelationBatchLoader $relationBatchLoader */ + $relationBatchLoader = BatchLoaderRegistry::instance( + $this->qualifyPath($args, $resolveInfo), + function () use ($resolveInfo): RelationBatchLoader { + return new RelationBatchLoader($this->relationLoader($resolveInfo)); + } + ); + + return $relationBatchLoader->load($parent); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/ExecutableTypeNodeConverter.php b/vendor/nuwave/lighthouse/src/Schema/ExecutableTypeNodeConverter.php new file mode 100644 index 0000000..1564efa --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/ExecutableTypeNodeConverter.php @@ -0,0 +1,37 @@ +typeRegistry = $typeRegistry; + } + + protected function nonNull($type): NonNull + { + return Type::nonNull($type); + } + + protected function listOf($type): ListOfType + { + return Type::listOf($type); + } + + protected function namedType(string $nodeName): Type + { + return Type::getStandardTypes()[$nodeName] + ?? $this->typeRegistry->get($nodeName); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Factories/ArgumentFactory.php b/vendor/nuwave/lighthouse/src/Schema/Factories/ArgumentFactory.php index 330c15f..e781563 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Factories/ArgumentFactory.php +++ b/vendor/nuwave/lighthouse/src/Schema/Factories/ArgumentFactory.php @@ -2,23 +2,22 @@ namespace Nuwave\Lighthouse\Schema\Factories; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; use GraphQL\Language\AST\InputValueDefinitionNode; -use Nuwave\Lighthouse\Schema\Conversion\DefinitionNodeConverter; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use Nuwave\Lighthouse\Schema\ExecutableTypeNodeConverter; class ArgumentFactory { /** * Convert input value definitions to a executable types. * - * @param \GraphQL\Language\AST\InputValueDefinitionNode[]|\GraphQL\Language\AST\NodeList $definitions - * @return mixed[] + * @param iterable<\GraphQL\Language\AST\InputValueDefinitionNode> $definitionNodes + * @return array> */ public function toTypeMap($definitionNodes): array { $arguments = []; - /* @var InputValueDefinitionNode $inputValueDefinitionNode */ foreach ($definitionNodes as $inputDefinition) { $arguments[$inputDefinition->name->value] = $this->convert($inputDefinition); } @@ -33,13 +32,14 @@ class ArgumentFactory * @see \GraphQL\Type\Definition\FieldArgument * @see \GraphQL\Type\Definition\InputObjectField * - * @param \GraphQL\Language\AST\InputValueDefinitionNode $definitionNode - * @return mixed[] + * @return array The configuration to construct an \GraphQL\Type\Definition\InputObjectField|\GraphQL\Type\Definition\FieldArgument */ public function convert(InputValueDefinitionNode $definitionNode): array { - $definitionNodeConverter = app(DefinitionNodeConverter::class); - $type = $definitionNodeConverter->toType($definitionNode->type); + /** @var \Nuwave\Lighthouse\Schema\ExecutableTypeNodeConverter $definitionNodeConverter */ + $definitionNodeConverter = app(ExecutableTypeNodeConverter::class); + /** @var \GraphQL\Type\Definition\Type&\GraphQL\Type\Definition\InputType $type */ + $type = $definitionNodeConverter->convert($definitionNode->type); $config = [ 'name' => $definitionNode->name->value, diff --git a/vendor/nuwave/lighthouse/src/Schema/Factories/ClientDirectiveFactory.php b/vendor/nuwave/lighthouse/src/Schema/Factories/ClientDirectiveFactory.php deleted file mode 100644 index 88aff30..0000000 --- a/vendor/nuwave/lighthouse/src/Schema/Factories/ClientDirectiveFactory.php +++ /dev/null @@ -1,70 +0,0 @@ -definitionNodeConverter = $definitionNodeConverter; - } - - /** - * Transform node to type. - * - * @param \GraphQL\Language\AST\DirectiveDefinitionNode $directive - * @return \GraphQL\Type\Definition\Directive - */ - public function handle(DirectiveDefinitionNode $directive): Directive - { - $arguments = []; - /** @var InputValueDefinitionNode $argument */ - foreach ($directive->arguments as $argument) { - $argumentType = $this->definitionNodeConverter->toType($argument->type); - - $fieldArgumentConfig = [ - 'name' => $argument->name->value, - 'description' => data_get($argument->description, 'value'), - 'type' => $argumentType, - ]; - - if ($defaultValue = $argument->defaultValue) { - $fieldArgumentConfig += [ - 'defaultValue' => ASTHelper::defaultValueForArgument($defaultValue, $argumentType), - ]; - } - - $arguments [] = new FieldArgument($fieldArgumentConfig); - } - - return new Directive([ - 'name' => $directive->name->value, - 'description' => data_get($directive->description, 'value'), - 'locations' => array_map( - function (NameNode $location): string { - return $location->value; - }, - $directive->locations - ), - 'args' => $arguments, - 'astNode' => $directive, - ]); - } -} diff --git a/vendor/nuwave/lighthouse/src/Schema/Factories/DirectiveFactory.php b/vendor/nuwave/lighthouse/src/Schema/Factories/DirectiveFactory.php index 65d8e6a..82b0dae 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Factories/DirectiveFactory.php +++ b/vendor/nuwave/lighthouse/src/Schema/Factories/DirectiveFactory.php @@ -2,215 +2,62 @@ namespace Nuwave\Lighthouse\Schema\Factories; -use Illuminate\Support\Arr; -use Illuminate\Support\Str; -use GraphQL\Language\AST\Node; -use Illuminate\Support\Collection; -use GraphQL\Language\AST\DirectiveNode; -use Nuwave\Lighthouse\Schema\DirectiveNamespacer; -use Nuwave\Lighthouse\Support\Contracts\Directive; -use Nuwave\Lighthouse\Exceptions\DirectiveException; -use Nuwave\Lighthouse\Schema\Directives\BaseDirective; +use GraphQL\Language\AST\DirectiveDefinitionNode; +use GraphQL\Type\Definition\Directive; +use GraphQL\Type\Definition\FieldArgument; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use Nuwave\Lighthouse\Schema\AST\TypeNodeConverter; class DirectiveFactory { /** - * A map from short directive names to full class names. - * - * E.g. - * [ - * 'create' => 'Nuwave\Lighthouse\Schema\Directives\CreateDirective', - * 'custom' => 'App\GraphQL\Directives\CustomDirective', - * ] - * - * @var string[] + * @var \Nuwave\Lighthouse\Schema\AST\TypeNodeConverter */ - protected $resolvedClassnames = []; + protected $typeNodeConverter; - /** - * The paths used for locating directive classes. - * - * Should be tried in the order they are contained in this array, - * going from the most significant to least significant. - * - * @var string[] - */ - protected $directiveNamespaces; - - /** - * @var DirectiveNamespacer - */ - protected $directiveNamespacer; - - /** - * DirectiveFactory constructor. - * - * @param \Nuwave\Lighthouse\Schema\DirectiveNamespacer $directiveNamespacer - * @return void - */ - public function __construct(DirectiveNamespacer $directiveNamespacer) + public function __construct(TypeNodeConverter $typeNodeConverter) { - $this->directiveNamespacer = $directiveNamespacer; + $this->typeNodeConverter = $typeNodeConverter; } /** - * Create a directive by the given directive name. - * - * @param string $directiveName - * @param \GraphQL\Language\AST\TypeSystemDefinitionNode|null $definitionNode - * @return \Nuwave\Lighthouse\Support\Contracts\Directive + * Transform node to type. */ - public function create(string $directiveName, $definitionNode = null): Directive + public function handle(DirectiveDefinitionNode $directive): Directive { - $directive = $this->resolve($directiveName) - ?? $this->createOrFail($directiveName); + $arguments = []; + foreach ($directive->arguments as $argument) { + /** @var \GraphQL\Type\Definition\Type&\GraphQL\Type\Definition\InputType $argumentType */ + $argumentType = $this->typeNodeConverter->convert($argument->type); - return $definitionNode - ? $this->hydrate($directive, $definitionNode) - : $directive; - } + $fieldArgumentConfig = [ + 'name' => $argument->name->value, + 'description' => data_get($argument->description, 'value'), + 'type' => $argumentType, + ]; - /** - * Create a directive from resolved directive classes. - * - * @param string $directiveName - * @return \Nuwave\Lighthouse\Support\Contracts\Directive|null - */ - protected function resolve(string $directiveName): ?Directive - { - if ($className = Arr::get($this->resolvedClassnames, $directiveName)) { - return app($className); - } - - return null; - } - - /** - * @param string $directiveName - * @return \Nuwave\Lighthouse\Support\Contracts\Directive - * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException - */ - protected function createOrFail(string $directiveName): Directive - { - if (! $this->directiveNamespaces) { - $this->directiveNamespaces = $this->directiveNamespacer->gather(); - } - - foreach ($this->directiveNamespaces as $baseNamespace) { - $className = $baseNamespace.'\\'.Str::studly($directiveName).'Directive'; - if (class_exists($className)) { - $directive = app($className); - - if (! $directive instanceof Directive) { - throw new DirectiveException("Class $className is not a directive."); - } - - $this->addResolved($directiveName, $className); - - return $directive; + if ($defaultValue = $argument->defaultValue) { + $fieldArgumentConfig += [ + 'defaultValue' => ASTHelper::defaultValueForArgument($defaultValue, $argumentType), + ]; } + + $arguments [] = new FieldArgument($fieldArgumentConfig); } - throw new DirectiveException("No directive found for `{$directiveName}`"); - } - - /** - * @param string $directiveName - * @param string $className - * @return $this - */ - public function addResolved(string $directiveName, string $className): self - { - // Bail to respect the priority of namespaces, the first - // resolved directive is kept - if (in_array($directiveName, $this->resolvedClassnames, true)) { - return $this; + $locations = []; + // Might be a NodeList, so we can not use array_map() + foreach ($directive->locations as $location) { + $locations[] = $location->value; } - $this->resolvedClassnames[$directiveName] = $className; - - return $this; - } - - /** - * @param string $directiveName - * @param string $className - * @return $this - */ - public function setResolved(string $directiveName, string $className): self - { - $this->resolvedClassnames[$directiveName] = $className; - - return $this; - } - - /** - * @return $this - */ - public function clearResolved(): self - { - $this->resolvedClassnames = []; - - return $this; - } - - /** - * Set the given definition on the directive. - * - * @param \Nuwave\Lighthouse\Support\Contracts\Directive $directive - * @param \GraphQL\Language\AST\Node $node - * @return \Nuwave\Lighthouse\Support\Contracts\Directive - */ - protected function hydrate(Directive $directive, Node $node): Directive - { - return $directive instanceof BaseDirective - ? $directive->hydrate($node) - : $directive; - } - - /** - * Get all directives of a certain type that are associated with an AST node. - * - * @param \GraphQL\Language\AST\Node $node - * @param string $directiveClass - * @return \Illuminate\Support\Collection <$directiveClass> - */ - public function createAssociatedDirectivesOfType(Node $node, string $directiveClass): Collection - { - return (new Collection($node->directives)) - ->map(function (DirectiveNode $directive) use ($node): Directive { - return $this->create($directive->name->value, $node); - }) - ->filter(function (Directive $directive) use ($directiveClass): bool { - return $directive instanceof $directiveClass; - }); - } - - /** - * Get a single directive of a type that belongs to an AST node. - * - * Use this for directives types that can only occur once, such as field resolvers. - * This throws if more than one such directive is found. - * - * @param \GraphQL\Language\AST\Node $node - * @param string $directiveClass - * @return \Nuwave\Lighthouse\Support\Contracts\Directive|null - * - * @throws \Nuwave\Lighthouse\Exceptions\DirectiveException - */ - public 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(); + return new Directive([ + 'name' => $directive->name->value, + 'description' => data_get($directive->description, 'value'), + 'locations' => $locations, + 'args' => $arguments, + 'isRepeatable' => $directive->repeatable, + 'astNode' => $directive, + ]); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Factories/FieldFactory.php b/vendor/nuwave/lighthouse/src/Schema/Factories/FieldFactory.php index 3f8cc2f..1211216 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Factories/FieldFactory.php +++ b/vendor/nuwave/lighthouse/src/Schema/Factories/FieldFactory.php @@ -2,41 +2,22 @@ namespace Nuwave\Lighthouse\Schema\Factories; -use Illuminate\Support\Arr; -use Illuminate\Support\Collection; -use GraphQL\Type\Definition\NonNull; -use GraphQL\Type\Definition\InputType; -use GraphQL\Type\Definition\ListOfType; -use Nuwave\Lighthouse\Support\Pipeline; -use Nuwave\Lighthouse\Execution\Builder; -use GraphQL\Type\Definition\InputObjectType; -use Nuwave\Lighthouse\Execution\ErrorBuffer; +use GraphQL\Type\Definition\ResolveInfo; +use Illuminate\Pipeline\Pipeline; +use Nuwave\Lighthouse\Execution\Arguments\ArgumentSetFactory; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use Nuwave\Lighthouse\Schema\DirectiveLocator; use Nuwave\Lighthouse\Schema\Values\FieldValue; -use GraphQL\Language\AST\InputValueDefinitionNode; -use Nuwave\Lighthouse\Support\Contracts\Directive; -use Nuwave\Lighthouse\Support\Contracts\ArgDirective; -use Nuwave\Lighthouse\Support\Contracts\FieldResolver; -use Nuwave\Lighthouse\Support\Contracts\ProvidesRules; -use Nuwave\Lighthouse\Support\Contracts\HasErrorBuffer; -use Nuwave\Lighthouse\Schema\Directives\SpreadDirective; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\HasArgumentPath; -use Nuwave\Lighthouse\Support\Contracts\ProvidesResolver; -use Nuwave\Lighthouse\Support\Traits\HasResolverArguments; -use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -use Nuwave\Lighthouse\Support\Contracts\ArgDirectiveForArray; -use Nuwave\Lighthouse\Support\Contracts\ArgTransformerDirective; -use Illuminate\Contracts\Validation\Factory as ValidationFactory; -use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver; +use Nuwave\Lighthouse\Support\Contracts\FieldResolver; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; class FieldFactory { - use HasResolverArguments; - /** - * @var \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory + * @var \Nuwave\Lighthouse\Schema\DirectiveLocator */ - protected $directiveFactory; + protected $directiveLocator; /** * @var \Nuwave\Lighthouse\Schema\Factories\ArgumentFactory @@ -44,185 +25,71 @@ class FieldFactory protected $argumentFactory; /** - * @var \Nuwave\Lighthouse\Support\Contracts\ProvidesResolver - */ - protected $providesResolver; - - /** - * @var \Nuwave\Lighthouse\Support\Pipeline + * @var \Illuminate\Pipeline\Pipeline */ protected $pipeline; /** - * @var \Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver + * @var \Nuwave\Lighthouse\Execution\Arguments\ArgumentSetFactory */ - protected $providesSubscriptionResolver; + protected $argumentSetFactory; - /** - * @var \Illuminate\Contracts\Validation\Factory - */ - protected $validationFactory; - - /** - * @var \Nuwave\Lighthouse\Schema\Values\FieldValue - */ - protected $fieldValue; - - /** - * @var \Nuwave\Lighthouse\Execution\Builder - */ - protected $builder; - - /** - * @var array - */ - protected $rules = []; - - /** - * @var array - */ - protected $messages = []; - - /** - * @var \Nuwave\Lighthouse\Execution\ErrorBuffer - */ - protected $validationErrorBuffer; - - /** - * A snapshot of the arguments that are passed to "handleArgDirectives". - * - * This is used to pause and resume the evaluation of arg directives - * before and after validation. - * - * @var mixed[] - */ - protected $handleArgDirectivesSnapshots = []; - - /** - * Arg paths to spread out. - * - * @var array[] - */ - protected $pathsToSpread = []; - - /** - * @param \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory $directiveFactory - * @param \Nuwave\Lighthouse\Schema\Factories\ArgumentFactory $argumentFactory - * @param \Nuwave\Lighthouse\Support\Pipeline $pipeline - * @param \Nuwave\Lighthouse\Support\Contracts\ProvidesResolver $providesResolver - * @param \Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver $providesSubscriptionResolver - * @param \Illuminate\Contracts\Validation\Factory $validationFactory - * @return void - */ public function __construct( - DirectiveFactory $directiveFactory, + DirectiveLocator $directiveLocator, ArgumentFactory $argumentFactory, Pipeline $pipeline, - ProvidesResolver $providesResolver, - ProvidesSubscriptionResolver $providesSubscriptionResolver, - ValidationFactory $validationFactory + ArgumentSetFactory $argumentSetFactory ) { - $this->directiveFactory = $directiveFactory; + $this->directiveLocator = $directiveLocator; $this->argumentFactory = $argumentFactory; $this->pipeline = $pipeline; - $this->providesResolver = $providesResolver; - $this->providesSubscriptionResolver = $providesSubscriptionResolver; - $this->validationFactory = $validationFactory; + $this->argumentSetFactory = $argumentSetFactory; } /** * Convert a FieldValue to an executable FieldDefinition. * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return array Configuration array for a FieldDefinition + * @return array Configuration array for a \GraphQL\Type\Definition\FieldDefinition */ public function handle(FieldValue $fieldValue): array { $fieldDefinitionNode = $fieldValue->getField(); // Directives have the first priority for defining a resolver for a field - if ($resolverDirective = $this->directiveFactory->createSingleDirectiveOfType($fieldDefinitionNode, FieldResolver::class)) { - $this->fieldValue = $resolverDirective->resolveField($fieldValue); + $resolverDirective = $this->directiveLocator->exclusiveOfType($fieldDefinitionNode, FieldResolver::class); + if ($resolverDirective instanceof FieldResolver) { + $fieldValue = $resolverDirective->resolveField($fieldValue); } else { - $this->fieldValue = $fieldValue->setResolver( - $fieldValue->getParentName() === 'Subscription' - ? $this->providesSubscriptionResolver->provideSubscriptionResolver($fieldValue) - : $this->providesResolver->provideResolver($fieldValue) - ); + $fieldValue = $fieldValue->useDefaultResolver(); } - $fieldMiddleware = $this->passResolverArguments( - $this->directiveFactory->createAssociatedDirectivesOfType($fieldDefinitionNode, FieldMiddleware::class) + // Middleware resolve in reversed order + + $globalFieldMiddleware = array_reverse( + config('lighthouse.field_middleware') ); - $this->validationErrorBuffer = (new ErrorBuffer)->setErrorType('validation'); + + $fieldMiddleware = $this->directiveLocator + ->associatedOfType($fieldDefinitionNode, FieldMiddleware::class) + ->reverse() + ->all(); $resolverWithMiddleware = $this->pipeline - ->send($this->fieldValue) - ->through( - $fieldMiddleware - ) + ->send($fieldValue) + ->through(array_merge($fieldMiddleware, $globalFieldMiddleware)) ->via('handleField') - ->then( - function (FieldValue $fieldValue): FieldValue { - return $fieldValue; - } - ) + // TODO replace when we cut support for Laravel 5.6 + //->thenReturn() + ->then(static function (FieldValue $fieldValue): FieldValue { + return $fieldValue; + }) ->getResolver(); - $argumentMap = $this->argumentFactory->toTypeMap( - $this->fieldValue->getField()->arguments - ); + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolverWithMiddleware) { + $resolveInfo->argumentSet = $this->argumentSetFactory->fromResolveInfo($args, $resolveInfo); - $this->fieldValue->setResolver( - function () use ($argumentMap, $resolverWithMiddleware) { - $this->setResolverArguments(...func_get_args()); - - $this->builder = new Builder; - - foreach ($argumentMap as $name => $argumentValue) { - $this->handleArgDirectivesRecursively( - $argumentValue['type'], - $argumentValue['astNode'], - [$name] - ); - } - - // Recurse down the given args and apply ArgDirectives - $this->runArgDirectives(); - - // Now that we are finished with all argument based validation, - // we flush the validation error buffer - $this->flushValidationErrorBuffer(); - - // Apply the argument spreadings after we are finished with all - // the other argument handling - foreach ($this->pathsToSpread as $argumentPath) { - $inputValues = $this->argValue($argumentPath); - - // If no input is given, there is nothing to spread - if (! $inputValues) { - continue; - } - - // We remove the value from where it was defined before - $this->unsetArgValue($argumentPath); - - // The last part of the path is the name of the input value, - // the exact thing we want to remove - array_pop($argumentPath); - - foreach ($inputValues as $key => $value) { - $this->setArgValue( - array_merge($argumentPath, [$key]), - $value - ); - } - } - - // The final resolver can access the builder through the ResolveInfo - $this->resolveInfo->builder = $this->builder; - - return $resolverWithMiddleware($this->root, $this->args, $this->context, $this->resolveInfo); + return $resolverWithMiddleware($root, $args, $context, $resolveInfo); } ); @@ -230,269 +97,15 @@ class FieldFactory // GraphQL\Type\Definition\FieldDefinition::getDefinition() return [ 'name' => $fieldDefinitionNode->name->value, - 'type' => $this->fieldValue->getReturnType(), - 'args' => $argumentMap, - 'resolve' => $this->fieldValue->getResolver(), + 'type' => $fieldValue->getReturnType(), + 'args' => $this->argumentFactory->toTypeMap( + $fieldValue->getField()->arguments + ), + 'resolve' => $fieldValue->getResolver(), 'description' => data_get($fieldDefinitionNode->description, 'value'), - 'complexity' => $this->fieldValue->getComplexity(), - 'deprecationReason' => $this->fieldValue->getDeprecationReason(), + 'complexity' => $fieldValue->getComplexity(), + 'deprecationReason' => ASTHelper::deprecationReason($fieldDefinitionNode), + 'astNode' => $fieldDefinitionNode, ]; } - - /** - * Handle the ArgMiddleware. - * - * @param \GraphQL\Type\Definition\InputType $type - * @param \GraphQL\Language\AST\InputValueDefinitionNode $astNode - * @param mixed[] $argumentPath - * @return void - */ - protected function handleArgDirectivesRecursively( - InputType $type, - InputValueDefinitionNode $astNode, - array $argumentPath - ): void { - if ($type instanceof NonNull) { - $this->handleArgDirectivesRecursively( - $type->getWrappedType(), - $astNode, - $argumentPath - ); - - return; - } - - $directives = $this->passResolverArguments( - $this->directiveFactory->createAssociatedDirectivesOfType($astNode, ArgDirective::class) - ); - - if ( - $directives->contains(function (Directive $directive): bool { - return $directive instanceof SpreadDirective; - }) - && $type instanceof InputObjectType - ) { - $this->pathsToSpread [] = $argumentPath; - } - - // Handle the argument itself. At this point, it can be wrapped - // in a list or an input object - $this->handleArgWithAssociatedDirectives($type, $astNode, $directives, $argumentPath); - - // If we no value or null is given, we bail here to prevent - // infinitely going down a chain of nested input objects - if (! $this->argValueExists($argumentPath) || $this->argValue($argumentPath) === null) { - return; - } - - if ($type instanceof InputObjectType) { - foreach ($type->getFields() as $field) { - $this->handleArgDirectivesRecursively( - $field->type, - $field->astNode, - array_merge($argumentPath, [$field->name]) - ); - } - } - - if ($type instanceof ListOfType) { - foreach ($this->argValue($argumentPath) as $index => $value) { - // here we are passing by reference so the `$argValue[$key]` is intended. - $this->handleArgDirectivesRecursively( - $type->ofType, - $astNode, - array_merge($argumentPath, [$index]) - ); - } - } - } - - /** - * @param \GraphQL\Type\Definition\InputType $type - * @param \GraphQL\Language\AST\InputValueDefinitionNode $astNode - * @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> $directives - * @param mixed[] $argumentPath - * @return void - */ - protected function handleArgWithAssociatedDirectives( - InputType $type, - InputValueDefinitionNode $astNode, - Collection $directives, - array $argumentPath - ): void { - $isArgDirectiveForArray = function (ArgDirective $directive): bool { - return $directive instanceof ArgDirectiveForArray; - }; - - $this->handleArgDirectives( - $astNode, - $argumentPath, - $type instanceof ListOfType - ? $directives->filter($isArgDirectiveForArray) - : $directives->reject($isArgDirectiveForArray) - ); - } - - /** - * @param \GraphQL\Language\AST\InputValueDefinitionNode $astNode - * @param mixed[] $argumentPath - * @param \Illuminate\Support\Collection $directives - * @return void - */ - protected function handleArgDirectives( - InputValueDefinitionNode $astNode, - array $argumentPath, - Collection $directives - ): void { - if ($directives->isEmpty()) { - return; - } - - $directives->each(function (Directive $directive) use ($argumentPath): void { - if ($directive instanceof HasErrorBuffer) { - $directive->setErrorBuffer($this->validationErrorBuffer); - } - - if ($directive instanceof HasArgumentPath) { - $directive->setArgumentPath($argumentPath); - } - }); - - // Remove the directive from the list to avoid evaluating the same directive twice - while ($directive = $directives->shift()) { - // Pause the iteration once we hit any directive that has to do - // with validation. We will resume running through the remaining - // directives later, after we completed validation - if ($directive instanceof ProvidesRules) { - // We gather the rules from all arguments and then run validation in one full swoop - $this->rules = array_merge($this->rules, $directive->rules()); - $this->messages = array_merge($this->messages, $directive->messages()); - - break; - } - - if ($directive instanceof ArgTransformerDirective && $this->argValueExists($argumentPath)) { - $this->setArgValue( - $argumentPath, - $directive->transform($this->argValue($argumentPath)) - ); - } - - if ($directive instanceof ArgBuilderDirective) { - $this->builder->addBuilderDirective( - $astNode->name->value, - $directive - ); - } - } - - // If directives remain, snapshot the state that we are in now - // to allow resuming after validation has run - if ($directives->isNotEmpty()) { - $this->handleArgDirectivesSnapshots[] = [$astNode, $argumentPath, $directives]; - } - } - - protected function argValueExists(array $argumentPath): bool - { - return Arr::has($this->args, implode('.', $argumentPath)); - } - - protected function setArgValue(array $argumentPath, $value): array - { - return Arr::set($this->args, implode('.', $argumentPath), $value); - } - - protected function unsetArgValue(array $argumentPath): void - { - Arr::forget($this->args, implode('.', $argumentPath)); - } - - protected function argValue(array $argumentPath) - { - return Arr::get($this->args, implode('.', $argumentPath)); - } - - protected function runArgDirectives(): void - { - $this->validateArgs(); - $this->resumeHandlingArgDirectives(); - } - - /** - * Run the gathered validation rules on the arguments. - * - * @return void - */ - protected function validateArgs(): void - { - if (! $this->rules) { - return; - } - - /** @var \Nuwave\Lighthouse\Execution\GraphQLValidator $validator */ - $validator = $this->validationFactory->make( - $this->args, - $this->rules, - $this->messages, - // The presence of those custom attributes ensures we get a GraphQLValidator - [ - 'root' => $this->root, - 'context' => $this->context, - 'resolveInfo' => $this->resolveInfo, - ] - ); - - if ($validator->fails()) { - $this->addValidationErrorsToBuffer( - $validator->errors()->getMessages() - ); - } - - // reset rules and messages - $this->rules = []; - $this->messages = []; - } - - /** - * Continue evaluating the arg directives after validation has run. - * - * @return void - */ - protected function resumeHandlingArgDirectives(): void - { - // copy and reset - $snapshots = $this->handleArgDirectivesSnapshots; - $this->handleArgDirectivesSnapshots = []; - - foreach ($snapshots as $handlerArgs) { - $this->handleArgDirectives(...$handlerArgs); - } - - // We might have hit more validation-relevant directives so we recurse - if (count($this->handleArgDirectivesSnapshots) > 0) { - $this->runArgDirectives(); - } - } - - protected function addValidationErrorsToBuffer(array $validationErrors): void - { - foreach ($validationErrors as $key => $errorMessages) { - foreach ($errorMessages as $errorMessage) { - $this->validationErrorBuffer->push($errorMessage, $key); - } - } - } - - protected function flushValidationErrorBuffer(): void - { - $path = implode( - '.', - $this->resolveInfo()->path - ); - - $this->validationErrorBuffer->flush( - "Validation failed for the field [$path]." - ); - } } diff --git a/vendor/nuwave/lighthouse/src/Schema/FallbackTypeNodeConverter.php b/vendor/nuwave/lighthouse/src/Schema/FallbackTypeNodeConverter.php new file mode 100644 index 0000000..cebcc30 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/FallbackTypeNodeConverter.php @@ -0,0 +1,50 @@ +typeRegistry = $typeRegistry; + } + + protected function nonNull($type): NonNull + { + return Type::nonNull($type); + } + + protected function listOf($type): ListOfType + { + return Type::listOf($type); + } + + protected function namedType(string $nodeName): Type + { + if (isset(Type::getStandardTypes()[$nodeName])) { + return Type::getStandardTypes()[$nodeName]; + } + + if (! $this->typeRegistry->has($nodeName)) { + $dummyType = new CustomScalarType([ + 'name' => $nodeName, + 'serialize' => function () { + }, + ]); + $this->typeRegistry->register($dummyType); + } + + return $this->typeRegistry->get($nodeName); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/ResolverProvider.php b/vendor/nuwave/lighthouse/src/Schema/ResolverProvider.php index 3e24a85..b5764c6 100644 --- a/vendor/nuwave/lighthouse/src/Schema/ResolverProvider.php +++ b/vendor/nuwave/lighthouse/src/Schema/ResolverProvider.php @@ -3,46 +3,32 @@ namespace Nuwave\Lighthouse\Schema; use Closure; -use Illuminate\Support\Str; use GraphQL\Executor\Executor; -use Nuwave\Lighthouse\Support\Utils; -use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Illuminate\Support\Str; use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\ProvidesResolver; +use Nuwave\Lighthouse\Support\Utils; class ResolverProvider implements ProvidesResolver { /** * Provide a field resolver in case no resolver directive is defined for a field. * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Closure - * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ public function provideResolver(FieldValue $fieldValue): Closure { if ($fieldValue->parentIsRootType()) { - // TODO use only __invoke in v5 - $resolverClass = $this->findResolverClass($fieldValue, 'resolve'); - if ($resolverClass) { - return Closure::fromCallable( - [app($resolverClass), 'resolve'] - ); - } - $resolverClass = $this->findResolverClass($fieldValue, '__invoke'); - if ($resolverClass) { - return Closure::fromCallable( - [app($resolverClass), '__invoke'] - ); + if ($resolverClass === null) { + $this->throwMissingResolver($fieldValue); } - if (! $resolverClass) { - throw new DefinitionException( - "Could not locate a default resolver for the field {$fieldValue->getFieldName()}" - ); - } + return Closure::fromCallable( + // @phpstan-ignore-next-line this works + [app($resolverClass), '__invoke'] + ); } return Closure::fromCallable( @@ -51,9 +37,7 @@ class ResolverProvider implements ProvidesResolver } /** - * @param FieldValue $fieldValue - * @param string $methodName - * @return string|null + * @return class-string|null */ protected function findResolverClass(FieldValue $fieldValue, string $methodName): ?string { @@ -65,4 +49,27 @@ class ResolverProvider implements ProvidesResolver } ); } + + /** + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + protected function throwMissingResolver(FieldValue $fieldValue): void + { + // Since we already know we are on the root type, this is either + // query, mutation or subscription + $parent = lcfirst($fieldValue->getParentName()); + $fieldName = $fieldValue->getFieldName(); + $proposedResolverClass = ucfirst($fieldName); + + throw new DefinitionException(<<typeRegistry = $typeRegistry; - $this->clientDirectiveFactory = $clientDirectiveFactory; + $this->astBuilder = $astBuilder; + } + + public function schema(): Schema + { + if (! isset($this->schema)) { + $this->schema = $this->build( + $this->astBuilder->documentAST() + ); + } + + return $this->schema; } /** - * Build an executable schema from AST. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @return \GraphQL\Type\Schema + * Build an executable schema from an AST. */ - public function build(DocumentAST $documentAST): Schema + protected function build(DocumentAST $documentAST): Schema { $config = SchemaConfig::create(); $this->typeRegistry->setDocumentAST($documentAST); // Always set Query since it is required - $config->setQuery( - $this->typeRegistry->get('Query') - ); + /** @var \GraphQL\Type\Definition\ObjectType $query */ + $query = $this->typeRegistry->get(RootType::QUERY); + $config->setQuery($query); - // Those are optional so only add them if they are present in the schema - if (isset($documentAST->types['Mutation'])) { - $config->setMutation( - $this->typeRegistry->get('Mutation') - ); + // Mutation and Subscription are optional, so only add them + // if they are present in the schema + if (isset($documentAST->types[RootType::MUTATION])) { + /** @var \GraphQL\Type\Definition\ObjectType $mutation */ + $mutation = $this->typeRegistry->get(RootType::MUTATION); + $config->setMutation($mutation); } - if (isset($documentAST->types['Subscription'])) { - /** @var \GraphQL\Type\Definition\ObjectType $subscription */ - $subscription = $this->typeRegistry->get('Subscription'); - // Eager-load the subscription fields to ensure they are registered - $subscription->getFields(); - $config->setSubscription( - $subscription - ); + if (isset($documentAST->types[RootType::SUBSCRIPTION])) { + /** @var \GraphQL\Type\Definition\ObjectType $subscription */ + $subscription = $this->typeRegistry->get(RootType::SUBSCRIPTION); + $config->setSubscription($subscription); } // Use lazy type loading to prevent unnecessary work $config->setTypeLoader( - [$this->typeRegistry, 'get'] + function (string $name): Type { + return $this->typeRegistry->get($name); + } ); // This is just used for introspection, it is required // to be able to retrieve all the types in the schema $config->setTypes( - [$this->typeRegistry, 'possibleTypes'] + /** + * @return array + */ + function (): array { + return $this->typeRegistry->possibleTypes(); + } ); - // There is no way to resolve client directives lazily, - // so we convert them eagerly - $clientDirectives = []; + // There is no way to resolve directives lazily, so we convert them eagerly + $directiveFactory = new DirectiveFactory( + new ExecutableTypeNodeConverter($this->typeRegistry) + ); + + $directives = []; foreach ($documentAST->directives as $directiveDefinition) { - $clientDirectives [] = $this->clientDirectiveFactory->handle($directiveDefinition); + $directives [] = $directiveFactory->handle($directiveDefinition); } + $config->setDirectives( - array_merge(GraphQL::getStandardDirectives(), $clientDirectives) + array_merge(GraphQL::getStandardDirectives(), $directives) ); return new Schema($config); diff --git a/vendor/nuwave/lighthouse/src/Schema/Source/SchemaSourceProvider.php b/vendor/nuwave/lighthouse/src/Schema/Source/SchemaSourceProvider.php index 662ca76..1adc99d 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Source/SchemaSourceProvider.php +++ b/vendor/nuwave/lighthouse/src/Schema/Source/SchemaSourceProvider.php @@ -2,23 +2,10 @@ namespace Nuwave\Lighthouse\Schema\Source; -/** - * Interface SchemaSourceProvider. - */ interface SchemaSourceProvider { - /** - * Set schema root path. - * - * @param string $path - * @return \Nuwave\Lighthouse\Schema\Source\SchemaSourceProvider - */ - public function setRootPath(string $path); - /** * Provide the schema definition. - * - * @return string */ public function getSchemaString(): string; } diff --git a/vendor/nuwave/lighthouse/src/Schema/Source/SchemaStitcher.php b/vendor/nuwave/lighthouse/src/Schema/Source/SchemaStitcher.php index d283c08..4f05ad9 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Source/SchemaStitcher.php +++ b/vendor/nuwave/lighthouse/src/Schema/Source/SchemaStitcher.php @@ -2,9 +2,10 @@ namespace Nuwave\Lighthouse\Schema\Source; -use Illuminate\Support\Str; -use Illuminate\Support\Collection; use Illuminate\Contracts\Filesystem\FileNotFoundException; +use Illuminate\Support\Collection; +use Illuminate\Support\Str; +use Safe\Exceptions\FilesystemException; class SchemaStitcher implements SchemaSourceProvider { @@ -13,34 +14,19 @@ class SchemaStitcher implements SchemaSourceProvider */ protected $rootSchemaPath; - /** - * SchemaStitcher constructor. - * - * @param string $rootSchemaPath - * @return void - */ public function __construct(string $rootSchemaPath) { + if (! file_exists($rootSchemaPath)) { + throw new FileNotFoundException( + "Failed to find a GraphQL schema file at {$rootSchemaPath}. If you just installed Lighthouse, run php artisan vendor:publish --tag=lighthouse-schema" + ); + } + $this->rootSchemaPath = $rootSchemaPath; } - /** - * Set schema root path. - * - * @param string $path - * @return $this - */ - public function setRootPath(string $path): self - { - $this->rootSchemaPath = $path; - - return $this; - } - /** * Stitch together schema documents and return the result as a string. - * - * @return string */ public function getSchemaString(): string { @@ -49,17 +35,10 @@ class SchemaStitcher implements SchemaSourceProvider /** * Get the schema, starting from a root schema, following the imports recursively. - * - * @param string $path - * @return string */ protected static function gatherSchemaImportsRecursively(string $path): string { - if (! file_exists($path)) { - self::throwFileNotFoundException($path); - } - - return (new Collection(file($path))) + return (new Collection(\Safe\file($path))) ->map(function (string $line) use ($path): string { if (! Str::startsWith(trim($line), '#import ')) { return rtrim($line, PHP_EOL).PHP_EOL; @@ -69,18 +48,20 @@ class SchemaStitcher implements SchemaSourceProvider $importFilePath = dirname($path).'/'.$importFileName; if (! Str::contains($importFileName, '*')) { - $realPath = realpath($importFilePath); - - if (! $realPath) { - self::throwFileNotFoundException($importFilePath); + try { + $realpath = \Safe\realpath($importFilePath); + } catch (FilesystemException $exception) { + throw new FileNotFoundException( + "Did not find GraphQL schema import at {$importFilePath}.", + $exception->getCode(), + $exception + ); } - return self::gatherSchemaImportsRecursively($realPath); + return self::gatherSchemaImportsRecursively($realpath); } - $importFilePaths = glob($importFilePath); - - return (new Collection($importFilePaths)) + return (new Collection(\Safe\glob($importFilePath))) ->map(function ($file): string { return self::gatherSchemaImportsRecursively($file); }) @@ -88,17 +69,4 @@ class SchemaStitcher implements SchemaSourceProvider }) ->implode(''); } - - /** - * @param string $path - * @return void - * - * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException - */ - protected static function throwFileNotFoundException(string $path): void - { - throw new FileNotFoundException( - "Failed to find a GraphQL schema file at {$path}. If you just installed Lighthouse, run php artisan vendor:publish --provider=\"Nuwave\Lighthouse\Providers\LighthouseServiceProvider\" --tag=schema" - ); - } } diff --git a/vendor/nuwave/lighthouse/src/Schema/TypeRegistry.php b/vendor/nuwave/lighthouse/src/Schema/TypeRegistry.php index 1ba26c6..791ddf8 100644 --- a/vendor/nuwave/lighthouse/src/Schema/TypeRegistry.php +++ b/vendor/nuwave/lighthouse/src/Schema/TypeRegistry.php @@ -3,51 +3,47 @@ namespace Nuwave\Lighthouse\Schema; use Closure; -use GraphQL\Type\Definition\Type; -use Illuminate\Support\Collection; -use Nuwave\Lighthouse\Support\Utils; use GraphQL\Error\InvariantViolation; -use GraphQL\Type\Definition\EnumType; -use GraphQL\Type\Definition\UnionType; -use GraphQL\Language\AST\NamedTypeNode; -use GraphQL\Type\Definition\ObjectType; -use GraphQL\Type\Definition\ScalarType; -use Nuwave\Lighthouse\Support\Pipeline; -use GraphQL\Type\Definition\InterfaceType; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; -use GraphQL\Language\AST\TypeDefinitionNode; -use GraphQL\Type\Definition\InputObjectType; -use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; -use Nuwave\Lighthouse\Schema\Values\TypeValue; -use Nuwave\Lighthouse\Schema\Values\FieldValue; use GraphQL\Language\AST\EnumTypeDefinitionNode; -use GraphQL\Language\AST\EnumValueDefinitionNode; -use GraphQL\Language\AST\UnionTypeDefinitionNode; +use GraphQL\Language\AST\InputObjectTypeDefinitionNode; +use GraphQL\Language\AST\InterfaceTypeDefinitionNode; use GraphQL\Language\AST\ObjectTypeDefinitionNode; use GraphQL\Language\AST\ScalarTypeDefinitionNode; -use Nuwave\Lighthouse\Schema\Factories\FieldFactory; -use GraphQL\Language\AST\InterfaceTypeDefinitionNode; +use GraphQL\Language\AST\TypeDefinitionNode; +use GraphQL\Language\AST\UnionTypeDefinitionNode; +use GraphQL\Type\Definition\EnumType; +use GraphQL\Type\Definition\InputObjectType; +use GraphQL\Type\Definition\InterfaceType; +use GraphQL\Type\Definition\ObjectType; +use GraphQL\Type\Definition\ScalarType; +use GraphQL\Type\Definition\Type; +use GraphQL\Type\Definition\UnionType; +use Illuminate\Pipeline\Pipeline; use Nuwave\Lighthouse\Exceptions\DefinitionException; -use Nuwave\Lighthouse\Support\Contracts\TypeResolver; -use GraphQL\Language\AST\InputObjectTypeDefinitionNode; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; +use Nuwave\Lighthouse\Schema\Directives\EnumDirective; +use Nuwave\Lighthouse\Schema\Directives\InterfaceDirective; use Nuwave\Lighthouse\Schema\Directives\UnionDirective; use Nuwave\Lighthouse\Schema\Factories\ArgumentFactory; +use Nuwave\Lighthouse\Schema\Factories\FieldFactory; +use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Nuwave\Lighthouse\Schema\Values\TypeValue; use Nuwave\Lighthouse\Support\Contracts\TypeMiddleware; -use Nuwave\Lighthouse\Schema\Factories\DirectiveFactory; -use Nuwave\Lighthouse\Schema\Directives\InterfaceDirective; +use Nuwave\Lighthouse\Support\Contracts\TypeResolver; +use Nuwave\Lighthouse\Support\Utils; class TypeRegistry { /** - * @var \Nuwave\Lighthouse\Support\Pipeline + * @var \Illuminate\Pipeline\Pipeline */ protected $pipeline; /** - * @var \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory + * @var \Nuwave\Lighthouse\Schema\DirectiveLocator */ - protected $directiveFactory; + protected $directiveLocator; /** * @var \Nuwave\Lighthouse\Schema\Factories\ArgumentFactory @@ -55,33 +51,37 @@ class TypeRegistry protected $argumentFactory; /** - * @var \GraphQL\Type\Definition\Type[] + * Lazily initialized. + * + * @var \Nuwave\Lighthouse\Schema\Factories\FieldFactory */ - protected $types; + protected $fieldFactory; /** + * Lazily initialized. + * * @var \Nuwave\Lighthouse\Schema\AST\DocumentAST */ protected $documentAST; /** - * @param \Nuwave\Lighthouse\Support\Pipeline $pipeline - * @param \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory $directiveFactory - * @param \Nuwave\Lighthouse\Schema\Factories\ArgumentFactory $argumentFactory - * @return void + * Map from type names to resolved types. + * + * @var array */ + protected $types = []; + public function __construct( Pipeline $pipeline, - DirectiveFactory $directiveFactory, + DirectiveLocator $directiveLocator, ArgumentFactory $argumentFactory ) { $this->pipeline = $pipeline; - $this->directiveFactory = $directiveFactory; + $this->directiveLocator = $directiveLocator; $this->argumentFactory = $argumentFactory; } /** - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST * @return $this */ public function setDocumentAST(DocumentAST $documentAST): self @@ -94,42 +94,84 @@ class TypeRegistry /** * Get the given GraphQL type by name. * - * @param string $name - * @return \GraphQL\Type\Definition\Type + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ public function get(string $name): Type { - if (! isset($this->types[$name])) { - $this->types[$name] = $this->handle( - $this->documentAST->types[$name] + if (! $this->has($name)) { + throw new DefinitionException(<<types[$name]; } + /** + * Is a type with the given name present? + */ + public function has(string $name): bool + { + return isset($this->types[$name]) + || $this->fromAST($name) instanceof Type; + } + /** * Register an executable GraphQL type. * - * @param \GraphQL\Type\Definition\Type $type * @return $this */ public function register(Type $type): self + { + $name = $type->name; + if ($this->has($name)) { + throw new DefinitionException("Tried to register a type that is already present in the schema: {$name}. Use overwrite() to ignore existing types."); + } + + $this->types[$name] = $type; + + return $this; + } + + /** + * Register a type, overwriting if it exists already. + * + * @return $this + */ + public function overwrite(Type $type): self { $this->types[$type->name] = $type; return $this; } + /** + * Attempt to make a type of the given name from the AST. + */ + protected function fromAST(string $name): ?Type + { + $typeDefinition = $this->documentAST->types[$name] ?? null; + if ($typeDefinition === null) { + return null; + } + + return $this->types[$name] = $this->handle($typeDefinition); + } + /** * Return all possible types that are registered. * - * @return \GraphQL\Type\Definition\Type[] + * @return array */ public function possibleTypes(): array { // Make sure all the types from the AST are eagerly converted - /** @var TypeDefinitionNode $typeDefinition */ + // to find orphaned types, such as an object type that is only + // ever used through its association to an interface foreach ($this->documentAST->types as $typeDefinition) { $name = $typeDefinition->name->value; @@ -141,27 +183,40 @@ class TypeRegistry return $this->types; } + /** + * Get the types that are currently resolved. + * + * Note that this does not all possible types, only those that + * are programmatically registered or already resolved. + * + * @return array + */ + public function resolvedTypes(): array + { + return $this->types; + } + /** * Transform a definition node to an executable type. * - * @param \GraphQL\Language\AST\TypeDefinitionNode $definition - * @return \GraphQL\Type\Definition\Type + * @param \GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node $definition */ public function handle(TypeDefinitionNode $definition): Type { - $typeValue = new TypeValue($definition); - return $this->pipeline - ->send($typeValue) + ->send( + new TypeValue($definition) + ) ->through( - $this->directiveFactory->createAssociatedDirectivesOfType($definition, TypeMiddleware::class) + $this->directiveLocator + ->associatedOfType($definition, TypeMiddleware::class) + ->all() ) ->via('handleNode') ->then(function (TypeValue $value) use ($definition): Type { - /** @var \Nuwave\Lighthouse\Support\Contracts\TypeResolver $typeResolver */ - $typeResolver = $this->directiveFactory->createSingleDirectiveOfType($definition, TypeResolver::class); - - if ($typeResolver) { + $typeResolver = $this->directiveLocator->exclusiveOfType($definition, TypeResolver::class); + if ($typeResolver !== null) { + /** @var \Nuwave\Lighthouse\Support\Contracts\TypeResolver $typeResolver */ return $typeResolver->resolveNode($value); } @@ -172,14 +227,13 @@ class TypeRegistry /** * The default type transformations. * - * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition - * @return \GraphQL\Type\Definition\Type + * @param \GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node $typeDefinition * + * @throws \GraphQL\Error\InvariantViolation * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ protected function resolveType(TypeDefinitionNode $typeDefinition): Type { - // Ignore TypeExtensionNode since they are merged before we get here switch (get_class($typeDefinition)) { case EnumTypeDefinitionNode::class: return $this->resolveEnumType($typeDefinition); @@ -200,45 +254,41 @@ class TypeRegistry } } - /** - * @param \GraphQL\Language\AST\EnumTypeDefinitionNode $enumDefinition - * @return \GraphQL\Type\Definition\EnumType - */ protected function resolveEnumType(EnumTypeDefinitionNode $enumDefinition): EnumType { + /** @var array> $values */ + $values = []; + + foreach ($enumDefinition->values as $enumValue) { + /** @var \Nuwave\Lighthouse\Schema\Directives\EnumDirective|null $enumDirective */ + $enumDirective = $this->directiveLocator->exclusiveOfType($enumValue, EnumDirective::class); + + $values[$enumValue->name->value] = [ + // If no explicit value is given, we default to the name of the value + 'value' => $enumDirective !== null + ? $enumDirective->value() + : $enumValue->name->value, + 'description' => data_get($enumValue->description, 'value'), + 'deprecationReason' => ASTHelper::deprecationReason($enumValue), + ]; + } + return new EnumType([ 'name' => $enumDefinition->name->value, 'description' => data_get($enumDefinition->description, 'value'), - 'values' => (new Collection($enumDefinition->values)) - ->mapWithKeys(function (EnumValueDefinitionNode $field): array { - // Get the directive that is defined on the field itself - $directive = ASTHelper::directiveDefinition($field, 'enum'); - - return [ - $field->name->value => [ - // If no explicit value is given, we default to the field name - 'value' => $directive - ? ASTHelper::directiveArgValue($directive, 'value') - : $field->name->value, - 'description' => data_get($field->description, 'value'), - ], - ]; - }) - ->toArray(), + 'values' => $values, + 'astNode' => $enumDefinition, ]); } /** - * @param \GraphQL\Language\AST\ScalarTypeDefinitionNode $scalarDefinition - * @return \GraphQL\Type\Definition\ScalarType - * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ protected function resolveScalarType(ScalarTypeDefinitionNode $scalarDefinition): ScalarType { $scalarName = $scalarDefinition->name->value; - if ($directive = ASTHelper::directiveDefinition($scalarDefinition, 'scalar')) { + if (($directive = ASTHelper::directiveDefinition($scalarDefinition, 'scalar')) !== null) { $className = ASTHelper::directiveArgValue($directive, 'class'); } else { $className = $scalarName; @@ -254,120 +304,118 @@ class TypeRegistry if (! $className) { throw new DefinitionException( - "No matching subclass of GraphQL\Type\Definition\ScalarType of found for the scalar {$scalarName}" + "No matching subclass of GraphQL\Type\Definition\ScalarType found for the scalar {$scalarName}" ); } return new $className([ 'name' => $scalarName, 'description' => data_get($scalarDefinition->description, 'value'), + 'astNode' => $scalarDefinition, ]); } - /** - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $objectDefinition - * @return \GraphQL\Type\Definition\ObjectType - */ protected function resolveObjectType(ObjectTypeDefinitionNode $objectDefinition): ObjectType { return new ObjectType([ 'name' => $objectDefinition->name->value, 'description' => data_get($objectDefinition->description, 'value'), - 'fields' => $this->resolveFieldsFunction($objectDefinition), - 'interfaces' => function () use ($objectDefinition): array { - return (new Collection($objectDefinition->interfaces)) - ->map(function (NamedTypeNode $interface): Type { - return $this->get($interface->name->value); - }) - ->toArray(); - }, + 'fields' => $this->makeFieldsLoader($objectDefinition), + 'interfaces' => + /** + * @return list<\GraphQL\Type\Definition\Type> + */ + function () use ($objectDefinition): array { + $interfaces = []; + + // Might be a NodeList, so we can not use array_map() + foreach ($objectDefinition->interfaces as $interface) { + $interfaces [] = $this->get($interface->name->value); + } + + return $interfaces; + }, + 'astNode' => $objectDefinition, ]); } /** * Returns a closure that lazy loads the fields for a constructed type. * - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\InterfaceTypeDefinitionNode $definition - * @return \Closure + * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode|\GraphQL\Language\AST\InterfaceTypeDefinitionNode $typeDefinition + * + * @return \Closure(): array> */ - protected function resolveFieldsFunction($definition): Closure + protected function makeFieldsLoader($typeDefinition): Closure { - return function () use ($definition): array { - return (new Collection($definition->fields)) - ->mapWithKeys(function (FieldDefinitionNode $fieldDefinition) use ($definition): array { - $fieldValue = new FieldValue( - new TypeValue($definition), - $fieldDefinition - ); + return + /** + * @return array> + */ + function () use ($typeDefinition): array { + $fieldFactory = $this->fieldFactory(); + $typeValue = new TypeValue($typeDefinition); + $fields = []; - return [ - $fieldDefinition->name->value => app(FieldFactory::class)->handle($fieldValue), - ]; - }) - ->toArray(); - }; + foreach ($typeDefinition->fields as $fieldDefinition) { + $fields[$fieldDefinition->name->value] = static function () use ($fieldFactory, $typeValue, $fieldDefinition): array { + return $fieldFactory->handle( + new FieldValue($typeValue, $fieldDefinition) + ); + }; + } + + return $fields; + }; } - /** - * @param \GraphQL\Language\AST\InputObjectTypeDefinitionNode $inputDefinition - * @return \GraphQL\Type\Definition\InputObjectType - */ protected function resolveInputObjectType(InputObjectTypeDefinitionNode $inputDefinition): InputObjectType { return new InputObjectType([ 'name' => $inputDefinition->name->value, 'description' => data_get($inputDefinition->description, 'value'), - 'fields' => function () use ($inputDefinition): array { - return $this->argumentFactory->toTypeMap($inputDefinition->fields); - }, + 'fields' => + /** + * @return array> + */ + function () use ($inputDefinition): array { + return $this->argumentFactory->toTypeMap($inputDefinition->fields); + }, + 'astNode' => $inputDefinition, ]); } - /** - * @param \GraphQL\Language\AST\InterfaceTypeDefinitionNode $interfaceDefinition - * @return \GraphQL\Type\Definition\InterfaceType - */ protected function resolveInterfaceType(InterfaceTypeDefinitionNode $interfaceDefinition): InterfaceType { $nodeName = $interfaceDefinition->name->value; - if ($directive = ASTHelper::directiveDefinition($interfaceDefinition, 'interface')) { - $interfaceDirective = (new InterfaceDirective)->hydrate($interfaceDefinition); + if (($directiveNode = ASTHelper::directiveDefinition($interfaceDefinition, 'interface')) !== null) { + $interfaceDirective = (new InterfaceDirective)->hydrate($directiveNode, $interfaceDefinition); $typeResolver = $interfaceDirective->getResolverFromArgument('resolveType'); } else { $typeResolver = - $this->findTypeResolverClass( + $this->typeResolverFromClass( $nodeName, (array) config('lighthouse.namespaces.interfaces') ) - ?: static::typeResolverFallback(); + ?: $this->typeResolverFallback(); } return new InterfaceType([ 'name' => $nodeName, 'description' => data_get($interfaceDefinition->description, 'value'), - 'fields' => $this->resolveFieldsFunction($interfaceDefinition), + 'fields' => $this->makeFieldsLoader($interfaceDefinition), 'resolveType' => $typeResolver, + 'astNode' => $interfaceDefinition, ]); } - protected function findTypeResolverClass(string $nodeName, array $namespaces): ?Closure + /** + * @param array $namespaces + */ + protected function typeResolverFromClass(string $nodeName, array $namespaces): ?Closure { - // TODO use only __invoke in v5 - $className = Utils::namespaceClassname( - $nodeName, - $namespaces, - function (string $className): bool { - return method_exists($className, 'resolveType'); - } - ); - if ($className) { - return Closure::fromCallable( - [app($className), 'resolveType'] - ); - } - $className = Utils::namespaceClassname( $nodeName, $namespaces, @@ -375,8 +423,10 @@ class TypeRegistry return method_exists($className, '__invoke'); } ); + if ($className) { return Closure::fromCallable( + // @phpstan-ignore-next-line this works [app($className), '__invoke'] ); } @@ -391,51 +441,65 @@ class TypeRegistry * field is a class that is named just like the concrete Object Type * that is supposed to be returned. * - * @return \Closure + * @return Closure(mixed): Type */ - public function typeResolverFallback(): Closure + protected function typeResolverFallback(): Closure { - return function ($rootValue): Type { - return $this->get( - class_basename($rootValue) - ); + return function ($root): Type { + if (is_array($root) && isset($root['__typename'])) { + $name = $root['__typename']; + } else { + $name = class_basename($root); + } + + return $this->get($name); }; } - /** - * @param \GraphQL\Language\AST\UnionTypeDefinitionNode $unionDefinition - * @return \GraphQL\Type\Definition\UnionType - */ protected function resolveUnionType(UnionTypeDefinitionNode $unionDefinition): UnionType { $nodeName = $unionDefinition->name->value; - if ($directive = ASTHelper::directiveDefinition($unionDefinition, 'union')) { - $unionDirective = (new UnionDirective)->hydrate($unionDefinition); + if (($directiveNode = ASTHelper::directiveDefinition($unionDefinition, 'union')) !== null) { + $unionDirective = (new UnionDirective)->hydrate($directiveNode, $unionDefinition); $typeResolver = $unionDirective->getResolverFromArgument('resolveType'); } else { $typeResolver = - $this->findTypeResolverClass( + $this->typeResolverFromClass( $nodeName, (array) config('lighthouse.namespaces.unions') ) - ?: static::typeResolverFallback(); + ?: $this->typeResolverFallback(); } return new UnionType([ 'name' => $nodeName, 'description' => data_get($unionDefinition->description, 'value'), - 'types' => function () use ($unionDefinition): array { - return (new Collection($unionDefinition->types)) - ->map(function (NamedTypeNode $type): Type { - return $this->get( - $type->name->value - ); - }) - ->toArray(); - }, + 'types' => + /** + * @return list<\GraphQL\Type\Definition\Type> + */ + function () use ($unionDefinition): array { + $types = []; + + foreach ($unionDefinition->types as $type) { + $types[] = $this->get($type->name->value); + } + + return $types; + }, 'resolveType' => $typeResolver, + 'astNode' => $unionDefinition, ]); } + + protected function fieldFactory(): FieldFactory + { + if (! isset($this->fieldFactory)) { + $this->fieldFactory = app(FieldFactory::class); + } + + return $this->fieldFactory; + } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/GraphQLSubscription.php b/vendor/nuwave/lighthouse/src/Schema/Types/GraphQLSubscription.php index 0df637c..d953878 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Types/GraphQLSubscription.php +++ b/vendor/nuwave/lighthouse/src/Schema/Types/GraphQLSubscription.php @@ -2,9 +2,9 @@ namespace Nuwave\Lighthouse\Schema\Types; -use Illuminate\Support\Str; -use Illuminate\Http\Request; use GraphQL\Type\Definition\ResolveInfo; +use Illuminate\Http\Request; +use Illuminate\Support\Str; use Nuwave\Lighthouse\Subscriptions\Subscriber; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; @@ -13,7 +13,6 @@ abstract class GraphQLSubscription /** * Check if subscriber is allowed to listen to this subscription. * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber * @return bool */ public function can(Subscriber $subscriber) @@ -24,8 +23,6 @@ abstract class GraphQLSubscription /** * Encode topic name. * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param string $fieldName * @return string */ public function encodeTopic(Subscriber $subscriber, string $fieldName) @@ -38,8 +35,6 @@ abstract class GraphQLSubscription /** * Decode topic name. * - * @param string $fieldName - * @param mixed $root * @return string */ public function decodeTopic(string $fieldName, $root) @@ -52,11 +47,8 @@ abstract class GraphQLSubscription /** * Resolve the subscription. * - * @param mixed $root - * @param mixed[] $args - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return mixed + * @param array $args + * @return mixed The root value. */ public function resolve($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { @@ -66,8 +58,6 @@ abstract class GraphQLSubscription /** * Check if subscriber is allowed to listen to the subscription. * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param \Illuminate\Http\Request $request * @return bool */ abstract public function authorize(Subscriber $subscriber, Request $request); @@ -75,8 +65,6 @@ abstract class GraphQLSubscription /** * Filter which subscribers should receive the subscription. * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param mixed $root * @return bool */ abstract public function filter(Subscriber $subscriber, $root); diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/LaravelEnumType.php b/vendor/nuwave/lighthouse/src/Schema/Types/LaravelEnumType.php index 3344aa3..d29791d 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Types/LaravelEnumType.php +++ b/vendor/nuwave/lighthouse/src/Schema/Types/LaravelEnumType.php @@ -1,12 +1,10 @@ $enumClass + * @param string|null $name The name the enum will have in the schema, defaults to the basename of the given class */ - public function __construct(string $enumClass) + public function __construct(string $enumClass, ?string $name = null) { if (! is_subclass_of($enumClass, Enum::class)) { throw new InvalidArgumentException( @@ -35,13 +33,16 @@ class LaravelEnumType extends EnumType $this->enumClass = $enumClass; parent::__construct([ - 'name' => class_basename($enumClass), + 'name' => $name ?? class_basename($enumClass), 'values' => array_map( + /** + * @return array Used to construct a \GraphQL\Type\Definition\EnumValueDefinition + */ function (Enum $enum): array { return [ 'name' => $enum->key, 'value' => $enum, - 'description' => "$enum->value", + 'description' => $enum->description, ]; }, $enumClass::getInstances() @@ -51,14 +52,11 @@ class LaravelEnumType extends EnumType /** * Overwrite the native EnumType serialization, as this class does not hold plain values. - * - * @param mixed $value - * @return string */ public function serialize($value): string { if (! $value instanceof Enum) { - $value = $this->enumClass::getInstance($value); + $value = $this->enumClass::fromValue($value); } return $value->key; diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/NotFoundSubscription.php b/vendor/nuwave/lighthouse/src/Schema/Types/NotFoundSubscription.php index 8881363..36ebeba 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Types/NotFoundSubscription.php +++ b/vendor/nuwave/lighthouse/src/Schema/Types/NotFoundSubscription.php @@ -2,8 +2,8 @@ namespace Nuwave\Lighthouse\Schema\Types; -use Illuminate\Http\Request; use GraphQL\Type\Definition\ResolveInfo; +use Illuminate\Http\Request; use Nuwave\Lighthouse\Subscriptions\Subscriber; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; @@ -11,10 +11,6 @@ class NotFoundSubscription extends GraphQLSubscription { /** * Authorize subscriber request. - * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param \Illuminate\Http\Request $request - * @return bool */ public function authorize(Subscriber $subscriber, Request $request): bool { @@ -23,10 +19,6 @@ class NotFoundSubscription extends GraphQLSubscription /** * Filter which subscribers should receive the subscription. - * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param mixed $root - * @return bool */ public function filter(Subscriber $subscriber, $root): bool { @@ -35,15 +27,8 @@ class NotFoundSubscription extends GraphQLSubscription /** * Resolve the subscription. - * - * @param mixed $root - * @param array $args - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return mixed */ - public function resolve($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) + public function resolve($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): void { - // } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Date.php b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Date.php index 2440cb6..ab556c6 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Date.php +++ b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Date.php @@ -2,81 +2,18 @@ namespace Nuwave\Lighthouse\Schema\Types\Scalars; -use Exception; -use Carbon\Carbon; -use GraphQL\Error\Error; -use GraphQL\Utils\Utils; -use GraphQL\Error\InvariantViolation; -use GraphQL\Type\Definition\ScalarType; -use GraphQL\Language\AST\StringValueNode; +use Illuminate\Support\Carbon; -class Date extends ScalarType +class Date extends DateScalar { - /** - * Serialize an internal value, ensuring it is a valid date string. - * - * @param \Carbon\Carbon|string $value - * @return string - */ - public function serialize($value): string + protected function format(Carbon $carbon): string { - if ($value instanceof Carbon) { - return $value->toDateString(); - } - - return $this->tryParsingDate($value, InvariantViolation::class) - ->toDateString(); + return $carbon->toDateString(); } - /** - * Parse a externally provided variable value into a Carbon instance. - * - * @param string $value - * @return \Carbon\Carbon - */ - public function parseValue($value): Carbon + protected function parse($value): Carbon { - return $this->tryParsingDate($value, Error::class); - } - - /** - * Parse a literal provided as part of a GraphQL query string into a Carbon instance. - * - * @param \GraphQL\Language\AST\Node $valueNode - * @param mixed[]|null $variables - * @return \Carbon\Carbon - * - * @throws \GraphQL\Error\Error - */ - public function parseLiteral($valueNode, ?array $variables = null): Carbon - { - if (! $valueNode instanceof StringValueNode) { - throw new Error( - "Query error: Can only parse strings, got {$valueNode->kind}", - [$valueNode] - ); - } - - return $this->tryParsingDate($valueNode->value, Error::class); - } - - /** - * Try to parse the given value into a Carbon instance, throw if it does not work. - * - * @param string $value - * @param string $exceptionClass - * @return \Carbon\Carbon - * - * @throws \GraphQL\Error\InvariantViolation|\GraphQL\Error\Error - */ - protected function tryParsingDate($value, string $exceptionClass): Carbon - { - try { - return Carbon::createFromFormat('Y-m-d', $value)->startOfDay(); - } catch (Exception $e) { - throw new $exceptionClass( - Utils::printSafeJson($e->getMessage()) - ); - } + // @phpstan-ignore-next-line We know the format to be good, so this can never return `false` + return Carbon::createFromFormat('Y-m-d', $value)->startOfDay(); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateScalar.php b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateScalar.php new file mode 100644 index 0000000..939d68f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateScalar.php @@ -0,0 +1,113 @@ +tryParsingDate($value, InvariantViolation::class); + } + + return $this->format($value); + } + + /** + * Parse a externally provided variable value into a Carbon instance. + * + * @param string $value + */ + public function parseValue($value): Carbon + { + return $this->tryParsingDate($value, Error::class); + } + + /** + * Parse a literal provided as part of a GraphQL query string into a Carbon instance. + * + * @param \GraphQL\Language\AST\Node $valueNode + * @param array|null $variables + * + * @throws \GraphQL\Error\Error + */ + public function parseLiteral($valueNode, ?array $variables = null): Carbon + { + if (! $valueNode instanceof StringValueNode) { + throw new Error( + "Query error: Can only parse strings, got {$valueNode->kind}", + $valueNode + ); + } + + return $this->tryParsingDate($valueNode->value, Error::class); + } + + /** + * Try to parse the given value into a Carbon instance, throw if it does not work. + * + * @param mixed $value Any value that might be a Date + * @param class-string<\Exception> $exceptionClass + * + * @throws \GraphQL\Error\InvariantViolation|\GraphQL\Error\Error + */ + protected function tryParsingDate($value, string $exceptionClass): Carbon + { + try { + if ( + is_object($value) + // We want to know if we have exactly a Carbon\Carbon, not a subclass thereof + // @noRector Rector\CodeQuality\Rector\Identical\GetClassToInstanceOfRector + && get_class($value) === \Carbon\Carbon::class + ) { + /** + * Given we had a valid \Carbon\Carbon before, this can not fail. + * + * @var \Illuminate\Support\Carbon $carbon + */ + $carbon = Carbon::create( + $value->year, + $value->month, + $value->day, + $value->hour, + $value->minute, + $value->second, + $value->timezone + ); + + return $carbon; + } + + return $this->parse($value); + } catch (Exception $e) { + throw new $exceptionClass( + Utils::printSafeJson($e->getMessage()) + ); + } + } + + /** + * Serialize the Carbon instance. + */ + abstract protected function format(Carbon $carbon): string; + + /** + * Try turning a client value into a Carbon instance. + * + * @param mixed $value A possibly faulty client value. + */ + abstract protected function parse($value): Carbon; +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTime.php b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTime.php index 366fe17..1c1f4a5 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTime.php +++ b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTime.php @@ -2,84 +2,18 @@ namespace Nuwave\Lighthouse\Schema\Types\Scalars; -use Exception; -use Carbon\Carbon; -use GraphQL\Error\Error; -use GraphQL\Utils\Utils; -use GraphQL\Error\InvariantViolation; -use GraphQL\Type\Definition\ScalarType; -use GraphQL\Language\AST\StringValueNode; +use Illuminate\Support\Carbon; -class DateTime extends ScalarType +class DateTime extends DateScalar { - /** - * Serialize an internal value, ensuring it is a valid datetime string. - * - * @param \Carbon\Carbon|string $value - * @return string - */ - public function serialize($value): string + protected function format(Carbon $carbon): string { - if ($value instanceof Carbon) { - return $value->toDateTimeString(); - } - - return $this - ->tryParsingDateTime($value, InvariantViolation::class) - ->toDateTimeString(); + return $carbon->toDateTimeString(); } - /** - * Parse a externally provided variable value into a Carbon instance. - * - * @param mixed $value - * @return \Carbon\Carbon - */ - public function parseValue($value): Carbon + protected function parse($value): Carbon { - return $this->tryParsingDateTime($value, Error::class); - } - - /** - * Parse a literal provided as part of a GraphQL query string into a Carbon instance. - * - * @param \GraphQL\Language\AST\Node $valueNode - * @param mixed[]|null $variables - * @return \Carbon\Carbon - * - * @throws \GraphQL\Error\Error - */ - public function parseLiteral($valueNode, ?array $variables = null): Carbon - { - if (! $valueNode instanceof StringValueNode) { - throw new Error( - 'Query error: Can only parse strings got: '.$valueNode->kind, - [$valueNode] - ); - } - - return $this->tryParsingDateTime($valueNode->value, Error::class); - } - - /** - * Try to parse the given value into a Carbon instance, throw if it does not work. - * - * @param mixed $value - * @param string $exceptionClass - * @return \Carbon\Carbon - * - * @throws \GraphQL\Error\InvariantViolation|\GraphQL\Error\Error - */ - protected function tryParsingDateTime($value, string $exceptionClass): Carbon - { - try { - return Carbon::createFromFormat(Carbon::DEFAULT_TO_STRING_FORMAT, $value); - } catch (Exception $e) { - throw new $exceptionClass( - Utils::printSafeJson( - $e->getMessage() - ) - ); - } + // @phpstan-ignore-next-line We know the format to be good, so this can never return `false` + return Carbon::createFromFormat(Carbon::DEFAULT_TO_STRING_FORMAT, $value); } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeTz.php b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeTz.php new file mode 100644 index 0000000..43979db --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeTz.php @@ -0,0 +1,23 @@ +toIso8601String(); + } + + protected function parse($value): Carbon + { + // @phpstan-ignore-next-line We know the format to be good, so this can never return `false` + return Carbon::createFromFormat( + // https://www.php.net/manual/en/class.datetimeinterface.php#datetime.constants.iso8601 + Carbon::ATOM, + $value + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeUtc.php b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeUtc.php new file mode 100644 index 0000000..7eab7d9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/DateTimeUtc.php @@ -0,0 +1,22 @@ +toJSON(); + } + + protected function parse($value): Carbon + { + // @phpstan-ignore-next-line We know the format to be good, so this can never return `false` + return Carbon::createFromIsoFormat('YYYY-MM-DDTHH:mm:ss.SSSSSSZ', $value); + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Upload.php b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Upload.php index e65ddf0..a1a3362 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Upload.php +++ b/vendor/nuwave/lighthouse/src/Schema/Types/Scalars/Upload.php @@ -3,19 +3,16 @@ namespace Nuwave\Lighthouse\Schema\Types\Scalars; use GraphQL\Error\Error; -use GraphQL\Utils\Utils; -use Illuminate\Http\UploadedFile; use GraphQL\Error\InvariantViolation; use GraphQL\Type\Definition\ScalarType; +use GraphQL\Utils\Utils; +use Illuminate\Http\UploadedFile; class Upload extends ScalarType { /** * This always throws, as the Upload scalar can only be used as an argument. * - * @param mixed $value - * @return void - * * @throws \GraphQL\Error\InvariantViolation */ public function serialize($value): void @@ -28,9 +25,6 @@ class Upload extends ScalarType /** * Parse a externally provided variable value into a Carbon instance. * - * @param mixed $value - * @return \Illuminate\Http\UploadedFile - * * @throws \GraphQL\Error\Error */ public function parseValue($value): UploadedFile @@ -48,8 +42,7 @@ class Upload extends ScalarType * This always throws, as the Upload scalar must be used with a multipart form request. * * @param \GraphQL\Language\AST\Node $valueNode - * @param mixed[]|null $variables - * @return void + * @param array|null $variables * * @throws \GraphQL\Error\Error */ diff --git a/vendor/nuwave/lighthouse/src/Schema/Values/CacheValue.php b/vendor/nuwave/lighthouse/src/Schema/Values/CacheValue.php index aa62370..64142bf 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Values/CacheValue.php +++ b/vendor/nuwave/lighthouse/src/Schema/Values/CacheValue.php @@ -2,40 +2,42 @@ namespace Nuwave\Lighthouse\Schema\Values; -use Illuminate\Support\Arr; +use GraphQL\Type\Definition\ResolveInfo; use Illuminate\Support\Collection; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; class CacheValue { /** - * @var \Nuwave\Lighthouse\Schema\Values\FieldValue + * @var mixed|null The root that was passed to the query. */ - protected $fieldValue; + protected $root; /** - * @var mixed - */ - protected $rootValue; - - /** - * @var array + * The args that were passed to the query. + * + * @var array */ protected $args; /** - * @var mixed + * The context that was passed to the query. + * + * @var \Nuwave\Lighthouse\Support\Contracts\GraphQLContext */ protected $context; /** + * The ResolveInfo that was passed to the query. + * * @var \GraphQL\Type\Definition\ResolveInfo */ protected $resolveInfo; /** - * @var mixed + * @var \Nuwave\Lighthouse\Schema\Values\FieldValue */ - protected $fieldKey; + protected $fieldValue; /** * @var bool @@ -43,53 +45,62 @@ class CacheValue protected $isPrivate; /** - * Create instance of cache value. - * - * @param array $arguments - * @return void + * @var mixed The key to use for caching this field. */ - public function __construct(array $arguments = []) - { - $this->fieldValue = Arr::get($arguments, 'field_value'); - $this->rootValue = Arr::get($arguments, 'root'); - $this->args = Arr::get($arguments, 'args'); - $this->context = Arr::get($arguments, 'context'); - $this->resolveInfo = Arr::get($arguments, 'resolve_info'); - $this->isPrivate = Arr::get($arguments, 'is_private'); + protected $fieldKey; + + /** + * @param mixed|null $root The root that was passed to the query. + * @param array $args + * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue + */ + public function __construct( + $root, + array $args, + GraphQLContext $context, + ResolveInfo $resolveInfo, + FieldValue $fieldValue, + bool $isPrivate + ) { + $this->root = $root; + $this->args = $args; + $this->context = $context; + $this->resolveInfo = $resolveInfo; + $this->fieldValue = $fieldValue; + $this->isPrivate = $isPrivate; $this->fieldKey = $this->fieldKey(); } /** * Resolve key from root value. - * - * @return string */ public function getKey(): string { - $argKeys = $this->argKeys(); - $user = app('auth')->user(); + $parts = []; - return $this->implode([ - $this->isPrivate && $user - ? 'auth' - : null, - $this->isPrivate && $user - ? $user->getKey() - : null, - strtolower($this->resolveInfo->parentType->name), - $this->fieldKey, - strtolower($this->resolveInfo->fieldName), - $argKeys->isNotEmpty() - ? $argKeys->implode(':') - : null, - ]); + $user = $this->context->user(); + if ($this->isPrivate && $user !== null) { + $parts [] = 'auth'; + $parts [] = $user->getAuthIdentifier(); + } + + $parts [] = strtolower($this->resolveInfo->parentType->name); + $parts [] = $this->fieldKey; + $parts [] = strtolower($this->resolveInfo->fieldName); + + $argKeys = $this->argKeys(); + if ($argKeys->isNotEmpty()) { + $parts [] = $argKeys->implode(':'); + } + + return $this->implode($parts); } /** * Get cache tags. * - * @return array + * @return array{0: string, 1: string} */ public function getTags(): array { @@ -112,18 +123,15 @@ class CacheValue /** * Convert input arguments to keys. * - * @return \Illuminate\Support\Collection + * @return \Illuminate\Support\Collection */ protected function argKeys(): Collection { - // TODO use ->sortKeys() once we drop support for Laravel 5.5 - $args = $this->args; - ksort($args); - - return (new Collection($args)) + return (new Collection($this->args)) + ->sortKeys() ->map(function ($value, $key): string { $keyValue = is_array($value) - ? json_encode($value, true) + ? \Safe\json_encode($value) : $value; return "{$key}:{$keyValue}"; @@ -137,7 +145,7 @@ class CacheValue */ protected function fieldKey() { - if (! $this->fieldValue || ! $this->rootValue) { + if ($this->root === null) { return; } @@ -146,15 +154,12 @@ class CacheValue ->getCacheKey(); if ($cacheFieldKey) { - return data_get($this->rootValue, $cacheFieldKey); + return data_get($this->root, $cacheFieldKey); } } /** - * Implode value to create string. - * - * @param array $items - * @return string + * @param array $items */ protected function implode(array $items): string { diff --git a/vendor/nuwave/lighthouse/src/Schema/Values/FieldValue.php b/vendor/nuwave/lighthouse/src/Schema/Values/FieldValue.php index 1d709cc..4983f9e 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Values/FieldValue.php +++ b/vendor/nuwave/lighthouse/src/Schema/Values/FieldValue.php @@ -3,10 +3,16 @@ namespace Nuwave\Lighthouse\Schema\Values; use Closure; -use GraphQL\Type\Definition\Type; -use GraphQL\Language\AST\StringValueNode; +use GraphQL\Deferred; use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\Conversion\DefinitionNodeConverter; +use GraphQL\Language\AST\StringValueNode; +use GraphQL\Type\Definition\ResolveInfo; +use GraphQL\Type\Definition\Type; +use Nuwave\Lighthouse\Schema\ExecutableTypeNodeConverter; +use Nuwave\Lighthouse\Schema\RootType; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Support\Contracts\ProvidesResolver; +use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver; class FieldValue { @@ -34,38 +40,19 @@ class FieldValue /** * The actual field resolver. * - * @var \Closure|null + * Lazily initialized through setResolver(). + * + * @var callable */ protected $resolver; - /** - * Text describing by this field is deprecated. - * - * @var string|null - */ - protected $deprecationReason = null; - /** * A closure that determines the complexity of executing the field. * - * @var \Closure + * @var \Closure|null */ protected $complexity; - /** - * Cache key should be private. - * - * @var bool - */ - protected $privateCache = false; - - /** - * Create new field value instance. - * - * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $parent - * @param \GraphQL\Language\AST\FieldDefinitionNode $field - * @return void - */ public function __construct(TypeValue $parent, FieldDefinitionNode $field) { $this->parent = $parent; @@ -75,20 +62,32 @@ class FieldValue /** * Overwrite the current/default resolver. * - * @param \Closure $resolver * @return $this */ - public function setResolver(Closure $resolver): self + public function setResolver(callable $resolver): self { $this->resolver = $resolver; return $this; } + /** + * Use the default resolver. + * + * @return $this + */ + public function useDefaultResolver(): self + { + $this->resolver = $this->getParentName() === RootType::SUBSCRIPTION + ? app(ProvidesSubscriptionResolver::class)->provideSubscriptionResolver($this) + : app(ProvidesResolver::class)->provideResolver($this); + + return $this; + } + /** * Define a closure that is used to determine the complexity of the field. * - * @param \Closure $complexity * @return $this */ public function setComplexity(Closure $complexity): self @@ -98,46 +97,25 @@ class FieldValue return $this; } - /** - * Set deprecation reason for field. - * - * @param string $deprecationReason - * @return $this - */ - public function setDeprecationReason(string $deprecationReason): self - { - $this->deprecationReason = $deprecationReason; - - return $this; - } - /** * Get an instance of the return type of the field. - * - * @return \GraphQL\Type\Definition\Type */ public function getReturnType(): Type { - if (! isset($this->returnType)) { - $this->returnType = app(DefinitionNodeConverter::class)->toType( - $this->field->type - ); + if ($this->returnType === null) { + /** @var \Nuwave\Lighthouse\Schema\ExecutableTypeNodeConverter $typeNodeConverter */ + $typeNodeConverter = app(ExecutableTypeNodeConverter::class); + $this->returnType = $typeNodeConverter->convert($this->field->type); } return $this->returnType; } - /** - * @return \Nuwave\Lighthouse\Schema\Values\TypeValue - */ public function getParent(): TypeValue { return $this->parent; } - /** - * @return string - */ public function getParentName(): string { return $this->getParent()->getTypeDefinitionName(); @@ -145,8 +123,6 @@ class FieldValue /** * Get the underlying AST definition for the field. - * - * @return \GraphQL\Language\AST\FieldDefinitionNode */ public function getField(): FieldDefinitionNode { @@ -155,10 +131,8 @@ class FieldValue /** * Get field resolver. - * - * @return \Closure */ - public function getResolver(): ?Closure + public function getResolver(): callable { return $this->resolver; } @@ -166,25 +140,22 @@ class FieldValue /** * Return the namespaces configured for the parent type. * - * @return string[] + * @return array */ public function defaultNamespacesForParent(): array { switch ($this->getParentName()) { - case 'Query': + case RootType::QUERY: return (array) config('lighthouse.namespaces.queries'); - case 'Mutation': + case RootType::MUTATION: return (array) config('lighthouse.namespaces.mutations'); - case 'Subscription': + case RootType::SUBSCRIPTION: return (array) config('lighthouse.namespaces.subscriptions'); default: return []; } } - /** - * @return \GraphQL\Language\AST\StringValueNode|null - */ public function getDescription(): ?StringValueNode { return $this->field->description; @@ -192,40 +163,65 @@ class FieldValue /** * Get current complexity. - * - * @return \Closure|null */ public function getComplexity(): ?Closure { return $this->complexity; } - /** - * @return string - */ public function getFieldName(): string { return $this->field->name->value; } - /** - * @return string|null - */ - public function getDeprecationReason(): ?string - { - return $this->deprecationReason; - } - /** * Is the parent of this field one of the root types? - * - * @return bool */ public function parentIsRootType(): bool { - return in_array( - $this->getParentName(), - ['Query', 'Mutation', 'Subscription'] - ); + return RootType::isRootType($this->getParentName()); + } + + /** + * Register a function that will receive the final result and resolver arguments. + * + * For example, the following handler tries to double the result. + * This is somewhat non-sensical, but shows the range of what you can do. + * + * function ($result, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { + * if (is_numeric($result)) { + * // A common use-case is to transform the result + * $result = $result * 2; + * } + * + * // You can also filter results conditionally + * if ($result === 42) { + * return null; + * } + * + * // You can also run side-effects + * Log::debug("Doubled to {$result}."); + * + * // Don't forget to return something + * return $result; + * } + * + * @param callable(mixed $result, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): mixed $handle + */ + public function resultHandler(callable $handle): void + { + $previousResolver = $this->resolver; + + $this->resolver = function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($previousResolver, $handle) { + $resolved = $previousResolver($root, $args, $context, $resolveInfo); + + if ($resolved instanceof Deferred) { + return $resolved->then(static function ($result) use ($handle, $args, $context, $resolveInfo) { + return $handle($result, $args, $context, $resolveInfo); + }); + } + + return $handle($resolved, $args, $context, $resolveInfo); + }; } } diff --git a/vendor/nuwave/lighthouse/src/Schema/Values/TypeValue.php b/vendor/nuwave/lighthouse/src/Schema/Values/TypeValue.php index 06b38e8..cc1e50d 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Values/TypeValue.php +++ b/vendor/nuwave/lighthouse/src/Schema/Values/TypeValue.php @@ -27,10 +27,6 @@ class TypeValue */ protected $cacheKey; - /** - * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition - * @return void - */ public function __construct(TypeDefinitionNode $typeDefinition) { $this->typeDefinition = $typeDefinition; @@ -38,8 +34,6 @@ class TypeValue /** * Get the name of the node. - * - * @return string */ public function getTypeDefinitionName(): string { @@ -48,28 +42,14 @@ class TypeValue /** * Get the underlying type definition. - * - * @return \GraphQL\Language\AST\TypeDefinitionNode */ public function getTypeDefinition(): TypeDefinitionNode { return $this->typeDefinition; } - /** - * Get the underlying type definition fields. - * - * @return \GraphQL\Language\AST\NodeList|array - */ - public function getTypeDefinitionFields() - { - return data_get($this->typeDefinition, 'fields', []); - } - /** * Get node's cache key. - * - * @return string|null */ public function getCacheKey(): ?string { @@ -79,7 +59,6 @@ class TypeValue /** * Set node cache key. * - * @param string|null $key * @return $this */ public function setCacheKey(string $key = null): self diff --git a/vendor/nuwave/lighthouse/src/Scout/ScoutBuilderDirective.php b/vendor/nuwave/lighthouse/src/Scout/ScoutBuilderDirective.php new file mode 100644 index 0000000..22514a6 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Scout/ScoutBuilderDirective.php @@ -0,0 +1,15 @@ + + */ + protected $searchArguments = []; + + /** + * Should not be there when @search is used. + * + * @var array + */ + protected $argumentsWithOnlyArgBuilders = []; + + /** + * Can enhance the scout builders. + * + * @var array + */ + protected $argumentsWithScoutBuilderDirectives = []; + + /** + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder + */ + public function __construct(ArgumentSet $argumentSet, object $builder) + { + $this->argumentSet = $argumentSet; + $this->builder = $builder; + + $this->gather($this->argumentSet); + } + + public function hasSearchArguments(): bool + { + return count($this->searchArguments) > 0; + } + + public function enhanceBuilder(): ScoutBuilder + { + if (count($this->searchArguments) > 1) { + throw new ScoutException('Found more than 1 argument with @search.'); + } + $searchArgument = $this->searchArguments[0]; + + if (count($this->argumentsWithOnlyArgBuilders) > 0) { + throw new ScoutException('Found arg builder arguments that do not work with @search'); + } + + if (! $this->builder instanceof EloquentBuilder) { + throw new ScoutException('Can only get Model from \Illuminate\Database\Eloquent\Builder, got: '.get_class($this->builder)); + } + $model = $this->builder->getModel(); + + if (! Utils::classUsesTrait($model, Searchable::class)) { + throw new ScoutException('Model class '.get_class($model).' does not implement trait '.Searchable::class); + } + + // @phpstan-ignore-next-line Can not use traits as types + /** + * @psalm-suppress UndefinedDocblockClass + * @var \Illuminate\Database\Eloquent\Model&\Laravel\Scout\Searchable $model + */ + $scoutBuilder = $model::search($searchArgument->toPlain()); + + /** + * We know this argument has this directive, because that is how we found it. + * + * @var \Nuwave\Lighthouse\Scout\SearchDirective $searchDirective + */ + $searchDirective = $searchArgument + ->directives + ->first(Utils::instanceofMatcher(SearchDirective::class)); + + $searchDirective->search($scoutBuilder); + + foreach ($this->argumentsWithScoutBuilderDirectives as $argument) { + /** @var \Nuwave\Lighthouse\Scout\ScoutBuilderDirective $scoutBuilderDirective */ + $scoutBuilderDirective = $argument + ->directives + ->first(Utils::instanceofMatcher(ScoutBuilderDirective::class)); + + $scoutBuilderDirective->handleScoutBuilder($scoutBuilder, $argument->toPlain()); + } + + return $scoutBuilder; + } + + protected function gather(ArgumentSet $argumentSet): void + { + foreach ($argumentSet->arguments as $argument) { + $argumentHasSearchDirective = $argument + ->directives + ->contains(Utils::instanceofMatcher(SearchDirective::class)); + + if ($argumentHasSearchDirective && is_string($argument->value)) { + $this->searchArguments [] = $argument; + } + + $argumentHasArgBuilderDirective = $argument + ->directives + ->contains(Utils::instanceofMatcher(ArgBuilderDirective::class)); + + $argumentHasScoutBuilderDirective = $argument + ->directives + ->contains(Utils::instanceofMatcher(ScoutBuilderDirective::class)); + + if ($argumentHasArgBuilderDirective && ! $argumentHasScoutBuilderDirective) { + $this->argumentsWithOnlyArgBuilders [] = $argument; + } + + if ($argumentHasScoutBuilderDirective) { + $this->argumentsWithScoutBuilderDirectives [] = $argument; + } + + Utils::applyEach( + function ($value) { + if ($value instanceof ArgumentSet) { + $this->gather($value); + } + }, + $argument->value + ); + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Scout/ScoutException.php b/vendor/nuwave/lighthouse/src/Scout/ScoutException.php new file mode 100644 index 0000000..a62e923 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Scout/ScoutException.php @@ -0,0 +1,9 @@ +listen( + RegisterDirectiveNamespaces::class, + function (RegisterDirectiveNamespaces $registerDirectiveNamespaces): string { + return __NAMESPACE__; + } + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Scout/SearchDirective.php b/vendor/nuwave/lighthouse/src/Scout/SearchDirective.php new file mode 100644 index 0000000..3aa2848 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Scout/SearchDirective.php @@ -0,0 +1,39 @@ +directiveArgValue('within'); + if (null !== $within) { + if (! is_string($within)) { + throw new DefinitionException( + "Expected the value of the `within` argument of @{$this->name()} on {$this->nodeName()} to be a string, got: ".\Safe\json_encode($within) + ); + } + + $builder->within($within); + } + } +} diff --git a/vendor/nuwave/lighthouse/src/SoftDeletes/ForceDeleteDirective.php b/vendor/nuwave/lighthouse/src/SoftDeletes/ForceDeleteDirective.php index 89c90ac..91c7b5e 100644 --- a/vendor/nuwave/lighthouse/src/SoftDeletes/ForceDeleteDirective.php +++ b/vendor/nuwave/lighthouse/src/SoftDeletes/ForceDeleteDirective.php @@ -2,35 +2,27 @@ namespace Nuwave\Lighthouse\SoftDeletes; -use Illuminate\Database\Eloquent\Model; use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use Illuminate\Database\Eloquent\Model; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; use Nuwave\Lighthouse\Schema\Directives\ModifyModelExistenceDirective; class ForceDeleteDirective extends ModifyModelExistenceDirective { - const MODEL_NOT_USING_SOFT_DELETES = 'Use the @forceDelete directive only for Model classes that use the SoftDeletes trait.'; - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'forceDelete'; - } + public const MODEL_NOT_USING_SOFT_DELETES = 'Use the @forceDelete directive only for Model classes that use the SoftDeletes trait.'; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Permanently remove one or more soft deleted models by their ID. +Permanently remove one or more soft deleted models by their ID. The field must have a single non-null argument that may be a list. """ directive @forceDelete( """ + DEPRECATED use @globalId, will be removed in v6 + Set to `true` to use global ids for finding the model. If set to `false`, regular non-global ids are used. """ @@ -38,43 +30,29 @@ directive @forceDelete( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Find one or more models by id. - * - * @param string|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\SoftDeletes $modelClass - * @param string|int|string[]|int[] $idOrIds - * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection - */ protected function find(string $modelClass, $idOrIds) { + /** @see \Illuminate\Database\Eloquent\SoftDeletes */ + // @phpstan-ignore-next-line because it involves mixins return $modelClass::withTrashed()->find($idOrIds); } - /** - * Bring a model in or out of existence. - * - * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\SoftDeletes $model - * @return void - */ - protected function modifyExistence(Model $model): void + protected function modifyExistence(Model $model): bool { - $model->forceDelete(); + /** @see \Illuminate\Database\Eloquent\SoftDeletes */ + // @phpstan-ignore-next-line because it involves mixins + return (bool) $model->forceDelete(); } /** * Manipulate the AST based on a field definition. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @return void */ public function manipulateFieldDefinition( DocumentAST &$documentAST, @@ -83,7 +61,9 @@ SDL; ): void { parent::manipulateFieldDefinition($documentAST, $fieldDefinition, $parentType); - SoftDeletesServiceProvider::assertModelUsesSoftDeletes($this->getModelClass(), - self::MODEL_NOT_USING_SOFT_DELETES); + SoftDeletesServiceProvider::assertModelUsesSoftDeletes( + $this->getModelClass(), + self::MODEL_NOT_USING_SOFT_DELETES + ); } } diff --git a/vendor/nuwave/lighthouse/src/SoftDeletes/RestoreDirective.php b/vendor/nuwave/lighthouse/src/SoftDeletes/RestoreDirective.php index e5bef60..a796dae 100644 --- a/vendor/nuwave/lighthouse/src/SoftDeletes/RestoreDirective.php +++ b/vendor/nuwave/lighthouse/src/SoftDeletes/RestoreDirective.php @@ -2,37 +2,28 @@ namespace Nuwave\Lighthouse\SoftDeletes; -use Illuminate\Database\Eloquent\Model; use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; use GraphQL\Language\AST\ObjectTypeDefinitionNode; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; -use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; +use Illuminate\Database\Eloquent\Model; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; use Nuwave\Lighthouse\Schema\Directives\ModifyModelExistenceDirective; +use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; -class RestoreDirective extends ModifyModelExistenceDirective implements DefinedDirective, FieldManipulator +class RestoreDirective extends ModifyModelExistenceDirective implements FieldManipulator { - const MODEL_NOT_USING_SOFT_DELETES = 'Use the @restore directive only for Model classes that use the SoftDeletes trait.'; - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'restore'; - } + public const MODEL_NOT_USING_SOFT_DELETES = 'Use the @restore directive only for Model classes that use the SoftDeletes trait.'; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ -Un-delete one or more soft deleted models by their ID. +Un-delete one or more soft deleted models by their ID. The field must have a single non-null argument that may be a list. """ directive @restore( """ + DEPRECATED use @globalId, will be removed in v6 + Set to `true` to use global ids for finding the model. If set to `false`, regular non-global ids are used. """ @@ -40,43 +31,29 @@ directive @restore( """ Specify the class name of the model to use. - This is only needed when the default model resolution does not work. + This is only needed when the default model detection does not work. """ model: String ) on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Find one or more models by id. - * - * @param string|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\SoftDeletes $modelClass - * @param string|int|string[]|int[] $idOrIds - * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection - */ protected function find(string $modelClass, $idOrIds) { + /** @see \Illuminate\Database\Eloquent\SoftDeletes */ + // @phpstan-ignore-next-line because it involves mixins return $modelClass::withTrashed()->find($idOrIds); } - /** - * Bring a model in or out of existence. - * - * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\SoftDeletes $model - * @return void - */ - protected function modifyExistence(Model $model): void + protected function modifyExistence(Model $model): bool { - $model->restore(); + /** @see \Illuminate\Database\Eloquent\SoftDeletes */ + // @phpstan-ignore-next-line because it involves mixins + return (bool) $model->restore(); } /** * Manipulate the AST based on a field definition. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @return void */ public function manipulateFieldDefinition( DocumentAST &$documentAST, @@ -85,7 +62,9 @@ SDL; ): void { parent::manipulateFieldDefinition($documentAST, $fieldDefinition, $parentType); - SoftDeletesServiceProvider::assertModelUsesSoftDeletes($this->getModelClass(), - self::MODEL_NOT_USING_SOFT_DELETES); + SoftDeletesServiceProvider::assertModelUsesSoftDeletes( + $this->getModelClass(), + self::MODEL_NOT_USING_SOFT_DELETES + ); } } diff --git a/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesDirective.php b/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesDirective.php index 6e38945..088411b 100644 --- a/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesDirective.php +++ b/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesDirective.php @@ -2,54 +2,35 @@ namespace Nuwave\Lighthouse\SoftDeletes; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; -use Nuwave\Lighthouse\Schema\AST\PartialParser; use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Language\Parser; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; use Nuwave\Lighthouse\Schema\Directives\BaseDirective; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; use Nuwave\Lighthouse\Support\Contracts\FieldManipulator; -class SoftDeletesDirective extends BaseDirective implements FieldManipulator, DefinedDirective +class SoftDeletesDirective extends BaseDirective implements FieldManipulator { - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'softDeletes'; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Allows to filter if trashed elements should be fetched. This manipulates the schema by adding the argument `trashed: Trashed @trashed` to the field. """ directive @softDeletes on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\FieldDefinitionNode $fieldDefinition - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @return void - */ public function manipulateFieldDefinition(DocumentAST &$documentAST, FieldDefinitionNode &$fieldDefinition, ObjectTypeDefinitionNode &$parentType): void { - $softDeletesArgument = PartialParser::inputValueDefinition(/* @lang GraphQL */ <<<'SDL' + $fieldDefinition->arguments [] = Parser::inputValueDefinition(/** @lang GraphQL */ <<<'GRAPHQL' """ Allows to filter if trashed elements should be fetched. """ trashed: Trashed @trashed -SDL +GRAPHQL ); - $fieldDefinition->arguments = ASTHelper::mergeNodeList($fieldDefinition->arguments, [$softDeletesArgument]); } } diff --git a/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesServiceProvider.php b/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesServiceProvider.php index bdc320b..d788622 100644 --- a/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesServiceProvider.php +++ b/vendor/nuwave/lighthouse/src/SoftDeletes/SoftDeletesServiceProvider.php @@ -2,44 +2,31 @@ namespace Nuwave\Lighthouse\SoftDeletes; -use Illuminate\Support\ServiceProvider; +use GraphQL\Language\Parser; use Illuminate\Contracts\Events\Dispatcher; -use Nuwave\Lighthouse\Events\ManipulateAST; use Illuminate\Database\Eloquent\SoftDeletes; -use Nuwave\Lighthouse\Schema\AST\PartialParser; -use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Illuminate\Support\ServiceProvider; +use Nuwave\Lighthouse\Events\ManipulateAST; use Nuwave\Lighthouse\Events\RegisterDirectiveNamespaces; +use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Support\Utils; class SoftDeletesServiceProvider extends ServiceProvider { /** - * Ensure a model uses the SoftDeletes trait. - * - * @param string $modelClass - * @param string $exceptionMessage - * @return void + * Ensure the model uses the SoftDeletes trait. * + * @param class-string<\Illuminate\Database\Eloquent\Model> $modelClass * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException * @see \Illuminate\Database\Eloquent\SoftDeletes */ public static function assertModelUsesSoftDeletes(string $modelClass, string $exceptionMessage): void { - if ( - ! in_array( - SoftDeletes::class, - class_uses_recursive($modelClass) - ) - ) { + if (! Utils::classUsesTrait($modelClass, SoftDeletes::class)) { throw new DefinitionException($exceptionMessage); } } - /** - * Bootstrap any application services. - * - * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher - * @return void - */ public function boot(Dispatcher $dispatcher): void { $dispatcher->listen( @@ -47,10 +34,16 @@ class SoftDeletesServiceProvider extends ServiceProvider function (ManipulateAST $manipulateAST): void { $manipulateAST->documentAST ->setTypeDefinition( - PartialParser::enumTypeDefinition(' + Parser::enumTypeDefinition(' + "Specify if you want to include or exclude trashed results from a query." enum Trashed { + "Only return trashed results." ONLY @enum(value: "only") + + "Return both trashed and non-trashed results." WITH @enum(value: "with") + + "Only return non-trashed results." WITHOUT @enum(value: "without") } ') @@ -60,7 +53,7 @@ class SoftDeletesServiceProvider extends ServiceProvider $dispatcher->listen( RegisterDirectiveNamespaces::class, - function (RegisterDirectiveNamespaces $registerDirectiveNamespaces): string { + static function (): string { return __NAMESPACE__; } ); diff --git a/vendor/nuwave/lighthouse/src/SoftDeletes/TrashedDirective.php b/vendor/nuwave/lighthouse/src/SoftDeletes/TrashedDirective.php index 1b27315..cb69429 100644 --- a/vendor/nuwave/lighthouse/src/SoftDeletes/TrashedDirective.php +++ b/vendor/nuwave/lighthouse/src/SoftDeletes/TrashedDirective.php @@ -2,69 +2,84 @@ namespace Nuwave\Lighthouse\SoftDeletes; +use Exception; +use GraphQL\Exception\InvalidArgument; +use Illuminate\Database\Eloquent\Builder as EloquentBuilder; +use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Builder as ScoutBuilder; -use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Database\Eloquent\Relations\Relation; -use Nuwave\Lighthouse\Exceptions\DefinitionException; use Nuwave\Lighthouse\Schema\Directives\BaseDirective; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Scout\ScoutBuilderDirective; +use Nuwave\Lighthouse\Scout\ScoutException; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; -class TrashedDirective extends BaseDirective implements ArgBuilderDirective, DefinedDirective +class TrashedDirective extends BaseDirective implements ArgBuilderDirective, ScoutBuilderDirective { - const MODEL_MUST_USE_SOFT_DELETES = 'Use @trashed only for Model classes that use the SoftDeletes trait.'; - - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return 'trashed'; - } + public const MODEL_MUST_USE_SOFT_DELETES = 'Use @trashed only for Model classes that use the SoftDeletes trait.'; public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Allows to filter if trashed elements should be fetched. """ directive @trashed on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Apply withTrashed, onlyTrashed or withoutTrashed to given $builder if needed. - * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param string|null $value "with", "without" or "only" - * - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder - */ - public function handleBuilder($builder, $value) + public function handleBuilder($builder, $value): object { - if ($builder instanceof Relation) { - $model = $builder->getRelated(); - } elseif ($builder instanceof ScoutBuilder) { - $model = $builder->model; - } else { - $model = $builder->getModel(); + if (! $builder instanceof EloquentBuilder) { + throw new Exception('Can not get model from builder of class: '.get_class($builder)); } + $model = $builder->getModel(); - if (! in_array(SoftDeletes::class, class_uses_recursive($model))) { - throw new DefinitionException( - self::MODEL_MUST_USE_SOFT_DELETES - ); - } + $this->assertModelUsesSoftDeletes($model); - if (! isset($value)) { + if ($value === null) { return $builder; } - $trashedModificationMethod = "{$value}Trashed"; - $builder->{$trashedModificationMethod}(); + /** @see \Illuminate\Database\Eloquent\SoftDeletes */ + switch ($value) { + case 'with': + // @phpstan-ignore-next-line because it involves mixins + return $builder->withTrashed(); + case 'only': + // @phpstan-ignore-next-line because it involves mixins + return $builder->onlyTrashed(); + case 'without': + // @phpstan-ignore-next-line because it involves mixins + return $builder->withoutTrashed(); + default: + throw new InvalidArgument('Unexpected value for Trashed filter: '.$value); + } + } - return $builder; + public function handleScoutBuilder(ScoutBuilder $builder, $value): ScoutBuilder + { + $model = $builder->model; + + $this->assertModelUsesSoftDeletes($model); + + if ($value === null) { + return $builder; + } + + switch ($value) { + case 'with': + return $builder->withTrashed(); + case 'only': + return $builder->onlyTrashed(); + default: + throw new ScoutException('Unexpected value for Trashed filter: '.$value); + } + } + + protected function assertModelUsesSoftDeletes(Model $model): void + { + SoftDeletesServiceProvider::assertModelUsesSoftDeletes( + get_class($model), + self::MODEL_MUST_USE_SOFT_DELETES + ); } } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Authorizer.php b/vendor/nuwave/lighthouse/src/Subscriptions/Authorizer.php index 137634e..dff9d12 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Authorizer.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Authorizer.php @@ -4,9 +4,9 @@ namespace Nuwave\Lighthouse\Subscriptions; use Exception; use Illuminate\Http\Request; -use Nuwave\Lighthouse\Schema\Types\GraphQLSubscription; -use Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions; +use Illuminate\Support\Str; use Nuwave\Lighthouse\Subscriptions\Contracts\AuthorizesSubscriptions; +use Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions; use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionExceptionHandler; class Authorizer implements AuthorizesSubscriptions @@ -26,12 +26,6 @@ class Authorizer implements AuthorizesSubscriptions */ protected $exceptionHandler; - /** - * @param \Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions $storage - * @param \Nuwave\Lighthouse\Subscriptions\SubscriptionRegistry $registry - * @param \Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionExceptionHandler $exceptionHandler - * @return void - */ public function __construct( StoresSubscriptions $storage, SubscriptionRegistry $registry, @@ -42,47 +36,54 @@ class Authorizer implements AuthorizesSubscriptions $this->exceptionHandler = $exceptionHandler; } - /** - * Authorize subscription request. - * - * @param \Illuminate\Http\Request $request - * @return bool - */ public function authorize(Request $request): bool { try { - $subscriber = $this->storage->subscriberByRequest( - $request->input(), - $request->headers->all() - ); + $channel = $request->input('channel_name'); + if (! is_string($channel)) { + return false; + } - if (! $subscriber) { + $channel = $this->sanitizeChannelName($channel); + + $subscriber = $this->storage->subscriberByChannel($channel); + if ($subscriber === null) { return false; } $subscriptions = $this->registry->subscriptions($subscriber); - if ($subscriptions->isEmpty()) { return false; } - $authorized = $subscriptions->reduce( - function ($authorized, GraphQLSubscription $subscription) use ($subscriber, $request): bool { - return $authorized === false - ? false - : $subscription->authorize($subscriber, $request); - } - ); + /** @var \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription $subscription */ + foreach ($subscriptions as $subscription) { + if (! $subscription->authorize($subscriber, $request)) { + $this->storage->deleteSubscriber($subscriber->channel); - if (! $authorized) { - $this->storage->deleteSubscriber($subscriber->channel); + return false; + } } - return $authorized; + return true; } catch (Exception $e) { $this->exceptionHandler->handleAuthError($e); return false; } } + + /** + * Removes the prefix "presence-" from the channel name. + * + * Laravel Echo prefixes channel names with "presence-", but we don't. + */ + protected function sanitizeChannelName(string $channelName): string + { + if (Str::startsWith($channelName, 'presence-')) { + return Str::substr($channelName, 9); + } + + return $channelName; + } } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/BroadcastManager.php b/vendor/nuwave/lighthouse/src/Subscriptions/BroadcastManager.php index 5c8a4e2..762ff24 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/BroadcastManager.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/BroadcastManager.php @@ -2,13 +2,16 @@ namespace Nuwave\Lighthouse\Subscriptions; -use Pusher\Pusher; -use RuntimeException; +use Illuminate\Contracts\Debug\ExceptionHandler as LaravelExceptionHandler; use Illuminate\Support\Arr; -use Nuwave\Lighthouse\Support\DriverManager; -use Nuwave\Lighthouse\Subscriptions\Contracts\Broadcaster; +use Nuwave\Lighthouse\Subscriptions\Broadcasters\EchoBroadcaster; use Nuwave\Lighthouse\Subscriptions\Broadcasters\LogBroadcaster; use Nuwave\Lighthouse\Subscriptions\Broadcasters\PusherBroadcaster; +use Nuwave\Lighthouse\Subscriptions\Contracts\Broadcaster; +use Nuwave\Lighthouse\Support\DriverManager; +use Psr\Log\LoggerInterface; +use Pusher\Pusher; +use RuntimeException; /** * @method void broadcast(\Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber, array $data) @@ -18,42 +21,24 @@ use Nuwave\Lighthouse\Subscriptions\Broadcasters\PusherBroadcaster; */ class BroadcastManager extends DriverManager { - /** - * Get configuration key. - * - * @return string - */ protected function configKey(): string { return 'lighthouse.subscriptions.broadcasters'; } - /** - * Get configuration driver key. - * - * @return string - */ protected function driverKey(): string { return 'lighthouse.subscriptions.broadcaster'; } - /** - * The interface the driver should implement. - * - * @return string - */ protected function interface(): string { return Broadcaster::class; } /** - * Create instance of pusher driver. - * - * @param mixed[] $config - * @return \Nuwave\Lighthouse\Subscriptions\Broadcasters\PusherBroadcaster - * @throws \Pusher\PusherException + * @param array $config + * @throws \RuntimeException */ protected function createPusherDriver(array $config): PusherBroadcaster { @@ -71,17 +56,23 @@ class BroadcastManager extends DriverManager $pusher = new Pusher($appKey, $appSecret, $appId, $options); - return new PusherBroadcaster($pusher); + if ($driverConfig['log'] ?? false) { + $pusher->setLogger($this->app->make(LoggerInterface::class)); + } + + return new PusherBroadcaster($pusher, $this->app->make(LaravelExceptionHandler::class)); } /** - * Create instance of log driver. - * - * @param mixed[] $config - * @return \Nuwave\Lighthouse\Subscriptions\Broadcasters\LogBroadcaster + * @param array $config */ protected function createLogDriver(array $config): LogBroadcaster { return new LogBroadcaster($config); } + + protected function createEchoDriver(): EchoBroadcaster + { + return $this->app->make(EchoBroadcaster::class); + } } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/BroadcastSubscriptionJob.php b/vendor/nuwave/lighthouse/src/Subscriptions/BroadcastSubscriptionJob.php new file mode 100644 index 0000000..a8142cb --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/BroadcastSubscriptionJob.php @@ -0,0 +1,47 @@ +subscription = $subscription; + $this->fieldName = $fieldName; + $this->root = $root; + } + + public function handle(BroadcastsSubscriptions $broadcaster): void + { + $broadcaster->broadcast($this->subscription, $this->fieldName, $this->root); + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/EchoBroadcaster.php b/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/EchoBroadcaster.php new file mode 100644 index 0000000..0614b68 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/EchoBroadcaster.php @@ -0,0 +1,62 @@ +broadcaster = $broadcaster; + } + + public function broadcast(Subscriber $subscriber, $data): void + { + $this->broadcaster->event( + new EchoSubscriptionEvent($subscriber->channel, $data) + ); + } + + public function authorized(Request $request): JsonResponse + { + $userId = md5( + $request->input('channel_name') + .$request->input('socket_id') + ); + + return new JsonResponse([ + 'channel_data' => [ + 'user_id' => $userId, + 'user_info' => [], + ], + ], 200); + } + + public function unauthorized(Request $request): JsonResponse + { + return new JsonResponse([ + 'message' => 'Unauthorized', + ], 403); + } + + public function hook(Request $request): JsonResponse + { + // Does nothing. + // The redis broadcaster has the lighthouse:subscribe command to take care of cleaning vacant channels. + + return new JsonResponse([ + 'message' => 'okay', + ], 200); + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/LogBroadcaster.php b/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/LogBroadcaster.php index 186e4c8..7d7dd76 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/LogBroadcaster.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/LogBroadcaster.php @@ -2,89 +2,66 @@ namespace Nuwave\Lighthouse\Subscriptions\Broadcasters; -use Illuminate\Support\Arr; -use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; -use Nuwave\Lighthouse\Subscriptions\Subscriber; +use Illuminate\Http\Request; +use Illuminate\Support\Arr; use Nuwave\Lighthouse\Subscriptions\Contracts\Broadcaster; +use Nuwave\Lighthouse\Subscriptions\Subscriber; class LogBroadcaster implements Broadcaster { /** * The user-defined configuration options. * - * @var mixed[] + * @var array */ protected $config = []; /** * A map from channel names to data. * - * @var mixed + * @var array */ protected $broadcasts = []; /** - * @param array $config - * @return void + * @param array $config */ public function __construct(array $config = []) { $this->config = $config; } - /** - * Authorize subscription request. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\JsonResponse - */ public function authorized(Request $request): JsonResponse { - return response()->json(['message' => 'ok'], 200); + return new JsonResponse([ + 'message' => 'ok', + ], 200); } - /** - * Handle unauthorized subscription request. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\JsonResponse - */ public function unauthorized(Request $request): JsonResponse { - return response()->json(['error' => 'unauthorized'], 403); + return new JsonResponse([ + 'error' => 'unauthorized', + ], 403); } - /** - * Handle subscription web hook. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\JsonResponse - */ public function hook(Request $request): JsonResponse { - return response()->json(['message' => 'okay']); + return new JsonResponse([ + 'message' => 'okay', + ], 200); } - /** - * Send data to subscriber. - * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param array $data - * @return void - */ - public function broadcast(Subscriber $subscriber, array $data): void + public function broadcast(Subscriber $subscriber, $data): void { $this->broadcasts[$subscriber->channel] = $data; } /** - * Get the data that is being broadcast. - * - * @param string|null $key - * @return array|null + * @return mixed The data that is being broadcast */ - public function broadcasts(?string $key = null): ?array + public function broadcasts(?string $key = null) { return Arr::get($this->broadcasts, $key); } @@ -92,7 +69,7 @@ class LogBroadcaster implements Broadcaster /** * Get configuration options. * - * @return mixed[] + * @return array */ public function config(): array { diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/PusherBroadcaster.php b/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/PusherBroadcaster.php index 3e4ebcd..deaf538 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/PusherBroadcaster.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Broadcasters/PusherBroadcaster.php @@ -2,106 +2,82 @@ namespace Nuwave\Lighthouse\Subscriptions\Broadcasters; -use Illuminate\Support\Arr; -use Illuminate\Http\Request; +use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Collection; -use Nuwave\Lighthouse\Subscriptions\Subscriber; +use Illuminate\Http\Request; use Nuwave\Lighthouse\Subscriptions\Contracts\Broadcaster; use Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions; +use Nuwave\Lighthouse\Subscriptions\Subscriber; +use Pusher\ApiErrorException; +use Pusher\Pusher; class PusherBroadcaster implements Broadcaster { - const EVENT_NAME = 'lighthouse-subscription'; - /** * @var \Pusher\Pusher */ protected $pusher; + /** + * @var \Illuminate\Contracts\Debug\ExceptionHandler + */ + protected $exceptionHandler; + /** * @var \Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions */ protected $storage; - /** - * Create instance of pusher broadcaster. - * - * @param \Pusher\Pusher $pusher - * @return void - */ - public function __construct($pusher) + public function __construct(Pusher $pusher, ExceptionHandler $exceptionHandler) { $this->pusher = $pusher; + $this->exceptionHandler = $exceptionHandler; $this->storage = app(StoresSubscriptions::class); } - /** - * Authorize subscription request. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\JsonResponse - */ public function authorized(Request $request): JsonResponse { $channel = $request->input('channel_name'); $socketId = $request->input('socket_id'); - $data = json_decode( + $data = \Safe\json_decode( $this->pusher->socket_auth($channel, $socketId), true ); - return response()->json($data, 200); + return new JsonResponse($data, 200); } - /** - * Handle unauthorized subscription request. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\JsonResponse - */ public function unauthorized(Request $request): JsonResponse { - return response()->json(['error' => 'unauthorized'], 403); + return new JsonResponse([ + 'error' => 'unauthorized', + ], 403); } - /** - * Handle subscription web hook. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\JsonResponse - */ 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') - ); - }); + foreach ($request->input('events', []) as $event) { + if ($event['name'] === 'channel_vacated') { + $this->storage->deleteSubscriber($event['channel']); + } + } - return response()->json(['message' => 'okay']); + return new JsonResponse(['message' => 'okay']); } - /** - * Send data to subscriber. - * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param mixed[] $data - * @return void - */ - public function broadcast(Subscriber $subscriber, array $data): void + public function broadcast(Subscriber $subscriber, $data): void { - $this->pusher->trigger( - $subscriber->channel, - self::EVENT_NAME, - [ - 'more' => true, - 'result' => $data, - ] - ); + try { + $this->pusher->trigger( + $subscriber->channel, + self::EVENT_NAME, + [ + 'more' => true, + 'result' => $data, + ] + ); + } catch (ApiErrorException $e) { + $this->exceptionHandler->report($e); + } } } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/AuthorizesSubscriptions.php b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/AuthorizesSubscriptions.php index 06ec932..5b2d573 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/AuthorizesSubscriptions.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/AuthorizesSubscriptions.php @@ -7,9 +7,8 @@ use Illuminate\Http\Request; interface AuthorizesSubscriptions { /** - * Authorize subscription request. + * Is the subscription request authorized? * - * @param \Illuminate\Http\Request $request * @return bool */ public function authorize(Request $request); diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/Broadcaster.php b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/Broadcaster.php index 3db53ee..4e3e88f 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/Broadcaster.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/Broadcaster.php @@ -7,10 +7,11 @@ use Nuwave\Lighthouse\Subscriptions\Subscriber; interface Broadcaster { + public const EVENT_NAME = 'lighthouse-subscription'; + /** * Handle authorized subscription request. * - * @param \Illuminate\Http\Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function authorized(Request $request); @@ -18,7 +19,6 @@ interface Broadcaster /** * Handle unauthorized subscription request. * - * @param \Illuminate\Http\Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function unauthorized(Request $request); @@ -26,7 +26,6 @@ interface Broadcaster /** * Handle subscription web hook. * - * @param \Illuminate\Http\Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function hook(Request $request); @@ -34,9 +33,8 @@ interface Broadcaster /** * Send data to subscriber. * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param mixed[] $data + * @param mixed $data The data to broadcast * @return void */ - public function broadcast(Subscriber $subscriber, array $data); + public function broadcast(Subscriber $subscriber, $data); } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/BroadcastsSubscriptions.php b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/BroadcastsSubscriptions.php index d559b2d..f8031dd 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/BroadcastsSubscriptions.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/BroadcastsSubscriptions.php @@ -10,18 +10,13 @@ interface BroadcastsSubscriptions /** * Push subscription data to subscribers. * - * @param \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription $subscription - * @param string $fieldName - * @param mixed $root + * @return void */ public function broadcast(GraphQLSubscription $subscription, string $fieldName, $root); /** * Queue pushing subscription data to subscribers. * - * @param \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription $subscription - * @param string $fieldName - * @param mixed $root * @return void */ public function queueBroadcast(GraphQLSubscription $subscription, string $fieldName, $root); @@ -29,7 +24,6 @@ interface BroadcastsSubscriptions /** * Authorize the subscription. * - * @param \Illuminate\Http\Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function authorize(Request $request); diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/ContextSerializer.php b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/ContextSerializer.php index 13fcc62..ed48638 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/ContextSerializer.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/ContextSerializer.php @@ -9,7 +9,6 @@ interface ContextSerializer /** * Serialize the context. * - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context * @return string */ public function serialize(GraphQLContext $context); @@ -17,7 +16,6 @@ interface ContextSerializer /** * Unserialize the context. * - * @param string $context * @return \Nuwave\Lighthouse\Support\Contracts\GraphQLContext */ public function unserialize(string $context); diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/StoresSubscriptions.php b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/StoresSubscriptions.php index b88fea7..fae2998 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/StoresSubscriptions.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/StoresSubscriptions.php @@ -7,43 +7,29 @@ use Nuwave\Lighthouse\Subscriptions\Subscriber; interface StoresSubscriptions { /** - * Get subscriber by request. + * Find a subscriber by its channel key. * - * @param array $input - * @param array $headers - * @return \Nuwave\Lighthouse\Subscriptions\Subscriber|null - */ - public function subscriberByRequest(array $input, array $headers); - - /** - * Find subscriber by channel. - * - * @param string $channel * @return \Nuwave\Lighthouse\Subscriptions\Subscriber|null */ public function subscriberByChannel(string $channel); /** - * Get collection of subscribers by topic. + * Get all subscribers for a topic. * - * @param string $topic * @return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> */ public function subscribersByTopic(string $topic); /** - * Store subscription. + * Store subscriber for a topic. * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param string $topic * @return void */ public function storeSubscriber(Subscriber $subscriber, string $topic); /** - * Delete subscriber. + * Delete subscriber by its channel key. * - * @param string $channel * @return \Nuwave\Lighthouse\Subscriptions\Subscriber|null */ public function deleteSubscriber(string $channel); diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionExceptionHandler.php b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionExceptionHandler.php index 2ffd6fa..1db041a 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionExceptionHandler.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionExceptionHandler.php @@ -9,7 +9,6 @@ interface SubscriptionExceptionHandler /** * Handle authentication error. * - * @param \Throwable $e * @return void */ public function handleAuthError(Throwable $e); @@ -17,7 +16,6 @@ interface SubscriptionExceptionHandler /** * Handle broadcast error. * - * @param \Throwable $e * @return void */ public function handleBroadcastError(Throwable $e); diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionIterator.php b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionIterator.php index 7bc1551..4af7f19 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionIterator.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Contracts/SubscriptionIterator.php @@ -8,12 +8,18 @@ use Illuminate\Support\Collection; interface SubscriptionIterator { /** - * Process collection of items. + * Process subscribers through the given callbacks. * - * @param \Illuminate\Support\Collection $items - * @param \Closure $cb - * @param \Closure|null $error + * @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> $subscribers + * The subscribers that receive the current subscription. + * + * @param \Closure $handleSubscriber + * Receives each subscriber in the passed in collection. + * function(\Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber) + * + * @param \Closure|null $handleError + * Is called when $handleSubscriber throws. * @return void */ - public function process(Collection $items, Closure $cb, Closure $error = null); + public function process(Collection $subscribers, Closure $handleSubscriber, Closure $handleError = null); } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Directives/BroadcastDirective.php b/vendor/nuwave/lighthouse/src/Subscriptions/Directives/BroadcastDirective.php new file mode 100644 index 0000000..7b30da2 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Directives/BroadcastDirective.php @@ -0,0 +1,50 @@ +directiveArgValue('subscription'); + $shouldQueue = $this->directiveArgValue('shouldQueue'); + + $fieldValue->resultHandler(function ($root) use ($subscriptionField, $shouldQueue) { + Subscription::broadcast($subscriptionField, $root, $shouldQueue); + + return $root; + }); + + return $fieldValue; + } +} diff --git a/vendor/nuwave/lighthouse/src/Schema/Directives/SubscriptionDirective.php b/vendor/nuwave/lighthouse/src/Subscriptions/Directives/SubscriptionDirective.php similarity index 60% rename from vendor/nuwave/lighthouse/src/Schema/Directives/SubscriptionDirective.php rename to vendor/nuwave/lighthouse/src/Subscriptions/Directives/SubscriptionDirective.php index b4b0e9e..77117a1 100644 --- a/vendor/nuwave/lighthouse/src/Schema/Directives/SubscriptionDirective.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Directives/SubscriptionDirective.php @@ -1,9 +1,9 @@ subscription = $subscription; - $this->fieldName = $fieldName; - $this->root = $root; - } -} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Events/BroadcastSubscriptionListener.php b/vendor/nuwave/lighthouse/src/Subscriptions/Events/BroadcastSubscriptionListener.php deleted file mode 100644 index 071d346..0000000 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Events/BroadcastSubscriptionListener.php +++ /dev/null @@ -1,38 +0,0 @@ -broadcaster = $broadcaster; - } - - /** - * Handle the event. - * - * @param \Nuwave\Lighthouse\Subscriptions\Events\BroadcastSubscriptionEvent $event - * @return void - */ - public function handle(BroadcastSubscriptionEvent $event): void - { - $this->broadcaster->broadcast( - $event->subscription, - $event->fieldName, - $event->root - ); - } -} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Events/EchoSubscriptionEvent.php b/vendor/nuwave/lighthouse/src/Subscriptions/Events/EchoSubscriptionEvent.php new file mode 100644 index 0000000..ab8081f --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Events/EchoSubscriptionEvent.php @@ -0,0 +1,44 @@ +channel = $channel; + $this->data = $data; + } + + public function broadcastOn(): Channel + { + return new Channel($this->channel); + } + + /** + * Returns an event name. + * + * Allows the echo client to receive this event using .listen('.lighthouse.subscription', () => ...). + */ + public function broadcastAs(): string + { + return Broadcaster::EVENT_NAME; + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/ExceptionHandler.php b/vendor/nuwave/lighthouse/src/Subscriptions/ExceptionHandler.php index ff7f5a4..90dddd7 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/ExceptionHandler.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/ExceptionHandler.php @@ -2,16 +2,13 @@ namespace Nuwave\Lighthouse\Subscriptions; -use Throwable; use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionExceptionHandler; +use Throwable; class ExceptionHandler implements SubscriptionExceptionHandler { /** * Handle authentication error. - * - * @param \Throwable $e - * @return void */ public function handleAuthError(Throwable $e): void { @@ -20,9 +17,6 @@ class ExceptionHandler implements SubscriptionExceptionHandler /** * Handle broadcast error. - * - * @param \Throwable $e - * @return void */ public function handleBroadcastError(Throwable $e): void { diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php b/vendor/nuwave/lighthouse/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php new file mode 100644 index 0000000..afc76ca --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Iterators/AuthenticatingSyncIterator.php @@ -0,0 +1,70 @@ +configRepository = $configRepository; + $this->authFactory = $authFactory; + } + + public function process(Collection $subscribers, Closure $handleSubscriber, Closure $handleError = null): void + { + // Store the previous default guard name so we can restore it after we're done + $previousGuardName = $this->configRepository->get('auth.defaults.guard'); + + // Set our subscription guard as the default guard for the application + $this->authFactory->shouldUse(SubscriptionGuard::GUARD_NAME); + + /** @var \Nuwave\Lighthouse\Subscriptions\SubscriptionGuard $guard */ + $guard = $this->authFactory->guard(SubscriptionGuard::GUARD_NAME); + + $subscribers->each(static function (Subscriber $item) use ($handleSubscriber, $handleError, $guard): void { + // If there is an authenticated user set in the context, set that user as the authenticated user + $user = $item->context->user(); + if ($user !== null) { + $guard->setUser($user); + } + + try { + $handleSubscriber($item); + } catch (Exception $e) { + if ($handleError === null) { + throw $e; + } + + $handleError($e); + } finally { + // Unset the authenticated user after each iteration to restore the guard to a unauthenticated state + $guard->reset(); + } + }); + + // Restore the previous default guard name + $this->authFactory->shouldUse($previousGuardName); + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Iterators/SyncIterator.php b/vendor/nuwave/lighthouse/src/Subscriptions/Iterators/SyncIterator.php index 54ed695..bab81e2 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Iterators/SyncIterator.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Iterators/SyncIterator.php @@ -9,25 +9,17 @@ use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator; class SyncIterator implements SubscriptionIterator { - /** - * Process collection of items. - * - * @param \Illuminate\Support\Collection $items - * @param \Closure $cb - * @param \Closure|null $error - * @return void - */ - public function process(Collection $items, Closure $cb, Closure $error = null): void + public function process(Collection $subscribers, Closure $handleSubscriber, Closure $handleError = null): void { - $items->each(function ($item) use ($cb, $error): void { + $subscribers->each(static function ($item) use ($handleSubscriber, $handleError): void { try { - $cb($item); + $handleSubscriber($item); } catch (Exception $e) { - if (! $error) { + if ($handleError === null) { throw $e; } - $error($e); + $handleError($e); } }); } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Serializer.php b/vendor/nuwave/lighthouse/src/Subscriptions/Serializer.php index ce6c416..cc5433f 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Serializer.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Serializer.php @@ -2,34 +2,27 @@ namespace Nuwave\Lighthouse\Subscriptions; -use Illuminate\Support\Arr; use Illuminate\Http\Request; +use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; +use Illuminate\Support\Arr; +use Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer; use Nuwave\Lighthouse\Support\Contracts\CreatesContext; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer; class Serializer implements ContextSerializer { + use SerializesAndRestoresModelIdentifiers; + /** * @var \Nuwave\Lighthouse\Support\Contracts\CreatesContext */ protected $createsContext; - /** - * @param \Nuwave\Lighthouse\Support\Contracts\CreatesContext $createsContext - * @return void - */ public function __construct(CreatesContext $createsContext) { $this->createsContext = $createsContext; } - /** - * Serialize the context. - * - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @return string - */ public function serialize(GraphQLContext $context): string { $request = $context->request(); @@ -44,16 +37,10 @@ class Serializer implements ContextSerializer 'server' => Arr::except($request->server->all(), ['HTTP_AUTHORIZATION']), 'content' => $request->getContent(), ], - 'user' => serialize($context->user()), + 'user' => $this->getSerializedPropertyValue($context->user()), ]); } - /** - * Unserialize the context. - * - * @param string $context - * @return \Nuwave\Lighthouse\Support\Contracts\GraphQLContext - */ public function unserialize(string $context): GraphQLContext { [ @@ -73,7 +60,7 @@ class Serializer implements ContextSerializer $request->setUserResolver( function () use ($rawUser) { - return unserialize($rawUser); + return $this->getRestoredPropertyValue($rawUser); } ); diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Storage/CacheStorageManager.php b/vendor/nuwave/lighthouse/src/Subscriptions/Storage/CacheStorageManager.php new file mode 100644 index 0000000..5908247 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Storage/CacheStorageManager.php @@ -0,0 +1,170 @@ +get('lighthouse.subscriptions.storage') ?? 'file'; + if (! is_string($storage)) { + throw new Exception('Config setting lighthouse.subscriptions.storage must be a string or `null`, got: '.\Safe\json_encode($storage)); + } + $this->cache = $cacheFactory->store($storage); + + $ttl = $config->get('lighthouse.subscriptions.storage_ttl'); + if (! is_null($ttl) && ! is_int($ttl)) { + throw new Exception('Config setting lighthouse.subscriptions.storage_ttl must be a int or `null`, got: '.\Safe\json_encode($ttl)); + } + $this->ttl = $ttl; + } + + public function subscriberByChannel(string $channel): ?Subscriber + { + return $this->cache->get(self::channelKey($channel)); + } + + public function subscribersByTopic(string $topic): Collection + { + /** @var \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> $subscribers */ + $subscribers = $this + ->retrieveTopic(self::topicKey($topic)) + ->map(function (string $channel): ?Subscriber { + return $this->subscriberByChannel($channel); + }) + ->filter(); + + return $subscribers; + } + + public function storeSubscriber(Subscriber $subscriber, string $topic): void + { + $subscriber->topic = $topic; + $this->addSubscriberToTopic($subscriber); + + $channelKey = self::channelKey($subscriber->channel); + if ($this->ttl === null) { + $this->cache->forever($channelKey, $subscriber); + } else { + // TODO: Change to just pass the ttl directly when support for Laravel <=5.7 is dropped + $this->cache->put($channelKey, $subscriber, Carbon::now()->addSeconds($this->ttl)); + } + } + + public function deleteSubscriber(string $channel): ?Subscriber + { + $subscriber = $this->cache->pull(self::channelKey($channel)); + + if ($subscriber !== null) { + $this->removeSubscriberFromTopic($subscriber); + } + + return $subscriber; + } + + /** + * Store a topic (list of channels) in the cache. + * + * @param \Illuminate\Support\Collection $topic + */ + protected function storeTopic(string $key, Collection $topic): void + { + if ($this->ttl === null) { + $this->cache->forever($key, $topic); + } else { + // TODO: Change to just pass the ttl directly when support for Laravel <=5.7 is dropped + $this->cache->put($key, $topic, Carbon::now()->addSeconds($this->ttl)); + } + } + + /** + * Retrieve a topic (list of channels) from the cache. + * + * @return \Illuminate\Support\Collection + */ + protected function retrieveTopic(string $key): Collection + { + return $this->cache->get($key, new Collection()); + } + + /** + * Add the subscriber to the topic they subscribe to. + */ + protected function addSubscriberToTopic(Subscriber $subscriber): void + { + $topicKey = self::topicKey($subscriber->topic); + + $topic = $this->retrieveTopic($topicKey); + $topic->push($subscriber->channel); + $this->storeTopic($topicKey, $topic); + } + + /** + * Remove the subscriber from the topic they are subscribed to. + */ + protected function removeSubscriberFromTopic(Subscriber $subscriber): void + { + $topicKey = self::topicKey($subscriber->topic); + $channelKeyToRemove = self::channelKey($subscriber->channel); + + $topicWithoutSubscriber = $this + ->retrieveTopic($topicKey) + ->reject(function (string $channel) use ($channelKeyToRemove): bool { + return self::channelKey($channel) === $channelKeyToRemove; + }); + + if ($topicWithoutSubscriber->isEmpty()) { + $this->cache->forget($topicKey); + + return; + } + + $this->storeTopic($topicKey, $topicWithoutSubscriber); + } + + protected static function channelKey(string $channel): string + { + return self::SUBSCRIBER_KEY.".{$channel}"; + } + + protected static function topicKey(string $topic): string + { + return self::TOPIC_KEY.".{$topic}"; + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Storage/RedisStorageManager.php b/vendor/nuwave/lighthouse/src/Subscriptions/Storage/RedisStorageManager.php new file mode 100644 index 0000000..adddf07 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Storage/RedisStorageManager.php @@ -0,0 +1,184 @@ +connection = $redis->connection( + $config->get('lighthouse.subscriptions.broadcasters.echo.connection') ?? 'default' + ); + $this->ttl = $config->get('lighthouse.subscriptions.storage_ttl'); + } + + public function subscriberByChannel(string $channel): ?Subscriber + { + return $this->getSubscriber( + $this->channelKey($channel) + ); + } + + /** + * @return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> + */ + public function subscribersByTopic(string $topic): Collection + { + // As explained in storeSubscriber, we use redis sets to store the names of subscribers of a topic. + // We can retrieve all members of a set using the command smembers. + $subscriberIds = $this->connection->command('smembers', [$this->topicKey($topic)]); + if (count($subscriberIds) === 0) { + return new Collection(); + } + + // Since we store the individual subscribers with a prefix, + // but not in the set, we have to add the prefix here. + $subscriberIds = array_map([$this, 'channelKey'], $subscriberIds); + + // Using the mget command, we can retrieve multiple values from redis. + // This is like using multiple get calls (getSubscriber uses the get command). + $subscribers = $this->connection->command('mget', [$subscriberIds]); + + return (new Collection($subscribers)) + ->map(function (string $subscriber) { + return $this->unserialize($subscriber); + }) + ->filter(); + } + + public function storeSubscriber(Subscriber $subscriber, string $topic): void + { + $subscriber->topic = $topic; + + // In contrast to the CacheStorageManager, we use redis sets. + // Instead of reading the entire list, adding the subscriber and storing the list; + // we simply add the name of the subscriber to the set of subscribers of this topic using the sadd command... + $topicKey = $this->topicKey($topic); + $this->connection->command('sadd', [ + $topicKey, + $subscriber->channel, + ]); + // ...and refresh the ttl of this set as well. + if ($this->ttl !== null) { + $this->connection->command('expire', [$topicKey, $this->ttl]); + } + + // Lastly, we store the subscriber as a serialized string... + $setCommand = 'set'; + $setArguments = [ + $this->channelKey($subscriber->channel), + $this->serialize($subscriber), + ]; + if ($this->ttl !== null) { + $setCommand = 'setex'; + array_splice($setArguments, 1, 0, [$this->ttl]); + } + $this->connection->command($setCommand, $setArguments); + } + + public function deleteSubscriber(string $channel): ?Subscriber + { + $key = $this->channelKey($channel); + $subscriber = $this->getSubscriber($key); + + if ($subscriber !== null) { + // Like in storeSubscriber (but in reverse), we delete the subscriber... + $this->connection->command('del', [$key]); + // ...and remove it from the set of subscribers of this topic. + $this->connection->command('srem', [ + $this->topicKey($subscriber->topic), + $channel, + ]); + } + + return $subscriber; + } + + protected function getSubscriber(string $channelKey): ?Subscriber + { + $subscriber = $this->unserialize( + $this->connection->command('get', [$channelKey]) + ); + + // unserialize could return false, so we make sure to only return a Subscriber or null + if ($subscriber instanceof Subscriber) { + return $subscriber; + } + + return null; + } + + protected function channelKey(string $channel): string + { + return self::SUBSCRIBER_KEY.'.'.$channel; + } + + protected function topicKey(string $topic): string + { + return self::TOPIC_KEY.'.'.$topic; + } + + /** + * @param mixed $value Value to serialize. + * @return mixed Storable value. + * @see \Illuminate\Cache\RedisStore::serialize + */ + protected function serialize($value) + { + $isProperNumber = is_numeric($value) + && ($value !== INF && $value !== -INF) + && ! is_nan(floatval($value)); + + return $isProperNumber + ? $value + : serialize($value); + } + + /** + * @param mixed $value Value to unserialize. + * @return mixed Unserialized value. + */ + protected function unserialize($value) + { + if (false === $value) { + return null; + } + + return is_numeric($value) + ? $value + : unserialize($value); + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/StorageManager.php b/vendor/nuwave/lighthouse/src/Subscriptions/StorageManager.php deleted file mode 100644 index 83c9b10..0000000 --- a/vendor/nuwave/lighthouse/src/Subscriptions/StorageManager.php +++ /dev/null @@ -1,136 +0,0 @@ -cache = $cacheManager->store( - config('lighthouse.subscriptions.storage', 'redis') - ); - } - - /** - * Get subscriber by request. - * - * @param array $input - * @param array $headers - * @return \Nuwave\Lighthouse\Subscriptions\Subscriber|null - */ - public function subscriberByRequest(array $input, array $headers): ?Subscriber - { - $channel = Arr::get($input, 'channel_name'); - - return $channel - ? $this->subscriberByChannel($channel) - : null; - } - - /** - * Find subscriber by channel. - * - * @param string $channel - * @return \Nuwave\Lighthouse\Subscriptions\Subscriber|null - */ - public function subscriberByChannel(string $channel): ?Subscriber - { - $key = self::SUBSCRIBER_KEY.".{$channel}"; - - return $this->cache->get($key); - } - - /** - * Get collection of subscribers by channel. - * - * @param string $topic - * @return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Subscriptions\Subscriber> - */ - public function subscribersByTopic(string $topic): Collection - { - $key = self::TOPIC_KEY.".{$topic}"; - - if (! $this->cache->has($key)) { - return new Collection; - } - - $channels = json_decode($this->cache->get($key), true); - - return (new Collection($channels)) - ->map(function (string $channel): ?Subscriber { - return $this->subscriberByChannel($channel); - }) - ->filter() - ->values(); - } - - /** - * Store subscription. - * - * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param string $topic - * @return void - */ - public function storeSubscriber(Subscriber $subscriber, string $topic): void - { - $topicKey = self::TOPIC_KEY.".{$topic}"; - $subscriberKey = self::SUBSCRIBER_KEY.".{$subscriber->channel}"; - - $topic = $this->cache->has($topicKey) - ? json_decode($this->cache->get($topicKey), true) - : []; - - $topic[] = $subscriber->channel; - - $this->cache->forever($topicKey, json_encode($topic)); - $this->cache->forever($subscriberKey, $subscriber); - } - - /** - * Delete subscriber. - * - * @param string $channel - * @return \Nuwave\Lighthouse\Subscriptions\Subscriber|null - */ - public function deleteSubscriber(string $channel): ?Subscriber - { - $key = self::SUBSCRIBER_KEY.".{$channel}"; - $hasSubscriber = $this->cache->has($key); - - $subscriber = $this->cache->get($key); - - if ($hasSubscriber) { - $this->cache->forget($key); - } - - return $subscriber; - } -} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/Subscriber.php b/vendor/nuwave/lighthouse/src/Subscriptions/Subscriber.php index ba2d36e..d2c4a27 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/Subscriber.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/Subscriber.php @@ -2,126 +2,160 @@ namespace Nuwave\Lighthouse\Subscriptions; -use Serializable; +use GraphQL\Language\AST\DocumentNode; +use GraphQL\Language\AST\NodeList; +use GraphQL\Type\Definition\ResolveInfo; use GraphQL\Utils\AST; use Illuminate\Support\Str; -use GraphQL\Language\AST\DocumentNode; -use GraphQL\Type\Definition\ResolveInfo; -use Nuwave\Lighthouse\Exceptions\SubscriptionException; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; use Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Serializable; class Subscriber implements Serializable { - const MISSING_OPERATION_NAME = 'Must pass an operation name when using a subscription.'; - /** + * A unique key for the subscriber's channel. + * + * This has to be unique for each subscriber, because each of them can send a different + * query and must receive a response that is specifically tailored towards that. + * * @var string */ public $channel; /** - * @var mixed + * The topic subscribed to. + * + * @var string */ - public $root; - - /** - * @var array - */ - public $args; - - /** - * @var mixed - */ - public $context; + public $topic; /** + * The contents of the query. + * * @var \GraphQL\Language\AST\DocumentNode */ public $query; /** + * The name of the queried field. + * + * Guaranteed be be unique because of + * @see \GraphQL\Validator\Rules\SingleFieldSubscription + * * @var string */ - public $operationName; + public $fieldName; /** - * @param mixed[] $args - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return void + * The root element of the query. * - * @throws \Nuwave\Lighthouse\Exceptions\SubscriptionException + * @var mixed Can be anything. + */ + public $root; + + /** + * The args passed to the subscription query. + * + * @var array + */ + public $args; + + /** + * The variables passed to the subscription query. + * + * @var array + */ + public $variables; + + /** + * The context passed to the query. + * + * @var \Nuwave\Lighthouse\Support\Contracts\GraphQLContext + */ + public $context; + + /** + * @param array $args */ public function __construct( array $args, GraphQLContext $context, ResolveInfo $resolveInfo ) { - $operationName = $resolveInfo->operation->name; - if (! $operationName) { - throw new SubscriptionException( - self::MISSING_OPERATION_NAME - ); - } - $this->operationName = $operationName->value; - + $this->fieldName = $resolveInfo->fieldName; $this->channel = self::uniqueChannelName(); $this->args = $args; + $this->variables = $resolveInfo->variableValues; $this->context = $context; - $documentNode = new DocumentNode([]); - $documentNode->definitions = $resolveInfo->fragments; - $documentNode->definitions[] = $resolveInfo->operation; - $this->query = $documentNode; + /** + * Must be here, since webonyx/graphql-php validated the subscription. + * + * @var \GraphQL\Language\AST\OperationDefinitionNode $operation + */ + $operation = $resolveInfo->operation; + + $this->query = new DocumentNode([ + 'definitions' => new NodeList(array_merge( + $resolveInfo->fragments, + [$operation] + )), + ]); } /** * Unserialize subscription from a JSON string. * * @param string $subscription - * @return $this */ - public function unserialize($subscription): self + public function unserialize($subscription): void { - $data = json_decode($subscription, true); + $data = \Safe\json_decode($subscription, true); - $this->operationName = $data['operation_name']; $this->channel = $data['channel']; + $this->topic = $data['topic']; + + /** + * We know the type since it is set during construction and serialized. + * + * @var \GraphQL\Language\AST\DocumentNode $documentNode + */ + $documentNode = AST::fromArray( + unserialize($data['query']) + ); + $this->query = $documentNode; + $this->fieldName = $data['field_name']; $this->args = $data['args']; + $this->variables = $data['variables']; $this->context = $this->contextSerializer()->unserialize( $data['context'] ); - $this->query = AST::fromArray( - unserialize($data['query']) - ); - - return $this; } /** * Convert this into a JSON string. - * - * @return false|string */ - public function serialize() + public function serialize(): string { - return json_encode([ - 'operation_name' => $this->operationName, + return \Safe\json_encode([ 'channel' => $this->channel, - 'args' => $this->args, - 'context' => $this->contextSerializer()->serialize($this->context), + 'topic' => $this->topic, 'query' => serialize( AST::toArray($this->query) ), + 'field_name' => $this->fieldName, + 'args' => $this->args, + 'variables' => $this->variables, + 'context' => $this->contextSerializer()->serialize($this->context), ]); } /** * Set root data. * - * @param mixed $root * @return $this + * @deprecated set the attribute directly */ public function setRoot($root): self { @@ -132,17 +166,12 @@ class Subscriber implements Serializable /** * Generate a unique private channel name. - * - * @return string */ public static function uniqueChannelName(): string { return 'private-lighthouse-'.Str::random(32).'-'.time(); } - /** - * @return \Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer - */ protected function contextSerializer(): ContextSerializer { return app(ContextSerializer::class); diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionBroadcaster.php b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionBroadcaster.php index edd836a..7275ec7 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionBroadcaster.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionBroadcaster.php @@ -2,15 +2,15 @@ namespace Nuwave\Lighthouse\Subscriptions; +use Illuminate\Contracts\Bus\Dispatcher as BusDispatcher; use Illuminate\Http\Request; use Nuwave\Lighthouse\GraphQL; -use Symfony\Component\HttpFoundation\Response; use Nuwave\Lighthouse\Schema\Types\GraphQLSubscription; -use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; -use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator; use Nuwave\Lighthouse\Subscriptions\Contracts\AuthorizesSubscriptions; use Nuwave\Lighthouse\Subscriptions\Contracts\BroadcastsSubscriptions; -use Nuwave\Lighthouse\Subscriptions\Events\BroadcastSubscriptionEvent; +use Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions; +use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator; +use Symfony\Component\HttpFoundation\Response; class SubscriptionBroadcaster implements BroadcastsSubscriptions { @@ -22,17 +22,17 @@ class SubscriptionBroadcaster implements BroadcastsSubscriptions /** * @var \Nuwave\Lighthouse\Subscriptions\Contracts\AuthorizesSubscriptions */ - protected $auth; + protected $subscriptionAuthorizer; /** - * @var \Nuwave\Lighthouse\Subscriptions\StorageManager + * @var \Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions */ - protected $storage; + protected $subscriptionStorage; /** * @var \Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator */ - protected $iterator; + protected $subscriptionIterator; /** * @var \Nuwave\Lighthouse\Subscriptions\BroadcastManager @@ -40,96 +40,67 @@ class SubscriptionBroadcaster implements BroadcastsSubscriptions protected $broadcastManager; /** - * @var \Illuminate\Contracts\Events\Dispatcher + * @var \Illuminate\Contracts\Bus\Dispatcher */ - protected $eventsDispatcher; + protected $busDispatcher; - /** - * @param \Nuwave\Lighthouse\GraphQL $graphQL - * @param \Nuwave\Lighthouse\Subscriptions\Contracts\AuthorizesSubscriptions $auth - * @param \Nuwave\Lighthouse\Subscriptions\StorageManager $storage - * @param \Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator $iterator - * @param \Nuwave\Lighthouse\Subscriptions\BroadcastManager $broadcastManager - * @param \Illuminate\Contracts\Events\Dispatcher $eventsDispatcher - * @return void - */ public function __construct( GraphQL $graphQL, - AuthorizesSubscriptions $auth, - StorageManager $storage, - SubscriptionIterator $iterator, + AuthorizesSubscriptions $subscriptionAuthorizer, + StoresSubscriptions $subscriptionStorage, + SubscriptionIterator $subscriptionIterator, BroadcastManager $broadcastManager, - EventsDispatcher $eventsDispatcher + BusDispatcher $busDispatcher ) { $this->graphQL = $graphQL; - $this->auth = $auth; - $this->storage = $storage; - $this->iterator = $iterator; + $this->subscriptionAuthorizer = $subscriptionAuthorizer; + $this->subscriptionStorage = $subscriptionStorage; + $this->subscriptionIterator = $subscriptionIterator; $this->broadcastManager = $broadcastManager; - $this->eventsDispatcher = $eventsDispatcher; + $this->busDispatcher = $busDispatcher; } - /** - * Queue pushing subscription data to subscribers. - * - * @param \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription $subscription - * @param string $fieldName - * @param mixed $root - * @return void - */ public function queueBroadcast(GraphQLSubscription $subscription, string $fieldName, $root): void { - $this->eventsDispatcher->dispatch( - new BroadcastSubscriptionEvent($subscription, $fieldName, $root) - ); + $broadcastSubscriptionJob = new BroadcastSubscriptionJob($subscription, $fieldName, $root); + $broadcastSubscriptionJob->onQueue(config('lighthouse.subscriptions.broadcasts_queue_name')); + + $this->busDispatcher->dispatch($broadcastSubscriptionJob); } - /** - * Push subscription data to subscribers. - * - * @param \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription $subscription - * @param string $fieldName - * @param mixed $root - * @return void - */ public function broadcast(GraphQLSubscription $subscription, string $fieldName, $root): void { $topic = $subscription->decodeTopic($fieldName, $root); - $subscribers = $this->storage + $subscribers = $this->subscriptionStorage ->subscribersByTopic($topic) ->filter(function (Subscriber $subscriber) use ($subscription, $root): bool { return $subscription->filter($subscriber, $root); }); - $this->iterator->process( + $this->subscriptionIterator->process( $subscribers, function (Subscriber $subscriber) use ($root): void { - $data = $this->graphQL->executeQuery( + $subscriber->root = $root; + + $executionResult = $this->graphQL->executeQuery( $subscriber->query, $subscriber->context, - $subscriber->args, - $subscriber->setRoot($root), - $subscriber->operationName + $subscriber->variables, + $subscriber ); $this->broadcastManager->broadcast( $subscriber, - $data->jsonSerialize() + $this->graphQL->serializable($executionResult) ); } ); } - /** - * Authorize the subscription. - * - * @param \Illuminate\Http\Request $request - * @return \Symfony\Component\HttpFoundation\Response - */ public function authorize(Request $request): Response { - return $this->auth->authorize($request) + return $this->subscriptionAuthorizer->authorize($request) ? $this->broadcastManager->authorized($request) : $this->broadcastManager->unauthorized($request); } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionController.php b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionController.php new file mode 100644 index 0000000..04196f0 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionController.php @@ -0,0 +1,20 @@ +authorize($request); + } + + public function webhook(Request $request, BroadcastManager $broadcastManager): Response + { + return $broadcastManager->hook($request); + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionGuard.php b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionGuard.php new file mode 100644 index 0000000..36327bf --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionGuard.php @@ -0,0 +1,40 @@ +user; + } + + public function reset(): void + { + $this->user = null; + } + + /** + * @param array $credentials + */ + public function validate(array $credentials = []): bool + { + throw new RuntimeException('The Lighthouse subscription guard cannot be used for credential based authentication.'); + } +} diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRegistry.php b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRegistry.php index ed482bb..1d20207 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRegistry.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRegistry.php @@ -2,17 +2,21 @@ namespace Nuwave\Lighthouse\Subscriptions; -use Illuminate\Support\Arr; -use GraphQL\Language\AST\Node; -use Nuwave\Lighthouse\GraphQL; -use Illuminate\Support\Collection; use GraphQL\Language\AST\FieldNode; -use Nuwave\Lighthouse\Events\StartExecution; use GraphQL\Language\AST\OperationDefinitionNode; +use GraphQL\Type\Definition\ObjectType; +use Illuminate\Contracts\Config\Repository as ConfigRepository; +use Illuminate\Support\Collection; +use Nuwave\Lighthouse\Events\BuildExtensionsResponse; +use Nuwave\Lighthouse\Events\StartExecution; +use Nuwave\Lighthouse\Exceptions\DefinitionException; use Nuwave\Lighthouse\Execution\ExtensionsResponse; +use Nuwave\Lighthouse\Schema\SchemaBuilder; use Nuwave\Lighthouse\Schema\Types\GraphQLSubscription; use Nuwave\Lighthouse\Schema\Types\NotFoundSubscription; use Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer; +use Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions; +use Nuwave\Lighthouse\Support\Utils; class SubscriptionRegistry { @@ -22,47 +26,45 @@ class SubscriptionRegistry protected $serializer; /** - * @var \Nuwave\Lighthouse\Subscriptions\StorageManager + * @var \Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions */ protected $storage; /** - * @var \Nuwave\Lighthouse\GraphQL + * @var \Nuwave\Lighthouse\Schema\SchemaBuilder */ - protected $graphQL; + protected $schemaBuilder; + + /** + * @var \Illuminate\Contracts\Config\Repository + */ + protected $configRepository; /** * A map from operation names to channel names. * - * @var string[] + * @var array */ protected $subscribers = []; /** * Active subscription fields of the schema. * - * @var \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription[] + * @var array */ protected $subscriptions = []; - /** - * @param \Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer $serializer - * @param \Nuwave\Lighthouse\Subscriptions\StorageManager $storage - * @param \Nuwave\Lighthouse\GraphQL $graphQL - * @return void - */ - public function __construct(ContextSerializer $serializer, StorageManager $storage, GraphQL $graphQL) + public function __construct(ContextSerializer $serializer, StoresSubscriptions $storage, SchemaBuilder $schemaBuilder, ConfigRepository $configRepository) { $this->serializer = $serializer; $this->storage = $storage; - $this->graphQL = $graphQL; + $this->schemaBuilder = $schemaBuilder; + $this->configRepository = $configRepository; } /** * Add subscription to registry. * - * @param \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription $subscription - * @param string $field * @return $this */ public function register(GraphQLSubscription $subscription, string $field): self @@ -74,33 +76,44 @@ class SubscriptionRegistry /** * Check if subscription is registered. - * - * @param string $key - * @return bool */ public function has(string $key): bool { - return isset($this->subscriptions[$key]); + if (isset($this->subscriptions[$key])) { + return true; + } + + return $this->subscriptionType()->hasField($key); } /** * Get subscription keys. * - * @return string[] + * @return array + * + * @deprecated Use the `GraphQL\Type\Schema::subscriptionType()->getFieldNames()` method directly. */ public function keys(): array { - return array_keys($this->subscriptions); + return $this->subscriptionType()->getFieldNames(); } /** * Get instance of subscription. - * - * @param string $key - * @return \Nuwave\Lighthouse\Schema\Types\GraphQLSubscription */ public function subscription(string $key): GraphQLSubscription { + if (! isset($this->subscriptions[$key])) { + /** + * Loading the field has the side effect of triggering a call to. + * @see \Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver::provideSubscriptionResolver() + * which is then expected to call @see register(). + * + * TODO make this more explicit and safe + */ + $this->subscriptionType()->getField($key); + } + return $this->subscriptions[$key]; } @@ -108,16 +121,12 @@ class SubscriptionRegistry * Add subscription to registry. * * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @param string $channel * @return $this */ - public function subscriber(Subscriber $subscriber, string $channel): self + public function subscriber(Subscriber $subscriber, string $topic): self { - if ($subscriber->channel) { - $this->storage->storeSubscriber($subscriber, $channel); - } - - $this->subscribers[$subscriber->operationName] = $subscriber->channel; + $this->storage->storeSubscriber($subscriber, $topic); + $this->subscribers[$subscriber->fieldName] = $subscriber->channel; return $this; } @@ -126,18 +135,14 @@ class SubscriptionRegistry * Get registered subscriptions. * * @param \Nuwave\Lighthouse\Subscriptions\Subscriber $subscriber - * @return \Illuminate\Support\Collection + * @return \Illuminate\Support\Collection<\Nuwave\Lighthouse\Schema\Types\GraphQLSubscription> */ public function subscriptions(Subscriber $subscriber): Collection { - // A subscription can be fired w/out a request so we must make - // sure the schema has been generated. - $this->graphQL->prepSchema(); - return (new Collection($subscriber->query->definitions)) - ->filter(function (Node $node): bool { - return $node instanceof OperationDefinitionNode; - }) + ->filter( + Utils::instanceofMatcher(OperationDefinitionNode::class) + ) ->filter(function (OperationDefinitionNode $node): bool { return $node->operation === 'subscription'; }) @@ -148,39 +153,65 @@ class SubscriptionRegistry }) ->all(); }) - ->map(function ($subscriptionField): GraphQLSubscription { - return Arr::get( - $this->subscriptions, - $subscriptionField, - new NotFoundSubscription - ); + ->map(function (string $subscriptionField): GraphQLSubscription { + if ($this->has($subscriptionField)) { + return $this->subscription($subscriptionField); + } + + return new NotFoundSubscription; }); } /** * Reset the collection of subscribers when a new execution starts. - * - * @param \Nuwave\Lighthouse\Events\StartExecution $startExecution - * @return void */ public function handleStartExecution(StartExecution $startExecution): void { $this->subscribers = []; } - /** - * Get all current subscribers. - * - * @return \Nuwave\Lighthouse\Execution\ExtensionsResponse - */ - public function handleBuildExtensionsResponse(): ExtensionsResponse + public function handleBuildExtensionsResponse(BuildExtensionsResponse $buildExtensionsResponse): ?ExtensionsResponse { - return new ExtensionsResponse( - 'lighthouse_subscriptions', - [ - 'version' => 1, - 'channels' => $this->subscribers, - ] - ); + $subscriptionsConfig = $this->configRepository->get('lighthouse.subscriptions'); + + $channel = count($this->subscribers) > 0 + ? reset($this->subscribers) + : null; + + if ($channel === null && ($subscriptionsConfig['exclude_empty'] ?? false)) { + return null; + } + + $version = $subscriptionsConfig['version'] ?? 1; + switch ((int) $version) { + case 1: + $content = [ + 'version' => 1, + 'channel' => $channel, + 'channels' => $this->subscribers, + ]; + break; + case 2: + $content = [ + 'version' => 2, + 'channel' => $channel, + ]; + break; + default: + throw new DefinitionException("Expected lighthouse.subscriptions.version to be 1 or 2, got: {$version}"); + } + + return new ExtensionsResponse('lighthouse_subscriptions', $content); + } + + protected function subscriptionType(): ObjectType + { + $subscriptionType = $this->schemaBuilder->schema()->getSubscriptionType(); + + if ($subscriptionType === null) { + throw new DefinitionException('Schema is missing subscription root type.'); + } + + return $subscriptionType; } } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionResolverProvider.php b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionResolverProvider.php index 742a1e8..bfc1ea0 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionResolverProvider.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionResolverProvider.php @@ -3,17 +3,17 @@ namespace Nuwave\Lighthouse\Subscriptions; use Closure; -use Illuminate\Support\Str; -use Nuwave\Lighthouse\Support\Utils; use GraphQL\Type\Definition\ResolveInfo; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; -use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Illuminate\Support\Str; use Nuwave\Lighthouse\Exceptions\DefinitionException; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; use Nuwave\Lighthouse\Schema\Types\GraphQLSubscription; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -use Nuwave\Lighthouse\Schema\Directives\SubscriptionDirective; -use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver; +use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Nuwave\Lighthouse\Subscriptions\Directives\SubscriptionDirective; use Nuwave\Lighthouse\Subscriptions\Exceptions\UnauthorizedSubscriber; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver; +use Nuwave\Lighthouse\Support\Utils; class SubscriptionResolverProvider implements ProvidesSubscriptionResolver { @@ -22,12 +22,6 @@ class SubscriptionResolverProvider implements ProvidesSubscriptionResolver */ protected $subscriptionRegistry; - /** - * ResolverProvider constructor. - * - * @param \Nuwave\Lighthouse\Subscriptions\SubscriptionRegistry $subscriptionRegistry - * @return void - */ public function __construct(SubscriptionRegistry $subscriptionRegistry) { $this->subscriptionRegistry = $subscriptionRegistry; @@ -36,16 +30,16 @@ class SubscriptionResolverProvider implements ProvidesSubscriptionResolver /** * Provide a resolver for a subscription field in case no resolver directive is defined. * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @return \Closure - * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + * + * @return \Closure(mixed, array, \Nuwave\Lighthouse\Support\Contracts\GraphQLContext, \GraphQL\Type\Definition\ResolveInfo): mixed */ public function provideSubscriptionResolver(FieldValue $fieldValue): Closure { $fieldName = $fieldValue->getFieldName(); - if ($directive = ASTHelper::directiveDefinition($fieldValue->getField(), SubscriptionDirective::NAME)) { + $directive = ASTHelper::directiveDefinition($fieldValue->getField(), SubscriptionDirective::NAME); + if ($directive !== null) { $className = ASTHelper::directiveArgValue($directive, 'class'); } else { $className = Str::studly($fieldName); @@ -96,6 +90,8 @@ class SubscriptionResolverProvider implements ProvidesSubscriptionResolver $subscriber, $subscription->encodeTopic($subscriber, $fieldName) ); + + return null; }; } } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRouter.php b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRouter.php index 622d207..5ff2bda 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRouter.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionRouter.php @@ -2,15 +2,12 @@ namespace Nuwave\Lighthouse\Subscriptions; -use Nuwave\Lighthouse\Support\Http\Controllers\SubscriptionController; - class SubscriptionRouter { /** * Register the routes for pusher based subscriptions. * - * @param \Illuminate\Routing\Router $router - * @return void + * @param \Illuminate\Contracts\Routing\Registrar|\Laravel\Lumen\Routing\Router $router */ public function pusher($router): void { @@ -20,8 +17,19 @@ class SubscriptionRouter ]); $router->post('graphql/subscriptions/webhook', [ - 'as' => 'lighthouse.subscriptions.auth', + 'as' => 'lighthouse.subscriptions.webhook', 'uses' => SubscriptionController::class.'@webhook', ]); } + + /** + * @param \Illuminate\Contracts\Routing\Registrar|\Laravel\Lumen\Routing\Router $router + */ + public function echoRoutes($router): void + { + $router->post('graphql/subscriptions/auth', [ + 'as' => 'lighthouse.subscriptions.auth', + 'uses' => SubscriptionController::class.'@authorize', + ]); + } } diff --git a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionServiceProvider.php b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionServiceProvider.php index 30bb64b..ee03d7f 100644 --- a/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionServiceProvider.php +++ b/vendor/nuwave/lighthouse/src/Subscriptions/SubscriptionServiceProvider.php @@ -2,37 +2,54 @@ namespace Nuwave\Lighthouse\Subscriptions; -use Illuminate\Support\Str; -use Illuminate\Support\ServiceProvider; -use Nuwave\Lighthouse\Events\StartExecution; -use Nuwave\Lighthouse\Events\BuildExtensionsResponse; -use Nuwave\Lighthouse\Subscriptions\Iterators\SyncIterator; +use Illuminate\Auth\AuthManager; +use Illuminate\Container\Container; use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; -use Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer; -use Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions; -use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator; -use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver; +use Illuminate\Support\ServiceProvider; +use Illuminate\Support\Str; +use Nuwave\Lighthouse\Events\BuildExtensionsResponse; +use Nuwave\Lighthouse\Events\RegisterDirectiveNamespaces; +use Nuwave\Lighthouse\Events\StartExecution; use Nuwave\Lighthouse\Subscriptions\Contracts\AuthorizesSubscriptions; use Nuwave\Lighthouse\Subscriptions\Contracts\BroadcastsSubscriptions; -use Nuwave\Lighthouse\Subscriptions\Events\BroadcastSubscriptionEvent; -use Nuwave\Lighthouse\Subscriptions\Events\BroadcastSubscriptionListener; +use Nuwave\Lighthouse\Subscriptions\Contracts\ContextSerializer; +use Nuwave\Lighthouse\Subscriptions\Contracts\StoresSubscriptions; use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionExceptionHandler; +use Nuwave\Lighthouse\Subscriptions\Contracts\SubscriptionIterator; +use Nuwave\Lighthouse\Subscriptions\Iterators\AuthenticatingSyncIterator; +use Nuwave\Lighthouse\Subscriptions\Iterators\SyncIterator; +use Nuwave\Lighthouse\Subscriptions\Storage\CacheStorageManager; +use Nuwave\Lighthouse\Subscriptions\Storage\RedisStorageManager; +use Nuwave\Lighthouse\Support\Contracts\ProvidesSubscriptionResolver; class SubscriptionServiceProvider extends ServiceProvider { - /** - * @param \Illuminate\Contracts\Events\Dispatcher $eventsDispatcher - * @param \Illuminate\Contracts\Config\Repository $configRepository - * @return void - */ + public function register(): void + { + $this->app->singleton(BroadcastManager::class); + $this->app->singleton(SubscriptionRegistry::class); + $this->app->singleton(StoresSubscriptions::class, static function (Container $app): StoresSubscriptions { + /** @var \Illuminate\Contracts\Config\Repository $configRepository */ + $configRepository = $app->make(ConfigRepository::class); + switch ($configRepository->get('lighthouse.subscriptions.storage')) { + case 'redis': + return $app->make(RedisStorageManager::class); + default: + return $app->make(CacheStorageManager::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); + } + public function boot(EventsDispatcher $eventsDispatcher, ConfigRepository $configRepository): void { - $eventsDispatcher->listen( - BroadcastSubscriptionEvent::class, - BroadcastSubscriptionListener::class - ); - $eventsDispatcher->listen( StartExecution::class, SubscriptionRegistry::class.'@handleStartExecution' @@ -43,36 +60,43 @@ class SubscriptionServiceProvider extends ServiceProvider SubscriptionRegistry::class.'@handleBuildExtensionsResponse' ); - // Register the routes for the configured broadcaster. The specific - // method that is used can be changed, so we retrieve its name - // dynamically and then call it with an instance of 'router'. - $broadcaster = $configRepository->get('lighthouse.subscriptions.broadcaster'); - if ($routesMethod = $configRepository->get("lighthouse.subscriptions.broadcasters.{$broadcaster}.routes")) { - [$router, $method] = Str::parseCallback($routesMethod, 'pusher'); + $eventsDispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__.'\\Directives'; + } + ); - call_user_func( - [$this->app->make($router), $method], - $this->app->make('router') - ); + $this->registerBroadcasterRoutes($configRepository); + + // If authentication is used, we can log in subscribers when broadcasting an update + if ($this->app->bound(AuthManager::class)) { + config([ + 'auth.guards.'.SubscriptionGuard::GUARD_NAME => [ + 'driver' => SubscriptionGuard::GUARD_NAME, + ], + ]); + + $this->app->bind(SubscriptionIterator::class, AuthenticatingSyncIterator::class); + + $this->app->make(AuthManager::class)->extend(SubscriptionGuard::GUARD_NAME, static function () { + return new SubscriptionGuard; + }); } } - /** - * Register subscription services. - * - * @return void - */ - public function register(): void + protected function registerBroadcasterRoutes(ConfigRepository $configRepository): void { - $this->app->singleton(BroadcastManager::class); - $this->app->singleton(SubscriptionRegistry::class); - $this->app->singleton(StoresSubscriptions::class, StorageManager::class); + $broadcaster = $configRepository->get('lighthouse.subscriptions.broadcaster'); - $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); + if ($routesMethod = $configRepository->get("lighthouse.subscriptions.broadcasters.{$broadcaster}.routes")) { + [$routesProviderClass, $method] = Str::parseCallback($routesMethod, 'pusher'); + /** @var class-string $routesProviderClass */ + /** @var string $method */ + $routesProvider = $this->app->make($routesProviderClass); + $router = $this->app->make('router'); + + $routesProvider->{$method}($router); + } } } diff --git a/vendor/nuwave/lighthouse/src/Support/AppVersion.php b/vendor/nuwave/lighthouse/src/Support/AppVersion.php new file mode 100644 index 0000000..e198e0d --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/AppVersion.php @@ -0,0 +1,39 @@ += $version; + } + + public static function below(float $version): bool + { + return self::versionNumber() < $version; + } + + protected static function version(): string + { + return app()->version(); + } + + protected static function versionNumber(): float + { + if (self::isLumen()) { + // Lumen version strings look like: "Lumen (2.3.4)..." + return (float) Str::after(self::version(), '('); + } + + // Regular Laravel versions look like: "2.3.4" + return (float) self::version(); + } +} diff --git a/vendor/nuwave/lighthouse/src/Support/Compatibility/LaravelMiddlewareAdapter.php b/vendor/nuwave/lighthouse/src/Support/Compatibility/LaravelMiddlewareAdapter.php index 518c405..c99c8e9 100644 --- a/vendor/nuwave/lighthouse/src/Support/Compatibility/LaravelMiddlewareAdapter.php +++ b/vendor/nuwave/lighthouse/src/Support/Compatibility/LaravelMiddlewareAdapter.php @@ -11,32 +11,16 @@ class LaravelMiddlewareAdapter implements MiddlewareAdapter */ protected $router; - /** - * Create a middleware adapter for Laravel applications. - * - * @param \Illuminate\Routing\Router $router - * @return void - */ public function __construct(Router $router) { $this->router = $router; } - /** - * Get all of the defined middleware short-hand names. - * - * @return string[] - */ public function getMiddleware(): array { return $this->router->getMiddleware(); } - /** - * Get all of the defined middleware groups. - * - * @return string[] - */ public function getMiddlewareGroups(): array { return $this->router->getMiddlewareGroups(); diff --git a/vendor/nuwave/lighthouse/src/Support/Compatibility/LumenMiddlewareAdapter.php b/vendor/nuwave/lighthouse/src/Support/Compatibility/LumenMiddlewareAdapter.php index 8daaa34..5b3c92f 100644 --- a/vendor/nuwave/lighthouse/src/Support/Compatibility/LumenMiddlewareAdapter.php +++ b/vendor/nuwave/lighthouse/src/Support/Compatibility/LumenMiddlewareAdapter.php @@ -12,22 +12,11 @@ class LumenMiddlewareAdapter implements MiddlewareAdapter */ protected $app; - /** - * Create a middleware adapter for Lumen applications. - * - * @param \Laravel\Lumen\Application $app - * @return void - */ - public function __construct(Application $app) + public function __construct() { - $this->app = $app; + $this->app = Application::getInstance(); } - /** - * Get all of the defined middleware short-hand names. - * - * @return string[] - */ public function getMiddleware(): array { // TODO remove once Lumen gains public access to the middleware/routeMiddleware @@ -37,11 +26,6 @@ class LumenMiddlewareAdapter implements MiddlewareAdapter return array_merge($globalMiddleware, $routeMiddleware); } - /** - * Get all of the defined middleware groups. - * - * @return string[] - */ public function getMiddlewareGroups(): array { // Lumen doesn't have middleware groups diff --git a/vendor/nuwave/lighthouse/src/Support/Compatibility/MiddlewareAdapter.php b/vendor/nuwave/lighthouse/src/Support/Compatibility/MiddlewareAdapter.php index df8732e..a99edf6 100644 --- a/vendor/nuwave/lighthouse/src/Support/Compatibility/MiddlewareAdapter.php +++ b/vendor/nuwave/lighthouse/src/Support/Compatibility/MiddlewareAdapter.php @@ -7,14 +7,14 @@ interface MiddlewareAdapter /** * Get all of the defined middleware short-hand names. * - * @return string[] + * @return array */ public function getMiddleware(): array; /** * Get all of the defined middleware groups. * - * @return string[] + * @return array */ public function getMiddlewareGroups(): array; } diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgBuilderDirective.php b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgBuilderDirective.php index 8f37c5d..46b2ce1 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgBuilderDirective.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgBuilderDirective.php @@ -2,14 +2,14 @@ namespace Nuwave\Lighthouse\Support\Contracts; -interface ArgBuilderDirective extends ArgDirective +interface ArgBuilderDirective extends Directive { /** * Add additional constraints to the builder based on the given argument value. * - * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder - * @param mixed $value - * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder The builder used to resolve the field. + * @param mixed $value The client given value of the argument. + * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder The modified builder. */ public function handleBuilder($builder, $value); } diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgDirectiveForArray.php b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgDirectiveForArray.php index 0bcdc2a..d10d8b8 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgDirectiveForArray.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgDirectiveForArray.php @@ -6,7 +6,7 @@ namespace Nuwave\Lighthouse\Support\Contracts; * This directive can only be used upon a list argument and * applies to the whole list, not the items inside it. */ -interface ArgDirectiveForArray extends ArgDirective +interface ArgDirectiveForArray extends Directive { // } diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgManipulator.php b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgManipulator.php index ef8c2a0..a082403 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgManipulator.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgManipulator.php @@ -3,20 +3,16 @@ namespace Nuwave\Lighthouse\Support\Contracts; use GraphQL\Language\AST\FieldDefinitionNode; -use Nuwave\Lighthouse\Schema\AST\DocumentAST; use GraphQL\Language\AST\InputValueDefinitionNode; use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use Nuwave\Lighthouse\Schema\AST\DocumentAST; interface ArgManipulator extends Directive { /** * Manipulate the AST. * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\InputValueDefinitionNode $argDefinition - * @param \GraphQL\Language\AST\FieldDefinitionNode $parentField - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @return \Nuwave\Lighthouse\Schema\AST\DocumentAST + * @return void */ public function manipulateArgDefinition( DocumentAST &$documentAST, diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgResolver.php b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgResolver.php new file mode 100644 index 0000000..73df264 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgResolver.php @@ -0,0 +1,13 @@ + $value The slice of arguments that belongs to this nested resolver. + * @return mixed|null May return the modified $root + */ + public function __invoke($root, $value); +} diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgSanitizerDirective.php b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgSanitizerDirective.php new file mode 100644 index 0000000..b62f4ca --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgSanitizerDirective.php @@ -0,0 +1,14 @@ +> + */ + public function rules(): array; + + /** + * Specify custom messages for the rules. + * + * The returned array must map field + rule names (dot notation) to messages, e.g.: + * [ + * 'foo.email' => 'The foo must be an email', + * 'foo.required' => 'Everybody needs a foo', + * 'bar.required' => 'You must pass the bar', + * ] + * + * @return array + */ + public function messages(): array; + + /** + * Specify custom attribute names to use in the validation message. + * + * @return array + */ + public function attributes(): array; +} diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/ArgumentValidation.php b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgumentValidation.php new file mode 100644 index 0000000..e64abbf --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/ArgumentValidation.php @@ -0,0 +1,36 @@ + + */ + public function rules(): array; + + /** + * Specify custom messages for the rules. + * + * The returned array must map rule names to messages, e.g.: + * [ + * 'email' => 'Must be an email', + * 'required' => 'Has to be there', + * ] + * + * @return array + */ + public function messages(): array; + + /** + * Specify a custom attribute name to use in the validation message. + */ + public function attribute(): ?string; +} diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/CanStreamResponse.php b/vendor/nuwave/lighthouse/src/Support/Contracts/CanStreamResponse.php index d8da16f..a07ae09 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/CanStreamResponse.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/CanStreamResponse.php @@ -7,10 +7,9 @@ interface CanStreamResponse /** * Stream graphql response. * - * @param array $data - * @param array $paths - * @param bool $final - * @return mixed + * @param array $data + * @param array $paths + * @return void This function is expected to emit a stream as a side effect */ - public function stream(array $data, array $paths, bool $final); + public function stream(array $data, array $paths, bool $isFinalChunk); } diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesContext.php b/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesContext.php index ee8e294..06ada51 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesContext.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesContext.php @@ -9,7 +9,6 @@ interface CreatesContext /** * Generate GraphQL context. * - * @param \Illuminate\Http\Request $request * @return \Nuwave\Lighthouse\Support\Contracts\GraphQLContext */ public function generate(Request $request); diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesResponse.php b/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesResponse.php index 7555d01..c012659 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesResponse.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/CreatesResponse.php @@ -7,7 +7,7 @@ interface CreatesResponse /** * Create a HTTP response from the final result. * - * @param mixed[] $result + * @param array|array> $result * @return \Symfony\Component\HttpFoundation\Response */ public function createResponse(array $result); diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/DefinedDirective.php b/vendor/nuwave/lighthouse/src/Support/Contracts/DefinedDirective.php deleted file mode 100644 index fd08608..0000000 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/DefinedDirective.php +++ /dev/null @@ -1,13 +0,0 @@ -setResolver() before returning * the FieldValue. * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue * @return \Nuwave\Lighthouse\Schema\Values\FieldValue */ public function resolveField(FieldValue $fieldValue); diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/GlobalId.php b/vendor/nuwave/lighthouse/src/Support/Contracts/GlobalId.php index 1dcf3d2..c169b7f 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/GlobalId.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/GlobalId.php @@ -4,39 +4,32 @@ namespace Nuwave\Lighthouse\Support\Contracts; /** * Encode and decode globally unique IDs. + * + * TODO move to GlobalId namespace in v6 */ interface GlobalId { /** - * Encode a type and an id to create a Global ID. + * Glue together a type and an id to create a global id. * - * @param string $type * @param string|int $id - * @return string */ public function encode(string $type, $id): string; /** - * Decode a Global ID into the type and the id it contains. + * Split a global id into the type and the id it contains. * - * @param string $globalID - * @return array Contains [$type, $id], e.g. ['User', '123'] + * @return array{0: string, 1: string} A tuple of [$type, $id], e.g. ['User', '123'] */ public function decode(string $globalID): array; /** * Decode the Global ID and get just the ID. - * - * @param string $globalID - * @return string */ public function decodeID(string $globalID): string; /** * Decode the Global ID and get just the type. - * - * @param string $globalID - * @return string */ public function decodeType(string $globalID): string; } diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/GraphQLContext.php b/vendor/nuwave/lighthouse/src/Support/Contracts/GraphQLContext.php index c64a120..e80504a 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/GraphQLContext.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/GraphQLContext.php @@ -7,7 +7,7 @@ interface GraphQLContext /** * Get an instance of the authenticated user. * - * @return \Illuminate\Foundation\Auth\User|null + * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function user(); diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/HasArgumentPath.php b/vendor/nuwave/lighthouse/src/Support/Contracts/HasArgumentPath.php deleted file mode 100644 index 7bed47c..0000000 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/HasArgumentPath.php +++ /dev/null @@ -1,19 +0,0 @@ -, \GraphQL\Validator\Rules\ValidationRule>|null + */ + public function validationRules(): ?array; +} diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeExtensionManipulator.php b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeExtensionManipulator.php index 8930a8b..a37426a 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeExtensionManipulator.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeExtensionManipulator.php @@ -8,10 +8,8 @@ use Nuwave\Lighthouse\Schema\AST\DocumentAST; interface TypeExtensionManipulator extends Directive { /** - * Apply manipulations from a type definition node. + * Apply manipulations from a type extension node. * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeExtensionNode $typeExtension * @return void */ public function manipulateTypeExtension(DocumentAST &$documentAST, TypeExtensionNode &$typeExtension); diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeManipulator.php b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeManipulator.php index db2e29f..5023a02 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeManipulator.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeManipulator.php @@ -10,8 +10,7 @@ interface TypeManipulator extends Directive /** * Apply manipulations from a type definition node. * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\TypeDefinitionNode $typeDefinition + * @param \GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node $typeDefinition * @return void */ public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition); diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeMiddleware.php b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeMiddleware.php index 97b01fb..3dc97dc 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeMiddleware.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeMiddleware.php @@ -10,8 +10,6 @@ interface TypeMiddleware extends Directive /** * Handle a type AST as it is converted to an executable type. * - * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $value - * @param \Closure $next * @return \GraphQL\Type\Definition\Type */ public function handleNode(TypeValue $value, Closure $next); diff --git a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeResolver.php b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeResolver.php index 95981c4..2e4ca24 100644 --- a/vendor/nuwave/lighthouse/src/Support/Contracts/TypeResolver.php +++ b/vendor/nuwave/lighthouse/src/Support/Contracts/TypeResolver.php @@ -9,7 +9,6 @@ interface TypeResolver extends Directive /** * Resolve a type AST to a GraphQL Type. * - * @param \Nuwave\Lighthouse\Schema\Values\TypeValue $value * @return \GraphQL\Type\Definition\Type */ public function resolveNode(TypeValue $value); diff --git a/vendor/nuwave/lighthouse/src/Support/DriverManager.php b/vendor/nuwave/lighthouse/src/Support/DriverManager.php index 13b757a..42ff17b 100644 --- a/vendor/nuwave/lighthouse/src/Support/DriverManager.php +++ b/vendor/nuwave/lighthouse/src/Support/DriverManager.php @@ -3,10 +3,10 @@ namespace Nuwave\Lighthouse\Support; use Closure; -use ReflectionClass; -use InvalidArgumentException; use Illuminate\Container\Container as Application; +use InvalidArgumentException; use Nuwave\Lighthouse\Exceptions\InvalidDriverException; +use ReflectionClass; /** * NOTE: Implementation pulled from \Illuminate\Cache\CacheManager. Purpose is @@ -25,23 +25,17 @@ abstract class DriverManager /** * The array of resolved drivers. * - * @var array + * @var array */ protected $drivers = []; /** * The registered custom driver creators. * - * @var array + * @var array */ protected $customCreators = []; - /** - * Create a new driver manager instance. - * - * @param \Illuminate\Container\Container $app - * @return void - */ public function __construct(Application $app) { $this->app = $app; @@ -50,8 +44,7 @@ abstract class DriverManager /** * Get a driver instance by name. * - * @param string|null $name - * @return mixed + * @return object The driver instance. */ public function driver(?string $name = null) { @@ -63,8 +56,7 @@ abstract class DriverManager /** * Attempt to get the driver from the local cache. * - * @param string $name - * @return mixed + * @return object The resolved driver. */ protected function get(string $name) { @@ -73,8 +65,6 @@ abstract class DriverManager /** * Get the default driver name. - * - * @return string */ public function getDefaultDriver(): string { @@ -83,9 +73,6 @@ abstract class DriverManager /** * Set the default driver name. - * - * @param string $name - * @return void */ public function setDefaultDriver(string $name): void { @@ -95,13 +82,12 @@ abstract class DriverManager /** * Get the driver configuration. * - * @param string $name - * @return array + * @return array */ protected function getConfig(string $name): array { return $this->app['config']->get( - $this->configKey().".{$name}", + "{$this->configKey()}.{$name}", ['driver' => $name] ); } @@ -109,8 +95,6 @@ abstract class DriverManager /** * Register a custom driver creator Closure. * - * @param string $driver - * @param \Closure $callback * @return $this */ public function extend(string $driver, Closure $callback): self @@ -123,8 +107,7 @@ abstract class DriverManager /** * Resolve the given driver. * - * @param string $name - * @return mixed + * @return object The resolved driver. * * @throws \InvalidArgumentException */ @@ -132,10 +115,6 @@ abstract class DriverManager { $config = $this->getConfig($name); - if ($config === null) { - throw new InvalidArgumentException("Driver [{$name}] is not defined."); - } - if (isset($this->customCreators[$config['driver']])) { return $this->validateDriver($this->callCustomCreator($config)); } @@ -152,8 +131,8 @@ abstract class DriverManager /** * Call a custom driver creator. * - * @param array $config - * @return mixed + * @param array $config + * @return object The created driver. */ protected function callCustomCreator(array $config) { @@ -163,8 +142,8 @@ abstract class DriverManager /** * Validate driver implements the proper interface. * - * @param mixed $driver - * @return mixed + * @param object $driver + * @return object * * @throws \Nuwave\Lighthouse\Exceptions\InvalidDriverException */ @@ -182,9 +161,8 @@ abstract class DriverManager /** * Dynamically call the default driver instance. * - * @param string $method - * @param array $parameters - * @return mixed + * @param array $parameters + * @return mixed Whatever the driver returned. */ public function __call(string $method, array $parameters) { diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Controllers/GraphQLController.php b/vendor/nuwave/lighthouse/src/Support/Http/Controllers/GraphQLController.php index c75a93d..174d23d 100644 --- a/vendor/nuwave/lighthouse/src/Support/Http/Controllers/GraphQLController.php +++ b/vendor/nuwave/lighthouse/src/Support/Http/Controllers/GraphQLController.php @@ -2,96 +2,41 @@ namespace Nuwave\Lighthouse\Support\Http\Controllers; -use Nuwave\Lighthouse\GraphQL; -use Illuminate\Routing\Controller; -use Illuminate\Container\Container; -use Nuwave\Lighthouse\Events\StartRequest; -use Nuwave\Lighthouse\Execution\GraphQLRequest; -use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; +use Illuminate\Http\Request; +use Laragraph\Utils\RequestParser; +use Nuwave\Lighthouse\Events\EndRequest; +use Nuwave\Lighthouse\Events\StartRequest; +use Nuwave\Lighthouse\GraphQL; +use Nuwave\Lighthouse\Support\Contracts\CreatesContext; +use Nuwave\Lighthouse\Support\Contracts\CreatesResponse; +use Symfony\Component\HttpFoundation\Response; -class GraphQLController extends Controller +class GraphQLController { - /** - * @var \Nuwave\Lighthouse\GraphQL - */ - protected $graphQL; - - /** - * @var \Illuminate\Contracts\Events\Dispatcher - */ - protected $eventsDispatcher; - - /** - * @var \Nuwave\Lighthouse\Support\Contracts\CreatesResponse - */ - protected $createsResponse; - - /** - * @var \Illuminate\Container\Container - */ - protected $container; - - /** - * Inject middleware into request. - * - * @param \Nuwave\Lighthouse\GraphQL $graphQL - * @param \Illuminate\Contracts\Events\Dispatcher $eventsDispatcher - * @param \Nuwave\Lighthouse\Support\Contracts\CreatesResponse $createsResponse - * @param \Illuminate\Container\Container $container - * @return void - */ - public function __construct( + public function __invoke( + Request $request, GraphQL $graphQL, EventsDispatcher $eventsDispatcher, + RequestParser $requestParser, CreatesResponse $createsResponse, - Container $container - ) { - $this->graphQL = $graphQL; - $this->eventsDispatcher = $eventsDispatcher; - $this->createsResponse = $createsResponse; - $this->container = $container; - } - - /** - * Execute GraphQL query. - * - * @param \Nuwave\Lighthouse\Execution\GraphQLRequest $request - * @return \Symfony\Component\HttpFoundation\Response - */ - public function query(GraphQLRequest $request) - { - $this->eventsDispatcher->dispatch( + CreatesContext $createsContext + ): Response { + $eventsDispatcher->dispatch( new StartRequest($request) ); - $result = $request->isBatched() - ? $this->executeBatched($request) - : $this->graphQL->executeRequest($request); + $operationOrOperations = $requestParser->parseRequest($request); + $context = $createsContext->generate($request); - $response = $this->createsResponse->createResponse($result); + $result = $graphQL->executeOperationOrOperations($operationOrOperations, $context); - // When handling multiple requests during the application lifetime, - // for example in tests, we need a new GraphQLRequest instance - // for each HTTP request, so we forget the singleton here. - $this->container->forgetInstance(GraphQLRequest::class); + $response = $createsResponse->createResponse($result); + + $eventsDispatcher->dispatch( + new EndRequest($response) + ); return $response; } - - /** - * Loop through the individual batched queries and collect the results. - * - * @param \Nuwave\Lighthouse\Execution\GraphQLRequest $request - * @return mixed[] - */ - protected function executeBatched(GraphQLRequest $request): array - { - $results = []; - do { - $results[] = $this->graphQL->executeRequest($request); - } while ($request->advanceBatchIndex()); - - return $results; - } } diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Controllers/SubscriptionController.php b/vendor/nuwave/lighthouse/src/Support/Http/Controllers/SubscriptionController.php deleted file mode 100644 index a0ae4ae..0000000 --- a/vendor/nuwave/lighthouse/src/Support/Http/Controllers/SubscriptionController.php +++ /dev/null @@ -1,55 +0,0 @@ -broadcaster = $broadcaster; - $this->broadcasterManager = $broadcastManager; - } - - /** - * Authenticate subscriber. - * - * @param \Illuminate\Http\Request $request - * @return \Symfony\Component\HttpFoundation\Response - */ - public function authorize(Request $request): Response - { - return $this->broadcaster->authorize($request); - } - - /** - * Handle pusher webhook. - * - * @param \Illuminate\Http\Request $request - * @return \Symfony\Component\HttpFoundation\Response - */ - public function webhook(Request $request): Response - { - return $this->broadcasterManager->hook($request); - } -} diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AcceptJson.php b/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AcceptJson.php index db52ed2..da14910 100644 --- a/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AcceptJson.php +++ b/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AcceptJson.php @@ -1,7 +1,5 @@ headers->set('Accept', 'application/json'); + $request->headers->set(self::ACCEPT, self::APPLICATION_JSON); return $next($request); } diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AttemptAuthentication.php b/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AttemptAuthentication.php new file mode 100644 index 0000000..4831298 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/Http/Middleware/AttemptAuthentication.php @@ -0,0 +1,52 @@ +authFactory = $authFactory; + } + + /** + * @param string ...$guards + * @return mixed Any kind of response + */ + public function handle(Request $request, Closure $next, ...$guards) + { + $this->attemptAuthentication($guards); + + return $next($request); + } + + /** + * @param array ...$guards + */ + protected function attemptAuthentication(array $guards): void + { + if (empty($guards)) { + $guards = [config('lighthouse.guard')]; + } + + foreach ($guards as $guard) { + if ($this->authFactory->guard($guard)->check()) { + $this->authFactory->shouldUse($guard); + + return; + } + } + } +} diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Middleware/LogGraphQLQueries.php b/vendor/nuwave/lighthouse/src/Support/Http/Middleware/LogGraphQLQueries.php new file mode 100644 index 0000000..6cf727d --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/Http/Middleware/LogGraphQLQueries.php @@ -0,0 +1,38 @@ +logger = $logger; + } + + /** + * @return mixed Any kind of response + */ + public function handle(Request $request, Closure $next) + { + $this->logger->info( + self::MESSAGE, + $request->json()->all() + ); + + return $next($request); + } +} diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Responses/MemoryStream.php b/vendor/nuwave/lighthouse/src/Support/Http/Responses/MemoryStream.php index 1af8938..91906ae 100644 --- a/vendor/nuwave/lighthouse/src/Support/Http/Responses/MemoryStream.php +++ b/vendor/nuwave/lighthouse/src/Support/Http/Responses/MemoryStream.php @@ -3,40 +3,32 @@ namespace Nuwave\Lighthouse\Support\Http\Responses; use Illuminate\Support\Arr; -use Illuminate\Support\Collection; use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse; class MemoryStream extends Stream implements CanStreamResponse { /** - * @var mixed[] + * @var array */ public $chunks = []; - /** - * Stream graphql response. - * - * @param array $data - * @param array $paths - * @param bool $final - * @return void - */ - public function stream(array $data, array $paths, bool $final): void + public function stream(array $data, array $paths, bool $isFinalChunk): void { - if (! empty($paths)) { - $data = (new Collection($paths)) - ->mapWithKeys(function ($path) use ($data): array { - $response['data'] = Arr::get($data, "data.{$path}", []); - $errors = $this->chunkError($path, $data); - if (! empty($errors)) { - $response['errors'] = $errors; - } + if (empty($paths)) { + $this->chunks[] = $data; + } else { + $chunk = []; + foreach ($paths as $path) { + $response = ['data' => Arr::get($data, "data.{$path}", [])]; - return [$path => $response]; - }) - ->all(); + $errors = $this->chunkError($path, $data); + if (! empty($errors)) { + $response['errors'] = $errors; + } + + $chunk[$path] = $response; + } + $this->chunks[] = $chunk; } - - $this->chunks[] = $data; } } diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Responses/ResponseStream.php b/vendor/nuwave/lighthouse/src/Support/Http/Responses/ResponseStream.php index 5f26a74..c896c74 100644 --- a/vendor/nuwave/lighthouse/src/Support/Http/Responses/ResponseStream.php +++ b/vendor/nuwave/lighthouse/src/Support/Http/Responses/ResponseStream.php @@ -10,67 +10,51 @@ use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse; class ResponseStream extends Stream implements CanStreamResponse { - /** - * @var string - */ - const EOL = "\r\n"; + public const EOL = "\r\n"; - /** - * Stream graphql response. - * - * @param array $data - * @param array $paths - * @param bool $final - * @return void - */ - public function stream(array $data, array $paths, bool $final): void + public function stream(array $data, array $paths, bool $isFinalChunk): void { - if (! empty($paths)) { - $paths = new Collection($paths); - $lastKey = $paths->count() - 1; - - $paths - ->map(function (string $path, int $i) use ($data, $final, $lastKey): string { - $terminating = $final && ($i === $lastKey); - $chunk['data'] = Arr::get($data, "data.{$path}"); - $chunk['path'] = (new Collection(explode('.', $path))) - ->map(function ($partial) { - return is_numeric($partial) - ? (int) $partial - : $partial; - }) - ->all(); - - $errors = $this->chunkError($path, $data); - if (! empty($errors)) { - $chunk['errors'] = $errors; - } - - return $this->chunk($chunk, $terminating); - }) - ->each(function (string $chunk) { - $this->emit($chunk); - }); + if (empty($paths)) { + $this->emit( + $this->chunk($data, $isFinalChunk) + ); } else { - $this->emit($this->chunk($data, $final)); + $chunk = []; + $lastKey = count($paths) - 1; + + foreach ($paths as $i => $path) { + $chunk['data'] = Arr::get($data, "data.{$path}"); + $chunk['path'] = (new Collection(explode('.', $path))) + ->map(function ($partial) { + return is_numeric($partial) + ? (int) $partial + : $partial; + }) + ->all(); + + $errors = $this->chunkError($path, $data); + if (! empty($errors)) { + $chunk['errors'] = $errors; + } + + $terminating = $isFinalChunk && $i === $lastKey; + + $this->emit( + $this->chunk($chunk, $terminating) + ); + } } - if ($final) { + if ($isFinalChunk) { $this->emit($this->terminatingBoundary()); } } - /** - * @return string - */ protected function boundary(): string { return self::EOL.'---'.self::EOL; } - /** - * @return string - */ protected function terminatingBoundary(): string { return self::EOL.'-----'.self::EOL; @@ -79,13 +63,12 @@ class ResponseStream extends Stream implements CanStreamResponse /** * Format chunked data. * - * @param array $data - * @param bool $terminating - * @return string + * @param array $data */ protected function chunk(array $data, bool $terminating): string { - $json = json_encode($data, 0); + $json = \Safe\json_encode($data); + $length = $terminating ? strlen($json) : strlen($json.self::EOL); @@ -93,9 +76,9 @@ class ResponseStream extends Stream implements CanStreamResponse $chunk = implode(self::EOL, [ 'Content-Type: application/json', 'Content-Length: '.$length, - null, + '', $json, - null, + '', ]); return $this->boundary().$chunk; @@ -103,9 +86,6 @@ class ResponseStream extends Stream implements CanStreamResponse /** * Stream chunked data to client. - * - * @param string $chunk - * @return void */ protected function emit(string $chunk): void { @@ -117,12 +97,9 @@ class ResponseStream extends Stream implements CanStreamResponse /** * Flush buffer cache. - * Note: We can run into exceptions when flushing the buffer, - * these should be safe to ignore. - * @todo Investigate exceptions that occur on Apache * - * @param \Closure $flush - * @return void + * Note: We can run into exceptions when flushing the buffer, these should be safe to ignore. + * TODO Investigate exceptions that occur on Apache */ protected function flush(Closure $flush): void { diff --git a/vendor/nuwave/lighthouse/src/Support/Http/Responses/Stream.php b/vendor/nuwave/lighthouse/src/Support/Http/Responses/Stream.php index 053b716..78c09e7 100644 --- a/vendor/nuwave/lighthouse/src/Support/Http/Responses/Stream.php +++ b/vendor/nuwave/lighthouse/src/Support/Http/Responses/Stream.php @@ -3,28 +3,29 @@ namespace Nuwave\Lighthouse\Support\Http\Responses; use Illuminate\Support\Str; -use Illuminate\Support\Collection; abstract class Stream { /** * Get error from chunk if it exists. * - * @param string $path - * @param array $data - * @return array|null + * @param array $data + * @return array>|null */ protected function chunkError(string $path, array $data): ?array { - if (! isset($data['errors'])) { + $errors = $data['errors'] ?? null; + if (! is_array($errors)) { return null; } - return (new Collection($data['errors'])) - ->filter(function (array $error) use ($path): bool { + $errorsMatchingPath = array_filter( + $errors, + function (array $error) use ($path): bool { return Str::startsWith(implode('.', $error['path']), $path); - }) - ->values() - ->all(); + } + ); + + return array_values($errorsMatchingPath); } } diff --git a/vendor/nuwave/lighthouse/src/Support/Http/routes.php b/vendor/nuwave/lighthouse/src/Support/Http/routes.php index a596167..24fff50 100644 --- a/vendor/nuwave/lighthouse/src/Support/Http/routes.php +++ b/vendor/nuwave/lighthouse/src/Support/Http/routes.php @@ -1,23 +1,29 @@ version(), '5.5.')) { - $method = 'match'; + $actions = [ + 'as' => $routeConfig['name'] ?? 'graphql', + 'uses' => \Nuwave\Lighthouse\Support\Http\Controllers\GraphQLController::class, + ]; + + if (isset($routeConfig['middleware'])) { + $actions['middleware'] = $routeConfig['middleware']; } - $router->$method( + if (isset($routeConfig['prefix'])) { + $actions['prefix'] = $routeConfig['prefix']; + } + + if (isset($routeConfig['domain'])) { + $actions['domain'] = $routeConfig['domain']; + } + + $router->addRoute( ['GET', 'POST'], $routeConfig['uri'] ?? 'graphql', - [ - 'as' => $routeConfig['name'] ?? 'graphql', - 'uses' => \Nuwave\Lighthouse\Support\Http\Controllers\GraphQLController::class.'@query', - 'middleware' => $routeConfig['middleware'], - ] + $actions ); } diff --git a/vendor/nuwave/lighthouse/src/Support/Pipeline.php b/vendor/nuwave/lighthouse/src/Support/Pipeline.php deleted file mode 100644 index 1037136..0000000 --- a/vendor/nuwave/lighthouse/src/Support/Pipeline.php +++ /dev/null @@ -1,61 +0,0 @@ -all(); - } - - return parent::through($pipes); - } - - /** - * Get a \Closure that represents a slice of the application onion. - * - * @return \Closure - */ - 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); - }; - }; - } - - /** - * Set always variable. - * - * @param \Closure $always - * @return $this - */ - public function always(Closure $always): self - { - $this->always = $always; - - return $this; - } -} diff --git a/vendor/nuwave/lighthouse/src/Support/Traits/GeneratesColumnsEnum.php b/vendor/nuwave/lighthouse/src/Support/Traits/GeneratesColumnsEnum.php new file mode 100644 index 0000000..e61f11c --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/Traits/GeneratesColumnsEnum.php @@ -0,0 +1,104 @@ +directiveArgValue('columns')); + $hasColumnsEnum = ! is_null($this->directiveArgValue('columnsEnum')); + + if ($hasColumns && $hasColumnsEnum) { + throw new DefinitionException( + 'The @'.$this->name().' directive can only have one of the following arguments: `columns`, `columnsEnum`.' + ); + } + + return $hasColumns || $hasColumnsEnum; + } + + /** + * Generate the enumeration type for the list of allowed columns. + * + * @return string The name of the used enum. + */ + protected function generateColumnsEnum( + DocumentAST &$documentAST, + InputValueDefinitionNode &$argDefinition, + FieldDefinitionNode &$parentField, + ObjectTypeDefinitionNode &$parentType + ): string { + $columnsEnum = $this->directiveArgValue('columnsEnum'); + + if (! is_null($columnsEnum)) { + return $columnsEnum; + } + + $allowedColumnsEnumName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType).'Column'; + + $documentAST + ->setTypeDefinition( + static::createAllowedColumnsEnum( + $argDefinition, + $parentField, + $parentType, + $this->directiveArgValue('columns'), + $allowedColumnsEnumName + ) + ); + + return $allowedColumnsEnumName; + } + + /** + * Create the Enum that holds the allowed columns. + * + * @param array $allowedColumns + */ + protected function createAllowedColumnsEnum( + InputValueDefinitionNode &$argDefinition, + FieldDefinitionNode &$parentField, + ObjectTypeDefinitionNode &$parentType, + array $allowedColumns, + string $allowedColumnsEnumName + ): EnumTypeDefinitionNode { + $enumValues = array_map( + function (string $columnName): string { + return + strtoupper( + Str::snake($columnName) + ) + .' @enum(value: "'.$columnName.'")'; + }, + $allowedColumns + ); + + $enumDefinition = "\"Allowed column names for the `{$argDefinition->name->value}` argument on field `{$parentField->name->value}` on type `{$parentType->name->value}`.\"\n" + ."enum $allowedColumnsEnumName {\n"; + foreach ($enumValues as $enumValue) { + $enumDefinition .= "$enumValue\n"; + } + $enumDefinition .= '}'; + + return Parser::enumTypeDefinition($enumDefinition); + } +} diff --git a/vendor/nuwave/lighthouse/src/Support/Traits/HandlesCompositeKey.php b/vendor/nuwave/lighthouse/src/Support/Traits/HandlesCompositeKey.php deleted file mode 100644 index d993d5c..0000000 --- a/vendor/nuwave/lighthouse/src/Support/Traits/HandlesCompositeKey.php +++ /dev/null @@ -1,21 +0,0 @@ -argumentPath; - } - - /** - * @return string - */ - public function argumentPathAsDotNotation(): string - { - return implode('.', $this->argumentPath); - } - - /** - * @param mixed[] $argumentPath - * @return $this - */ - public function setArgumentPath(array $argumentPath): self - { - $this->argumentPath = $argumentPath; - - return $this; - } -} diff --git a/vendor/nuwave/lighthouse/src/Support/Traits/HasArgumentValue.php b/vendor/nuwave/lighthouse/src/Support/Traits/HasArgumentValue.php new file mode 100644 index 0000000..fd633e9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Support/Traits/HasArgumentValue.php @@ -0,0 +1,30 @@ +argumentValue; + } + + /** + * @param \Nuwave\Lighthouse\Execution\Arguments\Argument|\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet $argument + * @return $this + */ + public function setArgumentValue($argument): self + { + $this->argumentValue = $argument; + + return $this; + } +} diff --git a/vendor/nuwave/lighthouse/src/Support/Traits/HasErrorBuffer.php b/vendor/nuwave/lighthouse/src/Support/Traits/HasErrorBuffer.php deleted file mode 100644 index e770eb2..0000000 --- a/vendor/nuwave/lighthouse/src/Support/Traits/HasErrorBuffer.php +++ /dev/null @@ -1,36 +0,0 @@ -errorBuffer; - } - - /** - * Set the ErrorBuffer instance. - * - * @param \Nuwave\Lighthouse\Execution\ErrorBuffer $errorBuffer - * @return $this - */ - public function setErrorBuffer(ErrorBuffer $errorBuffer): self - { - $this->errorBuffer = $errorBuffer; - - return $this; - } -} diff --git a/vendor/nuwave/lighthouse/src/Support/Traits/HasResolverArguments.php b/vendor/nuwave/lighthouse/src/Support/Traits/HasResolverArguments.php deleted file mode 100644 index 7a78bca..0000000 --- a/vendor/nuwave/lighthouse/src/Support/Traits/HasResolverArguments.php +++ /dev/null @@ -1,166 +0,0 @@ -root; - } - - /** - * @param mixed $root - * @return $this - */ - public function setRoot($root): self - { - $this->root = $root; - - return $this; - } - - /** - * @return mixed[] - */ - public function args(): array - { - return $this->args; - } - - /** - * @param mixed[] $args - * @return $this - */ - public function setArgs(array $args): self - { - $this->args = $args; - - return $this; - } - - /** - * @return \Nuwave\Lighthouse\Support\Contracts\GraphQLContext - */ - public function context(): GraphQLContext - { - return $this->context; - } - - /** - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @return $this - */ - public function setContext(GraphQLContext $context): self - { - $this->context = $context; - - return $this; - } - - /** - * @return \GraphQL\Type\Definition\ResolveInfo - */ - public function resolveInfo(): ResolveInfo - { - return $this->resolveInfo; - } - - /** - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return $this - */ - public function setResolveInfo(ResolveInfo $resolveInfo): self - { - $this->resolveInfo = $resolveInfo; - - return $this; - } - - /** - * Set all resolver arguments at once. - * - * @param mixed|null $root - * @param mixed[] $args - * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo - * @return $this - */ - public function setResolverArguments($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): self - { - return $this - ->setRoot($root) - ->setArgs($args) - ->setContext($context) - ->setResolveInfo($resolveInfo); - } - - /** - * Get all the resolver arguments. - * - * @return mixed[] - */ - public function getResolverArguments(): array - { - return [ - $this->root(), - $this->args(), - $this->context(), - $this->resolveInfo(), - ]; - } - - /** - * Pass the resolver arguments to a given class if it also uses this trait. - * - * @param object|iterable $receiver - * @return object|iterable - */ - public function passResolverArguments($receiver) - { - if (is_iterable($receiver)) { - foreach ($receiver as $single) { - $this->passResolverArguments($single); - } - } - - return $receiver; - } - - /** - * @param object $receiver - * @return void - */ - protected function passResolverArgumentsToObject($receiver): void - { - if (method_exists($receiver, 'setResolverArguments')) { - $receiver->setResolverArguments(...$this->getResolverArguments()); - } - } -} diff --git a/vendor/nuwave/lighthouse/src/Support/Utils.php b/vendor/nuwave/lighthouse/src/Support/Utils.php index d15c004..a203364 100644 --- a/vendor/nuwave/lighthouse/src/Support/Utils.php +++ b/vendor/nuwave/lighthouse/src/Support/Utils.php @@ -3,9 +3,9 @@ namespace Nuwave\Lighthouse\Support; use Closure; +use Nuwave\Lighthouse\Exceptions\DefinitionException; use ReflectionClass; use ReflectionException; -use Nuwave\Lighthouse\Exceptions\DefinitionException; class Utils { @@ -15,14 +15,14 @@ class Utils * If the class itself exists, it is simply returned as is. * Else, the given namespaces are tried in order. * - * @param string $classCandidate - * @param array $namespacesToTry - * @param callable $determineMatch - * @return string|null + * @param array $namespacesToTry + * @param callable(string $className): bool $determineMatch + * @return class-string|null */ public static function namespaceClassname(string $classCandidate, array $namespacesToTry, callable $determineMatch): ?string { if ($determineMatch($classCandidate)) { + /** @var class-string $classCandidate */ return $classCandidate; } @@ -32,6 +32,7 @@ class Utils $className = array_shift($namespacesToTry).'\\'.$classCandidate; if ($determineMatch($className)) { + /** @var class-string $className */ return $className; } } @@ -42,9 +43,8 @@ class Utils /** * Construct a closure that passes through the arguments. * - * @param string $className This class is resolved through the container. + * @param class-string $className This class is resolved through the container. * @param string $methodName The method that gets passed the arguments of the closure. - * @return \Closure * * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException */ @@ -54,7 +54,10 @@ class Utils throw new DefinitionException("Method '{$methodName}' does not exist on class '{$className}'"); } - return Closure::fromCallable([app($className), $methodName]); + return Closure::fromCallable( + // @phpstan-ignore-next-line this works + [app($className), $methodName] + ); } /** @@ -79,4 +82,44 @@ class Utils return $default; } } + + /** + * Apply a callback to a value or each value in an array. + * + * @param mixed|array $valueOrValues + * @return mixed|array + */ + public static function applyEach(\Closure $callback, $valueOrValues) + { + if (is_array($valueOrValues)) { + return array_map($callback, $valueOrValues); + } + + return $callback($valueOrValues); + } + + /** + * Determine if a class uses a trait. + * + * @param object|string $class + */ + public static function classUsesTrait($class, string $trait): bool + { + return in_array( + $trait, + class_uses_recursive($class) + ); + } + + /** + * Construct a callback that checks if its input is a given class. + * + * @return Closure(mixed): bool + */ + public static function instanceofMatcher(string $classLike): Closure + { + return function ($object) use ($classLike): bool { + return $object instanceof $classLike; + }; + } } diff --git a/vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequests.php b/vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequests.php index 3baf3d7..f52aa81 100644 --- a/vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequests.php +++ b/vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequests.php @@ -2,15 +2,19 @@ namespace Nuwave\Lighthouse\Testing; -use Illuminate\Support\Arr; use GraphQL\Type\Introspection; -use Illuminate\Foundation\Testing\TestResponse; +use Illuminate\Container\Container; +use Illuminate\Contracts\Config\Repository as ConfigRepository; +use Illuminate\Support\Arr; +use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse; +use Nuwave\Lighthouse\Support\Http\Responses\MemoryStream; +use PHPUnit\Framework\Assert; +use Symfony\Component\HttpFoundation\StreamedResponse; /** - * Useful helpers for PHPUnit testing. + * Testing helpers for making requests to the GraphQL endpoint. * - * It depends upon methods defined in - * @see \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests + * @mixin \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests */ trait MakesGraphQLRequests { @@ -20,65 +24,49 @@ trait MakesGraphQLRequests * On the first call to introspect() this property is set to * cache the result, as introspection is quite expensive. * - * @var \Illuminate\Foundation\Testing\TestResponse|null + * @var \Illuminate\Testing\TestResponse|null */ protected $introspectionResult; /** - * Visit the given URI with a POST request, expecting a JSON response. + * Used to test deferred queries. * - * @param string $uri - * @param array $data - * @param array $headers - * @return \Illuminate\Foundation\Testing\TestResponse + * @var \Nuwave\Lighthouse\Support\Http\Responses\MemoryStream|null */ - abstract public function postJson($uri, array $data = [], array $headers = []); - - /** - * Call the given URI and return the Response. - * - * @param string $method - * @param string $uri - * @param array $parameters - * @param array $cookies - * @param array $files - * @param array $server - * @param string $content - * @return \Illuminate\Foundation\Testing\TestResponse - */ - abstract public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null); - - /** - * Transform headers array to array of $_SERVER vars with HTTP_* format. - * - * @param array $headers - * @return array - */ - abstract protected function transformHeadersToServerVars(array $headers); + protected $deferStream; /** * Execute a query as if it was sent as a request to the server. * - * @param string $query - * @return \Illuminate\Foundation\Testing\TestResponse + * @param string $query The GraphQL query to send + * @param array $variables The variables to include in the query + * @param array $extraParams Extra parameters to add to the JSON payload + * @return \Illuminate\Testing\TestResponse */ - protected function graphQL(string $query): TestResponse + protected function graphQL(string $query, array $variables = [], array $extraParams = []) { - return $this->postGraphQL( - [ - 'query' => $query, - ] - ); + $params = ['query' => $query]; + + if ($variables !== []) { + $params += ['variables' => $variables]; + } + + $params += $extraParams; + + return $this->postGraphQL($params); } /** - * Execute a query as if it was sent as a request to the server. + * Execute a POST to the GraphQL endpoint. * - * @param mixed[] $data - * @param mixed[] $headers - * @return \Illuminate\Foundation\Testing\TestResponse + * Use this over graphQL() when you need more control or want to + * test how your server behaves on incorrect inputs. + * + * @param array $data + * @param array $headers + * @return \Illuminate\Testing\TestResponse */ - protected function postGraphQL(array $data, array $headers = []): TestResponse + protected function postGraphQL(array $data, array $headers = []) { return $this->postJson( $this->graphQLEndpointUrl(), @@ -93,32 +81,42 @@ trait MakesGraphQLRequests * This is used for file uploads conforming to the specification: * https://github.com/jaydenseric/graphql-multipart-request-spec * - * @param mixed[] $parameters - * @param mixed[] $files - * @return \Illuminate\Foundation\Testing\TestResponse + * @param array|array> $operations + * @param array> $map + * @param array|array $files + * @param array $headers Will be merged with Content-Type: multipart/form-data + * @return \Illuminate\Testing\TestResponse */ - protected function multipartGraphQL(array $parameters, array $files): TestResponse + protected function multipartGraphQL(array $operations, array $map, array $files, array $headers = []) { + $parameters = [ + 'operations' => json_encode($operations), + 'map' => json_encode($map), + ]; + return $this->call( 'POST', $this->graphQLEndpointUrl(), $parameters, [], $files, - $this->transformHeadersToServerVars([ - 'Content-Type' => 'multipart/form-data', - ]) + $this->transformHeadersToServerVars(array_merge( + [ + 'Content-Type' => 'multipart/form-data', + ], + $headers + )) ); } /** * Execute the introspection query on the GraphQL server. * - * @return \Illuminate\Foundation\Testing\TestResponse + * @return \Illuminate\Testing\TestResponse */ - protected function introspect(): TestResponse + protected function introspect() { - if ($this->introspectionResult) { + if ($this->introspectionResult !== null) { return $this->introspectionResult; } @@ -128,8 +126,7 @@ trait MakesGraphQLRequests /** * Run introspection and return a type by name, if present. * - * @param string $name - * @return mixed[]|null + * @return array|null */ protected function introspectType(string $name): ?array { @@ -139,8 +136,7 @@ trait MakesGraphQLRequests /** * Run introspection and return a directive by name, if present. * - * @param string $name - * @return mixed[]|null + * @return array|null */ protected function introspectDirective(string $name): ?array { @@ -150,25 +146,19 @@ trait MakesGraphQLRequests /** * Run introspection and return a result from the given path by name, if present. * - * @param string $path - * @param string $name - * @return mixed[]|null + * @return array|null */ protected function introspectByName(string $path, string $name): ?array { - if (! $this->introspectionResult) { + if ($this->introspectionResult === null) { $this->introspect(); } - // TODO Replace with ->json() once we remove support for Laravel 5.5 - $results = data_get( - $this->introspectionResult->decodeResponseJson(), - $path - ); + $results = $this->introspectionResult->json($path); return Arr::first( $results, - function (array $result) use ($name): bool { + static function (array $result) use ($name): bool { return $result['name'] === $name; } ); @@ -176,11 +166,56 @@ trait MakesGraphQLRequests /** * Return the full URL to the GraphQL endpoint. - * - * @return string */ protected function graphQLEndpointUrl(): string { - return config('lighthouse.route.uri'); + /** @var \Illuminate\Contracts\Config\Repository $config */ + $config = app(ConfigRepository::class); + + return route($config->get('lighthouse.route.name')); + } + + /** + * Send the query and capture all chunks of the streamed response. + * + * @param string $query The GraphQL query to send + * @param array $variables The variables to include in the query + * @param array $extraParams Extra parameters to add to the HTTP payload + * @return array The chunked results + */ + protected function streamGraphQL(string $query, array $variables = [], array $extraParams = []): array + { + if ($this->deferStream === null) { + $this->setUpDeferStream(); + } + + $response = $this->graphQL($query, $variables, $extraParams); + + if (! $response->baseResponse instanceof StreamedResponse) { + Assert::fail('Expected the response to be a streamed response but got a regular response.'); + } + + $response->send(); + + return $this->deferStream->chunks; + } + + /** + * Set up the stream to make queries with `@defer`. + */ + protected function setUpDeferStream(): void + { + $this->deferStream = new MemoryStream; + + Container::getInstance()->singleton(CanStreamResponse::class, function (): MemoryStream { + return $this->deferStream; + }); + } + + protected function rethrowGraphQLErrors(): void + { + /** @var \Illuminate\Contracts\Config\Repository $config */ + $config = app(ConfigRepository::class); + $config->set('lighthouse.error_handlers', [RethrowingErrorHandler::class]); } } diff --git a/vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequestsLumen.php b/vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequestsLumen.php new file mode 100644 index 0000000..72ab29d --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/MakesGraphQLRequestsLumen.php @@ -0,0 +1,232 @@ + $variables The variables to include in the query + * @param array $extraParams Extra parameters to add to the JSON payload + * @return $this + */ + protected function graphQL(string $query, array $variables = [], array $extraParams = []): self + { + $params = ['query' => $query]; + + if ($variables) { + $params += ['variables' => $variables]; + } + + $params += $extraParams; + $this->postGraphQL($params); + + return $this; + } + + /** + * Execute a POST to the GraphQL endpoint. + * + * Use this over graphQL() when you need more control or want to + * test how your server behaves on incorrect inputs. + * + * @param array $data + * @param array $headers + * @return $this + */ + protected function postGraphQL(array $data, array $headers = []): self + { + $this->post( + $this->graphQLEndpointUrl(), + $data, + $headers + ); + + return $this; + } + + /** + * Send a multipart form request to GraphQL. + * + * This is used for file uploads conforming to the specification: + * https://github.com/jaydenseric/graphql-multipart-request-spec + * + * @param array|array> $operations + * @param array> $map + * @param array|array $files + * @param array $headers Will be merged with Content-Type: multipart/form-data + * @return $this + */ + protected function multipartGraphQL(array $operations, array $map, array $files, array $headers = []) + { + $parameters = [ + 'operations' => json_encode($operations), + 'map' => json_encode($map), + ]; + + $this->call( + 'POST', + $this->graphQLEndpointUrl(), + $parameters, + [], + $files, + $this->transformHeadersToServerVars(array_merge( + [ + 'Content-Type' => 'multipart/form-data', + ], + $headers + )) + ); + + return $this; + } + + /** + * Execute the introspection query on the GraphQL server. + * + * @return $this + */ + protected function introspect(): self + { + if ($this->introspectionResult) { + return $this; + } + + $this->graphQL(Introspection::getIntrospectionQuery()); + $this->introspectionResult = $this->response; + + return $this; + } + + /** + * Run introspection and return a type by name, if present. + * + * @return array|null + */ + protected function introspectType(string $name): ?array + { + return $this->introspectByName('data.__schema.types', $name); + } + + /** + * Run introspection and return a directive by name, if present. + * + * @return array|null + */ + protected function introspectDirective(string $name): ?array + { + return $this->introspectByName('data.__schema.directives', $name); + } + + /** + * Run introspection and return a result from the given path by name, if present. + * + * @return array|null + */ + protected function introspectByName(string $path, string $name): ?array + { + if (! $this->introspectionResult) { + $this->introspect(); + } + + $results = data_get( + json_decode($this->introspectionResult->getContent(), true), + $path + ); + + return Arr::first( + $results, + static function (array $result) use ($name): bool { + return $result['name'] === $name; + } + ); + } + + /** + * Return the full URL to the GraphQL endpoint. + */ + protected function graphQLEndpointUrl(): string + { + /** @var \Illuminate\Contracts\Config\Repository $config */ + $config = app(ConfigRepository::class); + + return route($config->get('lighthouse.route.name')); + } + + /** + * Send the query and capture all chunks of the streamed response. + * + * @param string $query The GraphQL query to send + * @param array $variables The variables to include in the query + * @param array $extraParams Extra parameters to add to the HTTP payload + * @return array The chunked results + */ + protected function streamGraphQL(string $query, array $variables = [], array $extraParams = []): array + { + if ($this->deferStream === null) { + $this->setUpDeferStream(); + } + + $response = $this->graphQL($query, $variables, $extraParams); + + if (! $response->response instanceof StreamedResponse) { + Assert::fail('Expected the response to be a streamed response but got a regular response.'); + } + + $response->response->send(); + + return $this->deferStream->chunks; + } + + /** + * Set up the stream to make queries with @defer. + */ + protected function setUpDeferStream(): void + { + $this->deferStream = new MemoryStream; + + Container::getInstance()->singleton(CanStreamResponse::class, function (): MemoryStream { + return $this->deferStream; + }); + } + + protected function rethrowGraphQLErrors(): void + { + /** @var \Illuminate\Contracts\Config\Repository $config */ + $config = app(ConfigRepository::class); + $config->set('lighthouse.error_handlers', [RethrowingErrorHandler::class]); + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/MockDirective.php b/vendor/nuwave/lighthouse/src/Testing/MockDirective.php new file mode 100644 index 0000000..83b05fd --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/MockDirective.php @@ -0,0 +1,50 @@ +mockResolverService = $mockResolverService; + } + + /** + * SDL definition of the directive. + */ + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Allows you to easily hook up a resolver for an endpoint. +""" +directive @mock( + """ + Specify a unique key for the mock resolver. + """ + key: String = "default" +) on FIELD_DEFINITION +GRAPHQL; + } + + public function resolveField(FieldValue $fieldValue): FieldValue + { + return $fieldValue->setResolver( + function () { + $key = $this->directiveArgValue('key', 'default'); + $resolver = $this->mockResolverService->get($key); + + return $resolver(...func_get_args()); + } + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/MockResolver.php b/vendor/nuwave/lighthouse/src/Testing/MockResolver.php new file mode 100644 index 0000000..3c73d21 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/MockResolver.php @@ -0,0 +1,18 @@ +getMockBuilder(\stdClass::class)->addMethods(['__invoke']) + * once we no longer support PHPUnit 7. + */ +class MockResolver +{ + /** + * @noRector \Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector + * @return mixed|void Anything whatsoever. + */ + public function __invoke() + { + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/MockResolverService.php b/vendor/nuwave/lighthouse/src/Testing/MockResolverService.php new file mode 100644 index 0000000..d022005 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/MockResolverService.php @@ -0,0 +1,27 @@ + + */ + protected $mocks; + + /** + * Register a mock resolver that will be called through this resolver. + */ + public function register(callable $mock, string $key): void + { + $this->mocks[$key] = $mock; + } + + /** + * Return a mock resolver that was previously registered. + */ + public function get(string $key): callable + { + return $this->mocks[$key]; + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/MocksResolvers.php b/vendor/nuwave/lighthouse/src/Testing/MocksResolvers.php new file mode 100644 index 0000000..f537fc7 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/MocksResolvers.php @@ -0,0 +1,55 @@ +mockResolverExpects($this->atLeastOnce(), $key); + + if (is_callable($resolverOrValue)) { + $method->willReturnCallback($resolverOrValue); + } else { + $method->willReturn($resolverOrValue); + } + + return $method; + } + + /** + * Register a resolver for `@mock`. + * + * @param \PHPUnit\Framework\MockObject\Rule\InvocationOrder $invocationOrder + */ + protected function mockResolverExpects(object $invocationOrder, string $key = 'default'): InvocationMocker + { + $mock = $this->createMock(MockResolver::class); + + $this->registerMockResolver($mock, $key); + + return $mock + ->expects($invocationOrder) + ->method('__invoke'); + } + + /** + * Register a mock resolver that will be called through the `@mock` directive. + */ + protected function registerMockResolver(callable $mock, string $key): void + { + /** @var \Nuwave\Lighthouse\Testing\MockResolverService $mockResolverService */ + $mockResolverService = app(MockResolverService::class); + $mockResolverService->register($mock, $key); + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/RethrowingErrorHandler.php b/vendor/nuwave/lighthouse/src/Testing/RethrowingErrorHandler.php new file mode 100644 index 0000000..96797b4 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/RethrowingErrorHandler.php @@ -0,0 +1,22 @@ +assertJson([ + 'errors' => [ + [ + 'extensions' => [ + 'validation' => [ + $key => [ + $message, + ], + ], + ], + ], + ], + ]); + + return $this; + }; + } + + public function assertGraphQLValidationKeys(): Closure + { + return function (array $keys) { + $validation = TestResponseUtils::extractValidationErrors($this); + + Assert::assertNotNull($validation, 'Expected the query to return validation errors for specific fields.'); + /** @var array $validation */ + Assert::assertArrayHasKey('extensions', $validation); + $extensions = $validation['extensions']; + + Assert::assertNotNull($extensions, 'Expected the query to return validation errors for specific fields.'); + /** @var array $extensions */ + Assert::assertSame( + $keys, + array_keys($extensions[ValidationException::CATEGORY]), + 'Expected the query to return validation errors for specific fields.' + ); + + return $this; + }; + } + + public function assertGraphQLValidationPasses(): Closure + { + return function () { + $validation = TestResponseUtils::extractValidationErrors($this); + + Assert::assertNull($validation, 'Expected the query to have no validation errors.'); + + return $this; + }; + } + + public function assertGraphQLErrorMessage(): Closure + { + return function (string $message) { + $messages = $this->json('errors.*.message'); + Assert::assertContains( + $message, + $messages, + "Expected the GraphQL response to contain error message `{$message}`, got: ".\Safe\json_encode($messages) + ); + + return $this; + }; + } + + public function assertGraphQLErrorCategory(): Closure + { + return function (string $category) { + $this->assertJson([ + 'errors' => [ + [ + 'extensions' => [ + 'category' => $category, + ], + ], + ], + ]); + + return $this; + }; + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/TestResponseUtils.php b/vendor/nuwave/lighthouse/src/Testing/TestResponseUtils.php new file mode 100644 index 0000000..0f516ae --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/TestResponseUtils.php @@ -0,0 +1,29 @@ +json('errors') ?? []; + + return Arr::first( + $errors, + function (array $error): bool { + return Arr::get($error, 'extensions.category') === ValidationException::CATEGORY; + } + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/TestSchemaProvider.php b/vendor/nuwave/lighthouse/src/Testing/TestSchemaProvider.php new file mode 100644 index 0000000..862bf40 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/TestSchemaProvider.php @@ -0,0 +1,26 @@ +schema = &$schema; + } + + public function getSchemaString(): string + { + return $this->schema; + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/TestingServiceProvider.php b/vendor/nuwave/lighthouse/src/Testing/TestingServiceProvider.php new file mode 100644 index 0000000..04fac4e --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/TestingServiceProvider.php @@ -0,0 +1,31 @@ +app->singleton(MockResolverService::class); + + if (class_exists('Illuminate\Testing\TestResponse')) { + \Illuminate\Testing\TestResponse::mixin(new TestResponseMixin()); + } elseif (class_exists('Illuminate\Foundation\Testing\TestResponse')) { + \Illuminate\Foundation\Testing\TestResponse::mixin(new TestResponseMixin()); + } + } + + public function boot(Dispatcher $dispatcher): void + { + $dispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Testing/UsesTestSchema.php b/vendor/nuwave/lighthouse/src/Testing/UsesTestSchema.php new file mode 100644 index 0000000..b8cf0f6 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Testing/UsesTestSchema.php @@ -0,0 +1,29 @@ +bind( + SchemaSourceProvider::class, + function (): TestSchemaProvider { + if (! isset($this->schema)) { + throw new \Exception('Missing test schema, provide one by setting $this->schema.'); + } + + return new TestSchemaProvider($this->schema); + } + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Tracing/Tracing.php b/vendor/nuwave/lighthouse/src/Tracing/Tracing.php index 94903f5..42a6e57 100644 --- a/vendor/nuwave/lighthouse/src/Tracing/Tracing.php +++ b/vendor/nuwave/lighthouse/src/Tracing/Tracing.php @@ -2,22 +2,22 @@ namespace Nuwave\Lighthouse\Tracing; -use Carbon\Carbon; +use GraphQL\Language\Parser; use GraphQL\Type\Definition\ResolveInfo; -use Nuwave\Lighthouse\Events\StartRequest; -use Nuwave\Lighthouse\Events\ManipulateAST; -use Nuwave\Lighthouse\Schema\AST\ASTHelper; -use Nuwave\Lighthouse\Events\StartExecution; -use Nuwave\Lighthouse\Schema\AST\PartialParser; -use Nuwave\Lighthouse\Execution\ExtensionsResponse; +use Illuminate\Support\Carbon; use Nuwave\Lighthouse\Events\BuildExtensionsResponse; +use Nuwave\Lighthouse\Events\ManipulateAST; +use Nuwave\Lighthouse\Events\StartExecution; +use Nuwave\Lighthouse\Events\StartRequest; +use Nuwave\Lighthouse\Execution\ExtensionsResponse; +use Nuwave\Lighthouse\Schema\AST\ASTHelper; class Tracing { /** * The timestamp the request was initially started. * - * @var \Carbon\Carbon + * @var \Illuminate\Support\Carbon */ protected $requestStart; @@ -35,29 +35,23 @@ class Tracing * * Is reset between batches. * - * @var array[] + * @var array> */ protected $resolverTraces = []; /** * Set the tracing directive on all fields of the query to enable tracing them. - * - * @param \Nuwave\Lighthouse\Events\ManipulateAST $manipulateAST - * @return void */ public function handleManipulateAST(ManipulateAST $manipulateAST): void { ASTHelper::attachDirectiveToObjectTypeFields( $manipulateAST->documentAST, - PartialParser::directive('@tracing') + Parser::constDirective('@tracing') ); } /** * Handle request start. - * - * @param \Nuwave\Lighthouse\Events\StartRequest $startRequest - * @return void */ public function handleStartRequest(StartRequest $startRequest): void { @@ -67,9 +61,6 @@ class Tracing /** * Handle batch request start. - * - * @param \Nuwave\Lighthouse\Events\StartExecution $startExecution - * @return void */ public function handleStartExecution(StartExecution $startExecution): void { @@ -78,9 +69,6 @@ class Tracing /** * Return additional information for the result. - * - * @param \Nuwave\Lighthouse\Events\BuildExtensionsResponse $buildExtensionsResponse - * @return \Nuwave\Lighthouse\Execution\ExtensionsResponse */ public function handleBuildExtensionsResponse(BuildExtensionsResponse $buildExtensionsResponse): ExtensionsResponse { @@ -104,10 +92,8 @@ class Tracing /** * Record resolver execution time. * - * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo * @param float|int $start * @param float|int $end - * @return void */ public function record(ResolveInfo $resolveInfo, $start, $end): void { @@ -140,12 +126,11 @@ class Tracing * * @param float|int $start * @param float|int $end - * @return int */ protected function diffTimeInNanoseconds($start, $end): int { if ($this->platformSupportsNanoseconds()) { - return $end - $start; + return (int) ($end - $start); } // Difference is in seconds (with microsecond precision) @@ -157,8 +142,6 @@ class Tracing /** * Test if the current PHP version has the `hrtime` function available to get a nanosecond precision point in time. - * - * @return bool */ protected function platformSupportsNanoseconds(): bool { diff --git a/vendor/nuwave/lighthouse/src/Tracing/TracingDirective.php b/vendor/nuwave/lighthouse/src/Tracing/TracingDirective.php index de28e1d..73c1e10 100644 --- a/vendor/nuwave/lighthouse/src/Tracing/TracingDirective.php +++ b/vendor/nuwave/lighthouse/src/Tracing/TracingDirective.php @@ -3,84 +3,55 @@ namespace Nuwave\Lighthouse\Tracing; use Closure; -use GraphQL\Deferred; use GraphQL\Type\Definition\ResolveInfo; -use Nuwave\Lighthouse\Schema\Values\FieldValue; +use Nuwave\Lighthouse\Execution\Resolved; use Nuwave\Lighthouse\Schema\Directives\BaseDirective; -use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; +use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; -use Nuwave\Lighthouse\Support\Contracts\DefinedDirective; +use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; -class TracingDirective extends BaseDirective implements FieldMiddleware, DefinedDirective +class TracingDirective extends BaseDirective implements FieldMiddleware { - const NAME = 'tracing'; - /** * @var \Nuwave\Lighthouse\Tracing\Tracing */ protected $tracing; - /** - * TracingDirective constructor. - * - * @param \Nuwave\Lighthouse\Tracing\Tracing $tracing - * @return void - */ public function __construct(Tracing $tracing) { $this->tracing = $tracing; } - /** - * Name of the directive. - * - * @return string - */ - public function name(): string - { - return self::NAME; - } - public static function definition(): string { - return /* @lang GraphQL */ <<<'SDL' + return /** @lang GraphQL */ <<<'GRAPHQL' """ Do not use this directive directly, it is automatically added to the schema when using the tracing extension. """ directive @tracing on FIELD_DEFINITION -SDL; +GRAPHQL; } - /** - * Resolve the field directive. - * - * @param \Nuwave\Lighthouse\Schema\Values\FieldValue $fieldValue - * @param \Closure $next - * @return \Nuwave\Lighthouse\Schema\Values\FieldValue - */ public function handleField(FieldValue $fieldValue, Closure $next): FieldValue { + // Make sure this middleware is applied last $fieldValue = $next($fieldValue); - $resolver = $fieldValue->getResolver(); + $previousResolver = $fieldValue->getResolver(); - return $fieldValue->setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver) { + $fieldValue->setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($previousResolver) { $start = $this->tracing->getTime(); - - $result = $resolver($root, $args, $context, $resolveInfo); - + $result = $previousResolver($root, $args, $context, $resolveInfo); $end = $this->tracing->getTime(); - if ($result instanceof Deferred) { - $result->then(function () use ($resolveInfo, $start, $end): void { - $this->tracing->record($resolveInfo, $start, $end); - }); - } else { + Resolved::handle($result, function () use ($resolveInfo, $start, $end): void { $this->tracing->record($resolveInfo, $start, $end); - } + }); return $result; }); + + return $fieldValue; } } diff --git a/vendor/nuwave/lighthouse/src/Tracing/TracingServiceProvider.php b/vendor/nuwave/lighthouse/src/Tracing/TracingServiceProvider.php index f941a06..e2c2348 100644 --- a/vendor/nuwave/lighthouse/src/Tracing/TracingServiceProvider.php +++ b/vendor/nuwave/lighthouse/src/Tracing/TracingServiceProvider.php @@ -2,28 +2,28 @@ namespace Nuwave\Lighthouse\Tracing; -use Illuminate\Support\ServiceProvider; -use Nuwave\Lighthouse\Events\StartRequest; -use Nuwave\Lighthouse\Events\ManipulateAST; -use Nuwave\Lighthouse\Events\StartExecution; -use Nuwave\Lighthouse\Events\BuildExtensionsResponse; -use Nuwave\Lighthouse\Schema\Factories\DirectiveFactory; use Illuminate\Contracts\Events\Dispatcher as EventsDispatcher; +use Illuminate\Support\ServiceProvider; +use Nuwave\Lighthouse\Events\BuildExtensionsResponse; +use Nuwave\Lighthouse\Events\ManipulateAST; +use Nuwave\Lighthouse\Events\RegisterDirectiveNamespaces; +use Nuwave\Lighthouse\Events\StartExecution; +use Nuwave\Lighthouse\Events\StartRequest; class TracingServiceProvider extends ServiceProvider { - /** - * Bootstrap any application services. - * - * @param \Nuwave\Lighthouse\Schema\Factories\DirectiveFactory $directiveFactory - * @param \Illuminate\Contracts\Events\Dispatcher $eventsDispatcher - * @return void - */ - public function boot(DirectiveFactory $directiveFactory, EventsDispatcher $eventsDispatcher): void + public function register(): void { - $directiveFactory->addResolved( - TracingDirective::NAME, - TracingDirective::class + $this->app->singleton(Tracing::class); + } + + public function boot(EventsDispatcher $eventsDispatcher): void + { + $eventsDispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } ); $eventsDispatcher->listen( @@ -46,14 +46,4 @@ class TracingServiceProvider extends ServiceProvider Tracing::class.'@handleBuildExtensionsResponse' ); } - - /** - * Register any application services. - * - * @return void - */ - public function register(): void - { - $this->app->singleton(Tracing::class); - } } diff --git a/vendor/nuwave/lighthouse/src/Validation/BaseRulesDirective.php b/vendor/nuwave/lighthouse/src/Validation/BaseRulesDirective.php new file mode 100644 index 0000000..d710f63 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Validation/BaseRulesDirective.php @@ -0,0 +1,156 @@ +directiveArgValue('apply'); + + // Custom rules may be referenced through their fully qualified class name. + // The Laravel validator expects a class instance to be passed, so we + // resolve any given rule where a corresponding class exists. + foreach ($rules as $key => $rule) { + if (class_exists($rule)) { + $rules[$key] = app($rule); + } + } + + return $rules; + } + + public function messages(): array + { + $messages = $this->directiveArgValue('messages'); + if ($messages === null) { + return []; + } + + if (isset($messages[0])) { + /** @var array $flattened */ + $flattened = []; + + /** + * We know this holds true, because it has been validated before. + * + * @var array{rule: string, message: string} $messageMap + */ + foreach ($messages as $messageMap) { + $flattened[$messageMap['rule']] = $messageMap['message']; + } + + return $flattened; + } + + return $messages; + } + + public function attribute(): ?string + { + return $this->directiveArgValue('attribute'); + } + + public function manipulateArgDefinition( + DocumentAST &$documentAST, + InputValueDefinitionNode &$argDefinition, + FieldDefinitionNode &$parentField, + ObjectTypeDefinitionNode &$parentType + ) { + $this->validateRulesArg(); + $this->validateMessageArg(); + } + + protected function validateRulesArg(): void + { + $rules = $this->directiveArgValue('apply'); + + if (! is_array($rules)) { + $this->invalidApplyArgument($rules); + } + + if (count($rules) === 0) { + $this->invalidApplyArgument($rules); + } + + foreach ($rules as $rule) { + if (! is_string($rule)) { + $this->invalidApplyArgument($rules); + } + } + } + + protected function validateMessageArg(): void + { + $messages = $this->directiveArgValue('messages'); + if ($messages === null) { + return; + } + + if (! is_array($messages)) { + $this->invalidMessageArgument($messages); + } + + if (isset($messages[0])) { + foreach ($messages as $messageMap) { + if (! is_array($messageMap)) { + $this->invalidMessageArgument($messages); + } + + $rule = $messageMap['rule'] ?? null; + if (! is_string($rule)) { + $this->invalidMessageArgument($messages); + } + + $message = $messageMap['message'] ?? null; + if (! is_string($message)) { + $this->invalidMessageArgument($messages); + } + } + } else { + foreach ($messages as $rule => $message) { + if (! is_string($rule)) { + $this->invalidMessageArgument($messages); + } + + if (! is_string($message)) { + $this->invalidMessageArgument($messages); + } + } + } + } + + /** + * @param mixed $messages Whatever faulty value was given for messages + * @throws DefinitionException + */ + protected function invalidMessageArgument($messages): void + { + $encoded = \Safe\json_encode($messages); + throw new DefinitionException( + "The `messages` argument of @`{$this->name()}` on `{$this->nodeName()} must be a list of input values with the string keys `rule` and `message`, got: {$encoded}" + ); + } + + /** + * @param mixed $apply Any invalid value + * + * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException + */ + protected function invalidApplyArgument($apply): void + { + $encoded = \Safe\json_encode($apply); + throw new DefinitionException( + "The `apply` argument of @`{$this->name()}` on `{$this->nodeName()}` has to be a list of strings, got: {$encoded}" + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Validation/RulesDirective.php b/vendor/nuwave/lighthouse/src/Validation/RulesDirective.php new file mode 100644 index 0000000..bf7fb23 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Validation/RulesDirective.php @@ -0,0 +1,53 @@ + + */ + public $rules = []; + + /** + * The gathered messages. + * + * @var array + */ + public $messages = []; + + /** + * The gathered attributes. + * + * @var array + */ + public $attributes = []; + + public function __construct(ArgumentSet $argumentSet) + { + $this->gatherRulesRecursively($argumentSet, []); + } + + /** + * @param array $argumentPath + */ + public function gatherRulesRecursively(ArgumentSet $argumentSet, array $argumentPath): void + { + $this->gatherRulesForArgumentSet($argumentSet, $argumentSet->directives, $argumentPath); + + $argumentsWithUndefined = $argumentSet->argumentsWithUndefined(); + foreach ($argumentsWithUndefined as $name => $argument) { + $nestedPath = array_merge($argumentPath, [$name]); + + $directivesForArray = $argument->directives->filter( + Utils::instanceofMatcher(ArgDirectiveForArray::class) + ); + $this->gatherRulesForArgument($argument, $directivesForArray, $nestedPath); + + $directivesForArgument = $argument->directives->filter( + Utils::instanceofMatcher(ArgDirective::class) + ); + + if ( + $argument->type instanceof ListType + && is_array($argument->value) + ) { + foreach ($argument->value as $index => $value) { + $this->handleArgumentValue($value, $directivesForArgument, array_merge($nestedPath, [$index])); + } + } else { + $this->handleArgumentValue($argument->value, $directivesForArgument, $nestedPath); + } + } + } + + /** + * @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> $directives + * @param array $path + */ + public function gatherRulesForArgumentSet(ArgumentSet $argumentSet, Collection $directives, array $path): void + { + foreach ($directives as $directive) { + if ($directive instanceof ArgumentSetValidation) { + if (Utils::classUsesTrait($directive, HasArgumentValue::class)) { + /** + * @psalm-suppress UndefinedDocblockClass + * @var \Nuwave\Lighthouse\Support\Contracts\Directive&\Nuwave\Lighthouse\Support\Contracts\ArgumentSetValidation&\Nuwave\Lighthouse\Support\Traits\HasArgumentValue $directive + */ + // @phpstan-ignore-next-line using trait in typehint + $directive->setArgumentValue($argumentSet); + } + + $this->extractValidationForArgumentSet($directive, $path); + } + } + } + + /** + * @param mixed $value Any argument value is possible + * @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> $directives + * @param array $path + */ + public function gatherRulesForArgument($value, Collection $directives, array $path): void + { + foreach ($directives as $directive) { + if ($directive instanceof ArgumentValidation) { + if (Utils::classUsesTrait($directive, HasArgumentValue::class)) { + /** + * @psalm-suppress UndefinedDocblockClass + * @var \Nuwave\Lighthouse\Support\Contracts\Directive&\Nuwave\Lighthouse\Support\Contracts\ArgumentValidation&\Nuwave\Lighthouse\Support\Traits\HasArgumentValue $directive + */ + // @phpstan-ignore-next-line using trait in typehint + $directive->setArgumentValue($value); + } + + $this->extractValidationForArgument($directive, $path); + } + } + } + + /** + * @param \Nuwave\Lighthouse\Execution\Arguments\Argument|\Nuwave\Lighthouse\Execution\Arguments\ArgumentSet|mixed $value + * @param \Illuminate\Support\Collection<\Nuwave\Lighthouse\Support\Contracts\Directive> $directives + * @param array $path + */ + protected function handleArgumentValue($value, Collection $directives, array $path): void + { + $this->gatherRulesForArgument($value, $directives, $path); + + if ($value instanceof ArgumentSet) { + $this->gatherRulesRecursively($value, $path); + } + } + + /** + * @param array $argumentPath + */ + public function extractValidationForArgumentSet(ArgumentSetValidation $directive, array $argumentPath): void + { + $qualifiedRulesMap = array_map( + function (array $rules) use ($argumentPath): array { + return $this->qualifyArgumentReferences($rules, $argumentPath); + }, + $directive->rules() + ); + + $this->rules = array_merge_recursive( + $this->rules, + $this->wrap($qualifiedRulesMap, $argumentPath) + ); + + $this->messages += $this->wrap($directive->messages(), $argumentPath); + + $this->attributes = array_merge( + $this->attributes, + $this->wrap($directive->attributes(), $argumentPath) + ); + } + + /** + * @param array $argumentPath + */ + public function extractValidationForArgument(ArgumentValidation $directive, array $argumentPath): void + { + $qualifiedRules = $this->qualifyArgumentReferences( + $directive->rules(), + // The last element is the name of the argument the rule is defined upon. + // We want the qualified path to start from the parent level. + array_slice($argumentPath, 0, -1) + ); + + $this->rules = array_merge_recursive( + $this->rules, + [implode('.', $argumentPath) => $qualifiedRules] + ); + + $this->messages += $this->wrap($directive->messages(), $argumentPath); + + $attribute = $directive->attribute(); + if (null !== $attribute) { + $this->attributes = array_merge( + $this->attributes, + [implode('.', $argumentPath) => $attribute] + ); + } + } + + /** + * @param array $rulesOrMessages + * @param array $path + * @return array + */ + protected function wrap(array $rulesOrMessages, array $path): array + { + $withPath = []; + + foreach ($rulesOrMessages as $key => $value) { + $combinedPath = implode('.', array_merge($path, [$key])); + + $withPath[$combinedPath] = $value; + } + + return $withPath; + } + + /** + * Prepend rule arguments that refer to other arguments with the full path. + * + * This may be necessary to allow certain rules to be reusable when placed + * upon input arguments. For example, `required_with:foo` may be defined + * on an input value that is nested within the arguments under `input.0`. + * It is thus changed to the full reference `required_with:input.0.foo`. + * + * @param array $rules + * @param array $argumentPath + * @return array|object> + */ + protected function qualifyArgumentReferences(array $rules, array $argumentPath): array + { + return array_map( + static function ($rule) use ($argumentPath) { + if (is_object($rule)) { + return $rule; + } + + /** + * @var array{ + * 0: string, + * 1: array, + * } $parsed + */ + $parsed = ValidationRuleParser::parse($rule); + + $name = $parsed[0]; + $args = $parsed[1]; + + // Those rule lists are a subset of https://github.com/illuminate/validation/blob/8079fd53dee983e7c52d1819ae3b98c71a64fbc0/Validator.php#L206-L236 + // using the docs to know which ones reference other fields: https://laravel.com/docs/8.x/validation#available-validation-rules + // We do not handle the Exclude* rules, those mutate the input and are not supported. + + // Rules where the first argument is a field reference + if (in_array($name, [ + 'Different', + 'Gt', + 'Gte', + 'Lt', + 'Lte', + 'RequiredIf', + 'RequiredUnless', + 'ProhibitedIf', + 'ProhibitedUnless', + 'Same', + ])) { + $args[0] = implode('.', array_merge($argumentPath, [$args[0]])); + } + + // Rules where all arguments are field references + if (in_array($name, [ + 'RequiredWith', + 'RequiredWithAll', + 'RequiredWithout', + 'RequiredWithoutAll', + ])) { + $args = array_map( + static function (string $field) use ($argumentPath): string { + return implode('.', array_merge($argumentPath, [$field])); + }, + $args + ); + } + + // Laravel expects the rule to be a flat array of name, arg1, arg2, ... + return array_merge([$name], $args); + }, + $rules + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Validation/ValidateDirective.php b/vendor/nuwave/lighthouse/src/Validation/ValidateDirective.php new file mode 100644 index 0000000..5b22fb2 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Validation/ValidateDirective.php @@ -0,0 +1,65 @@ +validationFactory = $validationFactory; + } + + public static function definition(): string + { + return /** @lang GraphQL */ <<<'GRAPHQL' +""" +Run validation on a field. +""" +directive @validate on FIELD_DEFINITION +GRAPHQL; + } + + public function handleField(FieldValue $fieldValue, Closure $next): FieldValue + { + $resolver = $fieldValue->getResolver(); + + return $next( + $fieldValue->setResolver( + function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver) { + $argumentSet = $resolveInfo->argumentSet; + $rulesGatherer = new RulesGatherer($argumentSet); + + $validator = $this->validationFactory + ->make( + $args, + $rulesGatherer->rules, + $rulesGatherer->messages, + $rulesGatherer->attributes + ); + + if ($validator->fails()) { + $path = implode('.', $resolveInfo->path); + + throw new ValidationException("Validation failed for the field [$path].", $validator); + } + + return $resolver($root, $args, $context, $resolveInfo); + } + ) + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Validation/ValidationServiceProvider.php b/vendor/nuwave/lighthouse/src/Validation/ValidationServiceProvider.php new file mode 100644 index 0000000..8582252 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Validation/ValidationServiceProvider.php @@ -0,0 +1,20 @@ +listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Validation/Validator.php b/vendor/nuwave/lighthouse/src/Validation/Validator.php new file mode 100644 index 0000000..8d84678 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Validation/Validator.php @@ -0,0 +1,51 @@ +args = $args; + } + + /** + * Retrieve the value of an argument. + * + * @param string $key The key of the argument, may use dot notation to get nested values. + * @param mixed|null $default Returned in case the argument is not present. + * @return mixed The value of the argument or the default. + */ + protected function arg(string $key, $default = null) + { + return Arr::get( + $this->args->toArray(), + $key, + $default + ); + } +} diff --git a/vendor/nuwave/lighthouse/src/Validation/ValidatorDirective.php b/vendor/nuwave/lighthouse/src/Validation/ValidatorDirective.php new file mode 100644 index 0000000..a447b87 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/Validation/ValidatorDirective.php @@ -0,0 +1,156 @@ +validator()->rules(); + } + + public function messages(): array + { + return $this->validator()->messages(); + } + + public function attributes(): array + { + return $this->validator()->attributes(); + } + + protected function validator(): Validator + { + if ($this->validator === null) { + /** @var \Nuwave\Lighthouse\Validation\Validator $validator */ + $validator = app( + // We precomputed and validated the full class name at schema build time + $this->directiveArgValue('class') + ); + // @phpstan-ignore-next-line Since this directive can only be defined on a field or input, this must be ArgumentSet + $validator->setArgs($this->argumentValue); + + return $this->validator = $validator; + } + + return $this->validator; + } + + public function manipulateTypeDefinition(DocumentAST &$documentAST, TypeDefinitionNode &$typeDefinition) + { + if (! $typeDefinition instanceof InputObjectTypeDefinitionNode) { + throw new DefinitionException( + "Can not use @validator on non input type {$typeDefinition->name->value}." + ); + } + + if ($this->directiveHasArgument('class')) { + $classCandidate = $this->directiveArgValue('class'); + } else { + $classCandidate = $typeDefinition->name->value.'Validator'; + } + + $this->setFullClassnameOnDirective($typeDefinition, $classCandidate); + } + + public function manipulateFieldDefinition( + DocumentAST &$documentAST, + FieldDefinitionNode &$fieldDefinition, + ObjectTypeDefinitionNode &$parentType + ) { + if ($this->directiveHasArgument('class')) { + $classCandidate = $this->directiveArgValue('class'); + } else { + $classCandidate = $parentType->name->value + .'\\' + .ucfirst($fieldDefinition->name->value) + .'Validator'; + } + + $this->setFullClassnameOnDirective($fieldDefinition, $classCandidate); + } + + /** + * Set the full classname of the validator class on the directive. + * + * This allows accessing it straight away when resolving the query. + * + * @param (\GraphQL\Language\AST\TypeDefinitionNode&\GraphQL\Language\AST\Node)|\GraphQL\Language\AST\FieldDefinitionNode $definition + */ + protected function setFullClassnameOnDirective(Node &$definition, string $classCandidate): void + { + $validatorClass = $this->namespaceValidatorClass($classCandidate); + + // @phpstan-ignore-next-line The passed in Node types all have the property $directives + foreach ($definition->directives as $directive) { + if ($directive->name->value === $this->name()) { + $directive->arguments = ASTHelper::mergeUniqueNodeList( + $directive->arguments, + [Parser::argument('class: "'.addslashes($validatorClass).'"')], + true + ); + } + } + } + + /** + * @return class-string<\Nuwave\Lighthouse\Validation\Validator> + */ + protected function namespaceValidatorClass(string $classCandidate): string + { + /** + * @var class-string<\Nuwave\Lighthouse\Validation\Validator> $validatorClassName We know this because of the callback + */ + $validatorClassName = $this->namespaceClassName( + $classCandidate, + (array) config('lighthouse.namespaces.validators'), + function (string $classCandidate): bool { + return is_subclass_of($classCandidate, Validator::class); + } + ); + + return $validatorClassName; + } +} diff --git a/vendor/nuwave/lighthouse/src/WhereConditions/Operator.php b/vendor/nuwave/lighthouse/src/WhereConditions/Operator.php new file mode 100644 index 0000000..fd07d39 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/WhereConditions/Operator.php @@ -0,0 +1,38 @@ + $whereConditions + * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder + */ + public function applyConditions($builder, array $whereConditions, string $boolean); +} diff --git a/vendor/nuwave/lighthouse/src/WhereConditions/SQLOperator.php b/vendor/nuwave/lighthouse/src/WhereConditions/SQLOperator.php new file mode 100644 index 0000000..9f21430 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/WhereConditions/SQLOperator.php @@ -0,0 +1,128 @@ +`)" + GT @enum(value: ">") + + "Greater than or equal operator (`>=`)" + GTE @enum(value: ">=") + + "Less than operator (`<`)" + LT @enum(value: "<") + + "Less than or equal operator (`<=`)" + LTE @enum(value: "<=") + + "Simple pattern matching (`LIKE`)" + LIKE @enum(value: "LIKE") + + "Negation of simple pattern matching (`NOT LIKE`)" + NOT_LIKE @enum(value: "NOT_LIKE") + + "Whether a value is within a set of values (`IN`)" + IN @enum(value: "In") + + "Whether a value is not within a set of values (`NOT IN`)" + NOT_IN @enum(value: "NotIn") + + "Whether a value is within a range of values (`BETWEEN`)" + BETWEEN @enum(value: "Between") + + "Whether a value is not within a range of values (`NOT BETWEEN`)" + NOT_BETWEEN @enum(value: "NotBetween") + + "Whether a value is null (`IS NULL`)" + IS_NULL @enum(value: "Null") + + "Whether a value is not null (`IS NOT NULL`)" + IS_NOT_NULL @enum(value: "NotNull") +} +GRAPHQL; + } + + public function default(): string + { + return 'EQ'; + } + + public function defaultHasOperator(): string + { + return 'GTE'; + } + + public function applyConditions($builder, array $whereConditions, string $boolean) + { + $column = $whereConditions['column']; + + // Laravel's conditions always start off with this prefix + $method = 'where'; + + // The first argument to conditions methods is always the column name + $args = [$column]; + + // Some operators require calling Laravel's conditions in different ways + $operator = $whereConditions['operator']; + $arity = $this->operatorArity($operator); + + if ($arity === 3) { + // Usually, the operator is passed as the second argument to the condition + // method, e.g. ->where('some_col', '=', $value) + $args[] = $operator; + } else { + // We utilize the fact that the operators are named after Laravel's condition + // methods so we can simply append the name, e.g. whereNull, whereNotBetween + $method .= $operator; + } + + if ($arity > 1) { + // The conditions with arity 1 require no args apart from the column name. + // All other arities take a value to query against. + if (! array_key_exists('value', $whereConditions)) { + throw new Error( + self::missingValueForColumn($column) + ); + } + + $args[] = $whereConditions['value']; + } + + // The condition methods always have the `$boolean` arg after the value + $args[] = $boolean; + + return $builder->{$method}(...$args); + } + + protected function operatorArity(string $operator): int + { + if (in_array($operator, ['Null', 'NotNull'])) { + return 1; + } + + if (in_array($operator, ['In', 'NotIn', 'Between', 'NotBetween'])) { + return 2; + } + + return 3; + } +} diff --git a/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsBaseDirective.php b/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsBaseDirective.php new file mode 100644 index 0000000..a2592dd --- /dev/null +++ b/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsBaseDirective.php @@ -0,0 +1,200 @@ +operator = $operator; + } + + /** + * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder + * @param array $whereConditions + * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder + */ + public function handleWhereConditions( + object $builder, + array $whereConditions, + Model $model = null, + string $boolean = 'and' + ) { + if ($builder instanceof EloquentBuilder) { + $model = $builder->getModel(); + } + + if ($andConnectedConditions = $whereConditions['AND'] ?? null) { + $builder->whereNested( + function ($builder) use ($andConnectedConditions, $model): void { + foreach ($andConnectedConditions as $condition) { + $this->handleWhereConditions($builder, $condition, $model); + } + }, + $boolean + ); + } + + if ($orConnectedConditions = $whereConditions['OR'] ?? null) { + $builder->whereNested( + function ($builder) use ($orConnectedConditions, $model): void { + foreach ($orConnectedConditions as $condition) { + $this->handleWhereConditions($builder, $condition, $model, 'or'); + } + }, + $boolean + ); + } + + if (($hasRelationConditions = $whereConditions['HAS'] ?? null) && $model) { + $nestedBuilder = $this->handleHasCondition( + $model, + $hasRelationConditions['relation'], + $hasRelationConditions['operator'], + $hasRelationConditions['amount'], + $hasRelationConditions['condition'] ?? null + ); + + // @phpstan-ignore-next-line Simply wrong, maybe from Larastan? + $builder->addNestedWhereQuery($nestedBuilder, $boolean); + } + + if ($column = $whereConditions['column'] ?? null) { + static::assertValidColumnReference($column); + + return $this->operator->applyConditions($builder, $whereConditions, $boolean); + } + + return $builder; + } + + /** + * @param array|null $condition + */ + public function handleHasCondition( + Model $model, + string $relation, + string $operator, + int $amount, + ?array $condition = null + ): QueryBuilder { + return $model + ->newQuery() + ->whereHas( + $relation, + $condition + ? function ($builder) use ($condition): void { + $this->handleWhereConditions( + $builder, + $this->prefixConditionWithTableName( + $condition, + $builder->getModel() + ), + $builder->getModel() + ); + } + : null, + $operator, + $amount + ) + ->getQuery(); + } + + public static function invalidColumnName(string $column): string + { + return "Column names may contain only alphanumerics or underscores, and may not begin with a digit, got: $column"; + } + + public function manipulateArgDefinition( + DocumentAST &$documentAST, + InputValueDefinitionNode &$argDefinition, + FieldDefinitionNode &$parentField, + ObjectTypeDefinitionNode &$parentType + ): void { + if ($this->hasAllowedColumns()) { + $restrictedWhereConditionsName = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType).$this->generatedInputSuffix(); + $argDefinition->type = Parser::namedType($restrictedWhereConditionsName); + $allowedColumnsEnumName = $this->generateColumnsEnum($documentAST, $argDefinition, $parentField, $parentType); + + $documentAST + ->setTypeDefinition( + WhereConditionsServiceProvider::createWhereConditionsInputType( + $restrictedWhereConditionsName, + "Dynamic WHERE conditions for the `{$argDefinition->name->value}` argument on the query `{$parentField->name->value}`.", + $allowedColumnsEnumName + ) + ) + ->setTypeDefinition( + WhereConditionsServiceProvider::createHasConditionsInputType( + $restrictedWhereConditionsName, + "Dynamic HAS conditions for WHERE conditions for the `{$argDefinition->name->value}` argument on the query `{$parentField->name->value}`." + ) + ); + } else { + $argDefinition->type = Parser::namedType(WhereConditionsServiceProvider::DEFAULT_WHERE_CONDITIONS); + } + } + + /** + * Ensure the column name is well formed to prevent SQL injection. + * + * @throws \GraphQL\Error\Error + */ + protected static function assertValidColumnReference(string $column): void + { + // A valid column reference: + // - must not start with a digit, dot or hyphen + // - must contain only alphanumerics, digits, underscores, dots, hyphens or JSON references + $match = \Safe\preg_match('/^(?![0-9.-])([A-Za-z0-9_.-]|->)*$/', $column); + if ($match === 0) { + throw new Error( + self::invalidColumnName($column) + ); + } + } + + /** + * If the condition references a column, prefix it with the table name. + * + * This is important for queries which can otherwise be ambiguous, for + * example when multiple tables with a column "id" are involved. + * + * @param array $condition + * @return array + */ + protected function prefixConditionWithTableName(array $condition, Model $model): array + { + if ($column = $condition['column'] ?? null) { + $condition['column'] = $model->getTable().'.'.$column; + } + + return $condition; + } + + /** + * Get the suffix that will be added to generated input types. + */ + abstract protected function generatedInputSuffix(): string; +} diff --git a/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsDirective.php b/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsDirective.php new file mode 100644 index 0000000..88b37f6 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsDirective.php @@ -0,0 +1,47 @@ +|null $value + */ + public function handleBuilder($builder, $value): object + { + if (null === $value) { + return $builder; + } + + return $this->handleWhereConditions($builder, $value); + } + + protected function generatedInputSuffix(): string + { + return 'WhereConditions'; + } +} diff --git a/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsServiceProvider.php b/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsServiceProvider.php new file mode 100644 index 0000000..c0961f9 --- /dev/null +++ b/vendor/nuwave/lighthouse/src/WhereConditions/WhereConditionsServiceProvider.php @@ -0,0 +1,142 @@ +app->bind(Operator::class, SQLOperator::class); + } + + public function boot(Dispatcher $dispatcher): void + { + $dispatcher->listen( + RegisterDirectiveNamespaces::class, + static function (): string { + return __NAMESPACE__; + } + ); + + $dispatcher->listen( + ManipulateAST::class, + function (ManipulateAST $manipulateAST): void { + /** @var \Nuwave\Lighthouse\WhereConditions\Operator $operator */ + $operator = $this->app->make(Operator::class); + + $manipulateAST->documentAST + ->setTypeDefinition( + static::createWhereConditionsInputType( + static::DEFAULT_WHERE_CONDITIONS, + 'Dynamic WHERE conditions for queries.', + 'String' + ) + ) + ->setTypeDefinition( + static::createHasConditionsInputType( + static::DEFAULT_WHERE_CONDITIONS, + 'Dynamic HAS conditions for WHERE condition queries.' + ) + ) + ->setTypeDefinition( + Parser::enumTypeDefinition( + $operator->enumDefinition() + ) + ) + ->setTypeDefinition( + Parser::scalarTypeDefinition(/** @lang GraphQL */ ' + scalar Mixed @scalar(class: "MLL\\\GraphQLScalars\\\MixedScalar") + ') + ); + } + ); + } + + public static function createWhereConditionsInputType(string $name, string $description, string $columnType): InputObjectTypeDefinitionNode + { + $hasRelationInputName = $name.self::DEFAULT_WHERE_RELATION_CONDITIONS; + + /** @var \Nuwave\Lighthouse\WhereConditions\Operator $operator */ + $operator = app(Operator::class); + + $operatorName = Parser + ::enumTypeDefinition( + $operator->enumDefinition() + ) + ->name + ->value; + $operatorDefault = $operator->default(); + + return Parser::inputObjectTypeDefinition(/** @lang GraphQL */ <<enumDefinition() + ) + ->name + ->value; + $operatorDefault = $operator->defaultHasOperator(); + + return Parser::inputObjectTypeDefinition(/** @lang GraphQL */ <<|null $value The client given conditions + */ + public function handleBuilder($builder, $value): object + { + if (null === $value) { + return $builder; + } + + if (! $builder instanceof EloquentBuilder) { + throw new Exception('Can not get model from builder of class: '.get_class($builder)); + } + $model = $builder->getModel(); + + $this->handleWhereConditions( + $builder, + [ + 'HAS' => [ + 'relation' => $this->getRelationName(), + 'amount' => WhereConditionsServiceProvider::DEFAULT_HAS_AMOUNT, + 'operator' => '>=', + 'condition' => $value, + ], + ], + $model + ); + + return $builder; + } + + /** + * Get the name of the Eloquent relationship that is used for the query. + */ + public function getRelationName(): string + { + $relationName = $this->directiveArgValue('relation'); + + // If the relation name is not set explicitly, we assume the argument + // name follows a convention and contains the relation name + if (is_null($relationName)) { + $relationName = lcfirst( + Str::after($this->nodeName(), 'has') + ); + } + + return $relationName; + } + + protected function generatedInputSuffix(): string + { + return 'WhereHasConditions'; + } +} diff --git a/vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsDirective.php b/vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsDirective.php deleted file mode 100644 index fd5f9a1..0000000 --- a/vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsDirective.php +++ /dev/null @@ -1,224 +0,0 @@ -whereNested( - function ($builder) use ($andConnectedConstraints): void { - foreach ($andConnectedConstraints as $constraint) { - $this->handleBuilder($builder, $constraint); - } - } - ); - } - - if ($orConnectedConstraints = $whereConstraints['OR'] ?? null) { - $builder->whereNested( - function ($builder) use ($orConnectedConstraints): void { - foreach ($orConnectedConstraints as $constraint) { - $this->handleBuilder($builder, $constraint, true); - } - } - ); - } - - if ($notConnectedConstraints = $whereConstraints['NOT'] ?? null) { - $builder->whereNested( - function ($builder) use ($notConnectedConstraints): void { - foreach ($notConnectedConstraints as $constraint) { - $this->handleBuilder($builder, $constraint); - } - }, - 'not' - ); - } - - if ($column = $whereConstraints['column'] ?? null) { - if (! array_key_exists('value', $whereConstraints)) { - throw new Error( - self::missingValueForColumn($column) - ); - } - - if (! \Safe\preg_match('/^(?![0-9])[A-Za-z0-9_-]*$/', $column)) { - throw new Error( - self::INVALID_COLUMN_MESSAGE - ); - } - - $where = $nestedOr - ? 'orWhere' - : 'where'; - - $builder->{$where}( - $column, - $whereConstraints['operator'], - $whereConstraints['value'] - ); - } - - return $builder; - } - - public static function missingValueForColumn(string $column): string - { - return "Did not receive a value to match the WhereConstraints for column {$column}."; - } - - /** - * Manipulate the AST. - * - * @param \Nuwave\Lighthouse\Schema\AST\DocumentAST $documentAST - * @param \GraphQL\Language\AST\InputValueDefinitionNode $argDefinition - * @param \GraphQL\Language\AST\FieldDefinitionNode $parentField - * @param \GraphQL\Language\AST\ObjectTypeDefinitionNode $parentType - * @return \Nuwave\Lighthouse\Schema\AST\DocumentAST - */ - public function manipulateArgDefinition(DocumentAST &$documentAST, InputValueDefinitionNode &$argDefinition, FieldDefinitionNode &$parentField, ObjectTypeDefinitionNode &$parentType) - { - $allowedColumns = $this->directiveArgValue('columns'); - if (! $allowedColumns) { - return $documentAST; - } - - $restrictedWhereConstraintsName = $this->restrictedWhereConstraintsName($argDefinition, $parentField); - - $argDefinition->type = PartialParser::namedType($restrictedWhereConstraintsName); - - $allowedColumnsEnumName = $this->allowedColumnsEnumName($argDefinition, $parentField); - - return $documentAST - ->setTypeDefinition( - WhereConstraintsServiceProvider::createWhereConstraintsInputType( - $restrictedWhereConstraintsName, - "Dynamic WHERE constraints for the `{$argDefinition->name->value}` argument on the query `{$parentField->name->value}`.", - $allowedColumnsEnumName - ) - ) - ->setTypeDefinition( - $this->createAllowedColumnsEnum($argDefinition, $parentField, $allowedColumns, $allowedColumnsEnumName) - ); - } - - /** - * Create the name for the Enum that holds the allowed columns. - * - * @example FieldNameArgNameColumn - * - * @param \GraphQL\Language\AST\InputValueDefinitionNode $argDefinition - * @param \GraphQL\Language\AST\FieldDefinitionNode $parentField - * @return string - */ - protected function allowedColumnsEnumName(InputValueDefinitionNode &$argDefinition, FieldDefinitionNode &$parentField): string - { - return Str::studly($parentField->name->value) - .Str::studly($argDefinition->name->value) - .'Column'; - } - - /** - * Create the name for the restricted WhereConstraints input. - * - * @example FieldNameArgNameWhereConstraints - * - * @param \GraphQL\Language\AST\InputValueDefinitionNode $argDefinition - * @param \GraphQL\Language\AST\FieldDefinitionNode $parentField - * @return string - */ - protected function restrictedWhereConstraintsName(InputValueDefinitionNode &$argDefinition, FieldDefinitionNode &$parentField): string - { - return Str::studly($parentField->name->value) - .Str::studly($argDefinition->name->value) - .'WhereConstraints'; - } - - /** - * Create the Enum that holds the allowed columns. - * - * @param \GraphQL\Language\AST\InputValueDefinitionNode $argDefinition - * @param \GraphQL\Language\AST\FieldDefinitionNode $parentField - * @param string[] $allowedColumns - * @param string $allowedColumnsEnumName - * @return \GraphQL\Language\AST\EnumTypeDefinitionNode - */ - public function createAllowedColumnsEnum( - InputValueDefinitionNode &$argDefinition, - FieldDefinitionNode &$parentField, - array $allowedColumns, - string $allowedColumnsEnumName - ): EnumTypeDefinitionNode { - $enumValues = array_map( - function (string $columnName): string { - return - strtoupper( - Str::snake($columnName) - ) - .' @enum(value: "'.$columnName.'")'; - }, - $allowedColumns - ); - - $enumDefinition = "\"Allowed column names for the `{$argDefinition->name->value}` argument on the query `{$parentField->name->value}`.\"\n" - ."enum $allowedColumnsEnumName {\n"; - foreach ($enumValues as $enumValue) { - $enumDefinition .= "$enumValue\n"; - } - $enumDefinition .= '}'; - - return PartialParser::enumTypeDefinition($enumDefinition); - } -} diff --git a/vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsServiceProvider.php b/vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsServiceProvider.php deleted file mode 100644 index a3f0ae6..0000000 --- a/vendor/nuwave/lighthouse/src/WhereConstraints/WhereConstraintsServiceProvider.php +++ /dev/null @@ -1,61 +0,0 @@ -addResolved( - WhereConstraintsDirective::NAME, - WhereConstraintsDirective::class - ); - - $dispatcher->listen( - ManipulateAST::class, - function (ManipulateAST $manipulateAST): void { - $manipulateAST->documentAST - ->setTypeDefinition( - static::createWhereConstraintsInputType( - 'WhereConstraints', - 'Dynamic WHERE constraints for queries.', - 'String' - ) - ) - ->setTypeDefinition( - PartialParser::scalarTypeDefinition(' - scalar Mixed @scalar(class: "MLL\\\GraphQLScalars\\\Mixed") - ') - ); - } - ); - } - - public static function createWhereConstraintsInputType(string $name, string $description, string $columnType): InputObjectTypeDefinitionNode - { - return PartialParser::inputObjectTypeDefinition(" - input $name { - column: $columnType - operator: Operator = EQ - value: Mixed - AND: [$name!] - OR: [$name!] - NOT: [$name!] - } - "); - } -} diff --git a/vendor/nuwave/lighthouse/assets/default-schema.graphql b/vendor/nuwave/lighthouse/src/default-schema.graphql similarity index 64% rename from vendor/nuwave/lighthouse/assets/default-schema.graphql rename to vendor/nuwave/lighthouse/src/default-schema.graphql index 4c9db0e..96e0d0a 100644 --- a/vendor/nuwave/lighthouse/assets/default-schema.graphql +++ b/vendor/nuwave/lighthouse/src/default-schema.graphql @@ -1,12 +1,12 @@ -"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-01-01 13:00:00`." -scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime") - "A date string with format `Y-m-d`, e.g. `2011-05-23`." scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date") +"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`." +scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime") + type Query { - users: [User!]! @paginate(type: "paginator" model: "App\\User") - user(id: ID @eq): User @find(model: "App\\User") + users: [User!]! @paginate(defaultCount: 10) + user(id: ID @eq): User @find } type User { diff --git a/vendor/nuwave/lighthouse/src/lighthouse.php b/vendor/nuwave/lighthouse/src/lighthouse.php new file mode 100644 index 0000000..159366b --- /dev/null +++ b/vendor/nuwave/lighthouse/src/lighthouse.php @@ -0,0 +1,447 @@ + false, to disable the default route + | registration and take full control. + | + */ + + 'route' => [ + /* + * The URI the endpoint responds to, e.g. mydomain.com/graphql. + */ + 'uri' => '/graphql', + + /* + * Lighthouse creates a named route for convenient URL generation and redirects. + */ + 'name' => 'graphql', + + /* + * Beware that middleware defined here runs before the GraphQL execution phase, + * make sure to return spec-compliant responses in case an error is thrown. + */ + 'middleware' => [ + \Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class, + + // Logs in a user if they are authenticated. In contrast to Laravel's 'auth' + // middleware, this delegates auth and permission checks to the field level. + \Nuwave\Lighthouse\Support\Http\Middleware\AttemptAuthentication::class, + + // Logs every incoming GraphQL query. + // \Nuwave\Lighthouse\Support\Http\Middleware\LogGraphQLQueries::class, + ], + + /* + * The `prefix` and `domain` configuration options are optional. + */ + //'prefix' => '', + //'domain' => '', + ], + + /* + |-------------------------------------------------------------------------- + | Authentication Guard + |-------------------------------------------------------------------------- + | + | The guard to use for authenticating GraphQL requests, if needed. + | This setting is used whenever Lighthouse looks for an authenticated user, for example in directives + | such as `@guard` and when applying the `AttemptAuthentication` middleware. + | + */ + + 'guard' => 'api', + + /* + |-------------------------------------------------------------------------- + | Schema Location + |-------------------------------------------------------------------------- + | + | Path to your .graphql schema file. + | Additional schema files may be imported from within that file. + | + */ + + 'schema' => [ + 'register' => base_path('graphql/schema.graphql'), + ], + + /* + |-------------------------------------------------------------------------- + | Schema Cache + |-------------------------------------------------------------------------- + | + | A large part of schema generation consists of parsing and AST manipulation. + | This operation is very expensive, so it is highly recommended to enable + | caching of the final schema to optimize performance of large schemas. + | + */ + + 'cache' => [ + /* + * Setting to true enables schema caching. + */ + 'enable' => env('LIGHTHOUSE_CACHE_ENABLE', env('APP_ENV') !== 'local'), + + /* + * Allowed values: + * - 1: uses the store, key and ttl config values to store the schema as a string in the given cache store. + * - 2: uses the path config value to store the schema in a PHP file allowing OPcache to pick it up. + */ + 'version' => env('LIGHTHOUSE_CACHE_VERSION', 1), + + /* + * The name of the cache item for the schema cache. + * Only relevant if version is set to 1. + */ + 'key' => env('LIGHTHOUSE_CACHE_KEY', 'lighthouse-schema'), + + /* + * Allows using a specific cache store, uses the app's default if set to null. + * Only relevant if version is set to 1. + */ + 'store' => env('LIGHTHOUSE_CACHE_STORE', null), + + /* + * Duration in seconds the schema should remain cached, null means forever. + * Only relevant if version is set to 1. + */ + 'ttl' => env('LIGHTHOUSE_CACHE_TTL', null), + + /* + * File path to store the lighthouse schema. + * Only relevant if version is set to 2. + */ + 'path' => env('LIGHTHOUSE_CACHE_PATH', base_path('bootstrap/cache/lighthouse-schema.php')), + ], + + /* + |-------------------------------------------------------------------------- + | Namespaces + |-------------------------------------------------------------------------- + | + | These are the default namespaces where Lighthouse looks for classes to + | extend functionality of the schema. You may pass in either a string + | or an array, they are tried in order and the first match is used. + | + */ + + 'namespaces' => [ + 'models' => ['App', 'App\\Models'], + 'queries' => 'App\\GraphQL\\Queries', + 'mutations' => 'App\\GraphQL\\Mutations', + 'subscriptions' => 'App\\GraphQL\\Subscriptions', + 'interfaces' => 'App\\GraphQL\\Interfaces', + 'unions' => 'App\\GraphQL\\Unions', + 'scalars' => 'App\\GraphQL\\Scalars', + 'directives' => ['App\\GraphQL\\Directives'], + 'validators' => ['App\\GraphQL\\Validators'], + ], + + /* + |-------------------------------------------------------------------------- + | Security + |-------------------------------------------------------------------------- + | + | Control how Lighthouse handles security related query validation. + | Read more at https://webonyx.github.io/graphql-php/security/ + | + */ + + 'security' => [ + 'max_query_complexity' => \GraphQL\Validator\Rules\QueryComplexity::DISABLED, + 'max_query_depth' => \GraphQL\Validator\Rules\QueryDepth::DISABLED, + 'disable_introspection' => \GraphQL\Validator\Rules\DisableIntrospection::DISABLED, + ], + + /* + |-------------------------------------------------------------------------- + | Pagination + |-------------------------------------------------------------------------- + | + | Set defaults for the pagination features within Lighthouse, such as + | the @paginate directive, or paginated relation directives. + | + */ + + 'pagination' => [ + /* + * Allow clients to query paginated lists without specifying the amount of items. + * Setting this to `null` means clients have to explicitly ask for the count. + */ + 'default_count' => null, + + /* + * Limit the maximum amount of items that clients can request from paginated lists. + * Setting this to `null` means the count is unrestricted. + */ + 'max_count' => null, + ], + + /* + |-------------------------------------------------------------------------- + | Debug + |-------------------------------------------------------------------------- + | + | Control the debug level as described in https://webonyx.github.io/graphql-php/error-handling/ + | Debugging is only applied if the global Laravel debug config is set to true. + | + | When you set this value through an environment variable, use the following reference table: + | 0 => INCLUDE_NONE + | 1 => INCLUDE_DEBUG_MESSAGE + | 2 => INCLUDE_TRACE + | 3 => INCLUDE_TRACE | INCLUDE_DEBUG_MESSAGE + | 4 => RETHROW_INTERNAL_EXCEPTIONS + | 5 => RETHROW_INTERNAL_EXCEPTIONS | INCLUDE_DEBUG_MESSAGE + | 6 => RETHROW_INTERNAL_EXCEPTIONS | INCLUDE_TRACE + | 7 => RETHROW_INTERNAL_EXCEPTIONS | INCLUDE_TRACE | INCLUDE_DEBUG_MESSAGE + | 8 => RETHROW_UNSAFE_EXCEPTIONS + | 9 => RETHROW_UNSAFE_EXCEPTIONS | INCLUDE_DEBUG_MESSAGE + | 10 => RETHROW_UNSAFE_EXCEPTIONS | INCLUDE_TRACE + | 11 => RETHROW_UNSAFE_EXCEPTIONS | INCLUDE_TRACE | INCLUDE_DEBUG_MESSAGE + | 12 => RETHROW_UNSAFE_EXCEPTIONS | RETHROW_INTERNAL_EXCEPTIONS + | 13 => RETHROW_UNSAFE_EXCEPTIONS | RETHROW_INTERNAL_EXCEPTIONS | INCLUDE_DEBUG_MESSAGE + | 14 => RETHROW_UNSAFE_EXCEPTIONS | RETHROW_INTERNAL_EXCEPTIONS | INCLUDE_TRACE + | 15 => RETHROW_UNSAFE_EXCEPTIONS | RETHROW_INTERNAL_EXCEPTIONS | INCLUDE_TRACE | INCLUDE_DEBUG_MESSAGE + | + */ + + 'debug' => env('LIGHTHOUSE_DEBUG', \GraphQL\Error\DebugFlag::INCLUDE_DEBUG_MESSAGE | \GraphQL\Error\DebugFlag::INCLUDE_TRACE), + + /* + |-------------------------------------------------------------------------- + | Error Handlers + |-------------------------------------------------------------------------- + | + | Register error handlers that receive the Errors that occur during execution + | and handle them. You may use this to log, filter or format the errors. + | The classes must implement \Nuwave\Lighthouse\Execution\ErrorHandler + | + */ + + 'error_handlers' => [ + \Nuwave\Lighthouse\Execution\ValidationErrorHandler::class, + \Nuwave\Lighthouse\Execution\ExtensionErrorHandler::class, + \Nuwave\Lighthouse\Execution\ReportingErrorHandler::class, + ], + + /* + |-------------------------------------------------------------------------- + | Field Middleware + |-------------------------------------------------------------------------- + | + | Register global field middleware directives that wrap around every field. + | Execution happens in the defined order, before other field middleware. + | The classes must implement \Nuwave\Lighthouse\Support\Contracts\FieldMiddleware + | + */ + + 'field_middleware' => [ + \Nuwave\Lighthouse\Schema\Directives\TrimDirective::class, + \Nuwave\Lighthouse\Schema\Directives\SanitizeDirective::class, + \Nuwave\Lighthouse\Validation\ValidateDirective::class, + \Nuwave\Lighthouse\Schema\Directives\TransformArgsDirective::class, + \Nuwave\Lighthouse\Schema\Directives\SpreadDirective::class, + \Nuwave\Lighthouse\Schema\Directives\RenameArgsDirective::class, + ], + + /* + |-------------------------------------------------------------------------- + | Global ID + |-------------------------------------------------------------------------- + | + | The name that is used for the global id field on the Node interface. + | When creating a Relay compliant server, this must be named "id". + | + */ + + 'global_id_field' => 'id', + + /* + |-------------------------------------------------------------------------- + | Batched Queries + |-------------------------------------------------------------------------- + | + | GraphQL query batching means sending multiple queries to the server in one request, + | You may set this flag to either process or deny batched queries. + | + */ + + 'batched_queries' => true, + + /* + |-------------------------------------------------------------------------- + | Transactional Mutations + |-------------------------------------------------------------------------- + | + | If set to true, mutations such as @create or @update will be + | wrapped in a transaction to ensure atomicity. + | + */ + + 'transactional_mutations' => true, + + /* + |-------------------------------------------------------------------------- + | Mass Assignment Protection + |-------------------------------------------------------------------------- + | + | If set to true, mutations will use forceFill() over fill() when populating + | a model with arguments in mutation directives. Since GraphQL constrains + | allowed inputs by design, mass assignment protection is not needed. + | + */ + + 'force_fill' => true, + + /* + |-------------------------------------------------------------------------- + | Batchload Relations + |-------------------------------------------------------------------------- + | + | If set to true, relations marked with directives like @hasMany or @belongsTo + | will be optimized by combining the queries through the BatchLoader. + | + */ + + 'batchload_relations' => true, + + /* + |-------------------------------------------------------------------------- + | Non-Null Pagination Results + |-------------------------------------------------------------------------- + | + | If set to true, the generated result type of paginated lists will be marked + | as non-nullable. This is generally more convenient for clients, but will + | cause validation errors to bubble further up in the result. + | + | This setting will be removed and always true in v6. + | + */ + + 'non_null_pagination_results' => false, + + /* + |-------------------------------------------------------------------------- + | GraphQL Subscriptions + |-------------------------------------------------------------------------- + | + | Here you can define GraphQL subscription broadcaster and storage drivers + | as well their required configuration options. + | + */ + + 'subscriptions' => [ + /* + * Determines if broadcasts should be queued by default. + */ + 'queue_broadcasts' => env('LIGHTHOUSE_QUEUE_BROADCASTS', true), + + /* + * Determines the queue to use for broadcasting queue jobs. + */ + 'broadcasts_queue_name' => env('LIGHTHOUSE_BROADCASTS_QUEUE_NAME', null), + + /* + * Default subscription storage. + * + * Any Laravel supported cache driver options are available here. + */ + 'storage' => env('LIGHTHOUSE_SUBSCRIPTION_STORAGE', 'redis'), + + /* + * Default subscription storage time to live in seconds. + * + * Indicates how long a subscription can be active before it's automatically removed from storage. + * Setting this to `null` means the subscriptions are stored forever. This may cause + * stale subscriptions to linger indefinitely in case cleanup fails for any reason. + */ + 'storage_ttl' => env('LIGHTHOUSE_SUBSCRIPTION_STORAGE_TTL', null), + + /* + * Default subscription broadcaster. + */ + 'broadcaster' => env('LIGHTHOUSE_BROADCASTER', 'pusher'), + + /* + * Subscription broadcasting drivers with config options. + */ + 'broadcasters' => [ + 'log' => [ + 'driver' => 'log', + ], + 'pusher' => [ + 'driver' => 'pusher', + 'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class.'@pusher', + 'connection' => 'pusher', + ], + 'echo' => [ + 'driver' => 'echo', + 'connection' => env('LIGHTHOUSE_SUBSCRIPTION_REDIS_CONNECTION', 'default'), + 'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class.'@echoRoutes', + ], + ], + + /* + * Controls the format of the extensions response. + * Allowed values: 1, 2 + */ + 'version' => env('LIGHTHOUSE_SUBSCRIPTION_VERSION', 1), + + /* + * Should the subscriptions extension be excluded when the response has no subscription channel? + * This optimizes performance by sending less data, but clients must anticipate this appropriately. + * Will default to true in v6 and be removed in v7. + */ + 'exclude_empty' => env('LIGHTHOUSE_SUBSCRIPTION_EXCLUDE_EMPTY', false), + ], + + /* + |-------------------------------------------------------------------------- + | Defer + |-------------------------------------------------------------------------- + | + | Configuration for the experimental @defer directive support. + | + */ + + 'defer' => [ + /* + * Maximum number of nested fields that can be deferred in one query. + * Once reached, remaining fields will be resolved synchronously. + * 0 means unlimited. + */ + 'max_nested_fields' => 0, + + /* + * Maximum execution time for deferred queries in milliseconds. + * Once reached, remaining fields will be resolved synchronously. + * 0 means unlimited. + */ + 'max_execution_ms' => 0, + ], + + /* + |-------------------------------------------------------------------------- + | Apollo Federation + |-------------------------------------------------------------------------- + | + | Lighthouse can act as a federated service: https://www.apollographql.com/docs/federation/federation-spec. + | + */ + + 'federation' => [ + /* + * Location of resolver classes when resolving the `_entities` field. + */ + 'entities_resolver_namespace' => 'App\\GraphQL\\Entities', + ], + +]; diff --git a/vendor/thecodingmachine/safe/LICENSE b/vendor/thecodingmachine/safe/LICENSE new file mode 100644 index 0000000..4188a9b --- /dev/null +++ b/vendor/thecodingmachine/safe/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 TheCodingMachine + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/thecodingmachine/safe/README.md b/vendor/thecodingmachine/safe/README.md new file mode 100644 index 0000000..3c2ee62 --- /dev/null +++ b/vendor/thecodingmachine/safe/README.md @@ -0,0 +1,178 @@ +[![Latest Stable Version](https://poser.pugx.org/thecodingmachine/safe/v/stable.svg)](https://packagist.org/packages/thecodingmachine/safe) +[![Total Downloads](https://poser.pugx.org/thecodingmachine/safe/downloads.svg)](https://packagist.org/packages/thecodingmachine/safe) +[![Latest Unstable Version](https://poser.pugx.org/thecodingmachine/safe/v/unstable.svg)](https://packagist.org/packages/thecodingmachine/safe) +[![License](https://poser.pugx.org/thecodingmachine/safe/license.svg)](https://packagist.org/packages/thecodingmachine/safe) +[![Build Status](https://travis-ci.org/thecodingmachine/safe.svg?branch=master)](https://travis-ci.org/thecodingmachine/safe) +[![Continuous Integration](https://github.com/thecodingmachine/safe/workflows/Continuous%20Integration/badge.svg)](https://github.com/thecodingmachine/safe/actions) +[![codecov](https://codecov.io/gh/thecodingmachine/safe/branch/master/graph/badge.svg)](https://codecov.io/gh/thecodingmachine/safe) + +Safe PHP +======== + +**Work in progress** + +A set of core PHP functions rewritten to throw exceptions instead of returning `false` when an error is encountered. + +## The problem + +Most PHP core functions were written before exception handling was added to the language. Therefore, most PHP functions +do not throw exceptions. Instead, they return `false` in case of error. + +But most of us are too lazy to check explicitly for every single return of every core PHP function. + +```php +// This code is incorrect. Twice. +// "file_get_contents" can return false if the file does not exists +// "json_decode" can return false if the file content is not valid JSON +$content = file_get_contents('foobar.json'); +$foobar = json_decode($content); +``` + +The correct version of this code would be: + +```php +$content = file_get_contents('foobar.json'); +if ($content === false) { + throw new FileLoadingException('Could not load file foobar.json'); +} +$foobar = json_decode($content); +if (json_last_error() !== JSON_ERROR_NONE) { + throw new FileLoadingException('foobar.json does not contain valid JSON: '.json_last_error_msg()); +} +``` + +Obviously, while this snippet is correct, it is less easy to read. + +## The solution + +Enter *thecodingmachine/safe* aka Safe-PHP. + +Safe-PHP redeclares all core PHP functions. The new PHP functions act exactly as the old ones, except they +throw exceptions properly when an error is encountered. The "safe" functions have the same name as the core PHP +functions, except they are in the `Safe` namespace. + +```php +use function Safe\file_get_contents; +use function Safe\json_decode; + +// This code is both safe and simple! +$content = file_get_contents('foobar.json'); +$foobar = json_decode($content); +``` + +All PHP functions that can return `false` on error are part of Safe. +In addition, Safe also provide 2 'Safe' classes: `Safe\DateTime` and `Safe\DateTimeImmutable` whose methods will throw exceptions instead of returning false. + +## PHPStan integration + +> Yeah... but I must explicitly think about importing the "safe" variant of the function, for each and every file of my application. +> I'm sure I will forget some "use function" statements! + +Fear not! thecodingmachine/safe comes with a PHPStan rule. + +Never heard of [PHPStan](https://github.com/phpstan/phpstan) before? +Check it out, it's an amazing code analyzer for PHP. + +Simply install the Safe rule in your PHPStan setup (explained in the "Installation" section) and PHPStan will let you know each time you are using an "unsafe" function. + +The code below will trigger this warning: + +```php +$content = file_get_contents('foobar.json'); +``` + +> Function file_get_contents is unsafe to use. It can return FALSE instead of throwing an exception. Please add 'use function Safe\\file_get_contents;' at the beginning of the file to use the variant provided by the 'thecodingmachine/safe' library. + +## Installation + +Use composer to install Safe-PHP: + +```bash +$ composer require thecodingmachine/safe +``` + +*Highly recommended*: install PHPStan and PHPStan extension: + +```bash +$ composer require --dev thecodingmachine/phpstan-safe-rule +``` + +Now, edit your `phpstan.neon` file and add these rules: + +```yml +includes: + - vendor/thecodingmachine/phpstan-safe-rule/phpstan-safe-rule.neon +``` + +## Automated refactoring + +You have a large legacy codebase and want to use "Safe-PHP" functions throughout your project? PHPStan will help you +find these functions but changing the namespace of the functions one function at a time might be a tedious task. + +Fortunately, Safe comes bundled with a "Rector" configuration file. [Rector](https://github.com/rectorphp/rector) is a command-line +tool that performs instant refactoring of your application. + +Run + +```bash +$ composer require --dev rector/rector:^0.7 +``` + +to install `rector/rector`. + +Run + +```bash +vendor/bin/rector process src/ --config vendor/thecodingmachine/safe/rector-migrate-0.7.php +``` + +to run `rector/rector`. + +*Note:* do not forget to replace "src/" with the path to your source directory. + +**Important:** the refactoring only performs a "dumb" replacement of functions. It will not modify the way +"false" return values are handled. So if your code was already performing error handling, you will have to deal +with it manually. + +Especially, you should look for error handling that was already performed, like: + +```php +if (!mkdir($dirPath)) { + // Do something on error +} +``` + +This code will be refactored by Rector to: + +```php +if (!\Safe\mkdir($dirPath)) { + // Do something on error +} +``` + +You should then (manually) refactor it to: + +```php +try { + \Safe\mkdir($dirPath)); +} catch (\Safe\FilesystemException $e) { + // Do something on error +} +``` + +## Performance impact + +Safe is loading 1000+ functions from ~85 files on each request. Yet, the performance impact of this loading is quite low. + +In case you worry, using Safe will "cost" you ~700µs on each request. The [performance section](performance/README.md) +contains more information regarding the way we tested the performance impact of Safe. + +## Learn more + +Read [the release article on TheCodingMachine's blog](https://thecodingmachine.io/introducing-safe-php) if you want to +learn more about what triggered the development of Safe-PHP. + +## Contributing + +The files that contain all the functions are auto-generated from the PHP doc. +Read the [CONTRIBUTING.md](CONTRIBUTING.md) file to learn how to regenerate these files and to contribute to this library. diff --git a/vendor/thecodingmachine/safe/composer.json b/vendor/thecodingmachine/safe/composer.json new file mode 100644 index 0000000..2cd03fc --- /dev/null +++ b/vendor/thecodingmachine/safe/composer.json @@ -0,0 +1,123 @@ +{ + "name": "thecodingmachine/safe", + "description": "PHP core functions that throw exceptions instead of returning FALSE on error", + "license": "MIT", + "autoload": { + "psr-4": { + "Safe\\": [ + "lib/", + "deprecated/", + "generated/" + ] + }, + "files": [ + "deprecated/apc.php", + "deprecated/libevent.php", + "deprecated/mssql.php", + "deprecated/stats.php", + "lib/special_cases.php", + "generated/apache.php", + "generated/apcu.php", + "generated/array.php", + "generated/bzip2.php", + "generated/calendar.php", + "generated/classobj.php", + "generated/com.php", + "generated/cubrid.php", + "generated/curl.php", + "generated/datetime.php", + "generated/dir.php", + "generated/eio.php", + "generated/errorfunc.php", + "generated/exec.php", + "generated/fileinfo.php", + "generated/filesystem.php", + "generated/filter.php", + "generated/fpm.php", + "generated/ftp.php", + "generated/funchand.php", + "generated/gmp.php", + "generated/gnupg.php", + "generated/hash.php", + "generated/ibase.php", + "generated/ibmDb2.php", + "generated/iconv.php", + "generated/image.php", + "generated/imap.php", + "generated/info.php", + "generated/ingres-ii.php", + "generated/inotify.php", + "generated/json.php", + "generated/ldap.php", + "generated/libxml.php", + "generated/lzf.php", + "generated/mailparse.php", + "generated/mbstring.php", + "generated/misc.php", + "generated/msql.php", + "generated/mysql.php", + "generated/mysqli.php", + "generated/mysqlndMs.php", + "generated/mysqlndQc.php", + "generated/network.php", + "generated/oci8.php", + "generated/opcache.php", + "generated/openssl.php", + "generated/outcontrol.php", + "generated/password.php", + "generated/pcntl.php", + "generated/pcre.php", + "generated/pdf.php", + "generated/pgsql.php", + "generated/posix.php", + "generated/ps.php", + "generated/pspell.php", + "generated/readline.php", + "generated/rpminfo.php", + "generated/rrd.php", + "generated/sem.php", + "generated/session.php", + "generated/shmop.php", + "generated/simplexml.php", + "generated/sockets.php", + "generated/sodium.php", + "generated/solr.php", + "generated/spl.php", + "generated/sqlsrv.php", + "generated/ssdeep.php", + "generated/ssh2.php", + "generated/stream.php", + "generated/strings.php", + "generated/swoole.php", + "generated/uodbc.php", + "generated/uopz.php", + "generated/url.php", + "generated/var.php", + "generated/xdiff.php", + "generated/xml.php", + "generated/xmlrpc.php", + "generated/yaml.php", + "generated/yaz.php", + "generated/zip.php", + "generated/zlib.php" + ] + }, + "require": { + "php": ">=7.2" + }, + "require-dev": { + "phpstan/phpstan": "^0.12", + "thecodingmachine/phpstan-strict-rules": "^0.12", + "squizlabs/php_codesniffer": "^3.2" + }, + "scripts": { + "phpstan": "phpstan analyse lib -c phpstan.neon --level=max --no-progress -vvv", + "cs-fix": "phpcbf", + "cs-check": "phpcs" + }, + "extra": { + "branch-alias": { + "dev-master": "0.1-dev" + } + } +} \ No newline at end of file diff --git a/vendor/thecodingmachine/safe/deprecated/Exceptions/ApcException.php b/vendor/thecodingmachine/safe/deprecated/Exceptions/ApcException.php new file mode 100644 index 0000000..f344490 --- /dev/null +++ b/vendor/thecodingmachine/safe/deprecated/Exceptions/ApcException.php @@ -0,0 +1,11 @@ + + * + * + * + * The mode parameter consists of three octal + * number components specifying access restrictions for the owner, + * the user group in which the owner is in, and to everybody else in + * this order. One component can be computed by adding up the needed + * permissions for that target user base. Number 1 means that you + * grant execute rights, number 2 means that you make the file + * writeable, number 4 means that you make the file readable. Add + * up these numbers to specify needed rights. You can also read more + * about modes on Unix systems with 'man 1 chmod' + * and 'man 2 chmod'. + * + * + * + * + */ +function chmod(string $filename, int $mode): void +{ + error_clear_last(); + $result = \chmod($filename, $mode); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Attempts to change the owner of the file filename + * to user user. Only the superuser may change the + * owner of a file. + * + * @param string $filename Path to the file. + * @param string|int $user A user name or number. + * @throws FilesystemException + * + */ +function chown(string $filename, $user): void +{ + error_clear_last(); + $result = \chown($filename, $user); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Makes a copy of the file source to + * dest. + * + * If you wish to move a file, use the rename function. + * + * @param string $source Path to the source file. + * @param string $dest The destination path. If dest is a URL, the + * copy operation may fail if the wrapper does not support overwriting of + * existing files. + * + * If the destination file already exists, it will be overwritten. + * @param resource $context A valid context resource created with + * stream_context_create. + * @throws FilesystemException + * + */ +function copy(string $source, string $dest, $context = null): void +{ + error_clear_last(); + if ($context !== null) { + $result = \copy($source, $dest, $context); + } else { + $result = \copy($source, $dest); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Given a string containing a directory, this function will return the + * number of bytes available on the corresponding filesystem or disk + * partition. + * + * @param string $directory A directory of the filesystem or disk partition. + * + * Given a file name instead of a directory, the behaviour of the + * function is unspecified and may differ between operating systems and + * PHP versions. + * @return float Returns the number of available bytes as a float. + * @throws FilesystemException + * + */ +function disk_free_space(string $directory): float +{ + error_clear_last(); + $result = \disk_free_space($directory); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Given a string containing a directory, this function will return the total + * number of bytes on the corresponding filesystem or disk partition. + * + * @param string $directory A directory of the filesystem or disk partition. + * @return float Returns the total number of bytes as a float. + * @throws FilesystemException + * + */ +function disk_total_space(string $directory): float +{ + error_clear_last(); + $result = \disk_total_space($directory); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * The file pointed to by handle is closed. + * + * @param resource $handle The file pointer must be valid, and must point to a file successfully + * opened by fopen or fsockopen. + * @throws FilesystemException + * + */ +function fclose($handle): void +{ + error_clear_last(); + $result = \fclose($handle); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * This function forces a write of all buffered output to the resource + * pointed to by the file handle. + * + * @param resource $handle The file pointer must be valid, and must point to + * a file successfully opened by fopen or + * fsockopen (and not yet closed by + * fclose). + * @throws FilesystemException + * + */ +function fflush($handle): void +{ + error_clear_last(); + $result = \fflush($handle); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * This function is similar to file, except that + * file_get_contents returns the file in a + * string, starting at the specified offset + * up to maxlen bytes. On failure, + * file_get_contents will return FALSE. + * + * file_get_contents is the preferred way to read the + * contents of a file into a string. It will use memory mapping techniques if + * supported by your OS to enhance performance. + * + * @param string $filename Name of the file to read. + * @param bool $use_include_path The FILE_USE_INCLUDE_PATH constant can be used + * to trigger include path + * search. + * This is not possible if strict typing + * is enabled, since FILE_USE_INCLUDE_PATH is an + * int. Use TRUE instead. + * @param resource|null $context A valid context resource created with + * stream_context_create. If you don't need to use a + * custom context, you can skip this parameter by NULL. + * @param int $offset The offset where the reading starts on the original stream. + * Negative offsets count from the end of the stream. + * + * Seeking (offset) is not supported with remote files. + * Attempting to seek on non-local files may work with small offsets, but this + * is unpredictable because it works on the buffered stream. + * @param int $maxlen Maximum length of data read. The default is to read until end + * of file is reached. Note that this parameter is applied to the + * stream processed by the filters. + * @return string The function returns the read data. + * @throws FilesystemException + * + */ +function file_get_contents(string $filename, bool $use_include_path = false, $context = null, int $offset = 0, int $maxlen = null): string +{ + error_clear_last(); + if ($maxlen !== null) { + $result = \file_get_contents($filename, $use_include_path, $context, $offset, $maxlen); + } elseif ($offset !== 0) { + $result = \file_get_contents($filename, $use_include_path, $context, $offset); + } elseif ($context !== null) { + $result = \file_get_contents($filename, $use_include_path, $context); + } else { + $result = \file_get_contents($filename, $use_include_path); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * This function is identical to calling fopen, + * fwrite and fclose successively + * to write data to a file. + * + * If filename does not exist, the file is created. + * Otherwise, the existing file is overwritten, unless the + * FILE_APPEND flag is set. + * + * @param string $filename Path to the file where to write the data. + * @param mixed $data The data to write. Can be either a string, an + * array or a stream resource. + * + * If data is a stream resource, the + * remaining buffer of that stream will be copied to the specified file. + * This is similar with using stream_copy_to_stream. + * + * You can also specify the data parameter as a single + * dimension array. This is equivalent to + * file_put_contents($filename, implode('', $array)). + * @param int $flags The value of flags can be any combination of + * the following flags, joined with the binary OR (|) + * operator. + * + * + * Available flags + * + * + * + * Flag + * Description + * + * + * + * + * + * FILE_USE_INCLUDE_PATH + * + * + * Search for filename in the include directory. + * See include_path for more + * information. + * + * + * + * + * FILE_APPEND + * + * + * If file filename already exists, append + * the data to the file instead of overwriting it. + * + * + * + * + * LOCK_EX + * + * + * Acquire an exclusive lock on the file while proceeding to the + * writing. In other words, a flock call happens + * between the fopen call and the + * fwrite call. This is not identical to an + * fopen call with mode "x". + * + * + * + * + * + * @param resource $context A valid context resource created with + * stream_context_create. + * @return int This function returns the number of bytes that were written to the file. + * @throws FilesystemException + * + */ +function file_put_contents(string $filename, $data, int $flags = 0, $context = null): int +{ + error_clear_last(); + if ($context !== null) { + $result = \file_put_contents($filename, $data, $flags, $context); + } else { + $result = \file_put_contents($filename, $data, $flags); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Reads an entire file into an array. + * + * @param string $filename Path to the file. + * @param int $flags The optional parameter flags can be one, or + * more, of the following constants: + * + * + * + * FILE_USE_INCLUDE_PATH + * + * + * + * Search for the file in the include_path. + * + * + * + * + * + * FILE_IGNORE_NEW_LINES + * + * + * + * Omit newline at the end of each array element + * + * + * + * + * + * FILE_SKIP_EMPTY_LINES + * + * + * + * Skip empty lines + * + * + * + * + * @param resource $context + * @return array Returns the file in an array. Each element of the array corresponds to a + * line in the file, with the newline still attached. Upon failure, + * file returns FALSE. + * @throws FilesystemException + * + */ +function file(string $filename, int $flags = 0, $context = null): array +{ + error_clear_last(); + if ($context !== null) { + $result = \file($filename, $flags, $context); + } else { + $result = \file($filename, $flags); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * + * + * @param string $filename Path to the file. + * @return int Returns the time the file was last accessed. + * The time is returned as a Unix timestamp. + * @throws FilesystemException + * + */ +function fileatime(string $filename): int +{ + error_clear_last(); + $result = \fileatime($filename); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Gets the inode change time of a file. + * + * @param string $filename Path to the file. + * @return int Returns the time the file was last changed. + * The time is returned as a Unix timestamp. + * @throws FilesystemException + * + */ +function filectime(string $filename): int +{ + error_clear_last(); + $result = \filectime($filename); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Gets the file inode. + * + * @param string $filename Path to the file. + * @return int Returns the inode number of the file. + * @throws FilesystemException + * + */ +function fileinode(string $filename): int +{ + error_clear_last(); + $result = \fileinode($filename); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * This function returns the time when the data blocks of a file were being + * written to, that is, the time when the content of the file was changed. + * + * @param string $filename Path to the file. + * @return int Returns the time the file was last modified. + * The time is returned as a Unix timestamp, which is + * suitable for the date function. + * @throws FilesystemException + * + */ +function filemtime(string $filename): int +{ + error_clear_last(); + $result = \filemtime($filename); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Gets the file owner. + * + * @param string $filename Path to the file. + * @return int Returns the user ID of the owner of the file. + * The user ID is returned in numerical format, use + * posix_getpwuid to resolve it to a username. + * @throws FilesystemException + * + */ +function fileowner(string $filename): int +{ + error_clear_last(); + $result = \fileowner($filename); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Gets the size for the given file. + * + * @param string $filename Path to the file. + * @return int Returns the size of the file in bytes, or FALSE (and generates an error + * of level E_WARNING) in case of an error. + * @throws FilesystemException + * + */ +function filesize(string $filename): int +{ + error_clear_last(); + $result = \filesize($filename); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * flock allows you to perform a simple reader/writer + * model which can be used on virtually every platform (including most Unix + * derivatives and even Windows). + * + * On versions of PHP before 5.3.2, the lock is released also by + * fclose (which is also called automatically when script + * finished). + * + * PHP supports a portable way of locking complete files in an advisory way + * (which means all accessing programs have to use the same way of locking + * or it will not work). By default, this function will block until the + * requested lock is acquired; this may be controlled with the LOCK_NB option documented below. + * + * @param resource $handle A file system pointer resource + * that is typically created using fopen. + * @param int $operation operation is one of the following: + * + * + * + * LOCK_SH to acquire a shared lock (reader). + * + * + * + * + * LOCK_EX to acquire an exclusive lock (writer). + * + * + * + * + * LOCK_UN to release a lock (shared or exclusive). + * + * + * + * + * It is also possible to add LOCK_NB as a bitmask to one + * of the above operations, if flock should not + * block during the locking attempt. + * @param int|null $wouldblock The optional third argument is set to 1 if the lock would block + * (EWOULDBLOCK errno condition). + * @throws FilesystemException + * + */ +function flock($handle, int $operation, ?int &$wouldblock = null): void +{ + error_clear_last(); + $result = \flock($handle, $operation, $wouldblock); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * fopen binds a named resource, specified by + * filename, to a stream. + * + * @param string $filename If filename is of the form "scheme://...", it + * is assumed to be a URL and PHP will search for a protocol handler + * (also known as a wrapper) for that scheme. If no wrappers for that + * protocol are registered, PHP will emit a notice to help you track + * potential problems in your script and then continue as though + * filename specifies a regular file. + * + * If PHP has decided that filename specifies + * a local file, then it will try to open a stream on that file. + * The file must be accessible to PHP, so you need to ensure that + * the file access permissions allow this access. + * If you have enabled + * open_basedir further + * restrictions may apply. + * + * If PHP has decided that filename specifies + * a registered protocol, and that protocol is registered as a + * network URL, PHP will check to make sure that + * allow_url_fopen is + * enabled. If it is switched off, PHP will emit a warning and + * the fopen call will fail. + * + * The list of supported protocols can be found in . Some protocols (also referred to as + * wrappers) support context + * and/or php.ini options. Refer to the specific page for the + * protocol in use for a list of options which can be set. (e.g. + * php.ini value user_agent used by the + * http wrapper). + * + * On the Windows platform, be careful to escape any backslashes + * used in the path to the file, or use forward slashes. + * + * + * + * ]]> + * + * + * @param string $mode The mode parameter specifies the type of access + * you require to the stream. It may be any of the following: + * + * + * A list of possible modes for fopen + * using mode + * + * + * + * + * mode + * Description + * + * + * + * + * 'r' + * + * Open for reading only; place the file pointer at the + * beginning of the file. + * + * + * + * 'r+' + * + * Open for reading and writing; place the file pointer at + * the beginning of the file. + * + * + * + * 'w' + * + * Open for writing only; place the file pointer at the + * beginning of the file and truncate the file to zero length. + * If the file does not exist, attempt to create it. + * + * + * + * 'w+' + * + * Open for reading and writing; place the file pointer at + * the beginning of the file and truncate the file to zero + * length. If the file does not exist, attempt to create it. + * + * + * + * 'a' + * + * Open for writing only; place the file pointer at the end of + * the file. If the file does not exist, attempt to create it. + * In this mode, fseek has no effect, writes are always appended. + * + * + * + * 'a+' + * + * Open for reading and writing; place the file pointer at + * the end of the file. If the file does not exist, attempt to + * create it. In this mode, fseek only affects + * the reading position, writes are always appended. + * + * + * + * 'x' + * + * Create and open for writing only; place the file pointer at the + * beginning of the file. If the file already exists, the + * fopen call will fail by returning FALSE and + * generating an error of level E_WARNING. If + * the file does not exist, attempt to create it. This is equivalent + * to specifying O_EXCL|O_CREAT flags for the + * underlying open(2) system call. + * + * + * + * 'x+' + * + * Create and open for reading and writing; otherwise it has the + * same behavior as 'x'. + * + * + * + * 'c' + * + * Open the file for writing only. If the file does not exist, it is + * created. If it exists, it is neither truncated (as opposed to + * 'w'), nor the call to this function fails (as is + * the case with 'x'). The file pointer is + * positioned on the beginning of the file. This may be useful if it's + * desired to get an advisory lock (see flock) + * before attempting to modify the file, as using + * 'w' could truncate the file before the lock + * was obtained (if truncation is desired, + * ftruncate can be used after the lock is + * requested). + * + * + * + * 'c+' + * + * Open the file for reading and writing; otherwise it has the same + * behavior as 'c'. + * + * + * + * 'e' + * + * Set close-on-exec flag on the opened file descriptor. Only + * available in PHP compiled on POSIX.1-2008 conform systems. + * + * + * + * + * + * + * Different operating system families have different line-ending + * conventions. When you write a text file and want to insert a line + * break, you need to use the correct line-ending character(s) for your + * operating system. Unix based systems use \n as the + * line ending character, Windows based systems use \r\n + * as the line ending characters and Macintosh based systems (Mac OS Classic) used + * \r as the line ending character. + * + * If you use the wrong line ending characters when writing your files, you + * might find that other applications that open those files will "look + * funny". + * + * Windows offers a text-mode translation flag ('t') + * which will transparently translate \n to + * \r\n when working with the file. In contrast, you + * can also use 'b' to force binary mode, which will not + * translate your data. To use these flags, specify either + * 'b' or 't' as the last character + * of the mode parameter. + * + * The default translation mode is 'b'. + * You can use the 't' + * mode if you are working with plain-text files and you use + * \n to delimit your line endings in your script, but + * expect your files to be readable with applications such as old versions of notepad. You + * should use the 'b' in all other cases. + * + * If you specify the 't' flag when working with binary files, you + * may experience strange problems with your data, including broken image + * files and strange problems with \r\n characters. + * + * For portability, it is also strongly recommended that + * you re-write code that uses or relies upon the 't' + * mode so that it uses the correct line endings and + * 'b' mode instead. + * @param bool $use_include_path The optional third use_include_path parameter + * can be set to '1' or TRUE if you want to search for the file in the + * include_path, too. + * @param resource $context + * @return resource Returns a file pointer resource on success + * @throws FilesystemException + * + */ +function fopen(string $filename, string $mode, bool $use_include_path = false, $context = null) +{ + error_clear_last(); + if ($context !== null) { + $result = \fopen($filename, $mode, $use_include_path, $context); + } else { + $result = \fopen($filename, $mode, $use_include_path); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * fputcsv formats a line (passed as a + * fields array) as CSV and writes it (terminated by a + * newline) to the specified file handle. + * + * @param resource $handle The file pointer must be valid, and must point to + * a file successfully opened by fopen or + * fsockopen (and not yet closed by + * fclose). + * @param array $fields An array of strings. + * @param string $delimiter The optional delimiter parameter sets the field + * delimiter (one character only). + * @param string $enclosure The optional enclosure parameter sets the field + * enclosure (one character only). + * @param string $escape_char The optional escape_char parameter sets the + * escape character (at most one character). + * An empty string ("") disables the proprietary escape mechanism. + * @return int Returns the length of the written string. + * @throws FilesystemException + * + */ +function fputcsv($handle, array $fields, string $delimiter = ",", string $enclosure = '"', string $escape_char = "\\"): int +{ + error_clear_last(); + $result = \fputcsv($handle, $fields, $delimiter, $enclosure, $escape_char); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * fread reads up to + * length bytes from the file pointer + * referenced by handle. Reading stops as soon as one + * of the following conditions is met: + * + * + * + * length bytes have been read + * + * + * + * + * EOF (end of file) is reached + * + * + * + * + * a packet becomes available or the + * socket timeout occurs (for network streams) + * + * + * + * + * if the stream is read buffered and it does not represent a plain file, at + * most one read of up to a number of bytes equal to the chunk size (usually + * 8192) is made; depending on the previously buffered data, the size of the + * returned data may be larger than the chunk size. + * + * + * + * + * @param resource $handle A file system pointer resource + * that is typically created using fopen. + * @param int $length Up to length number of bytes read. + * @return string Returns the read string. + * @throws FilesystemException + * + */ +function fread($handle, int $length): string +{ + error_clear_last(); + $result = \fread($handle, $length); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Takes the filepointer, handle, and truncates the file to + * length, size. + * + * @param resource $handle The file pointer. + * + * The handle must be open for writing. + * @param int $size The size to truncate to. + * + * If size is larger than the file then the file + * is extended with null bytes. + * + * If size is smaller than the file then the file + * is truncated to that size. + * @throws FilesystemException + * + */ +function ftruncate($handle, int $size): void +{ + error_clear_last(); + $result = \ftruncate($handle, $size); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * + * + * @param resource $handle A file system pointer resource + * that is typically created using fopen. + * @param string $string The string that is to be written. + * @param int $length If the length argument is given, writing will + * stop after length bytes have been written or + * the end of string is reached, whichever comes + * first. + * + * Note that if the length argument is given, + * then the magic_quotes_runtime + * configuration option will be ignored and no slashes will be + * stripped from string. + * @return int + * @throws FilesystemException + * + */ +function fwrite($handle, string $string, int $length = null): int +{ + error_clear_last(); + if ($length !== null) { + $result = \fwrite($handle, $string, $length); + } else { + $result = \fwrite($handle, $string); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * The glob function searches for all the pathnames + * matching pattern according to the rules used by + * the libc glob() function, which is similar to the rules used by common + * shells. + * + * @param string $pattern The pattern. No tilde expansion or parameter substitution is done. + * + * Special characters: + * + * + * + * * - Matches zero or more characters. + * + * + * + * + * ? - Matches exactly one character (any character). + * + * + * + * + * [...] - Matches one character from a group of + * characters. If the first character is !, + * matches any character not in the group. + * + * + * + * + * \ - Escapes the following character, + * except when the GLOB_NOESCAPE flag is used. + * + * + * + * @param int $flags Valid flags: + * + * + * + * GLOB_MARK - Adds a slash (a backslash on Windows) to each directory returned + * + * + * + * + * GLOB_NOSORT - Return files as they appear in the + * directory (no sorting). When this flag is not used, the pathnames are + * sorted alphabetically + * + * + * + * + * GLOB_NOCHECK - Return the search pattern if no + * files matching it were found + * + * + * + * + * GLOB_NOESCAPE - Backslashes do not quote + * metacharacters + * + * + * + * + * GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', + * or 'c' + * + * + * + * + * GLOB_ONLYDIR - Return only directory entries + * which match the pattern + * + * + * + * + * GLOB_ERR - Stop on read errors (like unreadable + * directories), by default errors are ignored. + * + * + * + * @return array Returns an array containing the matched files/directories, an empty array + * if no file matched. + * @throws FilesystemException + * + */ +function glob(string $pattern, int $flags = 0): array +{ + error_clear_last(); + $result = \glob($pattern, $flags); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Attempts to change the group of the symlink filename + * to group. + * + * Only the superuser may change the group of a symlink arbitrarily; other + * users may change the group of a symlink to any group of which that user is + * a member. + * + * @param string $filename Path to the symlink. + * @param string|int $group The group specified by name or number. + * @throws FilesystemException + * + */ +function lchgrp(string $filename, $group): void +{ + error_clear_last(); + $result = \lchgrp($filename, $group); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Attempts to change the owner of the symlink filename + * to user user. + * + * Only the superuser may change the owner of a symlink. + * + * @param string $filename Path to the file. + * @param string|int $user User name or number. + * @throws FilesystemException + * + */ +function lchown(string $filename, $user): void +{ + error_clear_last(); + $result = \lchown($filename, $user); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * link creates a hard link. + * + * @param string $target Target of the link. + * @param string $link The link name. + * @throws FilesystemException + * + */ +function link(string $target, string $link): void +{ + error_clear_last(); + $result = \link($target, $link); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Attempts to create the directory specified by pathname. + * + * @param string $pathname The directory path. + * @param int $mode The mode is 0777 by default, which means the widest possible + * access. For more information on modes, read the details + * on the chmod page. + * + * mode is ignored on Windows. + * + * Note that you probably want to specify the mode as an octal number, + * which means it should have a leading zero. The mode is also modified + * by the current umask, which you can change using + * umask. + * @param bool $recursive Allows the creation of nested directories specified in the + * pathname. + * @param resource $context + * @throws FilesystemException + * + */ +function mkdir(string $pathname, int $mode = 0777, bool $recursive = false, $context = null): void +{ + error_clear_last(); + if ($context !== null) { + $result = \mkdir($pathname, $mode, $recursive, $context); + } else { + $result = \mkdir($pathname, $mode, $recursive); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * parse_ini_file loads in the + * ini file specified in filename, + * and returns the settings in it in an associative array. + * + * The structure of the ini file is the same as the php.ini's. + * + * @param string $filename The filename of the ini file being parsed. If a relative path is used, + * it is evaluated relative to the current working directory, then the + * include_path. + * @param bool $process_sections By setting the process_sections + * parameter to TRUE, you get a multidimensional array, with + * the section names and settings included. The default + * for process_sections is FALSE + * @param int $scanner_mode Can either be INI_SCANNER_NORMAL (default) or + * INI_SCANNER_RAW. If INI_SCANNER_RAW + * is supplied, then option values will not be parsed. + * + * + * As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. + * In this mode boolean, null and integer types are preserved when possible. + * String values "true", "on" and "yes" + * are converted to TRUE. "false", "off", "no" + * and "none" are considered FALSE. "null" is converted to NULL + * in typed mode. Also, all numeric strings are converted to integer type if it is possible. + * @return array The settings are returned as an associative array on success. + * @throws FilesystemException + * + */ +function parse_ini_file(string $filename, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array +{ + error_clear_last(); + $result = \parse_ini_file($filename, $process_sections, $scanner_mode); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * parse_ini_string returns the settings in string + * ini in an associative array. + * + * The structure of the ini string is the same as the php.ini's. + * + * @param string $ini The contents of the ini file being parsed. + * @param bool $process_sections By setting the process_sections + * parameter to TRUE, you get a multidimensional array, with + * the section names and settings included. The default + * for process_sections is FALSE + * @param int $scanner_mode Can either be INI_SCANNER_NORMAL (default) or + * INI_SCANNER_RAW. If INI_SCANNER_RAW + * is supplied, then option values will not be parsed. + * + * + * As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. + * In this mode boolean, null and integer types are preserved when possible. + * String values "true", "on" and "yes" + * are converted to TRUE. "false", "off", "no" + * and "none" are considered FALSE. "null" is converted to NULL + * in typed mode. Also, all numeric strings are converted to integer type if it is possible. + * @return array The settings are returned as an associative array on success. + * @throws FilesystemException + * + */ +function parse_ini_string(string $ini, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array +{ + error_clear_last(); + $result = \parse_ini_string($ini, $process_sections, $scanner_mode); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Reads a file and writes it to the output buffer. + * + * @param string $filename The filename being read. + * @param bool $use_include_path You can use the optional second parameter and set it to TRUE, if + * you want to search for the file in the include_path, too. + * @param resource $context A context stream resource. + * @return int Returns the number of bytes read from the file on success + * @throws FilesystemException + * + */ +function readfile(string $filename, bool $use_include_path = false, $context = null): int +{ + error_clear_last(); + if ($context !== null) { + $result = \readfile($filename, $use_include_path, $context); + } else { + $result = \readfile($filename, $use_include_path); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * readlink does the same as the readlink C function. + * + * @param string $path The symbolic link path. + * @return string Returns the contents of the symbolic link path. + * @throws FilesystemException + * + */ +function readlink(string $path): string +{ + error_clear_last(); + $result = \readlink($path); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * realpath expands all symbolic links and + * resolves references to /./, /../ and extra / characters in + * the input path and returns the canonicalized + * absolute pathname. + * + * @param string $path The path being checked. + * + * + * Whilst a path must be supplied, the value can be an empty string. + * In this case, the value is interpreted as the current directory. + * + * + * + * Whilst a path must be supplied, the value can be an empty string. + * In this case, the value is interpreted as the current directory. + * @return string Returns the canonicalized absolute pathname on success. The resulting path + * will have no symbolic link, /./ or /../ components. Trailing delimiters, + * such as \ and /, are also removed. + * + * realpath returns FALSE on failure, e.g. if + * the file does not exist. + * @throws FilesystemException + * + */ +function realpath(string $path): string +{ + error_clear_last(); + $result = \realpath($path); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Attempts to rename oldname to + * newname, moving it between directories if necessary. + * If renaming a file and newname exists, + * it will be overwritten. If renaming a directory and + * newname exists, + * this function will emit a warning. + * + * @param string $oldname The old name. + * + * The wrapper used in oldname + * must match the wrapper used in + * newname. + * @param string $newname The new name. + * @param resource $context + * @throws FilesystemException + * + */ +function rename(string $oldname, string $newname, $context = null): void +{ + error_clear_last(); + if ($context !== null) { + $result = \rename($oldname, $newname, $context); + } else { + $result = \rename($oldname, $newname); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Sets the file position indicator for handle + * to the beginning of the file stream. + * + * @param resource $handle The file pointer must be valid, and must point to a file + * successfully opened by fopen. + * @throws FilesystemException + * + */ +function rewind($handle): void +{ + error_clear_last(); + $result = \rewind($handle); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Attempts to remove the directory named by dirname. + * The directory must be empty, and the relevant permissions must permit this. + * A E_WARNING level error will be generated on failure. + * + * @param string $dirname Path to the directory. + * @param resource $context + * @throws FilesystemException + * + */ +function rmdir(string $dirname, $context = null): void +{ + error_clear_last(); + if ($context !== null) { + $result = \rmdir($dirname, $context); + } else { + $result = \rmdir($dirname); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * symlink creates a symbolic link to the existing + * target with the specified name + * link. + * + * @param string $target Target of the link. + * @param string $link The link name. + * @throws FilesystemException + * + */ +function symlink(string $target, string $link): void +{ + error_clear_last(); + $result = \symlink($target, $link); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Creates a file with a unique filename, with access permission set to 0600, in the specified directory. + * If the directory does not exist or is not writable, tempnam may + * generate a file in the system's temporary directory, and return + * the full path to that file, including its name. + * + * @param string $dir The directory where the temporary filename will be created. + * @param string $prefix The prefix of the generated temporary filename. + * @return string Returns the new temporary filename (with path). + * @throws FilesystemException + * + */ +function tempnam(string $dir, string $prefix): string +{ + error_clear_last(); + $result = \tempnam($dir, $prefix); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Creates a temporary file with a unique name in read-write (w+) mode and + * returns a file handle. + * + * The file is automatically removed when closed (for example, by calling + * fclose, or when there are no remaining references to + * the file handle returned by tmpfile), or when the + * script ends. + * + * @return resource Returns a file handle, similar to the one returned by + * fopen, for the new file. + * @throws FilesystemException + * + */ +function tmpfile() +{ + error_clear_last(); + $result = \tmpfile(); + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } + return $result; +} + + +/** + * Attempts to set the access and modification times of the file named in the + * filename parameter to the value given in + * time. + * Note that the access time is always modified, regardless of the number + * of parameters. + * + * If the file does not exist, it will be created. + * + * @param string $filename The name of the file being touched. + * @param int $time The touch time. If time is not supplied, + * the current system time is used. + * @param int $atime If present, the access time of the given filename is set to + * the value of atime. Otherwise, it is set to + * the value passed to the time parameter. + * If neither are present, the current system time is used. + * @throws FilesystemException + * + */ +function touch(string $filename, int $time = null, int $atime = null): void +{ + error_clear_last(); + if ($atime !== null) { + $result = \touch($filename, $time, $atime); + } elseif ($time !== null) { + $result = \touch($filename, $time); + } else { + $result = \touch($filename); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} + + +/** + * Deletes filename. Similar to the Unix C unlink() + * function. An E_WARNING level error will be generated on + * failure. + * + * @param string $filename Path to the file. + * @param resource $context + * @throws FilesystemException + * + */ +function unlink(string $filename, $context = null): void +{ + error_clear_last(); + if ($context !== null) { + $result = \unlink($filename, $context); + } else { + $result = \unlink($filename); + } + if ($result === false) { + throw FilesystemException::createFromPhpError(); + } +} diff --git a/vendor/thecodingmachine/safe/generated/filter.php b/vendor/thecodingmachine/safe/generated/filter.php new file mode 100644 index 0000000..2d836c6 --- /dev/null +++ b/vendor/thecodingmachine/safe/generated/filter.php @@ -0,0 +1,93 @@ + + * + * + * + * channels will be 3 for RGB pictures and 4 for CMYK + * pictures. + * + * bits is the number of bits for each color. + * + * For some image types, the presence of channels and + * bits values can be a bit + * confusing. As an example, GIF always uses 3 channels + * per pixel, but the number of bits per pixel cannot be calculated for an + * animated GIF with a global color table. + * + * On failure, FALSE is returned. + * @throws ImageException + * + */ +function getimagesize(string $filename, array &$imageinfo = null): array +{ + error_clear_last(); + $result = \getimagesize($filename, $imageinfo); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * image2wbmp outputs or save a WBMP + * version of the given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param string|null $filename Path to the saved file. If not given, the raw image stream will be + * output directly. + * @param int $foreground You can set the foreground color with this parameter by setting an + * identifier obtained from imagecolorallocate. + * The default foreground color is black. + * @throws ImageException + * + */ +function image2wbmp($image, ?string $filename = null, int $foreground = null): void +{ + error_clear_last(); + if ($foreground !== null) { + $result = \image2wbmp($image, $filename, $foreground); + } elseif ($filename !== null) { + $result = \image2wbmp($image, $filename); + } else { + $result = \image2wbmp($image); + } + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param array $affine Array with keys 0 to 5. + * @param array $clip Array with keys "x", "y", "width" and "height". + * @return resource Return affined image resource on success. + * @throws ImageException + * + */ +function imageaffine($image, array $affine, array $clip = null) +{ + error_clear_last(); + if ($clip !== null) { + $result = \imageaffine($image, $affine, $clip); + } else { + $result = \imageaffine($image, $affine); + } + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Returns the concatenation of two affine transformation matrices, + * what is useful if multiple transformations should be applied to the same + * image in one go. + * + * @param array $m1 An affine transformation matrix (an array with keys + * 0 to 5 and float values). + * @param array $m2 An affine transformation matrix (an array with keys + * 0 to 5 and float values). + * @return array{0:float,1:float,2:float,3:float,4:float,5:float} An affine transformation matrix (an array with keys + * 0 to 5 and float values). + * @throws ImageException + * + */ +function imageaffinematrixconcat(array $m1, array $m2): array +{ + error_clear_last(); + $result = \imageaffinematrixconcat($m1, $m2); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Returns an affine transformation matrix. + * + * @param int $type One of the IMG_AFFINE_* constants. + * @param array|float $options If type is IMG_AFFINE_TRANSLATE + * or IMG_AFFINE_SCALE, + * options has to be an array with keys x + * and y, both having float values. + * + * If type is IMG_AFFINE_ROTATE, + * IMG_AFFINE_SHEAR_HORIZONTAL or IMG_AFFINE_SHEAR_VERTICAL, + * options has to be a float specifying the angle. + * @return array{0:float,1:float,2:float,3:float,4:float,5:float} An affine transformation matrix (an array with keys + * 0 to 5 and float values). + * @throws ImageException + * + */ +function imageaffinematrixget(int $type, $options = null): array +{ + error_clear_last(); + if ($options !== null) { + $result = \imageaffinematrixget($type, $options); + } else { + $result = \imageaffinematrixget($type); + } + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagealphablending allows for two different + * modes of drawing on truecolor images. In blending mode, the + * alpha channel component of the color supplied to all drawing function, + * such as imagesetpixel determines how much of the + * underlying color should be allowed to shine through. As a result, gd + * automatically blends the existing color at that point with the drawing color, + * and stores the result in the image. The resulting pixel is opaque. In + * non-blending mode, the drawing color is copied literally with its alpha channel + * information, replacing the destination pixel. Blending mode is not available + * when drawing on palette images. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param bool $blendmode Whether to enable the blending mode or not. On true color images + * the default value is TRUE otherwise the default value is FALSE + * @throws ImageException + * + */ +function imagealphablending($image, bool $blendmode): void +{ + error_clear_last(); + $result = \imagealphablending($image, $blendmode); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Activate the fast drawing antialiased methods for lines and wired polygons. + * It does not support alpha components. It works using a direct blend + * operation. It works only with truecolor images. + * + * Thickness and styled are not supported. + * + * Using antialiased primitives with transparent background color can end with + * some unexpected results. The blend method uses the background color as any + * other colors. The lack of alpha component support does not allow an alpha + * based antialiasing method. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param bool $enabled Whether to enable antialiasing or not. + * @throws ImageException + * + */ +function imageantialias($image, bool $enabled): void +{ + error_clear_last(); + $result = \imageantialias($image, $enabled); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagearc draws an arc of circle centered at the given + * coordinates. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $cx x-coordinate of the center. + * @param int $cy y-coordinate of the center. + * @param int $width The arc width. + * @param int $height The arc height. + * @param int $start The arc start angle, in degrees. + * @param int $end The arc end angle, in degrees. + * 0° is located at the three-o'clock position, and the arc is drawn + * clockwise. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagearc($image, int $cx, int $cy, int $width, int $height, int $start, int $end, int $color): void +{ + error_clear_last(); + $result = \imagearc($image, $cx, $cy, $width, $height, $start, $end, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Outputs or saves a BMP version of the given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * + * NULL is invalid if the compressed arguments is + * not used. + * @param bool $compressed Whether the BMP should be compressed with run-length encoding (RLE), or not. + * @throws ImageException + * + */ +function imagebmp($image, $to = null, bool $compressed = true): void +{ + error_clear_last(); + $result = \imagebmp($image, $to, $compressed); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagechar draws the first character of + * c in the image identified by + * image with its upper-left at + * x,y (top left is 0, + * 0) with the color color. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $font Can be 1, 2, 3, 4, 5 for built-in + * fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your + * own font identifiers registered with imageloadfont. + * @param int $x x-coordinate of the start. + * @param int $y y-coordinate of the start. + * @param string $c The character to draw. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagechar($image, int $font, int $x, int $y, string $c, int $color): void +{ + error_clear_last(); + $result = \imagechar($image, $font, $x, $y, $c, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Draws the character c vertically at the specified + * coordinate on the given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $font Can be 1, 2, 3, 4, 5 for built-in + * fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your + * own font identifiers registered with imageloadfont. + * @param int $x x-coordinate of the start. + * @param int $y y-coordinate of the start. + * @param string $c The character to draw. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagecharup($image, int $font, int $x, int $y, string $c, int $color): void +{ + error_clear_last(); + $result = \imagecharup($image, $font, $x, $y, $c, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Returns the index of the color of the pixel at the + * specified location in the image specified by image. + * + * If the image is a + * truecolor image, this function returns the RGB value of that pixel as + * integer. Use bitshifting and masking to access the distinct red, green and blue + * component values: + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x x-coordinate of the point. + * @param int $y y-coordinate of the point. + * @return int Returns the index of the color. + * @throws ImageException + * + */ +function imagecolorat($image, int $x, int $y): int +{ + error_clear_last(); + $result = \imagecolorat($image, $x, $y); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * De-allocates a color previously allocated with + * imagecolorallocate or + * imagecolorallocatealpha. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $color The color identifier. + * @throws ImageException + * + */ +function imagecolordeallocate($image, int $color): void +{ + error_clear_last(); + $result = \imagecolordeallocate($image, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Makes the colors of the palette version of an image more closely match the true color version. + * + * @param resource $image1 A truecolor image resource. + * @param resource $image2 A palette image resource pointing to an image that has the same + * size as image1. + * @throws ImageException + * + */ +function imagecolormatch($image1, $image2): void +{ + error_clear_last(); + $result = \imagecolormatch($image1, $image2); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Applies a convolution matrix on the image, using the given coefficient and + * offset. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param array $matrix A 3x3 matrix: an array of three arrays of three floats. + * @param float $div The divisor of the result of the convolution, used for normalization. + * @param float $offset Color offset. + * @throws ImageException + * + */ +function imageconvolution($image, array $matrix, float $div, float $offset): void +{ + error_clear_last(); + $result = \imageconvolution($image, $matrix, $div, $offset); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Copy a part of src_im onto + * dst_im starting at the x,y coordinates + * src_x, src_y with + * a width of src_w and a height of + * src_h. The portion defined will be copied + * onto the x,y coordinates, dst_x and + * dst_y. + * + * @param resource $dst_im Destination image resource. + * @param resource $src_im Source image resource. + * @param int $dst_x x-coordinate of destination point. + * @param int $dst_y y-coordinate of destination point. + * @param int $src_x x-coordinate of source point. + * @param int $src_y y-coordinate of source point. + * @param int $src_w Source width. + * @param int $src_h Source height. + * @throws ImageException + * + */ +function imagecopy($dst_im, $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h): void +{ + error_clear_last(); + $result = \imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Copy a part of src_im onto + * dst_im starting at the x,y coordinates + * src_x, src_y with + * a width of src_w and a height of + * src_h. The portion defined will be copied + * onto the x,y coordinates, dst_x and + * dst_y. + * + * @param resource $dst_im Destination image resource. + * @param resource $src_im Source image resource. + * @param int $dst_x x-coordinate of destination point. + * @param int $dst_y y-coordinate of destination point. + * @param int $src_x x-coordinate of source point. + * @param int $src_y y-coordinate of source point. + * @param int $src_w Source width. + * @param int $src_h Source height. + * @param int $pct The two images will be merged according to pct + * which can range from 0 to 100. When pct = 0, + * no action is taken, when 100 this function behaves identically + * to imagecopy for pallete images, except for + * ignoring alpha components, while it implements alpha transparency + * for true colour images. + * @throws ImageException + * + */ +function imagecopymerge($dst_im, $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h, int $pct): void +{ + error_clear_last(); + $result = \imagecopymerge($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagecopymergegray copy a part of src_im onto + * dst_im starting at the x,y coordinates + * src_x, src_y with + * a width of src_w and a height of + * src_h. The portion defined will be copied + * onto the x,y coordinates, dst_x and + * dst_y. + * + * This function is identical to imagecopymerge except + * that when merging it preserves the hue of the source by converting + * the destination pixels to gray scale before the copy operation. + * + * @param resource $dst_im Destination image resource. + * @param resource $src_im Source image resource. + * @param int $dst_x x-coordinate of destination point. + * @param int $dst_y y-coordinate of destination point. + * @param int $src_x x-coordinate of source point. + * @param int $src_y y-coordinate of source point. + * @param int $src_w Source width. + * @param int $src_h Source height. + * @param int $pct The src_im will be changed to grayscale according + * to pct where 0 is fully grayscale and 100 is + * unchanged. When pct = 100 this function behaves + * identically to imagecopy for pallete images, except for + * ignoring alpha components, while + * it implements alpha transparency for true colour images. + * @throws ImageException + * + */ +function imagecopymergegray($dst_im, $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h, int $pct): void +{ + error_clear_last(); + $result = \imagecopymergegray($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagecopyresampled copies a rectangular + * portion of one image to another image, smoothly interpolating pixel + * values so that, in particular, reducing the size of an image still + * retains a great deal of clarity. + * + * In other words, imagecopyresampled will take a + * rectangular area from src_image of width + * src_w and height src_h at + * position (src_x,src_y) + * and place it in a rectangular area of dst_image + * of width dst_w and height dst_h + * at position (dst_x,dst_y). + * + * If the source and destination coordinates and width and heights + * differ, appropriate stretching or shrinking of the image fragment + * will be performed. The coordinates refer to the upper left + * corner. This function can be used to copy regions within the + * same image (if dst_image is the same as + * src_image) but if the regions overlap the + * results will be unpredictable. + * + * @param resource $dst_image Destination image resource. + * @param resource $src_image Source image resource. + * @param int $dst_x x-coordinate of destination point. + * @param int $dst_y y-coordinate of destination point. + * @param int $src_x x-coordinate of source point. + * @param int $src_y y-coordinate of source point. + * @param int $dst_w Destination width. + * @param int $dst_h Destination height. + * @param int $src_w Source width. + * @param int $src_h Source height. + * @throws ImageException + * + */ +function imagecopyresampled($dst_image, $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h): void +{ + error_clear_last(); + $result = \imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagecopyresized copies a rectangular + * portion of one image to another image. + * dst_image is the destination image, + * src_image is the source image identifier. + * + * In other words, imagecopyresized will take a + * rectangular area from src_image of width + * src_w and height src_h at + * position (src_x,src_y) + * and place it in a rectangular area of dst_image + * of width dst_w and height dst_h + * at position (dst_x,dst_y). + * + * If the source and destination coordinates and width and heights + * differ, appropriate stretching or shrinking of the image fragment + * will be performed. The coordinates refer to the upper left + * corner. This function can be used to copy regions within the + * same image (if dst_image is the same as + * src_image) but if the regions overlap the + * results will be unpredictable. + * + * @param resource $dst_image Destination image resource. + * @param resource $src_image Source image resource. + * @param int $dst_x x-coordinate of destination point. + * @param int $dst_y y-coordinate of destination point. + * @param int $src_x x-coordinate of source point. + * @param int $src_y y-coordinate of source point. + * @param int $dst_w Destination width. + * @param int $dst_h Destination height. + * @param int $src_w Source width. + * @param int $src_h Source height. + * @throws ImageException + * + */ +function imagecopyresized($dst_image, $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h): void +{ + error_clear_last(); + $result = \imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagecreate returns an image identifier + * representing a blank image of specified size. + * + * In general, we recommend the use of + * imagecreatetruecolor instead of + * imagecreate so that image processing occurs on the + * highest quality image possible. If you want to output a palette image, then + * imagetruecolortopalette should be called immediately + * before saving the image with imagepng or + * imagegif. + * + * @param int $width The image width. + * @param int $height The image height. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreate(int $width, int $height) +{ + error_clear_last(); + $result = \imagecreate($width, $height); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefrombmp returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the BMP image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefrombmp(string $filename) +{ + error_clear_last(); + $result = \imagecreatefrombmp($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Create a new image from GD file or URL. + * + * @param string $filename Path to the GD file. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromgd(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromgd($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Create a new image from GD2 file or URL. + * + * @param string $filename Path to the GD2 image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromgd2(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromgd2($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Create a new image from a given part of GD2 file or URL. + * + * @param string $filename Path to the GD2 image. + * @param int $srcX x-coordinate of source point. + * @param int $srcY y-coordinate of source point. + * @param int $width Source width. + * @param int $height Source height. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromgd2part(string $filename, int $srcX, int $srcY, int $width, int $height) +{ + error_clear_last(); + $result = \imagecreatefromgd2part($filename, $srcX, $srcY, $width, $height); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefromgif returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the GIF image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromgif(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromgif($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefromjpeg returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the JPEG image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromjpeg(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromjpeg($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefrompng returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the PNG image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefrompng(string $filename) +{ + error_clear_last(); + $result = \imagecreatefrompng($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefromwbmp returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the WBMP image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromwbmp(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromwbmp($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefromwebp returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the WebP image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromwebp(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromwebp($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefromxbm returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the XBM image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromxbm(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromxbm($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatefromxpm returns an image identifier + * representing the image obtained from the given filename. + * + * @param string $filename Path to the XPM image. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatefromxpm(string $filename) +{ + error_clear_last(); + $result = \imagecreatefromxpm($filename); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagecreatetruecolor returns an image identifier + * representing a black image of the specified size. + * + * @param int $width Image width. + * @param int $height Image height. + * @return resource Returns an image resource identifier on success, FALSE on errors. + * @throws ImageException + * + */ +function imagecreatetruecolor(int $width, int $height) +{ + error_clear_last(); + $result = \imagecreatetruecolor($width, $height); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Crops an image to the given rectangular area and returns the resulting image. + * The given image is not modified. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param array $rect The cropping rectangle as array with keys + * x, y, width and + * height. + * @return resource Return cropped image resource on success. + * @throws ImageException + * + */ +function imagecrop($image, array $rect) +{ + error_clear_last(); + $result = \imagecrop($image, $rect); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Automatically crops an image according to the given + * mode. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $mode One of the following constants: + * @param float $threshold + * @param int $color + * @return resource Returns a cropped image resource on success. + * If the complete image was cropped, imagecrop returns FALSE. + * @throws ImageException + * + */ +function imagecropauto($image, int $mode = IMG_CROP_DEFAULT, float $threshold = .5, int $color = -1) +{ + error_clear_last(); + $result = \imagecropauto($image, $mode, $threshold, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * This function is deprecated. Use combination of + * imagesetstyle and imageline + * instead. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x1 Upper left x coordinate. + * @param int $y1 Upper left y coordinate 0, 0 is the top left corner of the image. + * @param int $x2 Bottom right x coordinate. + * @param int $y2 Bottom right y coordinate. + * @param int $color The fill color. A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagedashedline($image, int $x1, int $y1, int $x2, int $y2, int $color): void +{ + error_clear_last(); + $result = \imagedashedline($image, $x1, $y1, $x2, $y2, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagedestroy frees any memory associated + * with image image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @throws ImageException + * + */ +function imagedestroy($image): void +{ + error_clear_last(); + $result = \imagedestroy($image); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Draws an ellipse centered at the specified coordinates. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $cx x-coordinate of the center. + * @param int $cy y-coordinate of the center. + * @param int $width The ellipse width. + * @param int $height The ellipse height. + * @param int $color The color of the ellipse. A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imageellipse($image, int $cx, int $cy, int $width, int $height, int $color): void +{ + error_clear_last(); + $result = \imageellipse($image, $cx, $cy, $width, $height, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Performs a flood fill starting at the given coordinate (top left is 0, 0) + * with the given color in the + * image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x x-coordinate of start point. + * @param int $y y-coordinate of start point. + * @param int $color The fill color. A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagefill($image, int $x, int $y, int $color): void +{ + error_clear_last(); + $result = \imagefill($image, $x, $y, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Draws a partial arc centered at the specified coordinate in the + * given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $cx x-coordinate of the center. + * @param int $cy y-coordinate of the center. + * @param int $width The arc width. + * @param int $height The arc height. + * @param int $start The arc start angle, in degrees. + * @param int $end The arc end angle, in degrees. + * 0° is located at the three-o'clock position, and the arc is drawn + * clockwise. + * @param int $color A color identifier created with imagecolorallocate. + * @param int $style A bitwise OR of the following possibilities: + * + * IMG_ARC_PIE + * IMG_ARC_CHORD + * IMG_ARC_NOFILL + * IMG_ARC_EDGED + * + * IMG_ARC_PIE and IMG_ARC_CHORD are + * mutually exclusive; IMG_ARC_CHORD just + * connects the starting and ending angles with a straight line, while + * IMG_ARC_PIE produces a rounded edge. + * IMG_ARC_NOFILL indicates that the arc + * or chord should be outlined, not filled. IMG_ARC_EDGED, + * used together with IMG_ARC_NOFILL, indicates that the + * beginning and ending angles should be connected to the center - this is a + * good way to outline (rather than fill) a 'pie slice'. + * @throws ImageException + * + */ +function imagefilledarc($image, int $cx, int $cy, int $width, int $height, int $start, int $end, int $color, int $style): void +{ + error_clear_last(); + $result = \imagefilledarc($image, $cx, $cy, $width, $height, $start, $end, $color, $style); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Draws an ellipse centered at the specified coordinate on the given + * image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $cx x-coordinate of the center. + * @param int $cy y-coordinate of the center. + * @param int $width The ellipse width. + * @param int $height The ellipse height. + * @param int $color The fill color. A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagefilledellipse($image, int $cx, int $cy, int $width, int $height, int $color): void +{ + error_clear_last(); + $result = \imagefilledellipse($image, $cx, $cy, $width, $height, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagefilledpolygon creates a filled polygon + * in the given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param array $points An array containing the x and y + * coordinates of the polygons vertices consecutively. + * @param int $num_points Total number of points (vertices), which must be at least 3. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagefilledpolygon($image, array $points, int $num_points, int $color): void +{ + error_clear_last(); + $result = \imagefilledpolygon($image, $points, $num_points, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Creates a rectangle filled with color in the given + * image starting at point 1 and ending at point 2. + * 0, 0 is the top left corner of the image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x1 x-coordinate for point 1. + * @param int $y1 y-coordinate for point 1. + * @param int $x2 x-coordinate for point 2. + * @param int $y2 y-coordinate for point 2. + * @param int $color The fill color. A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagefilledrectangle($image, int $x1, int $y1, int $x2, int $y2, int $color): void +{ + error_clear_last(); + $result = \imagefilledrectangle($image, $x1, $y1, $x2, $y2, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagefilltoborder performs a flood fill + * whose border color is defined by border. + * The starting point for the fill is x, + * y (top left is 0, 0) and the region is + * filled with color color. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x x-coordinate of start. + * @param int $y y-coordinate of start. + * @param int $border The border color. A color identifier created with imagecolorallocate. + * @param int $color The fill color. A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagefilltoborder($image, int $x, int $y, int $border, int $color): void +{ + error_clear_last(); + $result = \imagefilltoborder($image, $x, $y, $border, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagefilter applies the given filter + * filtertype on the image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $filtertype filtertype can be one of the following: + * + * + * + * IMG_FILTER_NEGATE: Reverses all colors of + * the image. + * + * + * + * + * IMG_FILTER_GRAYSCALE: Converts the image into + * grayscale by changing the red, green and blue components to their + * weighted sum using the same coefficients as the REC.601 luma (Y') + * calculation. The alpha components are retained. For palette images the + * result may differ due to palette limitations. + * + * + * + * + * IMG_FILTER_BRIGHTNESS: Changes the brightness + * of the image. Use arg1 to set the level of + * brightness. The range for the brightness is -255 to 255. + * + * + * + * + * IMG_FILTER_CONTRAST: Changes the contrast of + * the image. Use arg1 to set the level of + * contrast. + * + * + * + * + * IMG_FILTER_COLORIZE: Like + * IMG_FILTER_GRAYSCALE, except you can specify the + * color. Use arg1, arg2 and + * arg3 in the form of + * red, green, + * blue and arg4 for the + * alpha channel. The range for each color is 0 to 255. + * + * + * + * + * IMG_FILTER_EDGEDETECT: Uses edge detection to + * highlight the edges in the image. + * + * + * + * + * IMG_FILTER_EMBOSS: Embosses the image. + * + * + * + * + * IMG_FILTER_GAUSSIAN_BLUR: Blurs the image using + * the Gaussian method. + * + * + * + * + * IMG_FILTER_SELECTIVE_BLUR: Blurs the image. + * + * + * + * + * IMG_FILTER_MEAN_REMOVAL: Uses mean removal to + * achieve a "sketchy" effect. + * + * + * + * + * IMG_FILTER_SMOOTH: Makes the image smoother. + * Use arg1 to set the level of smoothness. + * + * + * + * + * IMG_FILTER_PIXELATE: Applies pixelation effect + * to the image, use arg1 to set the block size + * and arg2 to set the pixelation effect mode. + * + * + * + * + * IMG_FILTER_SCATTER: Applies scatter effect + * to the image, use arg1 and + * arg2 to define the effect strength and + * additionally arg3 to only apply the + * on select pixel colors. + * + * + * + * @param int $arg1 + * + * + * IMG_FILTER_BRIGHTNESS: Brightness level. + * + * + * + * + * IMG_FILTER_CONTRAST: Contrast level. + * + * + * + * + * IMG_FILTER_COLORIZE: Value of red component. + * + * + * + * + * IMG_FILTER_SMOOTH: Smoothness level. + * + * + * + * + * IMG_FILTER_PIXELATE: Block size in pixels. + * + * + * + * + * IMG_FILTER_SCATTER: Effect substraction level. + * This must not be higher or equal to the addition level set with + * arg2. + * + * + * + * @param int $arg2 + * + * + * IMG_FILTER_COLORIZE: Value of green component. + * + * + * + * + * IMG_FILTER_PIXELATE: Whether to use advanced pixelation + * effect or not (defaults to FALSE). + * + * + * + * + * IMG_FILTER_SCATTER: Effect addition level. + * + * + * + * @param int $arg3 + * + * + * IMG_FILTER_COLORIZE: Value of blue component. + * + * + * + * + * IMG_FILTER_SCATTER: Optional array indexed color values + * to apply effect at. + * + * + * + * @param int $arg4 + * + * + * IMG_FILTER_COLORIZE: Alpha channel, A value + * between 0 and 127. 0 indicates completely opaque while 127 indicates + * completely transparent. + * + * + * + * @throws ImageException + * + */ +function imagefilter($image, int $filtertype, int $arg1 = null, int $arg2 = null, int $arg3 = null, int $arg4 = null): void +{ + error_clear_last(); + if ($arg4 !== null) { + $result = \imagefilter($image, $filtertype, $arg1, $arg2, $arg3, $arg4); + } elseif ($arg3 !== null) { + $result = \imagefilter($image, $filtertype, $arg1, $arg2, $arg3); + } elseif ($arg2 !== null) { + $result = \imagefilter($image, $filtertype, $arg1, $arg2); + } elseif ($arg1 !== null) { + $result = \imagefilter($image, $filtertype, $arg1); + } else { + $result = \imagefilter($image, $filtertype); + } + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Flips the image image using the given + * mode. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $mode Flip mode, this can be one of the IMG_FLIP_* constants: + * + * + * + * + * + * Constant + * Meaning + * + * + * + * + * IMG_FLIP_HORIZONTAL + * + * Flips the image horizontally. + * + * + * + * IMG_FLIP_VERTICAL + * + * Flips the image vertically. + * + * + * + * IMG_FLIP_BOTH + * + * Flips the image both horizontally and vertically. + * + * + * + * + * + * @throws ImageException + * + */ +function imageflip($image, int $mode): void +{ + error_clear_last(); + $result = \imageflip($image, $mode); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Applies gamma correction to the given gd image + * given an input and an output gamma. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param float $inputgamma The input gamma. + * @param float $outputgamma The output gamma. + * @throws ImageException + * + */ +function imagegammacorrect($image, float $inputgamma, float $outputgamma): void +{ + error_clear_last(); + $result = \imagegammacorrect($image, $inputgamma, $outputgamma); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Outputs a GD image to the given to. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * @throws ImageException + * + */ +function imagegd($image, $to = null): void +{ + error_clear_last(); + $result = \imagegd($image, $to); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Outputs a GD2 image to the given to. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * @param int $chunk_size Chunk size. + * @param int $type Either IMG_GD2_RAW or + * IMG_GD2_COMPRESSED. Default is + * IMG_GD2_RAW. + * @throws ImageException + * + */ +function imagegd2($image, $to = null, int $chunk_size = 128, int $type = IMG_GD2_RAW): void +{ + error_clear_last(); + $result = \imagegd2($image, $to, $chunk_size, $type); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagegif creates the GIF + * file in to from the image image. The + * image argument is the return from the + * imagecreate or imagecreatefrom* + * function. + * + * The image format will be GIF87a unless the + * image has been made transparent with + * imagecolortransparent, in which case the + * image format will be GIF89a. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * @throws ImageException + * + */ +function imagegif($image, $to = null): void +{ + error_clear_last(); + $result = \imagegif($image, $to); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Grabs a screenshot of the whole screen. + * + * @return resource Returns an image resource identifier on success, FALSE on failure. + * @throws ImageException + * + */ +function imagegrabscreen() +{ + error_clear_last(); + $result = \imagegrabscreen(); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Grabs a window or its client area using a windows handle (HWND property in COM instance) + * + * @param int $window_handle The HWND window ID. + * @param int $client_area Include the client area of the application window. + * @return resource Returns an image resource identifier on success, FALSE on failure. + * @throws ImageException + * + */ +function imagegrabwindow(int $window_handle, int $client_area = 0) +{ + error_clear_last(); + $result = \imagegrabwindow($window_handle, $client_area); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagejpeg creates a JPEG file from + * the given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * @param int $quality quality is optional, and ranges from 0 (worst + * quality, smaller file) to 100 (best quality, biggest file). The + * default (-1) uses the default IJG quality value (about 75). + * @throws ImageException + * + */ +function imagejpeg($image, $to = null, int $quality = -1): void +{ + error_clear_last(); + $result = \imagejpeg($image, $to, $quality); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Set the alpha blending flag to use layering effects. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $effect One of the following constants: + * + * + * IMG_EFFECT_REPLACE + * + * + * Use pixel replacement (equivalent of passing TRUE to + * imagealphablending) + * + * + * + * + * IMG_EFFECT_ALPHABLEND + * + * + * Use normal pixel blending (equivalent of passing FALSE to + * imagealphablending) + * + * + * + * + * IMG_EFFECT_NORMAL + * + * + * Same as IMG_EFFECT_ALPHABLEND. + * + * + * + * + * IMG_EFFECT_OVERLAY + * + * + * Overlay has the effect that black background pixels will remain + * black, white background pixels will remain white, but grey + * background pixels will take the colour of the foreground pixel. + * + * + * + * + * IMG_EFFECT_MULTIPLY + * + * + * Overlays with a multiply effect. + * + * + * + * + * @throws ImageException + * + */ +function imagelayereffect($image, int $effect): void +{ + error_clear_last(); + $result = \imagelayereffect($image, $effect); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Draws a line between the two given points. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x1 x-coordinate for first point. + * @param int $y1 y-coordinate for first point. + * @param int $x2 x-coordinate for second point. + * @param int $y2 y-coordinate for second point. + * @param int $color The line color. A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imageline($image, int $x1, int $y1, int $x2, int $y2, int $color): void +{ + error_clear_last(); + $result = \imageline($image, $x1, $y1, $x2, $y2, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imageloadfont loads a user-defined bitmap and returns + * its identifier. + * + * @param string $file The font file format is currently binary and architecture + * dependent. This means you should generate the font files on the + * same type of CPU as the machine you are running PHP on. + * + * + * Font file format + * + * + * + * byte position + * C data type + * description + * + * + * + * + * byte 0-3 + * int + * number of characters in the font + * + * + * byte 4-7 + * int + * + * value of first character in the font (often 32 for space) + * + * + * + * byte 8-11 + * int + * pixel width of each character + * + * + * byte 12-15 + * int + * pixel height of each character + * + * + * byte 16- + * char + * + * array with character data, one byte per pixel in each + * character, for a total of (nchars*width*height) bytes. + * + * + * + * + * + * @return int The font identifier which is always bigger than 5 to avoid conflicts with + * built-in fontss. + * @throws ImageException + * + */ +function imageloadfont(string $file): int +{ + error_clear_last(); + $result = \imageloadfont($file); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imageopenpolygon draws an open polygon on the given + * image. Contrary to imagepolygon, + * no line is drawn between the last and the first point. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param array $points An array containing the polygon's vertices, e.g.: + * + * + * + * + * points[0] + * = x0 + * + * + * points[1] + * = y0 + * + * + * points[2] + * = x1 + * + * + * points[3] + * = y1 + * + * + * + * + * @param int $num_points Total number of points (vertices), which must be at least 3. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imageopenpolygon($image, array $points, int $num_points, int $color): void +{ + error_clear_last(); + $result = \imageopenpolygon($image, $points, $num_points, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Outputs or saves a PNG image from the given + * image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * + * NULL is invalid if the quality and + * filters arguments are not used. + * @param int $quality Compression level: from 0 (no compression) to 9. + * The default (-1) uses the zlib compression default. + * For more information see the zlib manual. + * @param int $filters Allows reducing the PNG file size. It is a bitmask field which may be + * set to any combination of the PNG_FILTER_XXX + * constants. PNG_NO_FILTER or + * PNG_ALL_FILTERS may also be used to respectively + * disable or activate all filters. + * The default value (-1) disables filtering. + * @throws ImageException + * + */ +function imagepng($image, $to = null, int $quality = -1, int $filters = -1): void +{ + error_clear_last(); + $result = \imagepng($image, $to, $quality, $filters); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagepolygon creates a polygon in the given + * image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param array $points An array containing the polygon's vertices, e.g.: + * + * + * + * + * points[0] + * = x0 + * + * + * points[1] + * = y0 + * + * + * points[2] + * = x1 + * + * + * points[3] + * = y1 + * + * + * + * + * @param int $num_points Total number of points (vertices), which must be at least 3. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagepolygon($image, array $points, int $num_points, int $color): void +{ + error_clear_last(); + $result = \imagepolygon($image, $points, $num_points, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagerectangle creates a rectangle starting at + * the specified coordinates. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x1 Upper left x coordinate. + * @param int $y1 Upper left y coordinate + * 0, 0 is the top left corner of the image. + * @param int $x2 Bottom right x coordinate. + * @param int $y2 Bottom right y coordinate. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagerectangle($image, int $x1, int $y1, int $x2, int $y2, int $color): void +{ + error_clear_last(); + $result = \imagerectangle($image, $x1, $y1, $x2, $y2, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Rotates the image image using the given + * angle in degrees. + * + * The center of rotation is the center of the image, and the rotated + * image may have different dimensions than the original image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param float $angle Rotation angle, in degrees. The rotation angle is interpreted as the + * number of degrees to rotate the image anticlockwise. + * @param int $bgd_color Specifies the color of the uncovered zone after the rotation + * @param int $dummy This parameter is unused. + * @return resource Returns an image resource for the rotated image. + * @throws ImageException + * + */ +function imagerotate($image, float $angle, int $bgd_color, int $dummy = 0) +{ + error_clear_last(); + $result = \imagerotate($image, $angle, $bgd_color, $dummy); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagesavealpha sets the flag which determines whether to retain + * full alpha channel information (as opposed to single-color transparency) + * when saving PNG images. + * + * Alphablending has to be disabled (imagealphablending($im, false)) + * to retain the alpha-channel in the first place. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param bool $saveflag Whether to save the alpha channel or not. Defaults to FALSE. + * @throws ImageException + * + */ +function imagesavealpha($image, bool $saveflag): void +{ + error_clear_last(); + $result = \imagesavealpha($image, $saveflag); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagescale scales an image using the given + * interpolation algorithm. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $new_width The width to scale the image to. + * @param int $new_height The height to scale the image to. If omitted or negative, the aspect + * ratio will be preserved. + * @param int $mode One of IMG_NEAREST_NEIGHBOUR, + * IMG_BILINEAR_FIXED, + * IMG_BICUBIC, + * IMG_BICUBIC_FIXED or anything else (will use two + * pass). + * + * + * IMG_WEIGHTED4 is not yet supported. + * + * + * @return resource Return the scaled image resource on success. + * @throws ImageException + * + */ +function imagescale($image, int $new_width, int $new_height = -1, int $mode = IMG_BILINEAR_FIXED) +{ + error_clear_last(); + $result = \imagescale($image, $new_width, $new_height, $mode); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagesetbrush sets the brush image to be + * used by all line drawing functions (such as imageline + * and imagepolygon) when drawing with the special + * colors IMG_COLOR_BRUSHED or + * IMG_COLOR_STYLEDBRUSHED. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param resource $brush An image resource. + * @throws ImageException + * + */ +function imagesetbrush($image, $brush): void +{ + error_clear_last(); + $result = \imagesetbrush($image, $brush); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagesetclip sets the current clipping rectangle, i.e. + * the area beyond which no pixels will be drawn. + * + * @param resource $im An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x1 The x-coordinate of the upper left corner. + * @param int $y1 The y-coordinate of the upper left corner. + * @param int $x2 The x-coordinate of the lower right corner. + * @param int $y2 The y-coordinate of the lower right corner. + * @throws ImageException + * + */ +function imagesetclip($im, int $x1, int $y1, int $x2, int $y2): void +{ + error_clear_last(); + $result = \imagesetclip($im, $x1, $y1, $x2, $y2); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Sets the interpolation method, setting an interpolation method affects the rendering + * of various functions in GD, such as the imagerotate function. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $method The interpolation method, which can be one of the following: + * + * + * + * IMG_BELL: Bell filter. + * + * + * + * + * IMG_BESSEL: Bessel filter. + * + * + * + * + * IMG_BICUBIC: Bicubic interpolation. + * + * + * + * + * IMG_BICUBIC_FIXED: Fixed point implementation of the bicubic interpolation. + * + * + * + * + * IMG_BILINEAR_FIXED: Fixed point implementation of the bilinear interpolation (default (also on image creation)). + * + * + * + * + * IMG_BLACKMAN: Blackman window function. + * + * + * + * + * IMG_BOX: Box blur filter. + * + * + * + * + * IMG_BSPLINE: Spline interpolation. + * + * + * + * + * IMG_CATMULLROM: Cubic Hermite spline interpolation. + * + * + * + * + * IMG_GAUSSIAN: Gaussian function. + * + * + * + * + * IMG_GENERALIZED_CUBIC: Generalized cubic spline fractal interpolation. + * + * + * + * + * IMG_HERMITE: Hermite interpolation. + * + * + * + * + * IMG_HAMMING: Hamming filter. + * + * + * + * + * IMG_HANNING: Hanning filter. + * + * + * + * + * IMG_MITCHELL: Mitchell filter. + * + * + * + * + * IMG_POWER: Power interpolation. + * + * + * + * + * IMG_QUADRATIC: Inverse quadratic interpolation. + * + * + * + * + * IMG_SINC: Sinc function. + * + * + * + * + * IMG_NEAREST_NEIGHBOUR: Nearest neighbour interpolation. + * + * + * + * + * IMG_WEIGHTED4: Weighting filter. + * + * + * + * + * IMG_TRIANGLE: Triangle interpolation. + * + * + * + * @throws ImageException + * + */ +function imagesetinterpolation($image, int $method = IMG_BILINEAR_FIXED): void +{ + error_clear_last(); + $result = \imagesetinterpolation($image, $method); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagesetpixel draws a pixel at the specified + * coordinate. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $x x-coordinate. + * @param int $y y-coordinate. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagesetpixel($image, int $x, int $y, int $color): void +{ + error_clear_last(); + $result = \imagesetpixel($image, $x, $y, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagesetstyle sets the style to be used by all + * line drawing functions (such as imageline + * and imagepolygon) when drawing with the special + * color IMG_COLOR_STYLED or lines of images with color + * IMG_COLOR_STYLEDBRUSHED. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param array $style An array of pixel colors. You can use the + * IMG_COLOR_TRANSPARENT constant to add a + * transparent pixel. + * Note that style must not be an empty array. + * @throws ImageException + * + */ +function imagesetstyle($image, array $style): void +{ + error_clear_last(); + $result = \imagesetstyle($image, $style); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagesetthickness sets the thickness of the lines + * drawn when drawing rectangles, polygons, arcs etc. to + * thickness pixels. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $thickness Thickness, in pixels. + * @throws ImageException + * + */ +function imagesetthickness($image, int $thickness): void +{ + error_clear_last(); + $result = \imagesetthickness($image, $thickness); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * imagesettile sets the tile image to be + * used by all region filling functions (such as imagefill + * and imagefilledpolygon) when filling with the special + * color IMG_COLOR_TILED. + * + * A tile is an image used to fill an area with a repeated pattern. Any + * GD image can be used as a tile, and by setting the transparent color index of the tile + * image with imagecolortransparent, a tile allows certain parts + * of the underlying area to shine through can be created. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param resource $tile The image resource to be used as a tile. + * @throws ImageException + * + */ +function imagesettile($image, $tile): void +{ + error_clear_last(); + $result = \imagesettile($image, $tile); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Draws a string at the given coordinates. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $font Can be 1, 2, 3, 4, 5 for built-in + * fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your + * own font identifiers registered with imageloadfont. + * @param int $x x-coordinate of the upper left corner. + * @param int $y y-coordinate of the upper left corner. + * @param string $string The string to be written. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagestring($image, int $font, int $x, int $y, string $string, int $color): void +{ + error_clear_last(); + $result = \imagestring($image, $font, $x, $y, $string, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Draws a string vertically at the given + * coordinates. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param int $font Can be 1, 2, 3, 4, 5 for built-in + * fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your + * own font identifiers registered with imageloadfont. + * @param int $x x-coordinate of the bottom left corner. + * @param int $y y-coordinate of the bottom left corner. + * @param string $string The string to be written. + * @param int $color A color identifier created with imagecolorallocate. + * @throws ImageException + * + */ +function imagestringup($image, int $font, int $x, int $y, string $string, int $color): void +{ + error_clear_last(); + $result = \imagestringup($image, $font, $x, $y, $string, $color); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Returns the width of the given image resource. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @return int Return the width of the images. + * @throws ImageException + * + */ +function imagesx($image): int +{ + error_clear_last(); + $result = \imagesx($image); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Returns the height of the given image resource. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @return int Return the height of the images. + * @throws ImageException + * + */ +function imagesy($image): int +{ + error_clear_last(); + $result = \imagesy($image); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagetruecolortopalette converts a truecolor image + * to a palette image. The code for this function was originally drawn from + * the Independent JPEG Group library code, which is excellent. The code + * has been modified to preserve as much alpha channel information as + * possible in the resulting palette, in addition to preserving colors as + * well as possible. This does not work as well as might be hoped. It is + * usually best to simply produce a truecolor output image instead, which + * guarantees the highest output quality. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param bool $dither Indicates if the image should be dithered - if it is TRUE then + * dithering will be used which will result in a more speckled image but + * with better color approximation. + * @param int $ncolors Sets the maximum number of colors that should be retained in the palette. + * @throws ImageException + * + */ +function imagetruecolortopalette($image, bool $dither, int $ncolors): void +{ + error_clear_last(); + $result = \imagetruecolortopalette($image, $dither, $ncolors); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * This function calculates and returns the bounding box in pixels + * for a TrueType text. + * + * @param float $size The font size in points. + * @param float $angle Angle in degrees in which text will be measured. + * @param string $fontfile The path to the TrueType font you wish to use. + * + * Depending on which version of the GD library PHP is using, when + * fontfile does not begin with a leading + * / then .ttf will be appended + * to the filename and the library will attempt to search for that + * filename along a library-defined font path. + * + * When using versions of the GD library lower than 2.0.18, a space character, + * rather than a semicolon, was used as the 'path separator' for different font files. + * Unintentional use of this feature will result in the warning message: + * Warning: Could not find/open font. For these affected versions, the + * only solution is moving the font to a path which does not contain spaces. + * + * In many cases where a font resides in the same directory as the script using it + * the following trick will alleviate any include problems. + * + * + * ]]> + * + * + * Note that open_basedir does + * not apply to fontfile. + * @param string $text The string to be measured. + * @return array imagettfbbox returns an array with 8 + * elements representing four points making the bounding box of the + * text on success and FALSE on error. + * + * + * + * + * key + * contents + * + * + * + * + * 0 + * lower left corner, X position + * + * + * 1 + * lower left corner, Y position + * + * + * 2 + * lower right corner, X position + * + * + * 3 + * lower right corner, Y position + * + * + * 4 + * upper right corner, X position + * + * + * 5 + * upper right corner, Y position + * + * + * 6 + * upper left corner, X position + * + * + * 7 + * upper left corner, Y position + * + * + * + * + * + * The points are relative to the text regardless of the + * angle, so "upper left" means in the top left-hand + * corner seeing the text horizontally. + * @throws ImageException + * + */ +function imagettfbbox(float $size, float $angle, string $fontfile, string $text): array +{ + error_clear_last(); + $result = \imagettfbbox($size, $angle, $fontfile, $text); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Writes the given text into the image using TrueType + * fonts. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param float $size The font size in points. + * @param float $angle The angle in degrees, with 0 degrees being left-to-right reading text. + * Higher values represent a counter-clockwise rotation. For example, a + * value of 90 would result in bottom-to-top reading text. + * @param int $x The coordinates given by x and + * y will define the basepoint of the first + * character (roughly the lower-left corner of the character). This + * is different from the imagestring, where + * x and y define the + * upper-left corner of the first character. For example, "top left" + * is 0, 0. + * @param int $y The y-ordinate. This sets the position of the fonts baseline, not the + * very bottom of the character. + * @param int $color The color index. Using the negative of a color index has the effect of + * turning off antialiasing. See imagecolorallocate. + * @param string $fontfile The path to the TrueType font you wish to use. + * + * Depending on which version of the GD library PHP is using, when + * fontfile does not begin with a leading + * / then .ttf will be appended + * to the filename and the library will attempt to search for that + * filename along a library-defined font path. + * + * When using versions of the GD library lower than 2.0.18, a space character, + * rather than a semicolon, was used as the 'path separator' for different font files. + * Unintentional use of this feature will result in the warning message: + * Warning: Could not find/open font. For these affected versions, the + * only solution is moving the font to a path which does not contain spaces. + * + * In many cases where a font resides in the same directory as the script using it + * the following trick will alleviate any include problems. + * + * + * ]]> + * + * + * Note that open_basedir does + * not apply to fontfile. + * @param string $text The text string in UTF-8 encoding. + * + * May include decimal numeric character references (of the form: + * &#8364;) to access characters in a font beyond position 127. + * The hexadecimal format (like &#xA9;) is supported. + * Strings in UTF-8 encoding can be passed directly. + * + * Named entities, such as &copy;, are not supported. Consider using + * html_entity_decode + * to decode these named entities into UTF-8 strings. + * + * If a character is used in the string which is not supported by the + * font, a hollow rectangle will replace the character. + * @return array Returns an array with 8 elements representing four points making the + * bounding box of the text. The order of the points is lower left, lower + * right, upper right, upper left. The points are relative to the text + * regardless of the angle, so "upper left" means in the top left-hand + * corner when you see the text horizontally. + * @throws ImageException + * + */ +function imagettftext($image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text): array +{ + error_clear_last(); + $result = \imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * imagewbmp outputs or save a WBMP + * version of the given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * @param int $foreground You can set the foreground color with this parameter by setting an + * identifier obtained from imagecolorallocate. + * The default foreground color is black. + * @throws ImageException + * + */ +function imagewbmp($image, $to = null, int $foreground = null): void +{ + error_clear_last(); + if ($foreground !== null) { + $result = \imagewbmp($image, $to, $foreground); + } else { + $result = \imagewbmp($image, $to); + } + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Outputs or saves a WebP version of the given image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param mixed $to The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly. + * @param int $quality quality ranges from 0 (worst + * quality, smaller file) to 100 (best quality, biggest file). + * @throws ImageException + * + */ +function imagewebp($image, $to = null, int $quality = 80): void +{ + error_clear_last(); + $result = \imagewebp($image, $to, $quality); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Outputs or save an XBM version of the given + * image. + * + * @param resource $image An image resource, returned by one of the image creation functions, + * such as imagecreatetruecolor. + * @param string|null $filename The path to save the file to, given as string. If NULL, the raw image stream will be output directly. + * + * The filename (without the .xbm extension) is also + * used for the C identifiers of the XBM, whereby non + * alphanumeric characters of the current locale are substituted by + * underscores. If filename is set to NULL, + * image is used to build the C identifiers. + * @param int $foreground You can set the foreground color with this parameter by setting an + * identifier obtained from imagecolorallocate. + * The default foreground color is black. All other colors are treated as + * background. + * @throws ImageException + * + */ +function imagexbm($image, ?string $filename, int $foreground = null): void +{ + error_clear_last(); + if ($foreground !== null) { + $result = \imagexbm($image, $filename, $foreground); + } else { + $result = \imagexbm($image, $filename); + } + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Embeds binary IPTC data into a JPEG image. + * + * @param string $iptcdata The data to be written. + * @param string $jpeg_file_name Path to the JPEG image. + * @param int $spool Spool flag. If the spool flag is less than 2 then the JPEG will be + * returned as a string. Otherwise the JPEG will be printed to STDOUT. + * @return string|bool If spool is less than 2, the JPEG will be returned. Otherwise returns TRUE on success. + * @throws ImageException + * + */ +function iptcembed(string $iptcdata, string $jpeg_file_name, int $spool = 0) +{ + error_clear_last(); + $result = \iptcembed($iptcdata, $jpeg_file_name, $spool); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Parses an IPTC block into its single tags. + * + * @param string $iptcblock A binary IPTC block. + * @return array Returns an array using the tagmarker as an index and the value as the + * value. It returns FALSE on error or if no IPTC data was found. + * @throws ImageException + * + */ +function iptcparse(string $iptcblock): array +{ + error_clear_last(); + $result = \iptcparse($iptcblock); + if ($result === false) { + throw ImageException::createFromPhpError(); + } + return $result; +} + + +/** + * Converts a JPEG file into a WBMP file. + * + * @param string $jpegname Path to JPEG file. + * @param string $wbmpname Path to destination WBMP file. + * @param int $dest_height Destination image height. + * @param int $dest_width Destination image width. + * @param int $threshold Threshold value, between 0 and 8 (inclusive). + * @throws ImageException + * + */ +function jpeg2wbmp(string $jpegname, string $wbmpname, int $dest_height, int $dest_width, int $threshold): void +{ + error_clear_last(); + $result = \jpeg2wbmp($jpegname, $wbmpname, $dest_height, $dest_width, $threshold); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} + + +/** + * Converts a PNG file into a WBMP file. + * + * @param string $pngname Path to PNG file. + * @param string $wbmpname Path to destination WBMP file. + * @param int $dest_height Destination image height. + * @param int $dest_width Destination image width. + * @param int $threshold Threshold value, between 0 and 8 (inclusive). + * @throws ImageException + * + */ +function png2wbmp(string $pngname, string $wbmpname, int $dest_height, int $dest_width, int $threshold): void +{ + error_clear_last(); + $result = \png2wbmp($pngname, $wbmpname, $dest_height, $dest_width, $threshold); + if ($result === false) { + throw ImageException::createFromPhpError(); + } +} diff --git a/vendor/thecodingmachine/safe/generated/imap.php b/vendor/thecodingmachine/safe/generated/imap.php new file mode 100644 index 0000000..acd8672 --- /dev/null +++ b/vendor/thecodingmachine/safe/generated/imap.php @@ -0,0 +1,1481 @@ + + * + * + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @throws LdapException + * + */ +function ldap_add($link_identifier, string $dn, array $entry, array $serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_add($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Does the same thing as ldap_bind but returns the LDAP result resource to be parsed with ldap_parse_result. + * + * @param resource $link_identifier + * @param string|null $bind_rdn + * @param string|null $bind_password + * @param array $serverctrls + * @return resource Returns an LDAP result identifier. + * @throws LdapException + * + */ +function ldap_bind_ext($link_identifier, ?string $bind_rdn = null, ?string $bind_password = null, array $serverctrls = null) +{ + error_clear_last(); + $result = \ldap_bind_ext($link_identifier, $bind_rdn, $bind_password, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Binds to the LDAP directory with specified RDN and password. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string|null $bind_rdn + * @param string|null $bind_password + * @throws LdapException + * + */ +function ldap_bind($link_identifier, ?string $bind_rdn = null, ?string $bind_password = null): void +{ + error_clear_last(); + $result = \ldap_bind($link_identifier, $bind_rdn, $bind_password); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Retrieve the pagination information send by the server. + * + * @param resource $link An LDAP link identifier, returned by ldap_connect. + * @param resource $result + * @param string|null $cookie An opaque structure sent by the server. + * @param int|null $estimated The estimated number of entries to retrieve. + * @throws LdapException + * + */ +function ldap_control_paged_result_response($link, $result, ?string &$cookie = null, ?int &$estimated = null): void +{ + error_clear_last(); + $result = \ldap_control_paged_result_response($link, $result, $cookie, $estimated); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Enable LDAP pagination by sending the pagination control (page size, cookie...). + * + * @param resource $link An LDAP link identifier, returned by ldap_connect. + * @param int $pagesize The number of entries by page. + * @param bool $iscritical Indicates whether the pagination is critical or not. + * If true and if the server doesn't support pagination, the search + * will return no result. + * @param string $cookie An opaque structure sent by the server + * (ldap_control_paged_result_response). + * @throws LdapException + * + */ +function ldap_control_paged_result($link, int $pagesize, bool $iscritical = false, string $cookie = ""): void +{ + error_clear_last(); + $result = \ldap_control_paged_result($link, $pagesize, $iscritical, $cookie); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Returns the number of entries stored in the result of previous search + * operations. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_identifier The internal LDAP result. + * @return int Returns number of entries in the result. + * @throws LdapException + * + */ +function ldap_count_entries($link_identifier, $result_identifier): int +{ + error_clear_last(); + $result = \ldap_count_entries($link_identifier, $result_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Does the same thing as ldap_delete but returns the LDAP result resource to be parsed with ldap_parse_result. + * + * @param resource $link_identifier + * @param string $dn + * @param array $serverctrls + * @return resource Returns an LDAP result identifier. + * @throws LdapException + * + */ +function ldap_delete_ext($link_identifier, string $dn, array $serverctrls = null) +{ + error_clear_last(); + $result = \ldap_delete_ext($link_identifier, $dn, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Deletes a particular entry in LDAP directory. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $dn The distinguished name of an LDAP entity. + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @throws LdapException + * + */ +function ldap_delete($link_identifier, string $dn, array $serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_delete($link_identifier, $dn, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Performs a PASSWD extended operation. + * + * @param resource $link An LDAP link identifier, returned by ldap_connect. + * @param string $user dn of the user to change the password of. + * @param string $oldpw The old password of this user. May be ommited depending of server configuration. + * @param string $newpw The new password for this user. May be omitted or empty to have a generated password. + * @param array $serverctrls If provided, a password policy request control is send with the request and this is + * filled with an array of LDAP Controls + * returned with the request. + * @return mixed Returns the generated password if newpw is empty or omitted. + * Otherwise returns TRUE on success. + * @throws LdapException + * + */ +function ldap_exop_passwd($link, string $user = "", string $oldpw = "", string $newpw = "", array &$serverctrls = null) +{ + error_clear_last(); + $result = \ldap_exop_passwd($link, $user, $oldpw, $newpw, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Performs a WHOAMI extended operation and returns the data. + * + * @param resource $link An LDAP link identifier, returned by ldap_connect. + * @return string The data returned by the server. + * @throws LdapException + * + */ +function ldap_exop_whoami($link): string +{ + error_clear_last(); + $result = \ldap_exop_whoami($link); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Performs an extended operation on the specified link with + * reqoid the OID of the operation and + * reqdata the data. + * + * @param resource $link An LDAP link identifier, returned by ldap_connect. + * @param string $reqoid The extended operation request OID. You may use one of LDAP_EXOP_START_TLS, LDAP_EXOP_MODIFY_PASSWD, LDAP_EXOP_REFRESH, LDAP_EXOP_WHO_AM_I, LDAP_EXOP_TURN, or a string with the OID of the operation you want to send. + * @param string $reqdata The extended operation request data. May be NULL for some operations like LDAP_EXOP_WHO_AM_I, may also need to be BER encoded. + * @param array|null $serverctrls Array of LDAP Controls to send with the request. + * @param string|null $retdata Will be filled with the extended operation response data if provided. + * If not provided you may use ldap_parse_exop on the result object + * later to get this data. + * @param string|null $retoid Will be filled with the response OID if provided, usually equal to the request OID. + * @return mixed When used with retdata, returns TRUE on success. + * When used without retdata, returns a result identifier. + * @throws LdapException + * + */ +function ldap_exop($link, string $reqoid, string $reqdata = null, ?array $serverctrls = null, ?string &$retdata = null, ?string &$retoid = null) +{ + error_clear_last(); + $result = \ldap_exop($link, $reqoid, $reqdata, $serverctrls, $retdata, $retoid); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Splits the DN returned by ldap_get_dn and breaks it + * up into its component parts. Each part is known as Relative Distinguished + * Name, or RDN. + * + * @param string $dn The distinguished name of an LDAP entity. + * @param int $with_attrib Used to request if the RDNs are returned with only values or their + * attributes as well. To get RDNs with the attributes (i.e. in + * attribute=value format) set with_attrib to 0 + * and to get only values set it to 1. + * @return array Returns an array of all DN components. + * The first element in the array has count key and + * represents the number of returned values, next elements are numerically + * indexed DN components. + * @throws LdapException + * + */ +function ldap_explode_dn(string $dn, int $with_attrib): array +{ + error_clear_last(); + $result = \ldap_explode_dn($dn, $with_attrib); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Gets the first attribute in the given entry. Remaining attributes are + * retrieved by calling ldap_next_attribute successively. + * + * Similar to reading entries, attributes are also read one by one from a + * particular entry. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_entry_identifier + * @return string Returns the first attribute in the entry on success and FALSE on + * error. + * @throws LdapException + * + */ +function ldap_first_attribute($link_identifier, $result_entry_identifier): string +{ + error_clear_last(); + $result = \ldap_first_attribute($link_identifier, $result_entry_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Returns the entry identifier for first entry in the result. This entry + * identifier is then supplied to ldap_next_entry + * routine to get successive entries from the result. + * + * Entries in the LDAP result are read sequentially using the + * ldap_first_entry and + * ldap_next_entry functions. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_identifier + * @return resource Returns the result entry identifier for the first entry on success and + * FALSE on error. + * @throws LdapException + * + */ +function ldap_first_entry($link_identifier, $result_identifier) +{ + error_clear_last(); + $result = \ldap_first_entry($link_identifier, $result_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Frees up the memory allocated internally to store the result. All result + * memory will be automatically freed when the script terminates. + * + * Typically all the memory allocated for the LDAP result gets freed at the + * end of the script. In case the script is making successive searches which + * return large result sets, ldap_free_result could be + * called to keep the runtime memory usage by the script low. + * + * @param resource $result_identifier + * @throws LdapException + * + */ +function ldap_free_result($result_identifier): void +{ + error_clear_last(); + $result = \ldap_free_result($result_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Reads attributes and values from an entry in the search result. + * + * Having located a specific entry in the directory, you can find out what + * information is held for that entry by using this call. You would use this + * call for an application which "browses" directory entries and/or where you + * do not know the structure of the directory entries. In many applications + * you will be searching for a specific attribute such as an email address or + * a surname, and won't care what other data is held. + * + * + * + * + * + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_entry_identifier + * @return array Returns a complete entry information in a multi-dimensional array + * on success and FALSE on error. + * @throws LdapException + * + */ +function ldap_get_attributes($link_identifier, $result_entry_identifier): array +{ + error_clear_last(); + $result = \ldap_get_attributes($link_identifier, $result_entry_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Finds out the DN of an entry in the result. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_entry_identifier + * @return string Returns the DN of the result entry and FALSE on error. + * @throws LdapException + * + */ +function ldap_get_dn($link_identifier, $result_entry_identifier): string +{ + error_clear_last(); + $result = \ldap_get_dn($link_identifier, $result_entry_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Reads multiple entries from the given result, and then reading the + * attributes and multiple values. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_identifier + * @return array Returns a complete result information in a multi-dimensional array on + * success and FALSE on error. + * + * The structure of the array is as follows. + * The attribute index is converted to lowercase. (Attributes are + * case-insensitive for directory servers, but not when used as + * array indices.) + * + * + * + * + * + * @throws LdapException + * + */ +function ldap_get_entries($link_identifier, $result_identifier): array +{ + error_clear_last(); + $result = \ldap_get_entries($link_identifier, $result_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Sets retval to the value of the specified option. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param int $option The parameter option can be one of: + * + * + * + * + * Option + * Type + * since + * + * + * + * + * LDAP_OPT_DEREF + * integer + * + * + * + * LDAP_OPT_SIZELIMIT + * integer + * + * + * + * LDAP_OPT_TIMELIMIT + * integer + * + * + * + * LDAP_OPT_NETWORK_TIMEOUT + * integer + * + * + * + * LDAP_OPT_PROTOCOL_VERSION + * integer + * + * + * + * LDAP_OPT_ERROR_NUMBER + * integer + * + * + * + * LDAP_OPT_DIAGNOSTIC_MESSAGE + * integer + * + * + * + * LDAP_OPT_REFERRALS + * bool + * + * + * + * LDAP_OPT_RESTART + * bool + * + * + * + * LDAP_OPT_HOST_NAME + * string + * + * + * + * LDAP_OPT_ERROR_STRING + * string + * + * + * + * LDAP_OPT_MATCHED_DN + * string + * + * + * + * LDAP_OPT_SERVER_CONTROLS + * array + * + * + * + * LDAP_OPT_CLIENT_CONTROLS + * array + * + * + * + * LDAP_OPT_X_KEEPALIVE_IDLE + * int + * 7.1 + * + * + * LDAP_OPT_X_KEEPALIVE_PROBES + * int + * 7.1 + * + * + * LDAP_OPT_X_KEEPALIVE_INTERVAL + * int + * 7.1 + * + * + * LDAP_OPT_X_TLS_CACERTDIR + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_CACERTFILE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_CERTFILE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_CIPHER_SUITE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_CRLCHECK + * integer + * 7.1 + * + * + * LDAP_OPT_X_TLS_CRL_NONE + * integer + * 7.1 + * + * + * LDAP_OPT_X_TLS_CRL_PEER + * integer + * 7.1 + * + * + * LDAP_OPT_X_TLS_CRL_ALL + * integer + * 7.1 + * + * + * LDAP_OPT_X_TLS_CRLFILE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_DHFILE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_KEYILE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_PACKAGE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_PROTOCOL_MIN + * integer + * 7.1 + * + * + * LDAP_OPT_X_TLS_RANDOM_FILE + * string + * 7.1 + * + * + * LDAP_OPT_X_TLS_REQUIRE_CERT + * integer + * + * + * + * + * + * @param mixed $retval This will be set to the option value. + * @throws LdapException + * + */ +function ldap_get_option($link_identifier, int $option, &$retval): void +{ + error_clear_last(); + $result = \ldap_get_option($link_identifier, $option, $retval); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Reads all the values of the attribute in the entry in the result. + * + * This function is used exactly like ldap_get_values + * except that it handles binary data and not string data. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_entry_identifier + * @param string $attribute + * @return array Returns an array of values for the attribute on success and FALSE on + * error. Individual values are accessed by integer index in the array. The + * first index is 0. The number of values can be found by indexing "count" + * in the resultant array. + * @throws LdapException + * + */ +function ldap_get_values_len($link_identifier, $result_entry_identifier, string $attribute): array +{ + error_clear_last(); + $result = \ldap_get_values_len($link_identifier, $result_entry_identifier, $attribute); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Reads all the values of the attribute in the entry in the result. + * + * This call needs a result_entry_identifier, + * so needs to be preceded by one of the ldap search calls and one + * of the calls to get an individual entry. + * + * You application will either be hard coded to look for certain + * attributes (such as "surname" or "mail") or you will have to use + * the ldap_get_attributes call to work out + * what attributes exist for a given entry. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_entry_identifier + * @param string $attribute + * @return array Returns an array of values for the attribute on success and FALSE on + * error. The number of values can be found by indexing "count" in the + * resultant array. Individual values are accessed by integer index in the + * array. The first index is 0. + * + * LDAP allows more than one entry for an attribute, so it can, for example, + * store a number of email addresses for one person's directory entry all + * labeled with the attribute "mail" + * + * + * return_value["count"] = number of values for attribute + * return_value[0] = first value of attribute + * return_value[i] = ith value of attribute + * + * + * @throws LdapException + * + */ +function ldap_get_values($link_identifier, $result_entry_identifier, string $attribute): array +{ + error_clear_last(); + $result = \ldap_get_values($link_identifier, $result_entry_identifier, $attribute); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Performs the search for a specified filter on the + * directory with the scope LDAP_SCOPE_ONELEVEL. + * + * LDAP_SCOPE_ONELEVEL means that the search should only + * return information that is at the level immediately below the + * base_dn given in the call. + * (Equivalent to typing "ls" and getting a list of files and folders in the + * current working directory.) + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $base_dn The base DN for the directory. + * @param string $filter + * @param array $attributes An array of the required attributes, e.g. array("mail", "sn", "cn"). + * Note that the "dn" is always returned irrespective of which attributes + * types are requested. + * + * Using this parameter is much more efficient than the default action + * (which is to return all attributes and their associated values). + * The use of this parameter should therefore be considered good + * practice. + * @param int $attrsonly Should be set to 1 if only attribute types are wanted. If set to 0 + * both attributes types and attribute values are fetched which is the + * default behaviour. + * @param int $sizelimit Enables you to limit the count of entries fetched. Setting this to 0 + * means no limit. + * + * This parameter can NOT override server-side preset sizelimit. You can + * set it lower though. + * + * Some directory server hosts will be configured to return no more than + * a preset number of entries. If this occurs, the server will indicate + * that it has only returned a partial results set. This also occurs if + * you use this parameter to limit the count of fetched entries. + * @param int $timelimit Sets the number of seconds how long is spend on the search. Setting + * this to 0 means no limit. + * + * This parameter can NOT override server-side preset timelimit. You can + * set it lower though. + * @param int $deref Specifies how aliases should be handled during the search. It can be + * one of the following: + * + * + * + * LDAP_DEREF_NEVER - (default) aliases are never + * dereferenced. + * + * + * + * + * LDAP_DEREF_SEARCHING - aliases should be + * dereferenced during the search but not when locating the base object + * of the search. + * + * + * + * + * LDAP_DEREF_FINDING - aliases should be + * dereferenced when locating the base object but not during the search. + * + * + * + * + * LDAP_DEREF_ALWAYS - aliases should be dereferenced + * always. + * + * + * + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @return resource Returns a search result identifier. + * @throws LdapException + * + */ +function ldap_list($link_identifier, string $base_dn, string $filter, array $attributes = null, int $attrsonly = 0, int $sizelimit = -1, int $timelimit = -1, int $deref = LDAP_DEREF_NEVER, array $serverctrls = null) +{ + error_clear_last(); + if ($serverctrls !== null) { + $result = \ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref, $serverctrls); + } elseif ($deref !== LDAP_DEREF_NEVER) { + $result = \ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref); + } elseif ($timelimit !== -1) { + $result = \ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit); + } elseif ($sizelimit !== -1) { + $result = \ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit); + } elseif ($attrsonly !== 0) { + $result = \ldap_list($link_identifier, $base_dn, $filter, $attributes, $attrsonly); + } elseif ($attributes !== null) { + $result = \ldap_list($link_identifier, $base_dn, $filter, $attributes); + } else { + $result = \ldap_list($link_identifier, $base_dn, $filter); + } + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Does the same thing as ldap_mod_add but returns the LDAP result resource to be parsed with ldap_parse_result. + * + * @param resource $link_identifier + * @param string $dn + * @param array $entry + * @param array $serverctrls + * @return resource Returns an LDAP result identifier. + * @throws LdapException + * + */ +function ldap_mod_add_ext($link_identifier, string $dn, array $entry, array $serverctrls = null) +{ + error_clear_last(); + $result = \ldap_mod_add_ext($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Adds one or more attribute values to the specified dn. + * To add a whole new object see ldap_add function. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $dn The distinguished name of an LDAP entity. + * @param array $entry An associative array listing the attirbute values to add. If an attribute was not existing yet it will be added. If an attribute is existing you can only add values to it if it supports multiple values. + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @throws LdapException + * + */ +function ldap_mod_add($link_identifier, string $dn, array $entry, array $serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_mod_add($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Does the same thing as ldap_mod_del but returns the LDAP result resource to be parsed with ldap_parse_result. + * + * @param resource $link_identifier + * @param string $dn + * @param array $entry + * @param array $serverctrls + * @return resource Returns an LDAP result identifier. + * @throws LdapException + * + */ +function ldap_mod_del_ext($link_identifier, string $dn, array $entry, array $serverctrls = null) +{ + error_clear_last(); + $result = \ldap_mod_del_ext($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Removes one or more attribute values from the specified dn. + * Object deletions are done by the + * ldap_delete function. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $dn The distinguished name of an LDAP entity. + * @param array $entry + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @throws LdapException + * + */ +function ldap_mod_del($link_identifier, string $dn, array $entry, array $serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_mod_del($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Does the same thing as ldap_mod_replace but returns the LDAP result resource to be parsed with ldap_parse_result. + * + * @param resource $link_identifier + * @param string $dn + * @param array $entry + * @param array $serverctrls + * @return resource Returns an LDAP result identifier. + * @throws LdapException + * + */ +function ldap_mod_replace_ext($link_identifier, string $dn, array $entry, array $serverctrls = null) +{ + error_clear_last(); + $result = \ldap_mod_replace_ext($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Replaces one or more attributes from the specified dn. + * It may also add or remove attributes. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $dn The distinguished name of an LDAP entity. + * @param array $entry An associative array listing the attributes to replace. Sending an empty array as value will remove the attribute, while sending an attribute not existing yet on this entry will add it. + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @throws LdapException + * + */ +function ldap_mod_replace($link_identifier, string $dn, array $entry, array $serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_mod_replace($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Modifies an existing entry in the LDAP directory. Allows detailed + * specification of the modifications to perform. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $dn The distinguished name of an LDAP entity. + * @param array $entry An array that specifies the modifications to make. Each entry in this + * array is an associative array with two or three keys: + * attrib maps to the name of the attribute to modify, + * modtype maps to the type of modification to perform, + * and (depending on the type of modification) values + * maps to an array of attribute values relevant to the modification. + * + * Possible values for modtype include: + * + * + * LDAP_MODIFY_BATCH_ADD + * + * + * Each value specified through values is added (as + * an additional value) to the attribute named by + * attrib. + * + * + * + * + * LDAP_MODIFY_BATCH_REMOVE + * + * + * Each value specified through values is removed + * from the attribute named by attrib. Any value of + * the attribute not contained in the values array + * will remain untouched. + * + * + * + * + * LDAP_MODIFY_BATCH_REMOVE_ALL + * + * + * All values are removed from the attribute named by + * attrib. A values entry must + * not be provided. + * + * + * + * + * LDAP_MODIFY_BATCH_REPLACE + * + * + * All current values of the attribute named by + * attrib are replaced with the values specified + * through values. + * + * + * + * + * + * Each value specified through values is added (as + * an additional value) to the attribute named by + * attrib. + * + * Each value specified through values is removed + * from the attribute named by attrib. Any value of + * the attribute not contained in the values array + * will remain untouched. + * + * All values are removed from the attribute named by + * attrib. A values entry must + * not be provided. + * + * All current values of the attribute named by + * attrib are replaced with the values specified + * through values. + * + * Note that any value for attrib must be a string, any + * value for values must be an array of strings, and + * any value for modtype must be one of the + * LDAP_MODIFY_BATCH_* constants listed above. + * @param array $serverctrls Each value specified through values is added (as + * an additional value) to the attribute named by + * attrib. + * @throws LdapException + * + */ +function ldap_modify_batch($link_identifier, string $dn, array $entry, array $serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_modify_batch($link_identifier, $dn, $entry, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Retrieves the attributes in an entry. The first call to + * ldap_next_attribute is made with the + * result_entry_identifier returned from + * ldap_first_attribute. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param resource $result_entry_identifier + * @return string Returns the next attribute in an entry on success and FALSE on + * error. + * @throws LdapException + * + */ +function ldap_next_attribute($link_identifier, $result_entry_identifier): string +{ + error_clear_last(); + $result = \ldap_next_attribute($link_identifier, $result_entry_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Parse LDAP extended operation data from result object result + * + * @param resource $link An LDAP link identifier, returned by ldap_connect. + * @param resource $result An LDAP result resource, returned by ldap_exop. + * @param string|null $retdata Will be filled by the response data. + * @param string|null $retoid Will be filled by the response OID. + * @throws LdapException + * + */ +function ldap_parse_exop($link, $result, ?string &$retdata = null, ?string &$retoid = null): void +{ + error_clear_last(); + $result = \ldap_parse_exop($link, $result, $retdata, $retoid); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Parses an LDAP search result. + * + * @param resource $link An LDAP link identifier, returned by ldap_connect. + * @param resource $result An LDAP result resource, returned by ldap_list or + * ldap_search. + * @param int|null $errcode A reference to a variable that will be set to the LDAP error code in + * the result, or 0 if no error occurred. + * @param string|null $matcheddn A reference to a variable that will be set to a matched DN if one was + * recognised within the request, otherwise it will be set to NULL. + * @param string|null $errmsg A reference to a variable that will be set to the LDAP error message in + * the result, or an empty string if no error occurred. + * @param array|null $referrals A reference to a variable that will be set to an array set + * to all of the referral strings in the result, or an empty array if no + * referrals were returned. + * @param array|null $serverctrls An array of LDAP Controls which have been sent with the response. + * @throws LdapException + * + */ +function ldap_parse_result($link, $result, ?int &$errcode, ?string &$matcheddn = null, ?string &$errmsg = null, ?array &$referrals = null, ?array &$serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_parse_result($link, $result, $errcode, $matcheddn, $errmsg, $referrals, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Performs the search for a specified filter on the + * directory with the scope LDAP_SCOPE_BASE. So it is + * equivalent to reading an entry from the directory. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $base_dn The base DN for the directory. + * @param string $filter An empty filter is not allowed. If you want to retrieve absolutely all + * information for this entry, use a filter of + * objectClass=*. If you know which entry types are + * used on the directory server, you might use an appropriate filter such + * as objectClass=inetOrgPerson. + * @param array $attributes An array of the required attributes, e.g. array("mail", "sn", "cn"). + * Note that the "dn" is always returned irrespective of which attributes + * types are requested. + * + * Using this parameter is much more efficient than the default action + * (which is to return all attributes and their associated values). + * The use of this parameter should therefore be considered good + * practice. + * @param int $attrsonly Should be set to 1 if only attribute types are wanted. If set to 0 + * both attributes types and attribute values are fetched which is the + * default behaviour. + * @param int $sizelimit Enables you to limit the count of entries fetched. Setting this to 0 + * means no limit. + * + * This parameter can NOT override server-side preset sizelimit. You can + * set it lower though. + * + * Some directory server hosts will be configured to return no more than + * a preset number of entries. If this occurs, the server will indicate + * that it has only returned a partial results set. This also occurs if + * you use this parameter to limit the count of fetched entries. + * @param int $timelimit Sets the number of seconds how long is spend on the search. Setting + * this to 0 means no limit. + * + * This parameter can NOT override server-side preset timelimit. You can + * set it lower though. + * @param int $deref Specifies how aliases should be handled during the search. It can be + * one of the following: + * + * + * + * LDAP_DEREF_NEVER - (default) aliases are never + * dereferenced. + * + * + * + * + * LDAP_DEREF_SEARCHING - aliases should be + * dereferenced during the search but not when locating the base object + * of the search. + * + * + * + * + * LDAP_DEREF_FINDING - aliases should be + * dereferenced when locating the base object but not during the search. + * + * + * + * + * LDAP_DEREF_ALWAYS - aliases should be dereferenced + * always. + * + * + * + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @return resource Returns a search result identifier. + * @throws LdapException + * + */ +function ldap_read($link_identifier, string $base_dn, string $filter, array $attributes = null, int $attrsonly = 0, int $sizelimit = -1, int $timelimit = -1, int $deref = LDAP_DEREF_NEVER, array $serverctrls = null) +{ + error_clear_last(); + if ($serverctrls !== null) { + $result = \ldap_read($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref, $serverctrls); + } elseif ($deref !== LDAP_DEREF_NEVER) { + $result = \ldap_read($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref); + } elseif ($timelimit !== -1) { + $result = \ldap_read($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit); + } elseif ($sizelimit !== -1) { + $result = \ldap_read($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit); + } elseif ($attrsonly !== 0) { + $result = \ldap_read($link_identifier, $base_dn, $filter, $attributes, $attrsonly); + } elseif ($attributes !== null) { + $result = \ldap_read($link_identifier, $base_dn, $filter, $attributes); + } else { + $result = \ldap_read($link_identifier, $base_dn, $filter); + } + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Does the same thing as ldap_rename but returns the LDAP result resource to be parsed with ldap_parse_result. + * + * @param resource $link_identifier + * @param string $dn + * @param string $newrdn + * @param string $newparent + * @param bool $deleteoldrdn + * @param array $serverctrls + * @return resource Returns an LDAP result identifier. + * @throws LdapException + * + */ +function ldap_rename_ext($link_identifier, string $dn, string $newrdn, string $newparent, bool $deleteoldrdn, array $serverctrls = null) +{ + error_clear_last(); + $result = \ldap_rename_ext($link_identifier, $dn, $newrdn, $newparent, $deleteoldrdn, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * The entry specified by dn is renamed/moved. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $dn The distinguished name of an LDAP entity. + * @param string $newrdn The new RDN. + * @param string $newparent The new parent/superior entry. + * @param bool $deleteoldrdn If TRUE the old RDN value(s) is removed, else the old RDN value(s) + * is retained as non-distinguished values of the entry. + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @throws LdapException + * + */ +function ldap_rename($link_identifier, string $dn, string $newrdn, string $newparent, bool $deleteoldrdn, array $serverctrls = null): void +{ + error_clear_last(); + $result = \ldap_rename($link_identifier, $dn, $newrdn, $newparent, $deleteoldrdn, $serverctrls); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * + * + * @param resource $link + * @param string $binddn + * @param string $password + * @param string $sasl_mech + * @param string $sasl_realm + * @param string $sasl_authc_id + * @param string $sasl_authz_id + * @param string $props + * @throws LdapException + * + */ +function ldap_sasl_bind($link, string $binddn = null, string $password = null, string $sasl_mech = null, string $sasl_realm = null, string $sasl_authc_id = null, string $sasl_authz_id = null, string $props = null): void +{ + error_clear_last(); + $result = \ldap_sasl_bind($link, $binddn, $password, $sasl_mech, $sasl_realm, $sasl_authc_id, $sasl_authz_id, $props); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Performs the search for a specified filter on the directory with the scope + * of LDAP_SCOPE_SUBTREE. This is equivalent to searching + * the entire directory. + * + * From 4.0.5 on it's also possible to do parallel searches. To do this + * you use an array of link identifiers, rather than a single identifier, + * as the first argument. If you don't want the same base DN and the + * same filter for all the searches, you can also use an array of base DNs + * and/or an array of filters. Those arrays must be of the same size as + * the link identifier array since the first entries of the arrays are + * used for one search, the second entries are used for another, and so + * on. When doing parallel searches an array of search result + * identifiers is returned, except in case of error, then the entry + * corresponding to the search will be FALSE. This is very much like + * the value normally returned, except that a result identifier is always + * returned when a search was made. There are some rare cases where the + * normal search returns FALSE while the parallel search returns an + * identifier. + * + * @param resource|array $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param string $base_dn The base DN for the directory. + * @param string $filter The search filter can be simple or advanced, using boolean operators in + * the format described in the LDAP documentation (see the Netscape Directory SDK or + * RFC4515 for full + * information on filters). + * @param array $attributes An array of the required attributes, e.g. array("mail", "sn", "cn"). + * Note that the "dn" is always returned irrespective of which attributes + * types are requested. + * + * Using this parameter is much more efficient than the default action + * (which is to return all attributes and their associated values). + * The use of this parameter should therefore be considered good + * practice. + * @param int $attrsonly Should be set to 1 if only attribute types are wanted. If set to 0 + * both attributes types and attribute values are fetched which is the + * default behaviour. + * @param int $sizelimit Enables you to limit the count of entries fetched. Setting this to 0 + * means no limit. + * + * This parameter can NOT override server-side preset sizelimit. You can + * set it lower though. + * + * Some directory server hosts will be configured to return no more than + * a preset number of entries. If this occurs, the server will indicate + * that it has only returned a partial results set. This also occurs if + * you use this parameter to limit the count of fetched entries. + * @param int $timelimit Sets the number of seconds how long is spend on the search. Setting + * this to 0 means no limit. + * + * This parameter can NOT override server-side preset timelimit. You can + * set it lower though. + * @param int $deref Specifies how aliases should be handled during the search. It can be + * one of the following: + * + * + * + * LDAP_DEREF_NEVER - (default) aliases are never + * dereferenced. + * + * + * + * + * LDAP_DEREF_SEARCHING - aliases should be + * dereferenced during the search but not when locating the base object + * of the search. + * + * + * + * + * LDAP_DEREF_FINDING - aliases should be + * dereferenced when locating the base object but not during the search. + * + * + * + * + * LDAP_DEREF_ALWAYS - aliases should be dereferenced + * always. + * + * + * + * @param array $serverctrls Array of LDAP Controls to send with the request. + * @return resource Returns a search result identifier. + * @throws LdapException + * + */ +function ldap_search($link_identifier, string $base_dn, string $filter, array $attributes = null, int $attrsonly = 0, int $sizelimit = -1, int $timelimit = -1, int $deref = LDAP_DEREF_NEVER, array $serverctrls = null) +{ + error_clear_last(); + if ($serverctrls !== null) { + $result = \ldap_search($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref, $serverctrls); + } elseif ($deref !== LDAP_DEREF_NEVER) { + $result = \ldap_search($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref); + } elseif ($timelimit !== -1) { + $result = \ldap_search($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit, $timelimit); + } elseif ($sizelimit !== -1) { + $result = \ldap_search($link_identifier, $base_dn, $filter, $attributes, $attrsonly, $sizelimit); + } elseif ($attrsonly !== 0) { + $result = \ldap_search($link_identifier, $base_dn, $filter, $attributes, $attrsonly); + } elseif ($attributes !== null) { + $result = \ldap_search($link_identifier, $base_dn, $filter, $attributes); + } else { + $result = \ldap_search($link_identifier, $base_dn, $filter); + } + if ($result === false) { + throw LdapException::createFromPhpError(); + } + return $result; +} + + +/** + * Sets the value of the specified option to be newval. + * + * @param resource|null $link_identifier An LDAP link identifier, returned by ldap_connect. + * @param int $option The parameter option can be one of: + * + * + * + * + * Option + * Type + * Available since + * + * + * + * + * LDAP_OPT_DEREF + * integer + * + * + * + * LDAP_OPT_SIZELIMIT + * integer + * + * + * + * LDAP_OPT_TIMELIMIT + * integer + * + * + * + * LDAP_OPT_NETWORK_TIMEOUT + * integer + * PHP 5.3.0 + * + * + * LDAP_OPT_PROTOCOL_VERSION + * integer + * + * + * + * LDAP_OPT_ERROR_NUMBER + * integer + * + * + * + * LDAP_OPT_REFERRALS + * bool + * + * + * + * LDAP_OPT_RESTART + * bool + * + * + * + * LDAP_OPT_HOST_NAME + * string + * + * + * + * LDAP_OPT_ERROR_STRING + * string + * + * + * + * LDAP_OPT_DIAGNOSTIC_MESSAGE + * string + * + * + * + * LDAP_OPT_MATCHED_DN + * string + * + * + * + * LDAP_OPT_SERVER_CONTROLS + * array + * + * + * + * LDAP_OPT_CLIENT_CONTROLS + * array + * + * + * + * LDAP_OPT_X_KEEPALIVE_IDLE + * int + * PHP 7.1.0 + * + * + * LDAP_OPT_X_KEEPALIVE_PROBES + * int + * PHP 7.1.0 + * + * + * LDAP_OPT_X_KEEPALIVE_INTERVAL + * int + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_CACERTDIR + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_CACERTFILE + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_CERTFILE + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_CIPHER_SUITE + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_CRLCHECK + * integer + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_CRLFILE + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_DHFILE + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_KEYFILE + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_PROTOCOL_MIN + * integer + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_RANDOM_FILE + * string + * PHP 7.1.0 + * + * + * LDAP_OPT_X_TLS_REQUIRE_CERT + * integer + * PHP 7.0.5 + * + * + * + * + * + * LDAP_OPT_SERVER_CONTROLS and + * LDAP_OPT_CLIENT_CONTROLS require a list of + * controls, this means that the value must be an array of controls. A + * control consists of an oid identifying the control, + * an optional value, and an optional flag for + * criticality. In PHP a control is given by an + * array containing an element with the key oid + * and string value, and two optional elements. The optional + * elements are key value with string value + * and key iscritical with boolean value. + * iscritical defaults to FALSE + * if not supplied. See draft-ietf-ldapext-ldap-c-api-xx.txt + * for details. See also the second example below. + * @param mixed $newval The new value for the specified option. + * @throws LdapException + * + */ +function ldap_set_option($link_identifier, int $option, $newval): void +{ + error_clear_last(); + $result = \ldap_set_option($link_identifier, $option, $newval); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} + + +/** + * Unbinds from the LDAP directory. + * + * @param resource $link_identifier An LDAP link identifier, returned by ldap_connect. + * @throws LdapException + * + */ +function ldap_unbind($link_identifier): void +{ + error_clear_last(); + $result = \ldap_unbind($link_identifier); + if ($result === false) { + throw LdapException::createFromPhpError(); + } +} diff --git a/vendor/thecodingmachine/safe/generated/libxml.php b/vendor/thecodingmachine/safe/generated/libxml.php new file mode 100644 index 0000000..cef784c --- /dev/null +++ b/vendor/thecodingmachine/safe/generated/libxml.php @@ -0,0 +1,43 @@ + + * + * The above example will output: + * + * example: , this is a test + * example: , this is a test + * ]]> + * + * + * So, $out[0] contains array of strings that matched full pattern, + * and $out[1] contains array of strings enclosed by tags. + * + * + * + * + * If the pattern contains named subpatterns, $matches + * additionally contains entries for keys with the subpattern name. + * + * + * If the pattern contains duplicate named subpatterns, only the rightmost + * subpattern is stored in $matches[NAME]. + * + * + * + * ]]> + * + * The above example will output: + * + * + * [1] => bar + * ) + * ]]> + * + * + * + * + * + * + * PREG_SET_ORDER + * + * + * Orders results so that $matches[0] is an array of first set + * of matches, $matches[1] is an array of second set of matches, + * and so on. + * + * + * + * ]]> + * + * The above example will output: + * + * example: , example: + * this is a test, this is a test + * ]]> + * + * + * + * + * + * + * PREG_OFFSET_CAPTURE + * + * + * If this flag is passed, for every occurring match the appendant string + * offset (in bytes) will also be returned. Note that this changes the value of + * matches into an array of arrays where every element is an + * array consisting of the matched string at offset 0 + * and its string offset into subject at offset + * 1. + * + * + * + * ]]> + * + * The above example will output: + * + * Array + * ( + * [0] => Array + * ( + * [0] => foobarbaz + * [1] => 0 + * ) + * + * ) + * + * [1] => Array + * ( + * [0] => Array + * ( + * [0] => foo + * [1] => 0 + * ) + * + * ) + * + * [2] => Array + * ( + * [0] => Array + * ( + * [0] => bar + * [1] => 3 + * ) + * + * ) + * + * [3] => Array + * ( + * [0] => Array + * ( + * [0] => baz + * [1] => 6 + * ) + * + * ) + * + * ) + * ]]> + * + * + * + * + * + * + * PREG_UNMATCHED_AS_NULL + * + * + * If this flag is passed, unmatched subpatterns are reported as NULL; + * otherwise they are reported as an empty string. + * + * + * + * + * + * Orders results so that $matches[0] is an array of full + * pattern matches, $matches[1] is an array of strings matched by + * the first parenthesized subpattern, and so on. + * + * + * + * + * ]]> + * + * The above example will output: + * + * example: , this is a test + * example: , this is a test + * ]]> + * + * + * So, $out[0] contains array of strings that matched full pattern, + * and $out[1] contains array of strings enclosed by tags. + * + * + * + * The above example will output: + * + * So, $out[0] contains array of strings that matched full pattern, + * and $out[1] contains array of strings enclosed by tags. + * + * If the pattern contains named subpatterns, $matches + * additionally contains entries for keys with the subpattern name. + * + * If the pattern contains duplicate named subpatterns, only the rightmost + * subpattern is stored in $matches[NAME]. + * + * + * + * ]]> + * + * The above example will output: + * + * + * [1] => bar + * ) + * ]]> + * + * + * + * The above example will output: + * + * Orders results so that $matches[0] is an array of first set + * of matches, $matches[1] is an array of second set of matches, + * and so on. + * + * + * + * ]]> + * + * The above example will output: + * + * example: , example: + * this is a test, this is a test + * ]]> + * + * + * + * The above example will output: + * + * If this flag is passed, for every occurring match the appendant string + * offset (in bytes) will also be returned. Note that this changes the value of + * matches into an array of arrays where every element is an + * array consisting of the matched string at offset 0 + * and its string offset into subject at offset + * 1. + * + * + * + * ]]> + * + * The above example will output: + * + * Array + * ( + * [0] => Array + * ( + * [0] => foobarbaz + * [1] => 0 + * ) + * + * ) + * + * [1] => Array + * ( + * [0] => Array + * ( + * [0] => foo + * [1] => 0 + * ) + * + * ) + * + * [2] => Array + * ( + * [0] => Array + * ( + * [0] => bar + * [1] => 3 + * ) + * + * ) + * + * [3] => Array + * ( + * [0] => Array + * ( + * [0] => baz + * [1] => 6 + * ) + * + * ) + * + * ) + * ]]> + * + * + * + * The above example will output: + * + * If this flag is passed, unmatched subpatterns are reported as NULL; + * otherwise they are reported as an empty string. + * + * If no order flag is given, PREG_PATTERN_ORDER is + * assumed. + * @param int $offset Orders results so that $matches[0] is an array of full + * pattern matches, $matches[1] is an array of strings matched by + * the first parenthesized subpattern, and so on. + * + * + * + * + * ]]> + * + * The above example will output: + * + * example: , this is a test + * example: , this is a test + * ]]> + * + * + * So, $out[0] contains array of strings that matched full pattern, + * and $out[1] contains array of strings enclosed by tags. + * + * + * + * The above example will output: + * + * So, $out[0] contains array of strings that matched full pattern, + * and $out[1] contains array of strings enclosed by tags. + * + * If the pattern contains named subpatterns, $matches + * additionally contains entries for keys with the subpattern name. + * + * If the pattern contains duplicate named subpatterns, only the rightmost + * subpattern is stored in $matches[NAME]. + * + * + * + * ]]> + * + * The above example will output: + * + * + * [1] => bar + * ) + * ]]> + * + * + * + * The above example will output: + * @return int Returns the number of full pattern matches (which might be zero). + * @throws PcreException + * + */ +function preg_match_all(string $pattern, string $subject, array &$matches = null, int $flags = PREG_PATTERN_ORDER, int $offset = 0): int +{ + error_clear_last(); + $result = \preg_match_all($pattern, $subject, $matches, $flags, $offset); + if ($result === false) { + throw PcreException::createFromPhpError(); + } + return $result; +} + + +/** + * Searches subject for a match to the regular + * expression given in pattern. + * + * @param string $pattern The pattern to search for, as a string. + * @param string $subject The input string. + * @param array $matches If matches is provided, then it is filled with + * the results of search. $matches[0] will contain the + * text that matched the full pattern, $matches[1] + * will have the text that matched the first captured parenthesized + * subpattern, and so on. + * @param int $flags flags can be a combination of the following flags: + * + * + * PREG_OFFSET_CAPTURE + * + * + * If this flag is passed, for every occurring match the appendant string + * offset (in bytes) will also be returned. Note that this changes the value of + * matches into an array where every element is an + * array consisting of the matched string at offset 0 + * and its string offset into subject at offset + * 1. + * + * + * + * ]]> + * + * The above example will output: + * + * Array + * ( + * [0] => foobarbaz + * [1] => 0 + * ) + * + * [1] => Array + * ( + * [0] => foo + * [1] => 0 + * ) + * + * [2] => Array + * ( + * [0] => bar + * [1] => 3 + * ) + * + * [3] => Array + * ( + * [0] => baz + * [1] => 6 + * ) + * + * ) + * ]]> + * + * + * + * + * + * + * PREG_UNMATCHED_AS_NULL + * + * + * If this flag is passed, unmatched subpatterns are reported as NULL; + * otherwise they are reported as an empty string. + * + * + * + * ]]> + * + * The above example will output: + * + * + * string(2) "ac" + * [1]=> + * string(1) "a" + * [2]=> + * string(0) "" + * [3]=> + * string(1) "c" + * } + * array(4) { + * [0]=> + * string(2) "ac" + * [1]=> + * string(1) "a" + * [2]=> + * NULL + * [3]=> + * string(1) "c" + * } + * ]]> + * + * + * + * + * + * + * + * If this flag is passed, for every occurring match the appendant string + * offset (in bytes) will also be returned. Note that this changes the value of + * matches into an array where every element is an + * array consisting of the matched string at offset 0 + * and its string offset into subject at offset + * 1. + * + * + * + * ]]> + * + * The above example will output: + * + * Array + * ( + * [0] => foobarbaz + * [1] => 0 + * ) + * + * [1] => Array + * ( + * [0] => foo + * [1] => 0 + * ) + * + * [2] => Array + * ( + * [0] => bar + * [1] => 3 + * ) + * + * [3] => Array + * ( + * [0] => baz + * [1] => 6 + * ) + * + * ) + * ]]> + * + * + * + * The above example will output: + * + * If this flag is passed, unmatched subpatterns are reported as NULL; + * otherwise they are reported as an empty string. + * + * + * + * ]]> + * + * The above example will output: + * + * + * string(2) "ac" + * [1]=> + * string(1) "a" + * [2]=> + * string(0) "" + * [3]=> + * string(1) "c" + * } + * array(4) { + * [0]=> + * string(2) "ac" + * [1]=> + * string(1) "a" + * [2]=> + * NULL + * [3]=> + * string(1) "c" + * } + * ]]> + * + * + * + * The above example will output: + * @param int $offset If this flag is passed, for every occurring match the appendant string + * offset (in bytes) will also be returned. Note that this changes the value of + * matches into an array where every element is an + * array consisting of the matched string at offset 0 + * and its string offset into subject at offset + * 1. + * + * + * + * ]]> + * + * The above example will output: + * + * Array + * ( + * [0] => foobarbaz + * [1] => 0 + * ) + * + * [1] => Array + * ( + * [0] => foo + * [1] => 0 + * ) + * + * [2] => Array + * ( + * [0] => bar + * [1] => 3 + * ) + * + * [3] => Array + * ( + * [0] => baz + * [1] => 6 + * ) + * + * ) + * ]]> + * + * + * + * The above example will output: + * @return int preg_match returns 1 if the pattern + * matches given subject, 0 if it does not. + * @throws PcreException + * + */ +function preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int +{ + error_clear_last(); + $result = \preg_match($pattern, $subject, $matches, $flags, $offset); + if ($result === false) { + throw PcreException::createFromPhpError(); + } + return $result; +} + + +/** + * Split the given string by a regular expression. + * + * @param string $pattern The pattern to search for, as a string. + * @param string $subject The input string. + * @param int|null $limit If specified, then only substrings up to limit + * are returned with the rest of the string being placed in the last + * substring. A limit of -1 or 0 means "no limit". + * @param int $flags flags can be any combination of the following + * flags (combined with the | bitwise operator): + * + * + * PREG_SPLIT_NO_EMPTY + * + * + * If this flag is set, only non-empty pieces will be returned by + * preg_split. + * + * + * + * + * PREG_SPLIT_DELIM_CAPTURE + * + * + * If this flag is set, parenthesized expression in the delimiter pattern + * will be captured and returned as well. + * + * + * + * + * PREG_SPLIT_OFFSET_CAPTURE + * + * + * If this flag is set, for every occurring match the appendant string + * offset will also be returned. Note that this changes the return + * value in an array where every element is an array consisting of the + * matched string at offset 0 and its string offset + * into subject at offset 1. + * + * + * + * + * + * If this flag is set, for every occurring match the appendant string + * offset will also be returned. Note that this changes the return + * value in an array where every element is an array consisting of the + * matched string at offset 0 and its string offset + * into subject at offset 1. + * @return array Returns an array containing substrings of subject + * split along boundaries matched by pattern. + * @throws PcreException + * + */ +function preg_split(string $pattern, string $subject, ?int $limit = -1, int $flags = 0): array +{ + error_clear_last(); + $result = \preg_split($pattern, $subject, $limit, $flags); + if ($result === false) { + throw PcreException::createFromPhpError(); + } + return $result; +} diff --git a/vendor/thecodingmachine/safe/generated/pdf.php b/vendor/thecodingmachine/safe/generated/pdf.php new file mode 100644 index 0000000..d039b27 --- /dev/null +++ b/vendor/thecodingmachine/safe/generated/pdf.php @@ -0,0 +1,1553 @@ + + * ]]> + * + * + * + * @param string $prompt The prompt message. + * @param callable $callback The callback function takes one parameter; the + * user input returned. + * @throws ReadlineException + * + */ +function readline_callback_handler_install(string $prompt, callable $callback): void +{ + error_clear_last(); + $result = \readline_callback_handler_install($prompt, $callback); + if ($result === false) { + throw ReadlineException::createFromPhpError(); + } +} + + +/** + * This function clears the entire command line history. + * + * @throws ReadlineException + * + */ +function readline_clear_history(): void +{ + error_clear_last(); + $result = \readline_clear_history(); + if ($result === false) { + throw ReadlineException::createFromPhpError(); + } +} + + +/** + * This function registers a completion function. This is the same kind of + * functionality you'd get if you hit your tab key while using Bash. + * + * @param callable $function You must supply the name of an existing function which accepts a + * partial command line and returns an array of possible matches. + * @throws ReadlineException + * + */ +function readline_completion_function(callable $function): void +{ + error_clear_last(); + $result = \readline_completion_function($function); + if ($result === false) { + throw ReadlineException::createFromPhpError(); + } +} + + +/** + * This function reads a command history from a file. + * + * @param string $filename Path to the filename containing the command history. + * @throws ReadlineException + * + */ +function readline_read_history(string $filename = null): void +{ + error_clear_last(); + if ($filename !== null) { + $result = \readline_read_history($filename); + } else { + $result = \readline_read_history(); + } + if ($result === false) { + throw ReadlineException::createFromPhpError(); + } +} + + +/** + * This function writes the command history to a file. + * + * @param string $filename Path to the saved file. + * @throws ReadlineException + * + */ +function readline_write_history(string $filename = null): void +{ + error_clear_last(); + if ($filename !== null) { + $result = \readline_write_history($filename); + } else { + $result = \readline_write_history(); + } + if ($result === false) { + throw ReadlineException::createFromPhpError(); + } +} diff --git a/vendor/thecodingmachine/safe/generated/rpminfo.php b/vendor/thecodingmachine/safe/generated/rpminfo.php new file mode 100644 index 0000000..44de1ce --- /dev/null +++ b/vendor/thecodingmachine/safe/generated/rpminfo.php @@ -0,0 +1,21 @@ + + * + * + * @param int $length If length is given and is positive, the string + * returned will contain at most length characters + * beginning from start (depending on the length of + * string). + * + * If length is given and is negative, then that many + * characters will be omitted from the end of string + * (after the start position has been calculated when a + * start is negative). If + * start denotes the position of this truncation or + * beyond, FALSE will be returned. + * + * If length is given and is 0, + * FALSE or NULL, an empty string will be returned. + * + * If length is omitted, the substring starting from + * start until the end of the string will be + * returned. + * @return string Returns the extracted part of string;, or + * an empty string. + * @throws StringsException + * + */ +function substr(string $string, int $start, int $length = null): string +{ + error_clear_last(); + if ($length !== null) { + $result = \substr($string, $start, $length); + } else { + $result = \substr($string, $start); + } + if ($result === false) { + throw StringsException::createFromPhpError(); + } + return $result; +} + + +/** + * Operates as sprintf but accepts an array of + * arguments, rather than a variable number of arguments. + * + * @param string $format The format string is composed of zero or more directives: + * ordinary characters (excluding %) that are + * copied directly to the result and conversion + * specifications, each of which results in fetching its + * own parameter. + * + * A conversion specification follows this prototype: + * %[argnum$][flags][width][.precision]specifier. + * + * An integer followed by a dollar sign $, + * to specify which number argument to treat in the conversion. + * + * + * Flags + * + * + * + * Flag + * Description + * + * + * + * + * - + * + * Left-justify within the given field width; + * Right justification is the default + * + * + * + * + + * + * Prefix positive numbers with a plus sign + * +; Default only negative + * are prefixed with a negative sign. + * + * + * + * (space) + * + * Pads the result with spaces. + * This is the default. + * + * + * + * 0 + * + * Only left-pads numbers with zeros. + * With s specifiers this can + * also right-pad with zeros. + * + * + * + * '(char) + * + * Pads the result with the character (char). + * + * + * + * + * + * + * An integer that says how many characters (minimum) + * this conversion should result in. + * + * A period . followed by an integer + * who's meaning depends on the specifier: + * + * + * + * For e, E, + * f and F + * specifiers: this is the number of digits to be printed + * after the decimal point (by default, this is 6). + * + * + * + * + * For g and G + * specifiers: this is the maximum number of significant + * digits to be printed. + * + * + * + * + * For s specifier: it acts as a cutoff point, + * setting a maximum character limit to the string. + * + * + * + * + * + * If the period is specified without an explicit value for precision, + * 0 is assumed. + * + * + * + * + * Specifiers + * + * + * + * Specifier + * Description + * + * + * + * + * % + * + * A literal percent character. No argument is required. + * + * + * + * b + * + * The argument is treated as an integer and presented + * as a binary number. + * + * + * + * c + * + * The argument is treated as an integer and presented + * as the character with that ASCII. + * + * + * + * d + * + * The argument is treated as an integer and presented + * as a (signed) decimal number. + * + * + * + * e + * + * The argument is treated as scientific notation (e.g. 1.2e+2). + * The precision specifier stands for the number of digits after the + * decimal point since PHP 5.2.1. In earlier versions, it was taken as + * number of significant digits (one less). + * + * + * + * E + * + * Like the e specifier but uses + * uppercase letter (e.g. 1.2E+2). + * + * + * + * f + * + * The argument is treated as a float and presented + * as a floating-point number (locale aware). + * + * + * + * F + * + * The argument is treated as a float and presented + * as a floating-point number (non-locale aware). + * Available as of PHP 5.0.3. + * + * + * + * g + * + * + * General format. + * + * + * Let P equal the precision if nonzero, 6 if the precision is omitted, + * or 1 if the precision is zero. + * Then, if a conversion with style E would have an exponent of X: + * + * + * If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). + * Otherwise, the conversion is with style e and precision P − 1. + * + * + * + * + * G + * + * Like the g specifier but uses + * E and f. + * + * + * + * o + * + * The argument is treated as an integer and presented + * as an octal number. + * + * + * + * s + * + * The argument is treated and presented as a string. + * + * + * + * u + * + * The argument is treated as an integer and presented + * as an unsigned decimal number. + * + * + * + * x + * + * The argument is treated as an integer and presented + * as a hexadecimal number (with lowercase letters). + * + * + * + * X + * + * The argument is treated as an integer and presented + * as a hexadecimal number (with uppercase letters). + * + * + * + * + * + * + * General format. + * + * Let P equal the precision if nonzero, 6 if the precision is omitted, + * or 1 if the precision is zero. + * Then, if a conversion with style E would have an exponent of X: + * + * If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). + * Otherwise, the conversion is with style e and precision P − 1. + * + * The c type specifier ignores padding and width + * + * Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results + * + * Variables will be co-erced to a suitable type for the specifier: + * + * Type Handling + * + * + * + * Type + * Specifiers + * + * + * + * + * string + * s + * + * + * integer + * + * d, + * u, + * c, + * o, + * x, + * X, + * b + * + * + * + * double + * + * g, + * G, + * e, + * E, + * f, + * F + * + * + * + * + * + * @param array $args + * @return string Return array values as a formatted string according to + * format. + * @throws StringsException + * + */ +function vsprintf(string $format, array $args): string +{ + error_clear_last(); + $result = \vsprintf($format, $args); + if ($result === false) { + throw StringsException::createFromPhpError(); + } + return $result; +} diff --git a/vendor/thecodingmachine/safe/generated/swoole.php b/vendor/thecodingmachine/safe/generated/swoole.php new file mode 100644 index 0000000..334d96b --- /dev/null +++ b/vendor/thecodingmachine/safe/generated/swoole.php @@ -0,0 +1,108 @@ +format('Y-m-d H:i:s.u'), $datetime->getTimezone()); + } + + /** + * @param string $format + * @param string $time + * @param DateTimeZone|null $timezone + * @throws DatetimeException + */ + public static function createFromFormat($format, $time, $timezone = null): self + { + $datetime = parent::createFromFormat($format, $time, $timezone); + if ($datetime === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($datetime); + } + + /** + * @param DateTimeInterface $datetime2 The date to compare to. + * @param boolean $absolute [optional] Whether to return absolute difference. + * @return DateInterval The DateInterval object representing the difference between the two dates. + * @throws DatetimeException + */ + public function diff($datetime2, $absolute = false): DateInterval + { + /** @var \DateInterval|false $result */ + $result = parent::diff($datetime2, $absolute); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return $result; + } + + /** + * @param string $modify A date/time string. Valid formats are explained in Date and Time Formats. + * @return DateTime Returns the DateTime object for method chaining. + * @throws DatetimeException + */ + public function modify($modify): self + { + /** @var DateTime|false $result */ + $result = parent::modify($modify); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return $result; + } + + /** + * @param int $year + * @param int $month + * @param int $day + * @return DateTime + * @throws DatetimeException + */ + public function setDate($year, $month, $day): self + { + /** @var DateTime|false $result */ + $result = parent::setDate($year, $month, $day); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return $result; + } +} diff --git a/vendor/thecodingmachine/safe/lib/DateTimeImmutable.php b/vendor/thecodingmachine/safe/lib/DateTimeImmutable.php new file mode 100644 index 0000000..114ec3a --- /dev/null +++ b/vendor/thecodingmachine/safe/lib/DateTimeImmutable.php @@ -0,0 +1,262 @@ +innerDateTime = new parent($time, $timezone); + } + + //switch between regular datetime and safe version + public static function createFromRegular(\DateTimeImmutable $datetime): self + { + $safeDatetime = new self($datetime->format('Y-m-d H:i:s.u'), $datetime->getTimezone()); //we need to also update the wrapper to not break the operators '<' and '>' + $safeDatetime->innerDateTime = $datetime; //to make sure we don't lose information because of the format(). + return $safeDatetime; + } + + //usefull if you need to switch back to regular DateTimeImmutable (for example when using DatePeriod) + public function getInnerDateTime(): \DateTimeImmutable + { + return $this->innerDateTime; + } + + ///////////////////////////////////////////////////////////////////////////// + // overload functions with false errors + + /** + * @param string $format + * @param string $time + * @param DateTimeZone|null $timezone + * @throws DatetimeException + */ + public static function createFromFormat($format, $time, $timezone = null): self + { + $datetime = parent::createFromFormat($format, $time, $timezone); + if ($datetime === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($datetime); + } + + /** + * @param string $format + * @return string + * @throws DatetimeException + */ + public function format($format): string + { + /** @var string|false $result */ + $result = $this->innerDateTime->format($format); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return $result; + } + + /** + * @param DateTimeInterface $datetime2 + * @param bool $absolute + * @return DateInterval + * @throws DatetimeException + */ + public function diff($datetime2, $absolute = false): DateInterval + { + /** @var \DateInterval|false $result */ + $result = $this->innerDateTime->diff($datetime2, $absolute); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return $result; + } + + /** + * @param string $modify + * @return DateTimeImmutable + * @throws DatetimeException + */ + public function modify($modify): self + { + /** @var \DateTimeImmutable|false $result */ + $result = $this->innerDateTime->modify($modify); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($result); //we have to recreate a safe datetime because modify create a new instance of \DateTimeImmutable + } + + /** + * @param int $year + * @param int $month + * @param int $day + * @return DateTimeImmutable + * @throws DatetimeException + */ + public function setDate($year, $month, $day): self + { + /** @var \DateTimeImmutable|false $result */ + $result = $this->innerDateTime->setDate($year, $month, $day); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($result); //we have to recreate a safe datetime because modify create a new instance of \DateTimeImmutable + } + + /** + * @param int $year + * @param int $week + * @param int $day + * @return DateTimeImmutable + * @throws DatetimeException + */ + public function setISODate($year, $week, $day = 1): self + { + /** @var \DateTimeImmutable|false $result */ + $result = $this->innerDateTime->setISODate($year, $week, $day); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($result); //we have to recreate a safe datetime because modify create a new instance of \DateTimeImmutable + } + + /** + * @param int $hour + * @param int $minute + * @param int $second + * @param int $microseconds + * @return DateTimeImmutable + * @throws DatetimeException + */ + public function setTime($hour, $minute, $second = 0, $microseconds = 0): self + { + /** @var \DateTimeImmutable|false $result */ + $result = $this->innerDateTime->setTime($hour, $minute, $second, $microseconds); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($result); + } + + /** + * @param int $unixtimestamp + * @return DateTimeImmutable + * @throws DatetimeException + */ + public function setTimestamp($unixtimestamp): self + { + /** @var \DateTimeImmutable|false $result */ + $result = $this->innerDateTime->setTimestamp($unixtimestamp); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($result); + } + + /** + * @param DateTimeZone $timezone + * @return DateTimeImmutable + * @throws DatetimeException + */ + public function setTimezone($timezone): self + { + /** @var \DateTimeImmutable|false $result */ + $result = $this->innerDateTime->setTimezone($timezone); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($result); + } + + /** + * @param DateInterval $interval + * @return DateTimeImmutable + * @throws DatetimeException + */ + public function sub($interval): self + { + /** @var \DateTimeImmutable|false $result */ + $result = $this->innerDateTime->sub($interval); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return self::createFromRegular($result); + } + + /** + * @throws DatetimeException + */ + public function getOffset(): int + { + /** @var int|false $result */ + $result = $this->innerDateTime->getOffset(); + if ($result === false) { + throw DatetimeException::createFromPhpError(); + } + return $result; + } + + ////////////////////////////////////////////////////////////////////////////////////////// + //overload getters to use the inner datetime immutable instead of itself + + /** + * @param DateInterval $interval + * @return DateTimeImmutable + */ + public function add($interval): self + { + return self::createFromRegular($this->innerDateTime->add($interval)); + } + + /** + * @param DateTime $dateTime + * @return DateTimeImmutable + */ + public static function createFromMutable($dateTime): self + { + return self::createFromRegular(parent::createFromMutable($dateTime)); + } + + /** + * @param mixed[] $array + * @return DateTimeImmutable + */ + public static function __set_state($array): self + { + return self::createFromRegular(parent::__set_state($array)); + } + + public function getTimezone(): DateTimeZone + { + return $this->innerDateTime->getTimezone(); + } + + public function getTimestamp(): int + { + return $this->innerDateTime->getTimestamp(); + } +} diff --git a/vendor/thecodingmachine/safe/lib/Exceptions/CurlException.php b/vendor/thecodingmachine/safe/lib/Exceptions/CurlException.php new file mode 100644 index 0000000..2814066 --- /dev/null +++ b/vendor/thecodingmachine/safe/lib/Exceptions/CurlException.php @@ -0,0 +1,15 @@ + 'PREG_INTERNAL_ERROR: Internal error', + PREG_BACKTRACK_LIMIT_ERROR => 'PREG_BACKTRACK_LIMIT_ERROR: Backtrack limit reached', + PREG_RECURSION_LIMIT_ERROR => 'PREG_RECURSION_LIMIT_ERROR: Recursion limit reached', + PREG_BAD_UTF8_ERROR => 'PREG_BAD_UTF8_ERROR: Invalid UTF8 character', + PREG_BAD_UTF8_OFFSET_ERROR => 'PREG_BAD_UTF8_OFFSET_ERROR', + PREG_JIT_STACKLIMIT_ERROR => 'PREG_JIT_STACKLIMIT_ERROR', + ]; + $errMsg = $errorMap[preg_last_error()] ?? 'Unknown PCRE error: '.preg_last_error(); + return new self($errMsg, \preg_last_error()); + } +} diff --git a/vendor/thecodingmachine/safe/lib/Exceptions/SafeExceptionInterface.php b/vendor/thecodingmachine/safe/lib/Exceptions/SafeExceptionInterface.php new file mode 100644 index 0000000..fbea6ad --- /dev/null +++ b/vendor/thecodingmachine/safe/lib/Exceptions/SafeExceptionInterface.php @@ -0,0 +1,9 @@ +services(); + + $services->set(RenameFunctionRector::class) + ->call('configure', [[ RenameFunctionRector::OLD_FUNCTION_TO_NEW_FUNCTION => [ + 'apache_getenv' => 'Safe\apache_getenv', + 'apache_get_version' => 'Safe\apache_get_version', + 'apache_request_headers' => 'Safe\apache_request_headers', + 'apache_reset_timeout' => 'Safe\apache_reset_timeout', + 'apache_response_headers' => 'Safe\apache_response_headers', + 'apache_setenv' => 'Safe\apache_setenv', + 'apcu_cache_info' => 'Safe\apcu_cache_info', + 'apcu_cas' => 'Safe\apcu_cas', + 'apcu_dec' => 'Safe\apcu_dec', + 'apcu_fetch' => 'Safe\apcu_fetch', + 'apcu_inc' => 'Safe\apcu_inc', + 'apcu_sma_info' => 'Safe\apcu_sma_info', + 'apc_fetch' => 'Safe\apc_fetch', + 'array_combine' => 'Safe\array_combine', + 'array_flip' => 'Safe\array_flip', + 'array_replace' => 'Safe\array_replace', + 'array_replace_recursive' => 'Safe\array_replace_recursive', + 'array_walk_recursive' => 'Safe\array_walk_recursive', + 'arsort' => 'Safe\arsort', + 'asort' => 'Safe\asort', + 'base64_decode' => 'Safe\base64_decode', + 'bzclose' => 'Safe\bzclose', + 'bzflush' => 'Safe\bzflush', + 'bzread' => 'Safe\bzread', + 'bzwrite' => 'Safe\bzwrite', + 'chdir' => 'Safe\chdir', + 'chgrp' => 'Safe\chgrp', + 'chmod' => 'Safe\chmod', + 'chown' => 'Safe\chown', + 'chroot' => 'Safe\chroot', + 'class_alias' => 'Safe\class_alias', + 'class_implements' => 'Safe\class_implements', + 'class_parents' => 'Safe\class_parents', + 'class_uses' => 'Safe\class_uses', + 'cli_set_process_title' => 'Safe\cli_set_process_title', + 'closelog' => 'Safe\closelog', + 'com_event_sink' => 'Safe\com_event_sink', + 'com_load_typelib' => 'Safe\com_load_typelib', + 'com_print_typeinfo' => 'Safe\com_print_typeinfo', + 'convert_uudecode' => 'Safe\convert_uudecode', + 'convert_uuencode' => 'Safe\convert_uuencode', + 'copy' => 'Safe\copy', + 'create_function' => 'Safe\create_function', + 'cubrid_free_result' => 'Safe\cubrid_free_result', + 'cubrid_get_charset' => 'Safe\cubrid_get_charset', + 'cubrid_get_client_info' => 'Safe\cubrid_get_client_info', + 'cubrid_get_db_parameter' => 'Safe\cubrid_get_db_parameter', + 'cubrid_get_server_info' => 'Safe\cubrid_get_server_info', + 'cubrid_insert_id' => 'Safe\cubrid_insert_id', + 'cubrid_lob2_new' => 'Safe\cubrid_lob2_new', + 'cubrid_lob2_size' => 'Safe\cubrid_lob2_size', + 'cubrid_lob2_size64' => 'Safe\cubrid_lob2_size64', + 'cubrid_lob2_tell' => 'Safe\cubrid_lob2_tell', + 'cubrid_lob2_tell64' => 'Safe\cubrid_lob2_tell64', + 'cubrid_set_db_parameter' => 'Safe\cubrid_set_db_parameter', + 'curl_escape' => 'Safe\curl_escape', + 'curl_exec' => 'Safe\curl_exec', + 'curl_getinfo' => 'Safe\curl_getinfo', + 'curl_init' => 'Safe\curl_init', + 'curl_multi_errno' => 'Safe\curl_multi_errno', + 'curl_multi_info_read' => 'Safe\curl_multi_info_read', + 'curl_multi_init' => 'Safe\curl_multi_init', + 'curl_setopt' => 'Safe\curl_setopt', + 'curl_share_errno' => 'Safe\curl_share_errno', + 'curl_share_setopt' => 'Safe\curl_share_setopt', + 'curl_unescape' => 'Safe\curl_unescape', + 'date' => 'Safe\date', + 'date_parse' => 'Safe\date_parse', + 'date_parse_from_format' => 'Safe\date_parse_from_format', + 'date_sunrise' => 'Safe\date_sunrise', + 'date_sunset' => 'Safe\date_sunset', + 'date_sun_info' => 'Safe\date_sun_info', + 'db2_autocommit' => 'Safe\db2_autocommit', + 'db2_bind_param' => 'Safe\db2_bind_param', + 'db2_client_info' => 'Safe\db2_client_info', + 'db2_close' => 'Safe\db2_close', + 'db2_commit' => 'Safe\db2_commit', + 'db2_execute' => 'Safe\db2_execute', + 'db2_free_result' => 'Safe\db2_free_result', + 'db2_free_stmt' => 'Safe\db2_free_stmt', + 'db2_get_option' => 'Safe\db2_get_option', + 'db2_pclose' => 'Safe\db2_pclose', + 'db2_rollback' => 'Safe\db2_rollback', + 'db2_server_info' => 'Safe\db2_server_info', + 'db2_set_option' => 'Safe\db2_set_option', + 'define' => 'Safe\define', + 'deflate_add' => 'Safe\deflate_add', + 'deflate_init' => 'Safe\deflate_init', + 'disk_free_space' => 'Safe\disk_free_space', + 'disk_total_space' => 'Safe\disk_total_space', + 'dl' => 'Safe\dl', + 'dns_get_record' => 'Safe\dns_get_record', + 'eio_busy' => 'Safe\eio_busy', + 'eio_chmod' => 'Safe\eio_chmod', + 'eio_chown' => 'Safe\eio_chown', + 'eio_close' => 'Safe\eio_close', + 'eio_custom' => 'Safe\eio_custom', + 'eio_dup2' => 'Safe\eio_dup2', + 'eio_event_loop' => 'Safe\eio_event_loop', + 'eio_fallocate' => 'Safe\eio_fallocate', + 'eio_fchmod' => 'Safe\eio_fchmod', + 'eio_fdatasync' => 'Safe\eio_fdatasync', + 'eio_fstat' => 'Safe\eio_fstat', + 'eio_fstatvfs' => 'Safe\eio_fstatvfs', + 'eio_fsync' => 'Safe\eio_fsync', + 'eio_ftruncate' => 'Safe\eio_ftruncate', + 'eio_futime' => 'Safe\eio_futime', + 'eio_grp' => 'Safe\eio_grp', + 'eio_lstat' => 'Safe\eio_lstat', + 'eio_mkdir' => 'Safe\eio_mkdir', + 'eio_mknod' => 'Safe\eio_mknod', + 'eio_nop' => 'Safe\eio_nop', + 'eio_readahead' => 'Safe\eio_readahead', + 'eio_readdir' => 'Safe\eio_readdir', + 'eio_readlink' => 'Safe\eio_readlink', + 'eio_rename' => 'Safe\eio_rename', + 'eio_rmdir' => 'Safe\eio_rmdir', + 'eio_seek' => 'Safe\eio_seek', + 'eio_sendfile' => 'Safe\eio_sendfile', + 'eio_stat' => 'Safe\eio_stat', + 'eio_statvfs' => 'Safe\eio_statvfs', + 'eio_symlink' => 'Safe\eio_symlink', + 'eio_sync' => 'Safe\eio_sync', + 'eio_syncfs' => 'Safe\eio_syncfs', + 'eio_sync_file_range' => 'Safe\eio_sync_file_range', + 'eio_truncate' => 'Safe\eio_truncate', + 'eio_unlink' => 'Safe\eio_unlink', + 'eio_utime' => 'Safe\eio_utime', + 'eio_write' => 'Safe\eio_write', + 'error_log' => 'Safe\error_log', + 'fastcgi_finish_request' => 'Safe\fastcgi_finish_request', + 'fbird_blob_cancel' => 'Safe\fbird_blob_cancel', + 'fclose' => 'Safe\fclose', + 'fflush' => 'Safe\fflush', + 'file' => 'Safe\file', + 'fileatime' => 'Safe\fileatime', + 'filectime' => 'Safe\filectime', + 'fileinode' => 'Safe\fileinode', + 'filemtime' => 'Safe\filemtime', + 'fileowner' => 'Safe\fileowner', + 'filesize' => 'Safe\filesize', + 'file_get_contents' => 'Safe\file_get_contents', + 'file_put_contents' => 'Safe\file_put_contents', + 'filter_input_array' => 'Safe\filter_input_array', + 'filter_var_array' => 'Safe\filter_var_array', + 'finfo_close' => 'Safe\finfo_close', + 'finfo_open' => 'Safe\finfo_open', + 'flock' => 'Safe\flock', + 'fopen' => 'Safe\fopen', + 'fputcsv' => 'Safe\fputcsv', + 'fread' => 'Safe\fread', + 'fsockopen' => 'Safe\fsockopen', + 'ftp_alloc' => 'Safe\ftp_alloc', + 'ftp_append' => 'Safe\ftp_append', + 'ftp_cdup' => 'Safe\ftp_cdup', + 'ftp_chdir' => 'Safe\ftp_chdir', + 'ftp_chmod' => 'Safe\ftp_chmod', + 'ftp_close' => 'Safe\ftp_close', + 'ftp_connect' => 'Safe\ftp_connect', + 'ftp_delete' => 'Safe\ftp_delete', + 'ftp_fget' => 'Safe\ftp_fget', + 'ftp_fput' => 'Safe\ftp_fput', + 'ftp_get' => 'Safe\ftp_get', + 'ftp_login' => 'Safe\ftp_login', + 'ftp_mkdir' => 'Safe\ftp_mkdir', + 'ftp_mlsd' => 'Safe\ftp_mlsd', + 'ftp_nlist' => 'Safe\ftp_nlist', + 'ftp_pasv' => 'Safe\ftp_pasv', + 'ftp_put' => 'Safe\ftp_put', + 'ftp_pwd' => 'Safe\ftp_pwd', + 'ftp_rename' => 'Safe\ftp_rename', + 'ftp_rmdir' => 'Safe\ftp_rmdir', + 'ftp_site' => 'Safe\ftp_site', + 'ftp_ssl_connect' => 'Safe\ftp_ssl_connect', + 'ftp_systype' => 'Safe\ftp_systype', + 'ftruncate' => 'Safe\ftruncate', + 'fwrite' => 'Safe\fwrite', + 'getallheaders' => 'Safe\getallheaders', + 'getcwd' => 'Safe\getcwd', + 'gethostname' => 'Safe\gethostname', + 'getimagesize' => 'Safe\getimagesize', + 'getlastmod' => 'Safe\getlastmod', + 'getmygid' => 'Safe\getmygid', + 'getmyinode' => 'Safe\getmyinode', + 'getmypid' => 'Safe\getmypid', + 'getmyuid' => 'Safe\getmyuid', + 'getopt' => 'Safe\getopt', + 'getprotobyname' => 'Safe\getprotobyname', + 'getprotobynumber' => 'Safe\getprotobynumber', + 'get_headers' => 'Safe\get_headers', + 'glob' => 'Safe\glob', + 'gmdate' => 'Safe\gmdate', + 'gmp_binomial' => 'Safe\gmp_binomial', + 'gmp_export' => 'Safe\gmp_export', + 'gmp_import' => 'Safe\gmp_import', + 'gmp_random_seed' => 'Safe\gmp_random_seed', + 'gnupg_adddecryptkey' => 'Safe\gnupg_adddecryptkey', + 'gnupg_addencryptkey' => 'Safe\gnupg_addencryptkey', + 'gnupg_addsignkey' => 'Safe\gnupg_addsignkey', + 'gnupg_cleardecryptkeys' => 'Safe\gnupg_cleardecryptkeys', + 'gnupg_clearencryptkeys' => 'Safe\gnupg_clearencryptkeys', + 'gnupg_clearsignkeys' => 'Safe\gnupg_clearsignkeys', + 'gnupg_setarmor' => 'Safe\gnupg_setarmor', + 'gnupg_setsignmode' => 'Safe\gnupg_setsignmode', + 'gzclose' => 'Safe\gzclose', + 'gzcompress' => 'Safe\gzcompress', + 'gzdecode' => 'Safe\gzdecode', + 'gzdeflate' => 'Safe\gzdeflate', + 'gzencode' => 'Safe\gzencode', + 'gzgets' => 'Safe\gzgets', + 'gzgetss' => 'Safe\gzgetss', + 'gzinflate' => 'Safe\gzinflate', + 'gzpassthru' => 'Safe\gzpassthru', + 'gzrewind' => 'Safe\gzrewind', + 'gzuncompress' => 'Safe\gzuncompress', + 'hash_hkdf' => 'Safe\hash_hkdf', + 'hash_update_file' => 'Safe\hash_update_file', + 'header_register_callback' => 'Safe\header_register_callback', + 'hex2bin' => 'Safe\hex2bin', + 'highlight_file' => 'Safe\highlight_file', + 'highlight_string' => 'Safe\highlight_string', + 'ibase_add_user' => 'Safe\ibase_add_user', + 'ibase_backup' => 'Safe\ibase_backup', + 'ibase_blob_cancel' => 'Safe\ibase_blob_cancel', + 'ibase_blob_create' => 'Safe\ibase_blob_create', + 'ibase_blob_get' => 'Safe\ibase_blob_get', + 'ibase_close' => 'Safe\ibase_close', + 'ibase_commit' => 'Safe\ibase_commit', + 'ibase_commit_ret' => 'Safe\ibase_commit_ret', + 'ibase_connect' => 'Safe\ibase_connect', + 'ibase_delete_user' => 'Safe\ibase_delete_user', + 'ibase_drop_db' => 'Safe\ibase_drop_db', + 'ibase_free_event_handler' => 'Safe\ibase_free_event_handler', + 'ibase_free_query' => 'Safe\ibase_free_query', + 'ibase_free_result' => 'Safe\ibase_free_result', + 'ibase_maintain_db' => 'Safe\ibase_maintain_db', + 'ibase_modify_user' => 'Safe\ibase_modify_user', + 'ibase_name_result' => 'Safe\ibase_name_result', + 'ibase_pconnect' => 'Safe\ibase_pconnect', + 'ibase_restore' => 'Safe\ibase_restore', + 'ibase_rollback' => 'Safe\ibase_rollback', + 'ibase_rollback_ret' => 'Safe\ibase_rollback_ret', + 'ibase_service_attach' => 'Safe\ibase_service_attach', + 'ibase_service_detach' => 'Safe\ibase_service_detach', + 'iconv' => 'Safe\iconv', + 'iconv_get_encoding' => 'Safe\iconv_get_encoding', + 'iconv_set_encoding' => 'Safe\iconv_set_encoding', + 'image2wbmp' => 'Safe\image2wbmp', + 'imageaffine' => 'Safe\imageaffine', + 'imageaffinematrixconcat' => 'Safe\imageaffinematrixconcat', + 'imageaffinematrixget' => 'Safe\imageaffinematrixget', + 'imagealphablending' => 'Safe\imagealphablending', + 'imageantialias' => 'Safe\imageantialias', + 'imagearc' => 'Safe\imagearc', + 'imagebmp' => 'Safe\imagebmp', + 'imagechar' => 'Safe\imagechar', + 'imagecharup' => 'Safe\imagecharup', + 'imagecolorat' => 'Safe\imagecolorat', + 'imagecolordeallocate' => 'Safe\imagecolordeallocate', + 'imagecolormatch' => 'Safe\imagecolormatch', + 'imageconvolution' => 'Safe\imageconvolution', + 'imagecopy' => 'Safe\imagecopy', + 'imagecopymerge' => 'Safe\imagecopymerge', + 'imagecopymergegray' => 'Safe\imagecopymergegray', + 'imagecopyresampled' => 'Safe\imagecopyresampled', + 'imagecopyresized' => 'Safe\imagecopyresized', + 'imagecreate' => 'Safe\imagecreate', + 'imagecreatefrombmp' => 'Safe\imagecreatefrombmp', + 'imagecreatefromgd' => 'Safe\imagecreatefromgd', + 'imagecreatefromgd2' => 'Safe\imagecreatefromgd2', + 'imagecreatefromgd2part' => 'Safe\imagecreatefromgd2part', + 'imagecreatefromgif' => 'Safe\imagecreatefromgif', + 'imagecreatefromjpeg' => 'Safe\imagecreatefromjpeg', + 'imagecreatefrompng' => 'Safe\imagecreatefrompng', + 'imagecreatefromwbmp' => 'Safe\imagecreatefromwbmp', + 'imagecreatefromwebp' => 'Safe\imagecreatefromwebp', + 'imagecreatefromxbm' => 'Safe\imagecreatefromxbm', + 'imagecreatefromxpm' => 'Safe\imagecreatefromxpm', + 'imagecreatetruecolor' => 'Safe\imagecreatetruecolor', + 'imagecrop' => 'Safe\imagecrop', + 'imagecropauto' => 'Safe\imagecropauto', + 'imagedashedline' => 'Safe\imagedashedline', + 'imagedestroy' => 'Safe\imagedestroy', + 'imageellipse' => 'Safe\imageellipse', + 'imagefill' => 'Safe\imagefill', + 'imagefilledarc' => 'Safe\imagefilledarc', + 'imagefilledellipse' => 'Safe\imagefilledellipse', + 'imagefilledpolygon' => 'Safe\imagefilledpolygon', + 'imagefilledrectangle' => 'Safe\imagefilledrectangle', + 'imagefilltoborder' => 'Safe\imagefilltoborder', + 'imagefilter' => 'Safe\imagefilter', + 'imageflip' => 'Safe\imageflip', + 'imagegammacorrect' => 'Safe\imagegammacorrect', + 'imagegd' => 'Safe\imagegd', + 'imagegd2' => 'Safe\imagegd2', + 'imagegif' => 'Safe\imagegif', + 'imagegrabscreen' => 'Safe\imagegrabscreen', + 'imagegrabwindow' => 'Safe\imagegrabwindow', + 'imagejpeg' => 'Safe\imagejpeg', + 'imagelayereffect' => 'Safe\imagelayereffect', + 'imageline' => 'Safe\imageline', + 'imageloadfont' => 'Safe\imageloadfont', + 'imageopenpolygon' => 'Safe\imageopenpolygon', + 'imagepng' => 'Safe\imagepng', + 'imagepolygon' => 'Safe\imagepolygon', + 'imagerectangle' => 'Safe\imagerectangle', + 'imagerotate' => 'Safe\imagerotate', + 'imagesavealpha' => 'Safe\imagesavealpha', + 'imagescale' => 'Safe\imagescale', + 'imagesetbrush' => 'Safe\imagesetbrush', + 'imagesetclip' => 'Safe\imagesetclip', + 'imagesetinterpolation' => 'Safe\imagesetinterpolation', + 'imagesetpixel' => 'Safe\imagesetpixel', + 'imagesetstyle' => 'Safe\imagesetstyle', + 'imagesetthickness' => 'Safe\imagesetthickness', + 'imagesettile' => 'Safe\imagesettile', + 'imagestring' => 'Safe\imagestring', + 'imagestringup' => 'Safe\imagestringup', + 'imagesx' => 'Safe\imagesx', + 'imagesy' => 'Safe\imagesy', + 'imagetruecolortopalette' => 'Safe\imagetruecolortopalette', + 'imagettfbbox' => 'Safe\imagettfbbox', + 'imagettftext' => 'Safe\imagettftext', + 'imagewbmp' => 'Safe\imagewbmp', + 'imagewebp' => 'Safe\imagewebp', + 'imagexbm' => 'Safe\imagexbm', + 'imap_append' => 'Safe\imap_append', + 'imap_check' => 'Safe\imap_check', + 'imap_clearflag_full' => 'Safe\imap_clearflag_full', + 'imap_close' => 'Safe\imap_close', + 'imap_createmailbox' => 'Safe\imap_createmailbox', + 'imap_deletemailbox' => 'Safe\imap_deletemailbox', + 'imap_fetchstructure' => 'Safe\imap_fetchstructure', + 'imap_gc' => 'Safe\imap_gc', + 'imap_headerinfo' => 'Safe\imap_headerinfo', + 'imap_mail' => 'Safe\imap_mail', + 'imap_mailboxmsginfo' => 'Safe\imap_mailboxmsginfo', + 'imap_mail_compose' => 'Safe\imap_mail_compose', + 'imap_mail_copy' => 'Safe\imap_mail_copy', + 'imap_mail_move' => 'Safe\imap_mail_move', + 'imap_mutf7_to_utf8' => 'Safe\imap_mutf7_to_utf8', + 'imap_num_msg' => 'Safe\imap_num_msg', + 'imap_open' => 'Safe\imap_open', + 'imap_renamemailbox' => 'Safe\imap_renamemailbox', + 'imap_savebody' => 'Safe\imap_savebody', + 'imap_setacl' => 'Safe\imap_setacl', + 'imap_setflag_full' => 'Safe\imap_setflag_full', + 'imap_set_quota' => 'Safe\imap_set_quota', + 'imap_sort' => 'Safe\imap_sort', + 'imap_subscribe' => 'Safe\imap_subscribe', + 'imap_thread' => 'Safe\imap_thread', + 'imap_timeout' => 'Safe\imap_timeout', + 'imap_undelete' => 'Safe\imap_undelete', + 'imap_unsubscribe' => 'Safe\imap_unsubscribe', + 'imap_utf8_to_mutf7' => 'Safe\imap_utf8_to_mutf7', + 'inet_ntop' => 'Safe\inet_ntop', + 'inflate_add' => 'Safe\inflate_add', + 'inflate_get_read_len' => 'Safe\inflate_get_read_len', + 'inflate_get_status' => 'Safe\inflate_get_status', + 'inflate_init' => 'Safe\inflate_init', + 'ingres_autocommit' => 'Safe\ingres_autocommit', + 'ingres_close' => 'Safe\ingres_close', + 'ingres_commit' => 'Safe\ingres_commit', + 'ingres_connect' => 'Safe\ingres_connect', + 'ingres_execute' => 'Safe\ingres_execute', + 'ingres_field_name' => 'Safe\ingres_field_name', + 'ingres_field_type' => 'Safe\ingres_field_type', + 'ingres_free_result' => 'Safe\ingres_free_result', + 'ingres_pconnect' => 'Safe\ingres_pconnect', + 'ingres_result_seek' => 'Safe\ingres_result_seek', + 'ingres_rollback' => 'Safe\ingres_rollback', + 'ingres_set_environment' => 'Safe\ingres_set_environment', + 'ini_get' => 'Safe\ini_get', + 'ini_set' => 'Safe\ini_set', + 'inotify_init' => 'Safe\inotify_init', + 'inotify_rm_watch' => 'Safe\inotify_rm_watch', + 'iptcembed' => 'Safe\iptcembed', + 'iptcparse' => 'Safe\iptcparse', + 'jdtounix' => 'Safe\jdtounix', + 'jpeg2wbmp' => 'Safe\jpeg2wbmp', + 'json_decode' => 'Safe\json_decode', + 'json_encode' => 'Safe\json_encode', + 'json_last_error_msg' => 'Safe\json_last_error_msg', + 'krsort' => 'Safe\krsort', + 'ksort' => 'Safe\ksort', + 'lchgrp' => 'Safe\lchgrp', + 'lchown' => 'Safe\lchown', + 'ldap_add' => 'Safe\ldap_add', + 'ldap_add_ext' => 'Safe\ldap_add_ext', + 'ldap_bind' => 'Safe\ldap_bind', + 'ldap_bind_ext' => 'Safe\ldap_bind_ext', + 'ldap_control_paged_result' => 'Safe\ldap_control_paged_result', + 'ldap_control_paged_result_response' => 'Safe\ldap_control_paged_result_response', + 'ldap_count_entries' => 'Safe\ldap_count_entries', + 'ldap_delete' => 'Safe\ldap_delete', + 'ldap_delete_ext' => 'Safe\ldap_delete_ext', + 'ldap_exop' => 'Safe\ldap_exop', + 'ldap_exop_passwd' => 'Safe\ldap_exop_passwd', + 'ldap_exop_whoami' => 'Safe\ldap_exop_whoami', + 'ldap_explode_dn' => 'Safe\ldap_explode_dn', + 'ldap_first_attribute' => 'Safe\ldap_first_attribute', + 'ldap_first_entry' => 'Safe\ldap_first_entry', + 'ldap_free_result' => 'Safe\ldap_free_result', + 'ldap_get_attributes' => 'Safe\ldap_get_attributes', + 'ldap_get_dn' => 'Safe\ldap_get_dn', + 'ldap_get_entries' => 'Safe\ldap_get_entries', + 'ldap_get_option' => 'Safe\ldap_get_option', + 'ldap_get_values' => 'Safe\ldap_get_values', + 'ldap_get_values_len' => 'Safe\ldap_get_values_len', + 'ldap_list' => 'Safe\ldap_list', + 'ldap_modify_batch' => 'Safe\ldap_modify_batch', + 'ldap_mod_add' => 'Safe\ldap_mod_add', + 'ldap_mod_add_ext' => 'Safe\ldap_mod_add_ext', + 'ldap_mod_del' => 'Safe\ldap_mod_del', + 'ldap_mod_del_ext' => 'Safe\ldap_mod_del_ext', + 'ldap_mod_replace' => 'Safe\ldap_mod_replace', + 'ldap_mod_replace_ext' => 'Safe\ldap_mod_replace_ext', + 'ldap_next_attribute' => 'Safe\ldap_next_attribute', + 'ldap_parse_exop' => 'Safe\ldap_parse_exop', + 'ldap_parse_result' => 'Safe\ldap_parse_result', + 'ldap_read' => 'Safe\ldap_read', + 'ldap_rename' => 'Safe\ldap_rename', + 'ldap_rename_ext' => 'Safe\ldap_rename_ext', + 'ldap_sasl_bind' => 'Safe\ldap_sasl_bind', + 'ldap_search' => 'Safe\ldap_search', + 'ldap_set_option' => 'Safe\ldap_set_option', + 'ldap_unbind' => 'Safe\ldap_unbind', + 'libxml_get_last_error' => 'Safe\libxml_get_last_error', + 'libxml_set_external_entity_loader' => 'Safe\libxml_set_external_entity_loader', + 'link' => 'Safe\link', + 'lzf_compress' => 'Safe\lzf_compress', + 'lzf_decompress' => 'Safe\lzf_decompress', + 'mailparse_msg_extract_part_file' => 'Safe\mailparse_msg_extract_part_file', + 'mailparse_msg_free' => 'Safe\mailparse_msg_free', + 'mailparse_msg_parse' => 'Safe\mailparse_msg_parse', + 'mailparse_msg_parse_file' => 'Safe\mailparse_msg_parse_file', + 'mailparse_stream_encode' => 'Safe\mailparse_stream_encode', + 'mb_chr' => 'Safe\mb_chr', + 'mb_detect_order' => 'Safe\mb_detect_order', + 'mb_encoding_aliases' => 'Safe\mb_encoding_aliases', + 'mb_eregi_replace' => 'Safe\mb_eregi_replace', + 'mb_ereg_replace' => 'Safe\mb_ereg_replace', + 'mb_ereg_replace_callback' => 'Safe\mb_ereg_replace_callback', + 'mb_ereg_search_getregs' => 'Safe\mb_ereg_search_getregs', + 'mb_ereg_search_init' => 'Safe\mb_ereg_search_init', + 'mb_ereg_search_regs' => 'Safe\mb_ereg_search_regs', + 'mb_ereg_search_setpos' => 'Safe\mb_ereg_search_setpos', + 'mb_http_output' => 'Safe\mb_http_output', + 'mb_internal_encoding' => 'Safe\mb_internal_encoding', + 'mb_ord' => 'Safe\mb_ord', + 'mb_parse_str' => 'Safe\mb_parse_str', + 'mb_regex_encoding' => 'Safe\mb_regex_encoding', + 'mb_send_mail' => 'Safe\mb_send_mail', + 'mb_split' => 'Safe\mb_split', + 'mb_str_split' => 'Safe\mb_str_split', + 'md5_file' => 'Safe\md5_file', + 'metaphone' => 'Safe\metaphone', + 'mime_content_type' => 'Safe\mime_content_type', + 'mkdir' => 'Safe\mkdir', + 'mktime' => 'Safe\mktime', + 'msg_queue_exists' => 'Safe\msg_queue_exists', + 'msg_receive' => 'Safe\msg_receive', + 'msg_remove_queue' => 'Safe\msg_remove_queue', + 'msg_send' => 'Safe\msg_send', + 'msg_set_queue' => 'Safe\msg_set_queue', + 'msql_affected_rows' => 'Safe\msql_affected_rows', + 'msql_close' => 'Safe\msql_close', + 'msql_connect' => 'Safe\msql_connect', + 'msql_create_db' => 'Safe\msql_create_db', + 'msql_data_seek' => 'Safe\msql_data_seek', + 'msql_db_query' => 'Safe\msql_db_query', + 'msql_drop_db' => 'Safe\msql_drop_db', + 'msql_field_len' => 'Safe\msql_field_len', + 'msql_field_name' => 'Safe\msql_field_name', + 'msql_field_seek' => 'Safe\msql_field_seek', + 'msql_field_table' => 'Safe\msql_field_table', + 'msql_field_type' => 'Safe\msql_field_type', + 'msql_free_result' => 'Safe\msql_free_result', + 'msql_pconnect' => 'Safe\msql_pconnect', + 'msql_query' => 'Safe\msql_query', + 'msql_select_db' => 'Safe\msql_select_db', + 'mysqli_get_cache_stats' => 'Safe\mysqli_get_cache_stats', + 'mysqli_get_client_stats' => 'Safe\mysqli_get_client_stats', + 'mysqlnd_ms_dump_servers' => 'Safe\mysqlnd_ms_dump_servers', + 'mysqlnd_ms_fabric_select_global' => 'Safe\mysqlnd_ms_fabric_select_global', + 'mysqlnd_ms_fabric_select_shard' => 'Safe\mysqlnd_ms_fabric_select_shard', + 'mysqlnd_ms_get_last_used_connection' => 'Safe\mysqlnd_ms_get_last_used_connection', + 'mysqlnd_qc_clear_cache' => 'Safe\mysqlnd_qc_clear_cache', + 'mysqlnd_qc_set_is_select' => 'Safe\mysqlnd_qc_set_is_select', + 'mysqlnd_qc_set_storage_handler' => 'Safe\mysqlnd_qc_set_storage_handler', + 'mysql_close' => 'Safe\mysql_close', + 'mysql_connect' => 'Safe\mysql_connect', + 'mysql_create_db' => 'Safe\mysql_create_db', + 'mysql_data_seek' => 'Safe\mysql_data_seek', + 'mysql_db_name' => 'Safe\mysql_db_name', + 'mysql_db_query' => 'Safe\mysql_db_query', + 'mysql_drop_db' => 'Safe\mysql_drop_db', + 'mysql_fetch_lengths' => 'Safe\mysql_fetch_lengths', + 'mysql_field_flags' => 'Safe\mysql_field_flags', + 'mysql_field_len' => 'Safe\mysql_field_len', + 'mysql_field_name' => 'Safe\mysql_field_name', + 'mysql_field_seek' => 'Safe\mysql_field_seek', + 'mysql_free_result' => 'Safe\mysql_free_result', + 'mysql_get_host_info' => 'Safe\mysql_get_host_info', + 'mysql_get_proto_info' => 'Safe\mysql_get_proto_info', + 'mysql_get_server_info' => 'Safe\mysql_get_server_info', + 'mysql_info' => 'Safe\mysql_info', + 'mysql_list_dbs' => 'Safe\mysql_list_dbs', + 'mysql_list_fields' => 'Safe\mysql_list_fields', + 'mysql_list_processes' => 'Safe\mysql_list_processes', + 'mysql_list_tables' => 'Safe\mysql_list_tables', + 'mysql_num_fields' => 'Safe\mysql_num_fields', + 'mysql_num_rows' => 'Safe\mysql_num_rows', + 'mysql_query' => 'Safe\mysql_query', + 'mysql_real_escape_string' => 'Safe\mysql_real_escape_string', + 'mysql_result' => 'Safe\mysql_result', + 'mysql_select_db' => 'Safe\mysql_select_db', + 'mysql_set_charset' => 'Safe\mysql_set_charset', + 'mysql_tablename' => 'Safe\mysql_tablename', + 'mysql_thread_id' => 'Safe\mysql_thread_id', + 'mysql_unbuffered_query' => 'Safe\mysql_unbuffered_query', + 'natcasesort' => 'Safe\natcasesort', + 'natsort' => 'Safe\natsort', + 'ob_end_clean' => 'Safe\ob_end_clean', + 'ob_end_flush' => 'Safe\ob_end_flush', + 'oci_bind_array_by_name' => 'Safe\oci_bind_array_by_name', + 'oci_bind_by_name' => 'Safe\oci_bind_by_name', + 'oci_cancel' => 'Safe\oci_cancel', + 'oci_close' => 'Safe\oci_close', + 'oci_commit' => 'Safe\oci_commit', + 'oci_connect' => 'Safe\oci_connect', + 'oci_define_by_name' => 'Safe\oci_define_by_name', + 'oci_execute' => 'Safe\oci_execute', + 'oci_fetch_all' => 'Safe\oci_fetch_all', + 'oci_field_name' => 'Safe\oci_field_name', + 'oci_field_precision' => 'Safe\oci_field_precision', + 'oci_field_scale' => 'Safe\oci_field_scale', + 'oci_field_size' => 'Safe\oci_field_size', + 'oci_field_type' => 'Safe\oci_field_type', + 'oci_field_type_raw' => 'Safe\oci_field_type_raw', + 'oci_free_descriptor' => 'Safe\oci_free_descriptor', + 'oci_free_statement' => 'Safe\oci_free_statement', + 'oci_new_collection' => 'Safe\oci_new_collection', + 'oci_new_connect' => 'Safe\oci_new_connect', + 'oci_new_cursor' => 'Safe\oci_new_cursor', + 'oci_new_descriptor' => 'Safe\oci_new_descriptor', + 'oci_num_fields' => 'Safe\oci_num_fields', + 'oci_num_rows' => 'Safe\oci_num_rows', + 'oci_parse' => 'Safe\oci_parse', + 'oci_pconnect' => 'Safe\oci_pconnect', + 'oci_result' => 'Safe\oci_result', + 'oci_rollback' => 'Safe\oci_rollback', + 'oci_server_version' => 'Safe\oci_server_version', + 'oci_set_action' => 'Safe\oci_set_action', + 'oci_set_call_timeout' => 'Safe\oci_set_call_timeout', + 'oci_set_client_identifier' => 'Safe\oci_set_client_identifier', + 'oci_set_client_info' => 'Safe\oci_set_client_info', + 'oci_set_db_operation' => 'Safe\oci_set_db_operation', + 'oci_set_edition' => 'Safe\oci_set_edition', + 'oci_set_module_name' => 'Safe\oci_set_module_name', + 'oci_set_prefetch' => 'Safe\oci_set_prefetch', + 'oci_statement_type' => 'Safe\oci_statement_type', + 'oci_unregister_taf_callback' => 'Safe\oci_unregister_taf_callback', + 'odbc_autocommit' => 'Safe\odbc_autocommit', + 'odbc_binmode' => 'Safe\odbc_binmode', + 'odbc_columnprivileges' => 'Safe\odbc_columnprivileges', + 'odbc_columns' => 'Safe\odbc_columns', + 'odbc_commit' => 'Safe\odbc_commit', + 'odbc_data_source' => 'Safe\odbc_data_source', + 'odbc_exec' => 'Safe\odbc_exec', + 'odbc_execute' => 'Safe\odbc_execute', + 'odbc_fetch_into' => 'Safe\odbc_fetch_into', + 'odbc_field_len' => 'Safe\odbc_field_len', + 'odbc_field_name' => 'Safe\odbc_field_name', + 'odbc_field_num' => 'Safe\odbc_field_num', + 'odbc_field_scale' => 'Safe\odbc_field_scale', + 'odbc_field_type' => 'Safe\odbc_field_type', + 'odbc_foreignkeys' => 'Safe\odbc_foreignkeys', + 'odbc_gettypeinfo' => 'Safe\odbc_gettypeinfo', + 'odbc_longreadlen' => 'Safe\odbc_longreadlen', + 'odbc_prepare' => 'Safe\odbc_prepare', + 'odbc_primarykeys' => 'Safe\odbc_primarykeys', + 'odbc_result' => 'Safe\odbc_result', + 'odbc_result_all' => 'Safe\odbc_result_all', + 'odbc_rollback' => 'Safe\odbc_rollback', + 'odbc_setoption' => 'Safe\odbc_setoption', + 'odbc_specialcolumns' => 'Safe\odbc_specialcolumns', + 'odbc_statistics' => 'Safe\odbc_statistics', + 'odbc_tableprivileges' => 'Safe\odbc_tableprivileges', + 'odbc_tables' => 'Safe\odbc_tables', + 'opcache_compile_file' => 'Safe\opcache_compile_file', + 'opcache_get_status' => 'Safe\opcache_get_status', + 'opendir' => 'Safe\opendir', + 'openlog' => 'Safe\openlog', + 'openssl_cipher_iv_length' => 'Safe\openssl_cipher_iv_length', + 'openssl_csr_export' => 'Safe\openssl_csr_export', + 'openssl_csr_export_to_file' => 'Safe\openssl_csr_export_to_file', + 'openssl_csr_get_subject' => 'Safe\openssl_csr_get_subject', + 'openssl_csr_new' => 'Safe\openssl_csr_new', + 'openssl_csr_sign' => 'Safe\openssl_csr_sign', + 'openssl_decrypt' => 'Safe\openssl_decrypt', + 'openssl_dh_compute_key' => 'Safe\openssl_dh_compute_key', + 'openssl_digest' => 'Safe\openssl_digest', + 'openssl_encrypt' => 'Safe\openssl_encrypt', + 'openssl_open' => 'Safe\openssl_open', + 'openssl_pbkdf2' => 'Safe\openssl_pbkdf2', + 'openssl_pkcs7_decrypt' => 'Safe\openssl_pkcs7_decrypt', + 'openssl_pkcs7_encrypt' => 'Safe\openssl_pkcs7_encrypt', + 'openssl_pkcs7_read' => 'Safe\openssl_pkcs7_read', + 'openssl_pkcs7_sign' => 'Safe\openssl_pkcs7_sign', + 'openssl_pkcs12_export' => 'Safe\openssl_pkcs12_export', + 'openssl_pkcs12_export_to_file' => 'Safe\openssl_pkcs12_export_to_file', + 'openssl_pkcs12_read' => 'Safe\openssl_pkcs12_read', + 'openssl_pkey_export' => 'Safe\openssl_pkey_export', + 'openssl_pkey_export_to_file' => 'Safe\openssl_pkey_export_to_file', + 'openssl_pkey_get_private' => 'Safe\openssl_pkey_get_private', + 'openssl_pkey_get_public' => 'Safe\openssl_pkey_get_public', + 'openssl_pkey_new' => 'Safe\openssl_pkey_new', + 'openssl_private_decrypt' => 'Safe\openssl_private_decrypt', + 'openssl_private_encrypt' => 'Safe\openssl_private_encrypt', + 'openssl_public_decrypt' => 'Safe\openssl_public_decrypt', + 'openssl_public_encrypt' => 'Safe\openssl_public_encrypt', + 'openssl_random_pseudo_bytes' => 'Safe\openssl_random_pseudo_bytes', + 'openssl_seal' => 'Safe\openssl_seal', + 'openssl_sign' => 'Safe\openssl_sign', + 'openssl_x509_export' => 'Safe\openssl_x509_export', + 'openssl_x509_export_to_file' => 'Safe\openssl_x509_export_to_file', + 'openssl_x509_fingerprint' => 'Safe\openssl_x509_fingerprint', + 'openssl_x509_read' => 'Safe\openssl_x509_read', + 'output_add_rewrite_var' => 'Safe\output_add_rewrite_var', + 'output_reset_rewrite_vars' => 'Safe\output_reset_rewrite_vars', + 'pack' => 'Safe\pack', + 'parse_ini_file' => 'Safe\parse_ini_file', + 'parse_ini_string' => 'Safe\parse_ini_string', + 'parse_url' => 'Safe\parse_url', + 'password_hash' => 'Safe\password_hash', + 'pcntl_exec' => 'Safe\pcntl_exec', + 'pcntl_getpriority' => 'Safe\pcntl_getpriority', + 'pcntl_setpriority' => 'Safe\pcntl_setpriority', + 'pcntl_signal_dispatch' => 'Safe\pcntl_signal_dispatch', + 'pcntl_sigprocmask' => 'Safe\pcntl_sigprocmask', + 'pcntl_strerror' => 'Safe\pcntl_strerror', + 'PDF_activate_item' => 'Safe\PDF_activate_item', + 'PDF_add_locallink' => 'Safe\PDF_add_locallink', + 'PDF_add_nameddest' => 'Safe\PDF_add_nameddest', + 'PDF_add_note' => 'Safe\PDF_add_note', + 'PDF_add_pdflink' => 'Safe\PDF_add_pdflink', + 'PDF_add_thumbnail' => 'Safe\PDF_add_thumbnail', + 'PDF_add_weblink' => 'Safe\PDF_add_weblink', + 'PDF_attach_file' => 'Safe\PDF_attach_file', + 'PDF_begin_layer' => 'Safe\PDF_begin_layer', + 'PDF_begin_page' => 'Safe\PDF_begin_page', + 'PDF_begin_page_ext' => 'Safe\PDF_begin_page_ext', + 'PDF_circle' => 'Safe\PDF_circle', + 'PDF_clip' => 'Safe\PDF_clip', + 'PDF_close' => 'Safe\PDF_close', + 'PDF_closepath' => 'Safe\PDF_closepath', + 'PDF_closepath_fill_stroke' => 'Safe\PDF_closepath_fill_stroke', + 'PDF_closepath_stroke' => 'Safe\PDF_closepath_stroke', + 'PDF_close_pdi' => 'Safe\PDF_close_pdi', + 'PDF_close_pdi_page' => 'Safe\PDF_close_pdi_page', + 'PDF_concat' => 'Safe\PDF_concat', + 'PDF_continue_text' => 'Safe\PDF_continue_text', + 'PDF_curveto' => 'Safe\PDF_curveto', + 'PDF_delete' => 'Safe\PDF_delete', + 'PDF_end_layer' => 'Safe\PDF_end_layer', + 'PDF_end_page' => 'Safe\PDF_end_page', + 'PDF_end_page_ext' => 'Safe\PDF_end_page_ext', + 'PDF_end_pattern' => 'Safe\PDF_end_pattern', + 'PDF_end_template' => 'Safe\PDF_end_template', + 'PDF_fill' => 'Safe\PDF_fill', + 'PDF_fill_stroke' => 'Safe\PDF_fill_stroke', + 'PDF_fit_image' => 'Safe\PDF_fit_image', + 'PDF_fit_pdi_page' => 'Safe\PDF_fit_pdi_page', + 'PDF_fit_textline' => 'Safe\PDF_fit_textline', + 'PDF_initgraphics' => 'Safe\PDF_initgraphics', + 'PDF_lineto' => 'Safe\PDF_lineto', + 'PDF_makespotcolor' => 'Safe\PDF_makespotcolor', + 'PDF_moveto' => 'Safe\PDF_moveto', + 'PDF_open_file' => 'Safe\PDF_open_file', + 'PDF_place_image' => 'Safe\PDF_place_image', + 'PDF_place_pdi_page' => 'Safe\PDF_place_pdi_page', + 'PDF_rect' => 'Safe\PDF_rect', + 'PDF_restore' => 'Safe\PDF_restore', + 'PDF_rotate' => 'Safe\PDF_rotate', + 'PDF_save' => 'Safe\PDF_save', + 'PDF_scale' => 'Safe\PDF_scale', + 'PDF_setcolor' => 'Safe\PDF_setcolor', + 'PDF_setdash' => 'Safe\PDF_setdash', + 'PDF_setdashpattern' => 'Safe\PDF_setdashpattern', + 'PDF_setflat' => 'Safe\PDF_setflat', + 'PDF_setfont' => 'Safe\PDF_setfont', + 'PDF_setgray' => 'Safe\PDF_setgray', + 'PDF_setgray_fill' => 'Safe\PDF_setgray_fill', + 'PDF_setgray_stroke' => 'Safe\PDF_setgray_stroke', + 'PDF_setlinejoin' => 'Safe\PDF_setlinejoin', + 'PDF_setlinewidth' => 'Safe\PDF_setlinewidth', + 'PDF_setmatrix' => 'Safe\PDF_setmatrix', + 'PDF_setmiterlimit' => 'Safe\PDF_setmiterlimit', + 'PDF_setrgbcolor' => 'Safe\PDF_setrgbcolor', + 'PDF_setrgbcolor_fill' => 'Safe\PDF_setrgbcolor_fill', + 'PDF_setrgbcolor_stroke' => 'Safe\PDF_setrgbcolor_stroke', + 'PDF_set_border_color' => 'Safe\PDF_set_border_color', + 'PDF_set_border_dash' => 'Safe\PDF_set_border_dash', + 'PDF_set_border_style' => 'Safe\PDF_set_border_style', + 'PDF_set_info' => 'Safe\PDF_set_info', + 'PDF_set_layer_dependency' => 'Safe\PDF_set_layer_dependency', + 'PDF_set_parameter' => 'Safe\PDF_set_parameter', + 'PDF_set_text_pos' => 'Safe\PDF_set_text_pos', + 'PDF_set_value' => 'Safe\PDF_set_value', + 'PDF_show' => 'Safe\PDF_show', + 'PDF_show_xy' => 'Safe\PDF_show_xy', + 'PDF_skew' => 'Safe\PDF_skew', + 'PDF_stroke' => 'Safe\PDF_stroke', + 'pg_cancel_query' => 'Safe\pg_cancel_query', + 'pg_client_encoding' => 'Safe\pg_client_encoding', + 'pg_close' => 'Safe\pg_close', + 'pg_connect' => 'Safe\pg_connect', + 'pg_connection_reset' => 'Safe\pg_connection_reset', + 'pg_convert' => 'Safe\pg_convert', + 'pg_copy_from' => 'Safe\pg_copy_from', + 'pg_copy_to' => 'Safe\pg_copy_to', + 'pg_dbname' => 'Safe\pg_dbname', + 'pg_delete' => 'Safe\pg_delete', + 'pg_end_copy' => 'Safe\pg_end_copy', + 'pg_execute' => 'Safe\pg_execute', + 'pg_field_name' => 'Safe\pg_field_name', + 'pg_field_table' => 'Safe\pg_field_table', + 'pg_field_type' => 'Safe\pg_field_type', + 'pg_flush' => 'Safe\pg_flush', + 'pg_free_result' => 'Safe\pg_free_result', + 'pg_host' => 'Safe\pg_host', + 'pg_insert' => 'Safe\pg_insert', + 'pg_last_error' => 'Safe\pg_last_error', + 'pg_last_notice' => 'Safe\pg_last_notice', + 'pg_last_oid' => 'Safe\pg_last_oid', + 'pg_lo_close' => 'Safe\pg_lo_close', + 'pg_lo_export' => 'Safe\pg_lo_export', + 'pg_lo_import' => 'Safe\pg_lo_import', + 'pg_lo_open' => 'Safe\pg_lo_open', + 'pg_lo_read' => 'Safe\pg_lo_read', + 'pg_lo_read_all' => 'Safe\pg_lo_read_all', + 'pg_lo_seek' => 'Safe\pg_lo_seek', + 'pg_lo_truncate' => 'Safe\pg_lo_truncate', + 'pg_lo_unlink' => 'Safe\pg_lo_unlink', + 'pg_lo_write' => 'Safe\pg_lo_write', + 'pg_meta_data' => 'Safe\pg_meta_data', + 'pg_options' => 'Safe\pg_options', + 'pg_parameter_status' => 'Safe\pg_parameter_status', + 'pg_pconnect' => 'Safe\pg_pconnect', + 'pg_ping' => 'Safe\pg_ping', + 'pg_port' => 'Safe\pg_port', + 'pg_prepare' => 'Safe\pg_prepare', + 'pg_put_line' => 'Safe\pg_put_line', + 'pg_query' => 'Safe\pg_query', + 'pg_query_params' => 'Safe\pg_query_params', + 'pg_result_error_field' => 'Safe\pg_result_error_field', + 'pg_result_seek' => 'Safe\pg_result_seek', + 'pg_select' => 'Safe\pg_select', + 'pg_send_execute' => 'Safe\pg_send_execute', + 'pg_send_prepare' => 'Safe\pg_send_prepare', + 'pg_send_query' => 'Safe\pg_send_query', + 'pg_send_query_params' => 'Safe\pg_send_query_params', + 'pg_socket' => 'Safe\pg_socket', + 'pg_trace' => 'Safe\pg_trace', + 'pg_tty' => 'Safe\pg_tty', + 'pg_update' => 'Safe\pg_update', + 'pg_version' => 'Safe\pg_version', + 'phpcredits' => 'Safe\phpcredits', + 'phpinfo' => 'Safe\phpinfo', + 'png2wbmp' => 'Safe\png2wbmp', + 'posix_access' => 'Safe\posix_access', + 'posix_getgrnam' => 'Safe\posix_getgrnam', + 'posix_getpgid' => 'Safe\posix_getpgid', + 'posix_initgroups' => 'Safe\posix_initgroups', + 'posix_kill' => 'Safe\posix_kill', + 'posix_mkfifo' => 'Safe\posix_mkfifo', + 'posix_mknod' => 'Safe\posix_mknod', + 'posix_setegid' => 'Safe\posix_setegid', + 'posix_seteuid' => 'Safe\posix_seteuid', + 'posix_setgid' => 'Safe\posix_setgid', + 'posix_setpgid' => 'Safe\posix_setpgid', + 'posix_setrlimit' => 'Safe\posix_setrlimit', + 'posix_setuid' => 'Safe\posix_setuid', + 'preg_match' => 'Safe\preg_match', + 'preg_match_all' => 'Safe\preg_match_all', + 'preg_replace' => 'Safe\preg_replace', + 'preg_split' => 'Safe\preg_split', + 'proc_get_status' => 'Safe\proc_get_status', + 'proc_nice' => 'Safe\proc_nice', + 'pspell_add_to_personal' => 'Safe\pspell_add_to_personal', + 'pspell_add_to_session' => 'Safe\pspell_add_to_session', + 'pspell_clear_session' => 'Safe\pspell_clear_session', + 'pspell_config_create' => 'Safe\pspell_config_create', + 'pspell_config_data_dir' => 'Safe\pspell_config_data_dir', + 'pspell_config_dict_dir' => 'Safe\pspell_config_dict_dir', + 'pspell_config_ignore' => 'Safe\pspell_config_ignore', + 'pspell_config_mode' => 'Safe\pspell_config_mode', + 'pspell_config_personal' => 'Safe\pspell_config_personal', + 'pspell_config_repl' => 'Safe\pspell_config_repl', + 'pspell_config_runtogether' => 'Safe\pspell_config_runtogether', + 'pspell_config_save_repl' => 'Safe\pspell_config_save_repl', + 'pspell_new' => 'Safe\pspell_new', + 'pspell_new_config' => 'Safe\pspell_new_config', + 'pspell_save_wordlist' => 'Safe\pspell_save_wordlist', + 'pspell_store_replacement' => 'Safe\pspell_store_replacement', + 'ps_add_launchlink' => 'Safe\ps_add_launchlink', + 'ps_add_locallink' => 'Safe\ps_add_locallink', + 'ps_add_note' => 'Safe\ps_add_note', + 'ps_add_pdflink' => 'Safe\ps_add_pdflink', + 'ps_add_weblink' => 'Safe\ps_add_weblink', + 'ps_arc' => 'Safe\ps_arc', + 'ps_arcn' => 'Safe\ps_arcn', + 'ps_begin_page' => 'Safe\ps_begin_page', + 'ps_begin_pattern' => 'Safe\ps_begin_pattern', + 'ps_begin_template' => 'Safe\ps_begin_template', + 'ps_circle' => 'Safe\ps_circle', + 'ps_clip' => 'Safe\ps_clip', + 'ps_close' => 'Safe\ps_close', + 'ps_closepath' => 'Safe\ps_closepath', + 'ps_closepath_stroke' => 'Safe\ps_closepath_stroke', + 'ps_close_image' => 'Safe\ps_close_image', + 'ps_continue_text' => 'Safe\ps_continue_text', + 'ps_curveto' => 'Safe\ps_curveto', + 'ps_delete' => 'Safe\ps_delete', + 'ps_end_page' => 'Safe\ps_end_page', + 'ps_end_pattern' => 'Safe\ps_end_pattern', + 'ps_end_template' => 'Safe\ps_end_template', + 'ps_fill' => 'Safe\ps_fill', + 'ps_fill_stroke' => 'Safe\ps_fill_stroke', + 'ps_get_parameter' => 'Safe\ps_get_parameter', + 'ps_hyphenate' => 'Safe\ps_hyphenate', + 'ps_include_file' => 'Safe\ps_include_file', + 'ps_lineto' => 'Safe\ps_lineto', + 'ps_moveto' => 'Safe\ps_moveto', + 'ps_new' => 'Safe\ps_new', + 'ps_open_file' => 'Safe\ps_open_file', + 'ps_place_image' => 'Safe\ps_place_image', + 'ps_rect' => 'Safe\ps_rect', + 'ps_restore' => 'Safe\ps_restore', + 'ps_rotate' => 'Safe\ps_rotate', + 'ps_save' => 'Safe\ps_save', + 'ps_scale' => 'Safe\ps_scale', + 'ps_setcolor' => 'Safe\ps_setcolor', + 'ps_setdash' => 'Safe\ps_setdash', + 'ps_setflat' => 'Safe\ps_setflat', + 'ps_setfont' => 'Safe\ps_setfont', + 'ps_setgray' => 'Safe\ps_setgray', + 'ps_setlinecap' => 'Safe\ps_setlinecap', + 'ps_setlinejoin' => 'Safe\ps_setlinejoin', + 'ps_setlinewidth' => 'Safe\ps_setlinewidth', + 'ps_setmiterlimit' => 'Safe\ps_setmiterlimit', + 'ps_setoverprintmode' => 'Safe\ps_setoverprintmode', + 'ps_setpolydash' => 'Safe\ps_setpolydash', + 'ps_set_border_color' => 'Safe\ps_set_border_color', + 'ps_set_border_dash' => 'Safe\ps_set_border_dash', + 'ps_set_border_style' => 'Safe\ps_set_border_style', + 'ps_set_info' => 'Safe\ps_set_info', + 'ps_set_parameter' => 'Safe\ps_set_parameter', + 'ps_set_text_pos' => 'Safe\ps_set_text_pos', + 'ps_set_value' => 'Safe\ps_set_value', + 'ps_shading' => 'Safe\ps_shading', + 'ps_shading_pattern' => 'Safe\ps_shading_pattern', + 'ps_shfill' => 'Safe\ps_shfill', + 'ps_show' => 'Safe\ps_show', + 'ps_show2' => 'Safe\ps_show2', + 'ps_show_xy' => 'Safe\ps_show_xy', + 'ps_show_xy2' => 'Safe\ps_show_xy2', + 'ps_stroke' => 'Safe\ps_stroke', + 'ps_symbol' => 'Safe\ps_symbol', + 'ps_translate' => 'Safe\ps_translate', + 'putenv' => 'Safe\putenv', + 'readfile' => 'Safe\readfile', + 'readgzfile' => 'Safe\readgzfile', + 'readline_add_history' => 'Safe\readline_add_history', + 'readline_callback_handler_install' => 'Safe\readline_callback_handler_install', + 'readline_clear_history' => 'Safe\readline_clear_history', + 'readline_completion_function' => 'Safe\readline_completion_function', + 'readline_read_history' => 'Safe\readline_read_history', + 'readline_write_history' => 'Safe\readline_write_history', + 'readlink' => 'Safe\readlink', + 'realpath' => 'Safe\realpath', + 'register_tick_function' => 'Safe\register_tick_function', + 'rename' => 'Safe\rename', + 'rewind' => 'Safe\rewind', + 'rewinddir' => 'Safe\rewinddir', + 'rmdir' => 'Safe\rmdir', + 'rpmaddtag' => 'Safe\rpmaddtag', + 'rrd_create' => 'Safe\rrd_create', + 'rsort' => 'Safe\rsort', + 'sapi_windows_cp_conv' => 'Safe\sapi_windows_cp_conv', + 'sapi_windows_cp_set' => 'Safe\sapi_windows_cp_set', + 'sapi_windows_generate_ctrl_event' => 'Safe\sapi_windows_generate_ctrl_event', + 'sapi_windows_vt100_support' => 'Safe\sapi_windows_vt100_support', + 'scandir' => 'Safe\scandir', + 'sem_acquire' => 'Safe\sem_acquire', + 'sem_get' => 'Safe\sem_get', + 'sem_release' => 'Safe\sem_release', + 'sem_remove' => 'Safe\sem_remove', + 'session_abort' => 'Safe\session_abort', + 'session_decode' => 'Safe\session_decode', + 'session_destroy' => 'Safe\session_destroy', + 'session_regenerate_id' => 'Safe\session_regenerate_id', + 'session_reset' => 'Safe\session_reset', + 'session_unset' => 'Safe\session_unset', + 'session_write_close' => 'Safe\session_write_close', + 'settype' => 'Safe\settype', + 'set_include_path' => 'Safe\set_include_path', + 'set_time_limit' => 'Safe\set_time_limit', + 'sha1_file' => 'Safe\sha1_file', + 'shmop_delete' => 'Safe\shmop_delete', + 'shmop_read' => 'Safe\shmop_read', + 'shmop_write' => 'Safe\shmop_write', + 'shm_put_var' => 'Safe\shm_put_var', + 'shm_remove' => 'Safe\shm_remove', + 'shm_remove_var' => 'Safe\shm_remove_var', + 'shuffle' => 'Safe\shuffle', + 'simplexml_import_dom' => 'Safe\simplexml_import_dom', + 'simplexml_load_file' => 'Safe\simplexml_load_file', + 'simplexml_load_string' => 'Safe\simplexml_load_string', + 'sleep' => 'Safe\sleep', + 'socket_accept' => 'Safe\socket_accept', + 'socket_addrinfo_bind' => 'Safe\socket_addrinfo_bind', + 'socket_addrinfo_connect' => 'Safe\socket_addrinfo_connect', + 'socket_bind' => 'Safe\socket_bind', + 'socket_connect' => 'Safe\socket_connect', + 'socket_create' => 'Safe\socket_create', + 'socket_create_listen' => 'Safe\socket_create_listen', + 'socket_create_pair' => 'Safe\socket_create_pair', + 'socket_export_stream' => 'Safe\socket_export_stream', + 'socket_getpeername' => 'Safe\socket_getpeername', + 'socket_getsockname' => 'Safe\socket_getsockname', + 'socket_get_option' => 'Safe\socket_get_option', + 'socket_import_stream' => 'Safe\socket_import_stream', + 'socket_listen' => 'Safe\socket_listen', + 'socket_read' => 'Safe\socket_read', + 'socket_send' => 'Safe\socket_send', + 'socket_sendmsg' => 'Safe\socket_sendmsg', + 'socket_sendto' => 'Safe\socket_sendto', + 'socket_set_block' => 'Safe\socket_set_block', + 'socket_set_nonblock' => 'Safe\socket_set_nonblock', + 'socket_set_option' => 'Safe\socket_set_option', + 'socket_shutdown' => 'Safe\socket_shutdown', + 'socket_write' => 'Safe\socket_write', + 'socket_wsaprotocol_info_export' => 'Safe\socket_wsaprotocol_info_export', + 'socket_wsaprotocol_info_import' => 'Safe\socket_wsaprotocol_info_import', + 'socket_wsaprotocol_info_release' => 'Safe\socket_wsaprotocol_info_release', + 'sodium_crypto_pwhash' => 'Safe\sodium_crypto_pwhash', + 'sodium_crypto_pwhash_str' => 'Safe\sodium_crypto_pwhash_str', + 'solr_get_version' => 'Safe\solr_get_version', + 'sort' => 'Safe\sort', + 'soundex' => 'Safe\soundex', + 'spl_autoload_register' => 'Safe\spl_autoload_register', + 'spl_autoload_unregister' => 'Safe\spl_autoload_unregister', + 'sprintf' => 'Safe\sprintf', + 'sqlsrv_begin_transaction' => 'Safe\sqlsrv_begin_transaction', + 'sqlsrv_cancel' => 'Safe\sqlsrv_cancel', + 'sqlsrv_client_info' => 'Safe\sqlsrv_client_info', + 'sqlsrv_close' => 'Safe\sqlsrv_close', + 'sqlsrv_commit' => 'Safe\sqlsrv_commit', + 'sqlsrv_configure' => 'Safe\sqlsrv_configure', + 'sqlsrv_execute' => 'Safe\sqlsrv_execute', + 'sqlsrv_free_stmt' => 'Safe\sqlsrv_free_stmt', + 'sqlsrv_get_field' => 'Safe\sqlsrv_get_field', + 'sqlsrv_next_result' => 'Safe\sqlsrv_next_result', + 'sqlsrv_num_fields' => 'Safe\sqlsrv_num_fields', + 'sqlsrv_num_rows' => 'Safe\sqlsrv_num_rows', + 'sqlsrv_prepare' => 'Safe\sqlsrv_prepare', + 'sqlsrv_query' => 'Safe\sqlsrv_query', + 'sqlsrv_rollback' => 'Safe\sqlsrv_rollback', + 'ssdeep_fuzzy_compare' => 'Safe\ssdeep_fuzzy_compare', + 'ssdeep_fuzzy_hash' => 'Safe\ssdeep_fuzzy_hash', + 'ssdeep_fuzzy_hash_filename' => 'Safe\ssdeep_fuzzy_hash_filename', + 'ssh2_auth_agent' => 'Safe\ssh2_auth_agent', + 'ssh2_auth_hostbased_file' => 'Safe\ssh2_auth_hostbased_file', + 'ssh2_auth_password' => 'Safe\ssh2_auth_password', + 'ssh2_auth_pubkey_file' => 'Safe\ssh2_auth_pubkey_file', + 'ssh2_connect' => 'Safe\ssh2_connect', + 'ssh2_disconnect' => 'Safe\ssh2_disconnect', + 'ssh2_exec' => 'Safe\ssh2_exec', + 'ssh2_publickey_add' => 'Safe\ssh2_publickey_add', + 'ssh2_publickey_init' => 'Safe\ssh2_publickey_init', + 'ssh2_publickey_remove' => 'Safe\ssh2_publickey_remove', + 'ssh2_scp_recv' => 'Safe\ssh2_scp_recv', + 'ssh2_scp_send' => 'Safe\ssh2_scp_send', + 'ssh2_sftp' => 'Safe\ssh2_sftp', + 'ssh2_sftp_chmod' => 'Safe\ssh2_sftp_chmod', + 'ssh2_sftp_mkdir' => 'Safe\ssh2_sftp_mkdir', + 'ssh2_sftp_rename' => 'Safe\ssh2_sftp_rename', + 'ssh2_sftp_rmdir' => 'Safe\ssh2_sftp_rmdir', + 'ssh2_sftp_symlink' => 'Safe\ssh2_sftp_symlink', + 'ssh2_sftp_unlink' => 'Safe\ssh2_sftp_unlink', + 'stream_context_set_params' => 'Safe\stream_context_set_params', + 'stream_copy_to_stream' => 'Safe\stream_copy_to_stream', + 'stream_filter_append' => 'Safe\stream_filter_append', + 'stream_filter_prepend' => 'Safe\stream_filter_prepend', + 'stream_filter_register' => 'Safe\stream_filter_register', + 'stream_filter_remove' => 'Safe\stream_filter_remove', + 'stream_get_contents' => 'Safe\stream_get_contents', + 'stream_isatty' => 'Safe\stream_isatty', + 'stream_resolve_include_path' => 'Safe\stream_resolve_include_path', + 'stream_set_blocking' => 'Safe\stream_set_blocking', + 'stream_set_timeout' => 'Safe\stream_set_timeout', + 'stream_socket_accept' => 'Safe\stream_socket_accept', + 'stream_socket_client' => 'Safe\stream_socket_client', + 'stream_socket_pair' => 'Safe\stream_socket_pair', + 'stream_socket_server' => 'Safe\stream_socket_server', + 'stream_socket_shutdown' => 'Safe\stream_socket_shutdown', + 'stream_supports_lock' => 'Safe\stream_supports_lock', + 'stream_wrapper_register' => 'Safe\stream_wrapper_register', + 'stream_wrapper_restore' => 'Safe\stream_wrapper_restore', + 'stream_wrapper_unregister' => 'Safe\stream_wrapper_unregister', + 'strptime' => 'Safe\strptime', + 'strtotime' => 'Safe\strtotime', + 'substr' => 'Safe\substr', + 'swoole_async_write' => 'Safe\swoole_async_write', + 'swoole_async_writefile' => 'Safe\swoole_async_writefile', + 'swoole_event_defer' => 'Safe\swoole_event_defer', + 'swoole_event_del' => 'Safe\swoole_event_del', + 'swoole_event_write' => 'Safe\swoole_event_write', + 'symlink' => 'Safe\symlink', + 'syslog' => 'Safe\syslog', + 'system' => 'Safe\system', + 'tempnam' => 'Safe\tempnam', + 'timezone_name_from_abbr' => 'Safe\timezone_name_from_abbr', + 'time_nanosleep' => 'Safe\time_nanosleep', + 'time_sleep_until' => 'Safe\time_sleep_until', + 'tmpfile' => 'Safe\tmpfile', + 'touch' => 'Safe\touch', + 'uasort' => 'Safe\uasort', + 'uksort' => 'Safe\uksort', + 'unlink' => 'Safe\unlink', + 'unpack' => 'Safe\unpack', + 'uopz_extend' => 'Safe\uopz_extend', + 'uopz_implement' => 'Safe\uopz_implement', + 'usort' => 'Safe\usort', + 'virtual' => 'Safe\virtual', + 'vsprintf' => 'Safe\vsprintf', + 'xdiff_file_bdiff' => 'Safe\xdiff_file_bdiff', + 'xdiff_file_bpatch' => 'Safe\xdiff_file_bpatch', + 'xdiff_file_diff' => 'Safe\xdiff_file_diff', + 'xdiff_file_diff_binary' => 'Safe\xdiff_file_diff_binary', + 'xdiff_file_patch_binary' => 'Safe\xdiff_file_patch_binary', + 'xdiff_file_rabdiff' => 'Safe\xdiff_file_rabdiff', + 'xdiff_string_bpatch' => 'Safe\xdiff_string_bpatch', + 'xdiff_string_patch' => 'Safe\xdiff_string_patch', + 'xdiff_string_patch_binary' => 'Safe\xdiff_string_patch_binary', + 'xmlrpc_set_type' => 'Safe\xmlrpc_set_type', + 'xml_parser_create' => 'Safe\xml_parser_create', + 'xml_parser_create_ns' => 'Safe\xml_parser_create_ns', + 'xml_set_object' => 'Safe\xml_set_object', + 'yaml_parse' => 'Safe\yaml_parse', + 'yaml_parse_file' => 'Safe\yaml_parse_file', + 'yaml_parse_url' => 'Safe\yaml_parse_url', + 'yaz_ccl_parse' => 'Safe\yaz_ccl_parse', + 'yaz_close' => 'Safe\yaz_close', + 'yaz_connect' => 'Safe\yaz_connect', + 'yaz_database' => 'Safe\yaz_database', + 'yaz_element' => 'Safe\yaz_element', + 'yaz_present' => 'Safe\yaz_present', + 'yaz_search' => 'Safe\yaz_search', + 'yaz_wait' => 'Safe\yaz_wait', + 'zip_entry_close' => 'Safe\zip_entry_close', + 'zip_entry_open' => 'Safe\zip_entry_open', + 'zip_entry_read' => 'Safe\zip_entry_read', + 'zlib_decode' => 'Safe\zlib_decode', +]]]); +}; diff --git a/vendor/webonyx/graphql-php/.coveralls.yml b/vendor/webonyx/graphql-php/.coveralls.yml new file mode 100644 index 0000000..da22584 --- /dev/null +++ b/vendor/webonyx/graphql-php/.coveralls.yml @@ -0,0 +1,2 @@ +coverage_clover: /tmp/coverage/*.xml +json_path: /tmp/coverage/coverage.json diff --git a/vendor/webonyx/graphql-php/.github/FUNDING.yml b/vendor/webonyx/graphql-php/.github/FUNDING.yml new file mode 100644 index 0000000..0306338 --- /dev/null +++ b/vendor/webonyx/graphql-php/.github/FUNDING.yml @@ -0,0 +1,2 @@ +# These are supported funding model platforms +open_collective: webonyx-graphql-php diff --git a/vendor/webonyx/graphql-php/.github/workflows/ci-build.yml b/vendor/webonyx/graphql-php/.github/workflows/ci-build.yml new file mode 100644 index 0000000..39a4faf --- /dev/null +++ b/vendor/webonyx/graphql-php/.github/workflows/ci-build.yml @@ -0,0 +1,162 @@ +name: CI + +on: + push: + branches: + tags: + pull_request: + +jobs: + build: + runs-on: ubuntu-18.04 + strategy: + matrix: + php: [7.1, 7.2, 7.3, 7.4, 8.0] + env: [ + 'EXECUTOR= DEPENDENCIES=--prefer-lowest', + 'EXECUTOR=coroutine DEPENDENCIES=--prefer-lowest', + 'EXECUTOR=', + 'EXECUTOR=coroutine', + ] + name: PHP ${{ matrix.php }} Test ${{ matrix.env }} + + steps: + - uses: actions/checkout@v2 + + - name: Install PHP + uses: shivammathur/setup-php@2.9.0 + with: + php-version: ${{ matrix.php }} + coverage: none + extensions: json, mbstring + - name: Get Composer Cache Directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache dependencies + uses: actions/cache@v1 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Remove dependencies not used in this job for PHP 8 compatibility + run: | + composer remove --dev --no-update phpbench/phpbench + composer remove --dev --no-update phpstan/phpstan + composer remove --dev --no-update phpstan/phpstan-phpunit + composer remove --dev --no-update phpstan/phpstan-strict-rules + composer remove --dev --no-update doctrine/coding-standard + + - name: Install Dependencies + run: composer update ${DEPENDENCIES} + + - name: Run unit tests + run: | + export $ENV + ./vendor/bin/phpunit --group default,ReactPromise + env: + ENV: ${{ matrix.env}} + + coding-standard: + runs-on: ubuntu-18.04 + name: Coding Standard + + steps: + - uses: actions/checkout@v2 + + - name: Install PHP + uses: shivammathur/setup-php@2.9.0 + with: + php-version: 7.1 + coverage: none + extensions: json, mbstring + + - name: Get Composer Cache Directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache dependencies + uses: actions/cache@v1 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install Dependencies + run: composer install ${DEPENDENCIES} + + - name: Coding Standard + run: composer lint + + phpstan: + runs-on: ubuntu-18.04 + name: PHPStan + + steps: + - uses: actions/checkout@v2 + + - name: Install PHP + uses: shivammathur/setup-php@2.9.0 + with: + php-version: 7.1 + coverage: none + extensions: json, mbstring + + - name: Get Composer Cache Directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache dependencies + uses: actions/cache@v1 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install Dependencies + run: composer install ${DEPENDENCIES} + + - name: PHPStan + run: composer stan + + coverage: + runs-on: ubuntu-18.04 + name: Code Coverage + + steps: + - uses: actions/checkout@v2 + with: + ref: ${{ github.ref }} + + - name: Install PHP + uses: shivammathur/setup-php@2.9.0 + with: + php-version: 7.2 + coverage: pcov + extensions: json, mbstring + + - name: Get Composer Cache Directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache dependencies + uses: actions/cache@v1 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install Dependencies + run: composer install ${DEPENDENCIES} + + - name: Code coverage + run: | + ./vendor/bin/phpunit --coverage-clover /tmp/coverage/clover_executor.xml + EXECUTOR=coroutine ./vendor/bin/phpunit --coverage-clover /tmp/coverage/clover_executor-coroutine.xml + + - name: Report to Coveralls + env: + COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + COVERALLS_RUN_LOCALLY: 1 + run: vendor/bin/php-coveralls --verbose diff --git a/vendor/webonyx/graphql-php/CHANGELOG.md b/vendor/webonyx/graphql-php/CHANGELOG.md index dcfdd39..fabb7d5 100644 --- a/vendor/webonyx/graphql-php/CHANGELOG.md +++ b/vendor/webonyx/graphql-php/CHANGELOG.md @@ -1,8 +1,178 @@ # Changelog -### v0.13.8 + +#### Unreleased + +#### 14.9.0 + +Feat: +- Add support for type config decorator in `SchemaExtender` + +#### 14.8.0 + +Feat: +- Implement `GraphQL\Utils\AST::getOperationAST()` + +#### 14.7.0 + +Feat: +- Allow providing field definitions as a callable and resolve them lazily + +#### 14.6.4 + +Fix: +- Avoid crashing in `QueryPlan` when `__typename` is used in the query + +#### 14.6.3 + +Refactoring: +- Improve performance of subtype checks + +#### 14.6.2 + +Fix: +- Fix overly eager validation of repeatable directive usage + +#### 14.6.1 + +Fix: +- Add fallback for `directive.isRepeatable` in `BuildClientSchema` + +#### 14.6.0 + +Feat: +- Open ReferenceExecutor for extending + +#### 14.5.1 + +Fix: +- Fix Input Object field shortcut definition with callable (#773) + +#### 14.5.0 + +Feat: +- Implement support for interfaces implementing interfaces (#740), huge kudos to @Kingdutch + +Deprecates: +- Constant `BreakingChangeFinder::BREAKING_CHANGE_INTERFACE_REMOVED_FROM_OBJECT`. + Use `BreakingChangeFinder::BREAKING_CHANGE_IMPLEMENTED_INTERFACE_REMOVED` instead. + Constant value also changed from `INTERFACE_REMOVED_FROM_OBJECT` to `IMPLEMENTED_INTERFACE_REMOVED`. + +- Constant `BreakingChangeFinder::DANGEROUS_CHANGE_INTERFACE_ADDED_TO_OBJECT` + Use `DANGEROUS_CHANGE_IMPLEMENTED_INTERFACE_ADDED` instead. + Constant value also changed from `INTERFACE_ADDED_TO_OBJECT` to `IMPLEMENTED_INTERFACE_ADDED`. + +Refactoring: +- Reify AST node types and remove unneeded nullability (#751) + +#### 14.4.1 + +Fix: +- Allow pushing nodes to `NodeList` via `[]=` (#767) +- Fix signature of `Error\FormattedError::prepareFormatter()` to address PHP8 deprecation (#742) +- Do not add errors key to result when errors discarded by custom error handler (#766) + +#### 14.4.0 + +Fix: +- Fixed `SchemaPrinter` so that it uses late static bindings when extended +- Parse `DirectiveDefinitionNode->locations` as `NodeList` (fixes AST::fromArray conversion) (#723) +- Parse `Parser::implementsInterfaces` as `NodeList` (fixes AST::fromArray conversion) +- Fix signature of `Parser::unionMemberTypes` to match actual `NodeList` + +#### v14.3.0 + +Feat: +- Allow `typeLoader` to return a type thunk (#687) + +Fix: +- Read getParsedBody() instead of getBody() when Request is ServerRequest (#715) +- Fix default get/set behavior on InputObjectField and FieldDefinition (#716) + +#### v14.2.0 + +Deprecates: +- Public access to `FieldDefinition::$type` property (#702) + +Fixes: +- Fix validation for input field definition directives (#714) + +#### v14.1.1 + +Fixes: +- Handle nullable `DirectiveNode#astNode` in `SchemaValidationContext` (#708) + +#### v14.1.0 + +New: +- Add partial parse functions for const variants (#693) + +Fixes: +- Differentiate between client-safe and non-client-safe errors in scalar validation (#706) +- Proper type hints for `IntValueNode` (#691) + +Refactoring: +- Ensure NamedTypeNode::$name is always a NameNode (#695) +- Visitor: simplify getVisitFn (#694) +- Replace function calls with type casts (#692) +- Fix "only booleans are allowed" errors (#659) + + +#### v14.0.2 + +- Optimize lazy types (#684) + +#### v14.0.1 + +Bug fixes: +- Fix for: Argument defaults with integer/float values crashes introspection query (#679) +- Fix for "Invalid AST Node: false" error (#685) +- Fix double Error wrapping when parsing variables (#688) + +Refactoring: +- Do not use call_user_func or call_user_func_array (#676) +- Codestyle and static analysis improvements (#648, #690) + +## v14.0.0 + +This release brings several breaking changes. Please refer to [UPGRADE](UPGRADE.md) document for details. + +- **BREAKING/BUGFIX:** Strict coercion of scalar types (#278) +- **BREAKING/BUGFIX:** Spec-compliance: Fixed ambiguity with null variable values and default values (#274) +- **BREAKING:** Removed deprecated directive introspection fields (onOperation, onFragment, onField) +- **BREAKING:** `GraphQL\Deferred` now extends `GraphQL\Executor\Promise\Adapter\SyncPromise` +- **BREAKING:** renamed several types of dangerous/breaking changes (returned by `BreakingChangesFinder`) +- **BREAKING:** Renamed `GraphQL\Error\Debug` to `GraphQL\Error\DebugFlag`. +- **BREAKING:** Debug flags in `GraphQL\Executor\ExecutionResult`, `GraphQL\Error\FormattedError` and `GraphQL\Server\ServerConfig` do not accept `boolean` value anymore but `int` only. +- **BREAKING:** `$positions` in `GraphQL\Error\Error` constructor are not nullable anymore. Same can be expressed by passing an empty array. + +Notable features and improvements: + +- Compliant with the GraphQL specification [June 2018 Edition](https://spec.graphql.org/June2018/) +- Support repeatable directives (#643) +- Perf: support lazy type definitions (#557) +- Simplified Deferred implementation (now allows chaining like promises, #573) +- Support SDL Validation and other schema validation improvements (e.g. #492) +- Added promise adapter for [Amp](https://amphp.org/) (#551) +- Query plan utility improvements (#513, #632) + +Other noteworthy changes: +- Allow retrieving query complexity once query has been completed (#316) +- Allow input types to be passed in from variables using \stdClass instead of associative arrays (#535) +- Support UTF-16 surrogate pairs within string literals (#554, #556) +- Having an empty string in `deprecationReason` will now print the `@deprecated` directive (only a `null` `deprecationReason` won't print the `@deprecated` directive). +- Deprecated Experimental executor (#397) + +Also some bugs fixed, heavily invested in [PHPStan](https://github.com/phpstan/phpstan) for static analysis. + +Special thanks to @simPod, @spawnia and @shmax for their major contributions! + +#### v0.13.9 +- Fix double Error wrapping when parsing variables (#689) + +#### v0.13.8 - Don't call global field resolver on introspection fields (#481) -### v0.13.7 +#### v0.13.7 - Added retrieving query complexity once query has been completed (#316) - Allow input types to be passed in from variables using \stdClass instead of associative arrays (#535) diff --git a/vendor/webonyx/graphql-php/README.md b/vendor/webonyx/graphql-php/README.md index 2cf46ba..b7702cc 100644 --- a/vendor/webonyx/graphql-php/README.md +++ b/vendor/webonyx/graphql-php/README.md @@ -1,6 +1,6 @@ # graphql-php -[![Build Status](https://travis-ci.org/webonyx/graphql-php.svg?branch=master)](https://travis-ci.org/webonyx/graphql-php) -[![Code Coverage](https://scrutinizer-ci.com/g/webonyx/graphql-php/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/webonyx/graphql-php) +![CI](https://github.com/webonyx/graphql-php/workflows/CI/badge.svg) +[![Coverage Status](https://coveralls.io/repos/github/webonyx/graphql-php/badge.svg?branch=master)](https://coveralls.io/github/webonyx/graphql-php?branch=master) [![Latest Stable Version](https://poser.pugx.org/webonyx/graphql-php/version)](https://packagist.org/packages/webonyx/graphql-php) [![License](https://poser.pugx.org/webonyx/graphql-php/license)](https://packagist.org/packages/webonyx/graphql-php) @@ -17,12 +17,11 @@ composer require webonyx/graphql-php Full documentation is available on the [Documentation site](https://webonyx.github.io/graphql-php/) as well as in the [docs](docs/) folder of the distribution. -If you don't know what GraphQL is, visit this [official website](http://graphql.org) -by the Facebook engineering team. +If you don't know what GraphQL is, visit the [official website](http://graphql.org) first. ## Examples -There are several ready examples in the [examples](examples/) folder of the distribution with specific -README file per example. +There are several ready examples in the [examples](examples) folder of the distribution, +with a specific README file per example. ## Contributors @@ -49,4 +48,4 @@ Support this project by becoming a sponsor. Your logo will show up here with a l ## License -See [LICENCE](LICENSE). +See [LICENSE](LICENSE). diff --git a/vendor/webonyx/graphql-php/UPGRADE.md b/vendor/webonyx/graphql-php/UPGRADE.md index a9d7256..23813e6 100644 --- a/vendor/webonyx/graphql-php/UPGRADE.md +++ b/vendor/webonyx/graphql-php/UPGRADE.md @@ -1,3 +1,207 @@ +## v0.13.x > v14.x.x + +### BREAKING: Strict coercion of scalar types (#278) + +**Impact: Major** + +This change may break API clients if they were sending loose variable values. + +
+ See Examples + +Consider the following query: + +```graphql +query($intQueryVariable: Int) { + test(intInput: $intQueryVariable) +} +``` + +What happens if we pass non-integer values as `$intQueryVariable`: +``` +[true, false, 1, 0, 0.0, 'true', 'false', '1', '0', '0.0', [], [0,1]] +``` + +#### Integer coercion, changed behavior: + +``` +bool(true): + 0.13.x: coerced to int(1) + 14.x.x: Error: Variable "$queryVariable" got invalid value true; Expected type Int; Int cannot represent non-integer value: true + +bool(false): + 0.13.x: coerced to int(0) + 14.x.x: Error: Variable "$queryVariable" got invalid value false; Expected type Int; Int cannot represent non-integer value: false + +string(1) "1" + 0.13.x: was coerced to int(1) + 14.x.x: Error: Variable "$queryVariable" got invalid value "1"; Expected type Int; Int cannot represent non-integer value: 1 + +string(1) "0" + 0.13.x: was coerced to int(0) + 14.x.x: Error: Variable "$queryVariable" got invalid value "0"; Expected type Int; Int cannot represent non-integer value: 0 + +string(3) "0.0" + 0.13.x: was coerced to int(0) + 14.x.x: Error: Variable "$queryVariable" got invalid value "0.0"; Expected type Int; Int cannot represent non-integer value: 0.0 +``` + +Did not change: +``` +int(1): coerced to int(1) +int(0) was coerced to int(0) +float(0) was coerced to int(0) + +string(4) "true": + Error: Variable "$queryVariable" got invalid value "true"; Expected type Int; Int cannot represent non 32-bit signed integer value: true + +string(5) "false": + Error: Variable "$queryVariable" got invalid value "false"; Expected type Int; Int cannot represent non 32-bit signed integer value: false + +array(0) {} + Error: Variable "$queryVariable" got invalid value []; Expected type Int; Int cannot represent non 32-bit signed integer value: [] + +array(2) { [0]=> int(0) [1]=> int(1) } + Error: Variable "$queryVariable" got invalid value [0,1]; Expected type Int; Int cannot represent non 32-bit signed integer value: [0,1] +``` + +#### Float coercion, changed behavior: +```graphql +query($queryVariable: Float) { + test(floatInput: $queryVariable) +} +``` + +``` +bool(true) + 0.13.x: was coerced to float(1) + 14.x.x: Error: Variable "$queryVariable" got invalid value true; Expected type Float; Float cannot represent non numeric value: true + +bool(false) + 0.13.x: was coerced to float(0) + 14.x.x: Error: Variable "$queryVariable" got invalid value false; Expected type Float; Float cannot represent non numeric value: false + +string(1) "1" + 0.13.x: was coerced to float(1) + 14.x.x: Error: Variable "$queryVariable" got invalid value "1"; Expected type Float; Float cannot represent non numeric value: 1 + +string(1) "0" + 0.13.x: was coerced to float(0) + 14.x.x: Error: Variable "$queryVariable" got invalid value "0"; Expected type Float; Float cannot represent non numeric value: 0 + +string(3) "0.0" + 0.13.x: was coerced to float(0) + 14.x.x: Error: Variable "$queryVariable" got invalid value "0.0"; Expected type Float; Float cannot represent non numeric value: 0.0 +``` + +#### String coercion, changed behavior: +```graphql +query($queryVariable: String) { + test(stringInput: $queryVariable) +} +``` + +``` +bool(true) + 0.13.x: was coerced to string(1) "1" + 14.x.x: Error: Variable "$queryVariable" got invalid value true; Expected type String; String cannot represent a non string value: true + +bool(false) + 0.13.x: was coerced to string(0) "" + 14.x.x: Error: Variable "$queryVariable" got invalid value false; Expected type String; String cannot represent a non string value: false + +int(1) + 0.13.x: was coerced to string(1) "1" + 14.x.x: Error: Variable "$queryVariable" got invalid value 1; Expected type String; String cannot represent a non string value: 1 + +int(0) + 0.13.x: was coerced to string(1) "0" + 14.x.x: Error: Variable "$queryVariable" got invalid value 0; Expected type String; String cannot represent a non string value: 0 + +float(0) + 0.13.x: was coerced to string(1) "0" + 14.x.x: Error: Variable "$queryVariable" got invalid value 0; Expected type String; String cannot represent a non string value: 0 +``` + +#### Boolean coercion did not change. + +
+ +### Breaking: renamed classes and changed signatures + +**Impact: Medium** + +- Dropped previously deprecated `GraphQL\Schema`. Use `GraphQL\Type\Schema`. +- Renamed `GraphQL\Error\Debug` to `GraphQL\Error\DebugFlag`. +- Debug flags in `GraphQL\Executor\ExecutionResult`, `GraphQL\Error\FormattedError` and `GraphQL\Server\ServerConfig` + do not accept `boolean` value anymore but `int` only (pass values of `GraphQL\Error\DebugFlag` constants) +- `$positions` in `GraphQL\Error\Error` are not nullable anymore. Same can be expressesed by passing empty array. + +### BREAKING: Removed deprecated directive introspection fields (onOperation, onFragment, onField) + +**Impact: Minor** + +Could affect developer tools relying on old introspection format. +Replaced with [Directive Locations](https://spec.graphql.org/June2018/#sec-Type-System.Directives). + +### BREAKING: Changes in validation rules: + +**Impact: Minor** + + - Removal of `VariablesDefaultValueAllowed` validation rule. All variables may now specify a default value. + - Renamed `ProvidedNonNullArguments` to `ProvidedRequiredArguments` (no longer require values to be provided to non-null arguments which provide a default value). + +Could affect projects using custom sets of validation rules. + +### BREAKING: `GraphQL\Deferred` now extends `GraphQL\Executor\Promise\Adapter\SyncPromise` + +**Impact: Minor** + +Can only affect a few projects that were somehow customizing deferreds or the default sync promise adapter. + + +### BREAKING: renamed several types of dangerous/breaking changes (returned by `BreakingChangesFinder`): + +**Impact: Minor** + +Can affect projects relying on `BreakingChangesFinder` utility in their CI. + +Following types of changes were renamed: + +``` +- `NON_NULL_ARG_ADDED` to `REQUIRED_ARG_ADDED` +- `NON_NULL_INPUT_FIELD_ADDED` to `REQUIRED_INPUT_FIELD_ADDED` +- `NON_NULL_DIRECTIVE_ARG_ADDED` to `REQUIRED_DIRECTIVE_ARG_ADDED` +- `NULLABLE_INPUT_FIELD_ADDED` to `OPTIONAL_INPUT_FIELD_ADDED` +- `NULLABLE_ARG_ADDED` to `OPTIONAL_ARG_ADDED` +``` + +### Breaking: Dropped `GraphQL\Error\Error::$message` + +**Impact: Minor** + +Use `GraphQL\Error\Error->getMessage()` instead. + +### Breaking: change TypeKind constants + +**Impact: Minor** + +The constants in `\GraphQL\Type\TypeKind` were partly renamed and their values +have been changed to match their name instead of a numeric index. + +### Breaking: some error messages were changed + +**Impact: Minor** + +Can affect projects relying on error messages parsing. + +One example: added quotes around `parentType.fieldName` in error message: +```diff +- Cannot return null for non-nullable field parentType.fieldName. ++ Cannot return null for non-nullable field "parentType.fieldName". +``` +But expect other simiar changes like this. + ## Upgrade v0.12.x > v0.13.x ### Breaking (major): minimum supported version of PHP diff --git a/vendor/webonyx/graphql-php/composer.json b/vendor/webonyx/graphql-php/composer.json index 113e79d..ee2a643 100644 --- a/vendor/webonyx/graphql-php/composer.json +++ b/vendor/webonyx/graphql-php/composer.json @@ -14,15 +14,19 @@ "ext-mbstring": "*" }, "require-dev": { + "amphp/amp": "^2.3", "doctrine/coding-standard": "^6.0", - "phpbench/phpbench": "^0.14.0", - "phpstan/phpstan": "^0.11.4", - "phpstan/phpstan-phpunit": "^0.11.0", - "phpstan/phpstan-strict-rules": "^0.11.0", - "phpunit/phpcov": "^5.0", - "phpunit/phpunit": "^7.2", + "nyholm/psr7": "^1.2", + "phpbench/phpbench": "^0.16.10", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "0.12.82", + "phpstan/phpstan-phpunit": "0.12.18", + "phpstan/phpstan-strict-rules": "0.12.9", + "phpunit/phpunit": "^7.2|^8.5", "psr/http-message": "^1.0", - "react/promise": "2.*" + "react/promise": "2.*", + "simpod/php-coveralls-mirror": "^3.0", + "squizlabs/php_codesniffer": "3.5.4" }, "config": { "preferred-install": "dist", @@ -49,8 +53,9 @@ "bench": "phpbench run .", "test": "phpunit", "lint" : "phpcs", - "fix-style" : "phpcbf", - "static-analysis": "phpstan analyse --ansi --memory-limit 256M", - "check-all": "composer lint && composer static-analysis && composer test" + "fix" : "phpcbf", + "stan": "phpstan --ansi", + "baseline": "phpstan --ansi --generate-baseline", + "check": "composer lint && composer stan && composer test" } } diff --git a/vendor/webonyx/graphql-php/docs/best-practices.md b/vendor/webonyx/graphql-php/docs/best-practices.md index a5f135e..4b7fc24 100644 --- a/vendor/webonyx/graphql-php/docs/best-practices.md +++ b/vendor/webonyx/graphql-php/docs/best-practices.md @@ -1,13 +1,3 @@ -# Config Validation -Defining types using arrays may be error-prone, but **graphql-php** provides config validation -tool to report when config has unexpected structure. - -This validation tool is **disabled by default** because it is time-consuming operation which only -makes sense during development. - -To enable validation - call: `GraphQL\Type\Definition\Config::enableValidation();` in your bootstrap -but make sure to restrict it to debug/development mode only. - # Type Registry **graphql-php** expects that each type in Schema is presented by single instance. Therefore if you define your types as separate PHP classes you need to ensure that each type is referenced only once. @@ -16,4 +6,4 @@ Technically you can create several instances of your type (for example for tests will throw on attempt to add different instances with the same name. There are several ways to achieve this depending on your preferences. We provide reference -implementation below that introduces TypeRegistry class: \ No newline at end of file +implementation below that introduces TypeRegistry class: diff --git a/vendor/webonyx/graphql-php/docs/complementary-tools.md b/vendor/webonyx/graphql-php/docs/complementary-tools.md index 4710ebd..5262649 100644 --- a/vendor/webonyx/graphql-php/docs/complementary-tools.md +++ b/vendor/webonyx/graphql-php/docs/complementary-tools.md @@ -3,8 +3,10 @@ * [Standard Server](executing-queries.md/#using-server) – Out of the box integration with any PSR-7 compatible framework (like [Slim](http://slimframework.com) or [Zend Expressive](http://zendframework.github.io/zend-expressive/)). * [Relay Library for graphql-php](https://github.com/ivome/graphql-relay-php) – Helps construct Relay related schema definitions. * [Lighthouse](https://github.com/nuwave/lighthouse) – Laravel based, uses Schema Definition Language +* [Laravel GraphQL](https://github.com/rebing/graphql-laravel) - Laravel wrapper for Facebook's GraphQL * [OverblogGraphQLBundle](https://github.com/overblog/GraphQLBundle) – Bundle for Symfony * [WP-GraphQL](https://github.com/wp-graphql/wp-graphql) - GraphQL API for WordPress +* [Siler](https://github.com/leocavalcante/siler) - Straightforward way to map GraphQL SDL to resolver callables, also built-in support for Swoole # GraphQL PHP Tools @@ -23,3 +25,4 @@ * [ChromeiQL](https://chrome.google.com/webstore/detail/chromeiql/fkkiamalmpiidkljmicmjfbieiclmeij) or [GraphiQL Feen](https://chrome.google.com/webstore/detail/graphiql-feen/mcbfdonlkfpbfdpimkjilhdneikhfklp) – GraphiQL as Google Chrome extension +* [Altair GraphQL Client](https://altair.sirmuel.design/) - A beautiful feature-rich GraphQL Client for all platforms diff --git a/vendor/webonyx/graphql-php/docs/data-fetching.md b/vendor/webonyx/graphql-php/docs/data-fetching.md index 4bc0cfb..c5152ba 100644 --- a/vendor/webonyx/graphql-php/docs/data-fetching.md +++ b/vendor/webonyx/graphql-php/docs/data-fetching.md @@ -103,23 +103,25 @@ for a field you simply override this default resolver. **graphql-php** provides following default field resolver: ```php fieldName; - $property = null; +function defaultFieldResolver($objectValue, $args, $context, \GraphQL\Type\Definition\ResolveInfo $info) + { + $fieldName = $info->fieldName; + $property = null; - if (is_array($source) || $source instanceof \ArrayAccess) { - if (isset($source[$fieldName])) { - $property = $source[$fieldName]; - } - } else if (is_object($source)) { - if (isset($source->{$fieldName})) { - $property = $source->{$fieldName}; + if (is_array($objectValue) || $objectValue instanceof \ArrayAccess) { + if (isset($objectValue[$fieldName])) { + $property = $objectValue[$fieldName]; + } + } elseif (is_object($objectValue)) { + if (isset($objectValue->{$fieldName})) { + $property = $objectValue->{$fieldName}; + } } + + return $property instanceof Closure + ? $property($objectValue, $args, $context, $info) + : $property; } - - return $property instanceof Closure ? $property($source, $args, $context, $info) : $property; -} ``` As you see it returns value by key (for arrays) or property (for objects). @@ -161,7 +163,6 @@ $userType = new ObjectType([ Keep in mind that **field resolver** has precedence over **default field resolver per type** which in turn has precedence over **default field resolver**. - # Solving N+1 Problem Since: 0.9.0 diff --git a/vendor/webonyx/graphql-php/docs/error-handling.md b/vendor/webonyx/graphql-php/docs/error-handling.md index 17b0a2a..c3841b2 100644 --- a/vendor/webonyx/graphql-php/docs/error-handling.md +++ b/vendor/webonyx/graphql-php/docs/error-handling.md @@ -17,7 +17,9 @@ By default, each error entry is converted to an associative array with following 'Error message', - 'category' => 'graphql', + 'extensions' => [ + 'category' => 'graphql' + ], 'locations' => [ ['line' => 1, 'column' => 2] ], @@ -67,7 +69,9 @@ When such exception is thrown it will be reported with a full error message: 'My reported error', - 'category' => 'businessLogic', + 'extensions' => [ + 'category' => 'businessLogic' + ], 'locations' => [ ['line' => 10, 'column' => 2] ], @@ -86,12 +90,12 @@ GraphQL\Error\FormattedError::setInternalErrorMessage("Unexpected error"); # Debugging tools -During development or debugging use `$result->toArray(true)` to add **debugMessage** key to +During development or debugging use `$result->toArray(DebugFlag::INCLUDE_DEBUG_MESSAGE)` to add **debugMessage** key to each formatted error entry. If you also want to add exception trace - pass flags instead: -``` -use GraphQL\Error\Debug; -$debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE; +```php +use GraphQL\Error\DebugFlag; +$debug = DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE; $result = GraphQL::executeQuery(/*args*/)->toArray($debug); ``` @@ -101,7 +105,9 @@ This will make each error entry to look like this: [ 'debugMessage' => 'Actual exception message', 'message' => 'Internal server error', - 'category' => 'internal', + 'extensions' => [ + 'category' => 'internal' + ], 'locations' => [ ['line' => 10, 'column' => 2] ], @@ -120,8 +126,8 @@ If you prefer the first resolver exception to be re-thrown, use following flags: ```php toArray($debug); diff --git a/vendor/webonyx/graphql-php/docs/executing-queries.md b/vendor/webonyx/graphql-php/docs/executing-queries.md index 29388a2..54f82da 100644 --- a/vendor/webonyx/graphql-php/docs/executing-queries.md +++ b/vendor/webonyx/graphql-php/docs/executing-queries.md @@ -66,11 +66,11 @@ Server also supports [PSR-7 request/response interfaces](http://www.php-fig.org/ setSchema($schema) ->setErrorFormatter($myFormatter) - ->setDebug($debug) + ->setDebugFlag($debug) ; $server = new StandardServer($config); diff --git a/vendor/webonyx/graphql-php/docs/getting-started.md b/vendor/webonyx/graphql-php/docs/getting-started.md index 4477cda..69abf8e 100644 --- a/vendor/webonyx/graphql-php/docs/getting-started.md +++ b/vendor/webonyx/graphql-php/docs/getting-started.md @@ -54,8 +54,8 @@ $queryType = new ObjectType([ 'args' => [ 'message' => Type::nonNull(Type::string()), ], - 'resolve' => function ($root, $args) { - return $root['prefix'] . $args['message']; + 'resolve' => function ($rootValue, $args) { + return $rootValue['prefix'] . $args['message']; } ], ], diff --git a/vendor/webonyx/graphql-php/docs/reference.md b/vendor/webonyx/graphql-php/docs/reference.md index e36e2cd..73f8114 100644 --- a/vendor/webonyx/graphql-php/docs/reference.md +++ b/vendor/webonyx/graphql-php/docs/reference.md @@ -20,9 +20,11 @@ See [related documentation](executing-queries.md). * rootValue: * The value provided as the first argument to resolver functions on the top * level type (e.g. the query object type). - * context: - * The value provided as the third argument to all resolvers. - * Use this to pass current session, user data, etc + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. * variableValues: * A mapping of variable name to runtime value to use for all variables * defined in the requestString. @@ -41,7 +43,7 @@ See [related documentation](executing-queries.md). * * @param string|DocumentNode $source * @param mixed $rootValue - * @param mixed $context + * @param mixed $contextValue * @param mixed[]|null $variableValues * @param ValidationRule[] $validationRules * @@ -51,12 +53,12 @@ static function executeQuery( GraphQL\Type\Schema $schema, $source, $rootValue = null, - $context = null, + $contextValue = null, $variableValues = null, string $operationName = null, callable $fieldResolver = null, array $validationRules = null -) +): GraphQL\Executor\ExecutionResult ``` ```php @@ -82,7 +84,7 @@ static function promiseToExecute( string $operationName = null, callable $fieldResolver = null, array $validationRules = null -) +): GraphQL\Executor\Promise\Promise ``` ```php @@ -93,7 +95,7 @@ static function promiseToExecute( * * @api */ -static function getStandardDirectives() +static function getStandardDirectives(): array ``` ```php @@ -104,7 +106,7 @@ static function getStandardDirectives() * * @api */ -static function getStandardTypes() +static function getStandardTypes(): array ``` ```php @@ -112,7 +114,7 @@ static function getStandardTypes() * Replaces standard types with types from this list (matching by name) * Standard types not listed here remain untouched. * - * @param Type[] $types + * @param array $types * * @api */ @@ -127,7 +129,7 @@ static function overrideStandardTypes(array $types) * * @api */ -static function getStandardValidationRules() +static function getStandardValidationRules(): array ``` ```php @@ -136,7 +138,7 @@ static function getStandardValidationRules() * * @api */ -static function setDefaultFieldResolver(callable $fn) +static function setDefaultFieldResolver(callable $fn): void ``` # GraphQL\Type\Definition\Type Registry of standard GraphQL types @@ -145,157 +147,114 @@ and a base class for all other types. **Class Methods:** ```php /** - * @return IDType - * * @api */ -static function id() +static function id(): GraphQL\Type\Definition\ScalarType ``` ```php /** - * @return StringType - * * @api */ -static function string() +static function string(): GraphQL\Type\Definition\ScalarType ``` ```php /** - * @return BooleanType - * * @api */ -static function boolean() +static function boolean(): GraphQL\Type\Definition\ScalarType ``` ```php /** - * @return IntType - * * @api */ -static function int() +static function int(): GraphQL\Type\Definition\ScalarType ``` ```php /** - * @return FloatType - * * @api */ -static function float() +static function float(): GraphQL\Type\Definition\ScalarType ``` ```php /** - * @param Type|ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType|NonNull $wrappedType - * - * @return ListOfType - * * @api */ -static function listOf($wrappedType) +static function listOf(GraphQL\Type\Definition\Type $wrappedType): GraphQL\Type\Definition\ListOfType ``` ```php /** - * @param NullableType $wrappedType - * - * @return NonNull + * @param callable|NullableType $wrappedType * * @api */ -static function nonNull($wrappedType) +static function nonNull($wrappedType): GraphQL\Type\Definition\NonNull ``` ```php /** * @param Type $type * - * @return bool - * * @api */ -static function isInputType($type) +static function isInputType($type): bool ``` ```php /** * @param Type $type * - * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType - * * @api */ -static function getNamedType($type) +static function getNamedType($type): GraphQL\Type\Definition\Type ``` ```php /** * @param Type $type * - * @return bool - * * @api */ -static function isOutputType($type) +static function isOutputType($type): bool ``` ```php /** * @param Type $type * - * @return bool - * * @api */ -static function isLeafType($type) +static function isLeafType($type): bool ``` ```php /** * @param Type $type * - * @return bool - * * @api */ -static function isCompositeType($type) +static function isCompositeType($type): bool ``` ```php /** * @param Type $type * - * @return bool - * * @api */ -static function isAbstractType($type) +static function isAbstractType($type): bool ``` ```php /** - * @param Type $type - * - * @return bool - * * @api */ -static function isType($type) -``` - -```php -/** - * @param Type $type - * - * @return NullableType - * - * @api - */ -static function getNullableType($type) +static function getNullableType(GraphQL\Type\Definition\Type $type): GraphQL\Type\Definition\Type ``` # GraphQL\Type\Definition\ResolveInfo Structure containing information useful for field resolution process. @@ -304,6 +263,14 @@ Passed as 4th argument to every field resolver. See [docs on field resolving (da **Class Props:** ```php +/** + * The definition of the field being resolved. + * + * @api + * @var FieldDefinition + */ +public $fieldDefinition; + /** * The name of the field being resolved. * @@ -312,6 +279,14 @@ Passed as 4th argument to every field resolver. See [docs on field resolving (da */ public $fieldName; +/** + * Expected return type of the field being resolved. + * + * @api + * @var Type + */ +public $returnType; + /** * AST of all nodes referencing this field in the query. * @@ -320,14 +295,6 @@ public $fieldName; */ public $fieldNodes; -/** - * Expected return type of the field being resolved. - * - * @api - * @var ScalarType|ObjectType|InterfaceType|UnionType|EnumType|ListOfType|NonNull - */ -public $returnType; - /** * Parent type of the field being resolved. * @@ -340,7 +307,7 @@ public $parentType; * Path to this field from the very root value. * * @api - * @var string[][] + * @var string[] */ public $path; @@ -420,7 +387,7 @@ public $variableValues; * * @param int $depth How many levels to include in output * - * @return bool[] + * @return array * * @api */ @@ -438,6 +405,7 @@ const FIELD = "FIELD"; const FRAGMENT_DEFINITION = "FRAGMENT_DEFINITION"; const FRAGMENT_SPREAD = "FRAGMENT_SPREAD"; const INLINE_FRAGMENT = "INLINE_FRAGMENT"; +const VARIABLE_DEFINITION = "VARIABLE_DEFINITION"; const SCHEMA = "SCHEMA"; const SCALAR = "SCALAR"; const OBJECT = "OBJECT"; @@ -481,7 +449,7 @@ static function create(array $options = []) ```php /** - * @return ObjectType + * @return ObjectType|null * * @api */ @@ -490,7 +458,7 @@ function getQuery() ```php /** - * @param ObjectType $query + * @param ObjectType|null $query * * @return SchemaConfig * @@ -501,7 +469,7 @@ function setQuery($query) ```php /** - * @return ObjectType + * @return ObjectType|null * * @api */ @@ -510,7 +478,7 @@ function getMutation() ```php /** - * @param ObjectType $mutation + * @param ObjectType|null $mutation * * @return SchemaConfig * @@ -521,7 +489,7 @@ function setMutation($mutation) ```php /** - * @return ObjectType + * @return ObjectType|null * * @api */ @@ -530,7 +498,7 @@ function getSubscription() ```php /** - * @param ObjectType $subscription + * @param ObjectType|null $subscription * * @return SchemaConfig * @@ -541,7 +509,7 @@ function setSubscription($subscription) ```php /** - * @return Type[] + * @return Type[]|callable * * @api */ @@ -561,7 +529,7 @@ function setTypes($types) ```php /** - * @return Directive[] + * @return Directive[]|null * * @api */ @@ -581,7 +549,7 @@ function setDirectives(array $directives) ```php /** - * @return callable + * @return callable(string $name):Type|null * * @api */ @@ -659,7 +627,7 @@ function getDirectives() * * @api */ -function getQueryType() +function getQueryType(): GraphQL\Type\Definition\Type ``` ```php @@ -670,7 +638,7 @@ function getQueryType() * * @api */ -function getMutationType() +function getMutationType(): GraphQL\Type\Definition\Type ``` ```php @@ -681,7 +649,7 @@ function getMutationType() * * @api */ -function getSubscriptionType() +function getSubscriptionType(): GraphQL\Type\Definition\Type ``` ```php @@ -695,15 +663,11 @@ function getConfig() ```php /** - * Returns type by it's name - * - * @param string $name - * - * @return Type|null + * Returns type by its name * * @api */ -function getType($name) +function getType(string $name): GraphQL\Type\Definition\Type ``` ```php @@ -713,11 +677,13 @@ function getType($name) * * This operation requires full schema scan. Do not use in production environment. * - * @return ObjectType[] + * @param InterfaceType|UnionType $abstractType + * + * @return array * * @api */ -function getPossibleTypes(GraphQL\Type\Definition\AbstractType $abstractType) +function getPossibleTypes(GraphQL\Type\Definition\Type $abstractType): array ``` ```php @@ -725,27 +691,21 @@ function getPossibleTypes(GraphQL\Type\Definition\AbstractType $abstractType) * Returns true if object type is concrete type of given abstract type * (implementation for interfaces and members of union type for unions) * - * @return bool - * * @api */ function isPossibleType( GraphQL\Type\Definition\AbstractType $abstractType, GraphQL\Type\Definition\ObjectType $possibleType -) +): bool ``` ```php /** * Returns instance of directive by name * - * @param string $name - * - * @return Directive - * * @api */ -function getDirective($name) +function getDirective(string $name): GraphQL\Type\Definition\Directive ``` ```php @@ -776,6 +736,42 @@ function validate() # GraphQL\Language\Parser Parses string containing GraphQL query or [type definition](type-system/type-language.md) to Abstract Syntax Tree. +Those magic functions allow partial parsing: + +@method static DocumentNode document(Source|string $source, bool[] $options = []) +@method static ExecutableDefinitionNode executableDefinition(Source|string $source, bool[] $options = []) +@method static string operationType(Source|string $source, bool[] $options = []) +@method static VariableDefinitionNode variableDefinition(Source|string $source, bool[] $options = []) +@method static SelectionSetNode selectionSet(Source|string $source, bool[] $options = []) +@method static FieldNode field(Source|string $source, bool[] $options = []) +@method static NodeList constArguments(Source|string $source, bool[] $options = []) +@method static ArgumentNode constArgument(Source|string $source, bool[] $options = []) +@method static FragmentDefinitionNode fragmentDefinition(Source|string $source, bool[] $options = []) +@method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|NullValueNode|ObjectValueNode|StringValueNode|VariableNode valueLiteral(Source|string $source, bool[] $options = []) +@method static StringValueNode stringLiteral(Source|string $source, bool[] $options = []) +@method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode variableValue(Source|string $source, bool[] $options = []) +@method static ListValueNode constArray(Source|string $source, bool[] $options = []) +@method static ObjectValueNode constObject(Source|string $source, bool[] $options = []) +@method static ObjectFieldNode constObjectField(Source|string $source, bool[] $options = []) +@method static NodeList constDirectives(Source|string $source, bool[] $options = []) +@method static DirectiveNode constDirective(Source|string $source, bool[] $options = []) +@method static NamedTypeNode namedType(Source|string $source, bool[] $options = []) +@method static StringValueNode|null description(Source|string $source, bool[] $options = []) +@method static OperationTypeDefinitionNode operationTypeDefinition(Source|string $source, bool[] $options = []) +@method static ObjectTypeDefinitionNode objectTypeDefinition(Source|string $source, bool[] $options = []) +@method static NodeList fieldsDefinition(Source|string $source, bool[] $options = []) +@method static NodeList argumentsDefinition(Source|string $source, bool[] $options = []) +@method static InterfaceTypeDefinitionNode interfaceTypeDefinition(Source|string $source, bool[] $options = []) +@method static NamedTypeNode[] unionMemberTypes(Source|string $source, bool[] $options = []) +@method static NodeList enumValuesDefinition(Source|string $source, bool[] $options = []) +@method static InputObjectTypeDefinitionNode inputObjectTypeDefinition(Source|string $source, bool[] $options = []) +@method static TypeExtensionNode typeExtension(Source|string $source, bool[] $options = []) +@method static ScalarTypeExtensionNode scalarTypeExtension(Source|string $source, bool[] $options = []) +@method static InterfaceTypeExtensionNode interfaceTypeExtension(Source|string $source, bool[] $options = []) +@method static EnumTypeExtensionNode enumTypeExtension(Source|string $source, bool[] $options = []) +@method static DirectiveDefinitionNode directiveDefinition(Source|string $source, bool[] $options = []) +@method static DirectiveLocation directiveLocation(Source|string $source, bool[] $options = []) + **Class Methods:** ```php /** @@ -866,7 +862,7 @@ static function parseValue($source, array $options = []) * @param Source|string $source * @param bool[] $options * - * @return ListTypeNode|NameNode|NonNullTypeNode + * @return ListTypeNode|NamedTypeNode|NonNullTypeNode * * @api */ @@ -1229,16 +1225,13 @@ function setErrorsHandler(callable $handler) * If debug argument is passed, output of error formatter is enriched which debugging information * ("debugMessage", "trace" keys depending on flags). * - * $debug argument must be either bool (only adds "debugMessage" to result) or sum of flags from - * GraphQL\Error\Debug - * - * @param bool|int $debug + * $debug argument must sum of flags from @see \GraphQL\Error\DebugFlag * * @return mixed[] * * @api */ -function toArray($debug = false) +function toArray(int $debug = "GraphQL\Error\DebugFlag::NONE"): array ``` # GraphQL\Executor\Promise\PromiseAdapter Provides a means for integration of async PHP platforms ([related docs](data-fetching.md#async-php)) @@ -1487,7 +1480,7 @@ const ALL = 63; * * @api */ -static function setWarningHandler(callable $warningHandler = null) +static function setWarningHandler(callable $warningHandler = null): void ``` ```php @@ -1503,7 +1496,7 @@ static function setWarningHandler(callable $warningHandler = null) * * @api */ -static function suppress($suppress = true) +static function suppress($suppress = true): void ``` ```php @@ -1519,7 +1512,7 @@ static function suppress($suppress = true) * * @api */ -static function enable($enable = true) +static function enable($enable = true): void ``` # GraphQL\Error\ClientAware This interface is used for [default error formatting](error-handling.md). @@ -1553,11 +1546,12 @@ function isClientSafe() */ function getCategory() ``` -# GraphQL\Error\Debug +# GraphQL\Error\DebugFlag Collection of flags for [error debugging](error-handling.md#debugging-tools). **Class Constants:** ```php +const NONE = 0; const INCLUDE_DEBUG_MESSAGE = 1; const INCLUDE_TRACE = 2; const RETHROW_INTERNAL_EXCEPTIONS = 4; @@ -1590,11 +1584,9 @@ static function setInternalErrorMessage($msg) * This method only exposes exception message when exception implements ClientAware interface * (or when debug flags are passed). * - * For a list of available debug flags see GraphQL\Error\Debug constants. + * For a list of available debug flags @see \GraphQL\Error\DebugFlag constants. * - * @param Throwable $e - * @param bool|int $debug - * @param string $internalErrorMessage + * @param string $internalErrorMessage * * @return mixed[] * @@ -1602,7 +1594,11 @@ static function setInternalErrorMessage($msg) * * @api */ -static function createFromException($e, $debug = false, $internalErrorMessage = null) +static function createFromException( + Throwable $exception, + int $debug = "GraphQL\Error\DebugFlag::NONE", + $internalErrorMessage = null +): array ``` ```php @@ -1718,7 +1714,7 @@ function executeRequest($parsedBody = null) * @api */ function processPsrRequest( - Psr\Http\Message\ServerRequestInterface $request, + Psr\Http\Message\RequestInterface $request, Psr\Http\Message\ResponseInterface $response, Psr\Http\Message\StreamInterface $writableBodyStream ) @@ -1733,7 +1729,7 @@ function processPsrRequest( * * @api */ -function executePsrRequest(Psr\Http\Message\ServerRequestInterface $request) +function executePsrRequest(Psr\Http\Message\RequestInterface $request) ``` ```php @@ -1832,7 +1828,7 @@ function setErrorsHandler(callable $handler) /** * Set validation rules for this server. * - * @param ValidationRule[]|callable $validationRules + * @param ValidationRule[]|callable|null $validationRules * * @return self * @@ -1865,15 +1861,11 @@ function setPersistentQueryLoader(callable $persistentQueryLoader) ```php /** - * Set response debug flags. See GraphQL\Error\Debug class for a list of all available flags - * - * @param bool|int $set - * - * @return self + * Set response debug flags. @see \GraphQL\Error\DebugFlag class for a list of all available flags * * @api */ -function setDebug($set = true) +function setDebugFlag(int $debugFlag = "GraphQL\Error\DebugFlag::INCLUDE_DEBUG_MESSAGE"): self ``` ```php @@ -1882,7 +1874,7 @@ function setDebug($set = true) * * @api */ -function setQueryBatching(bool $enableBatching) +function setQueryBatching(bool $enableBatching): self ``` ```php @@ -1947,7 +1939,7 @@ function parseRequestParams($method, array $bodyParams, array $queryParams) * Checks validity of OperationParams extracted from HTTP request and returns an array of errors * if params are invalid (or empty array when params are valid) * - * @return Error[] + * @return array * * @api */ @@ -2002,7 +1994,7 @@ function sendResponse($result, $exitWhenDone = false) * * @api */ -function parsePsrRequest(Psr\Http\Message\ServerRequestInterface $request) +function parsePsrRequest(Psr\Http\Message\RequestInterface $request) ``` ```php @@ -2073,7 +2065,7 @@ public $extensions; * * @api */ -static function create(array $params, bool $readonly = false) +static function create(array $params, bool $readonly = false): GraphQL\Server\OperationParams ``` ```php @@ -2133,6 +2125,7 @@ static function build($source, callable $typeConfigDecorator = null, array $opti * * - commentDescriptions: * Provide true to use preceding comments as the description. + * This option is provided to ease adoption and will be removed in v16. * * @param bool[] $options * @@ -2178,7 +2171,7 @@ Various utilities dealing with AST * * @api */ -static function fromArray(array $node) +static function fromArray(array $node): GraphQL\Language\AST\Node ``` ```php @@ -2189,7 +2182,7 @@ static function fromArray(array $node) * * @api */ -static function toArray(GraphQL\Language\AST\Node $node) +static function toArray(GraphQL\Language\AST\Node $node): array ``` ```php @@ -2213,7 +2206,7 @@ static function toArray(GraphQL\Language\AST\Node $node) * * @param Type|mixed|null $value * - * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode + * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode|null * * @api */ @@ -2240,8 +2233,8 @@ static function astFromValue($value, GraphQL\Type\Definition\InputType $type) * | Enum Value | Mixed | * | Null Value | null | * - * @param ValueNode|null $valueNode - * @param mixed[]|null $variables + * @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null $valueNode + * @param mixed[]|null $variables * * @return mixed[]|stdClass|null * @@ -2249,7 +2242,11 @@ static function astFromValue($value, GraphQL\Type\Definition\InputType $type) * * @api */ -static function valueFromAST($valueNode, GraphQL\Type\Definition\InputType $type, array $variables = null) +static function valueFromAST( + GraphQL\Language\AST\ValueNode $valueNode, + GraphQL\Type\Definition\Type $type, + array $variables = null +) ``` ```php @@ -2302,7 +2299,7 @@ static function typeFromAST(GraphQL\Type\Schema $schema, $inputTypeNode) * * @param string $operationName * - * @return bool + * @return bool|string * * @api */ @@ -2314,23 +2311,22 @@ Given an instance of Schema, prints it in GraphQL type language. **Class Methods:** ```php /** - * Accepts options as a second argument: - * + * @param array $options + * Available options: * - commentDescriptions: * Provide true to use preceding comments as the description. - * - * @param bool[] $options + * This option is provided to ease adoption and will be removed in v16. * * @api */ -static function doPrint(GraphQL\Type\Schema $schema, array $options = []) +static function doPrint(GraphQL\Type\Schema $schema, array $options = []): string ``` ```php /** - * @param bool[] $options + * @param array $options * * @api */ -static function printIntrospectionSchema(GraphQL\Type\Schema $schema, array $options = []) +static function printIntrospectionSchema(GraphQL\Type\Schema $schema, array $options = []): string ``` diff --git a/vendor/webonyx/graphql-php/docs/type-system/enum-types.md b/vendor/webonyx/graphql-php/docs/type-system/enum-types.md index 4cebdec..bfab3a5 100644 --- a/vendor/webonyx/graphql-php/docs/type-system/enum-types.md +++ b/vendor/webonyx/graphql-php/docs/type-system/enum-types.md @@ -158,7 +158,7 @@ $heroType = new ObjectType([ 'args' => [ 'episode' => Type::nonNull($enumType) ], - 'resolve' => function($_value, $args) { + 'resolve' => function($hero, $args) { return $args['episode'] === 5 ? true : false; } ] diff --git a/vendor/webonyx/graphql-php/docs/type-system/input-types.md b/vendor/webonyx/graphql-php/docs/type-system/input-types.md index 1b7ffc8..7138557 100644 --- a/vendor/webonyx/graphql-php/docs/type-system/input-types.md +++ b/vendor/webonyx/graphql-php/docs/type-system/input-types.md @@ -131,7 +131,7 @@ $queryType = new ObjectType([ 'type' => Type::listOf($storyType), 'args' => [ 'filters' => [ - 'type' => Type::nonNull($filters), + 'type' => $filters, 'defaultValue' => [ 'popular' => true ] diff --git a/vendor/webonyx/graphql-php/docs/type-system/interfaces.md b/vendor/webonyx/graphql-php/docs/type-system/interfaces.md index 5335d6d..100d510 100644 --- a/vendor/webonyx/graphql-php/docs/type-system/interfaces.md +++ b/vendor/webonyx/graphql-php/docs/type-system/interfaces.md @@ -134,3 +134,41 @@ concrete Object Type. If a **resolveType** option is omitted, graphql-php will loop through all interface implementors and use their **isTypeOf** callback to pick the first suitable one. This is obviously less efficient than single **resolveType** call. So it is recommended to define **resolveType** whenever possible. + +# Prevent invisible types +When object types that implement an interface are not directly referenced by a field, they cannot +be discovered during schema introspection. For example: + +```graphql +type Query { + animal: Animal +} + +interface Animal {...} + +type Cat implements Animal {...} +type Dog implements Animal {...} +``` + +In this example, `Cat` and `Dog` would be considered *invisible* types. Querying the `animal` field +would fail, since no possible implementing types for `Animal` can be found. + +There are two possible solutions: + +1. Add fields that reference the invisible types directly, e.g.: + + ```graphql + type Query { + dog: Dog + cat: Cat + } + ``` + +2. Pass the invisible types during schema construction, e.g.: + +```php +new GraphQLSchema([ + 'query' => ..., + 'types' => [$cat, $dog] +]); +``` diff --git a/vendor/webonyx/graphql-php/docs/type-system/object-types.md b/vendor/webonyx/graphql-php/docs/type-system/object-types.md index 9c1f2fb..0b950c0 100644 --- a/vendor/webonyx/graphql-php/docs/type-system/object-types.md +++ b/vendor/webonyx/graphql-php/docs/type-system/object-types.md @@ -80,7 +80,7 @@ Option | Type | Notes name | `string` | **Required.** Name of the field. When not set - inferred from **fields** array key (read about [shorthand field definition](#shorthand-field-definitions) below) type | `Type` | **Required.** An instance of internal or custom type. Note: type must be represented by a single instance within one schema (see also [Type Registry](index.md#type-registry)) args | `array` | An array of possible type arguments. Each entry is expected to be an array with keys: **name**, **type**, **description**, **defaultValue**. See [Field Arguments](#field-arguments) section below. -resolve | `callable` | **function($value, $args, $context, [ResolveInfo](../reference.md#graphqltypedefinitionresolveinfo) $info)**
Given the **$value** of this type, it is expected to return actual value of the current field. See section on [Data Fetching](../data-fetching.md) for details +resolve | `callable` | **function($objectValue, $args, $context, [ResolveInfo](../reference.md#graphqltypedefinitionresolveinfo) $info)**
Given the **$objectValue** of this type, it is expected to return actual value of the current field. See section on [Data Fetching](../data-fetching.md) for details complexity | `callable` | **function($childrenComplexity, $args)**
Used to restrict query complexity. The feature is disabled by default, read about [Security](../security.md#query-complexity-analysis) to use it. description | `string` | Plain-text description of this field for clients (e.g. used by [GraphiQL](https://github.com/graphql/graphiql) for auto-generated documentation) deprecationReason | `string` | Text describing why this field is deprecated. When not empty - field will not be returned by introspection queries (unless forced) diff --git a/vendor/webonyx/graphql-php/docs/type-system/scalar-types.md b/vendor/webonyx/graphql-php/docs/type-system/scalar-types.md index 3029238..074e8c6 100644 --- a/vendor/webonyx/graphql-php/docs/type-system/scalar-types.md +++ b/vendor/webonyx/graphql-php/docs/type-system/scalar-types.md @@ -100,7 +100,7 @@ class EmailType extends ScalarType * @return string * @throws Error */ - public function parseLiteral($valueNode, array $variables = null) + public function parseLiteral(Node $valueNode, ?array $variables = null) { // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL // error location in query: diff --git a/vendor/webonyx/graphql-php/docs/type-system/schema.md b/vendor/webonyx/graphql-php/docs/type-system/schema.md index 08ee12f..e3ae6e0 100644 --- a/vendor/webonyx/graphql-php/docs/type-system/schema.md +++ b/vendor/webonyx/graphql-php/docs/type-system/schema.md @@ -62,7 +62,7 @@ $mutationType = new ObjectType([ 'episode' => $episodeEnum, 'review' => $reviewInputObject ], - 'resolve' => function($val, $args) { + 'resolve' => function($rootValue, $args) { // TODOC } ] diff --git a/vendor/webonyx/graphql-php/examples/00-hello-world/README.md b/vendor/webonyx/graphql-php/examples/00-hello-world/README.md deleted file mode 100644 index 98a7393..0000000 --- a/vendor/webonyx/graphql-php/examples/00-hello-world/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Hello world -Clean and simple single-file example of main GraphQL concepts originally proposed and -implemented by [Leo Cavalcante](https://github.com/leocavalcante) - -### Run locally -``` -php -S localhost:8080 ./graphql.php -``` - -### Try query -``` -curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }' -``` - -### Try mutation -``` -curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }' -``` diff --git a/vendor/webonyx/graphql-php/examples/00-hello-world/graphql.php b/vendor/webonyx/graphql-php/examples/00-hello-world/graphql.php deleted file mode 100644 index 30b1f9c..0000000 --- a/vendor/webonyx/graphql-php/examples/00-hello-world/graphql.php +++ /dev/null @@ -1,69 +0,0 @@ - 'Query', - 'fields' => [ - 'echo' => [ - 'type' => Type::string(), - 'args' => [ - 'message' => ['type' => Type::string()], - ], - 'resolve' => function ($root, $args) { - return $root['prefix'] . $args['message']; - } - ], - ], - ]); - - $mutationType = new ObjectType([ - 'name' => 'Calc', - 'fields' => [ - 'sum' => [ - 'type' => Type::int(), - 'args' => [ - 'x' => ['type' => Type::int()], - 'y' => ['type' => Type::int()], - ], - 'resolve' => function ($root, $args) { - return $args['x'] + $args['y']; - }, - ], - ], - ]); - - // See docs on schema options: - // http://webonyx.github.io/graphql-php/type-system/schema/#configuration-options - $schema = new Schema([ - 'query' => $queryType, - 'mutation' => $mutationType, - ]); - - $rawInput = file_get_contents('php://input'); - $input = json_decode($rawInput, true); - $query = $input['query']; - $variableValues = isset($input['variables']) ? $input['variables'] : null; - - $rootValue = ['prefix' => 'You said: ']; - $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues); - $output = $result->toArray(); -} catch (\Exception $e) { - $output = [ - 'error' => [ - 'message' => $e->getMessage() - ] - ]; -} -header('Content-Type: application/json; charset=UTF-8'); -echo json_encode($output); - diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/AppContext.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/AppContext.php deleted file mode 100644 index f6c16cf..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/AppContext.php +++ /dev/null @@ -1,28 +0,0 @@ - new User([ - 'id' => '1', - 'email' => 'john@example.com', - 'firstName' => 'John', - 'lastName' => 'Doe' - ]), - '2' => new User([ - 'id' => '2', - 'email' => 'jane@example.com', - 'firstName' => 'Jane', - 'lastName' => 'Doe' - ]), - '3' => new User([ - 'id' => '3', - 'email' => 'john@example.com', - 'firstName' => 'John', - 'lastName' => 'Doe' - ]), - ]; - - self::$stories = [ - '1' => new Story(['id' => '1', 'authorId' => '1', 'body' => '

GraphQL is awesome!

']), - '2' => new Story(['id' => '2', 'authorId' => '1', 'body' => 'Test this']), - '3' => new Story(['id' => '3', 'authorId' => '3', 'body' => "This\n
story\n
spans\n
newlines"]), - ]; - - self::$storyLikes = [ - '1' => ['1', '2', '3'], - '2' => [], - '3' => ['1'] - ]; - - self::$comments = [ - // thread #1: - '100' => new Comment(['id' => '100', 'authorId' => '3', 'storyId' => '1', 'body' => 'Likes']), - '110' => new Comment(['id' =>'110', 'authorId' =>'2', 'storyId' => '1', 'body' => 'Reply #1', 'parentId' => '100']), - '111' => new Comment(['id' => '111', 'authorId' => '1', 'storyId' => '1', 'body' => 'Reply #1-1', 'parentId' => '110']), - '112' => new Comment(['id' => '112', 'authorId' => '3', 'storyId' => '1', 'body' => 'Reply #1-2', 'parentId' => '110']), - '113' => new Comment(['id' => '113', 'authorId' => '2', 'storyId' => '1', 'body' => 'Reply #1-3', 'parentId' => '110']), - '114' => new Comment(['id' => '114', 'authorId' => '1', 'storyId' => '1', 'body' => 'Reply #1-4', 'parentId' => '110']), - '115' => new Comment(['id' => '115', 'authorId' => '3', 'storyId' => '1', 'body' => 'Reply #1-5', 'parentId' => '110']), - '116' => new Comment(['id' => '116', 'authorId' => '1', 'storyId' => '1', 'body' => 'Reply #1-6', 'parentId' => '110']), - '117' => new Comment(['id' => '117', 'authorId' => '2', 'storyId' => '1', 'body' => 'Reply #1-7', 'parentId' => '110']), - '120' => new Comment(['id' => '120', 'authorId' => '3', 'storyId' => '1', 'body' => 'Reply #2', 'parentId' => '100']), - '130' => new Comment(['id' => '130', 'authorId' => '3', 'storyId' => '1', 'body' => 'Reply #3', 'parentId' => '100']), - '200' => new Comment(['id' => '200', 'authorId' => '2', 'storyId' => '1', 'body' => 'Me2']), - '300' => new Comment(['id' => '300', 'authorId' => '3', 'storyId' => '1', 'body' => 'U2']), - - # thread #2: - '400' => new Comment(['id' => '400', 'authorId' => '2', 'storyId' => '2', 'body' => 'Me too']), - '500' => new Comment(['id' => '500', 'authorId' => '2', 'storyId' => '2', 'body' => 'Nice!']), - ]; - - self::$storyComments = [ - '1' => ['100', '200', '300'], - '2' => ['400', '500'] - ]; - - self::$commentReplies = [ - '100' => ['110', '120', '130'], - '110' => ['111', '112', '113', '114', '115', '116', '117'], - ]; - - self::$storyMentions = [ - '1' => [ - self::$users['2'] - ], - '2' => [ - self::$stories['1'], - self::$users['3'] - ] - ]; - } - - public static function findUser($id) - { - return isset(self::$users[$id]) ? self::$users[$id] : null; - } - - public static function findStory($id) - { - return isset(self::$stories[$id]) ? self::$stories[$id] : null; - } - - public static function findComment($id) - { - return isset(self::$comments[$id]) ? self::$comments[$id] : null; - } - - public static function findLastStoryFor($authorId) - { - $storiesFound = array_filter(self::$stories, function(Story $story) use ($authorId) { - return $story->authorId == $authorId; - }); - return !empty($storiesFound) ? $storiesFound[count($storiesFound) - 1] : null; - } - - public static function findLikes($storyId, $limit) - { - $likes = isset(self::$storyLikes[$storyId]) ? self::$storyLikes[$storyId] : []; - $result = array_map( - function($userId) { - return self::$users[$userId]; - }, - $likes - ); - return array_slice($result, 0, $limit); - } - - public static function isLikedBy($storyId, $userId) - { - $subscribers = isset(self::$storyLikes[$storyId]) ? self::$storyLikes[$storyId] : []; - return in_array($userId, $subscribers); - } - - public static function getUserPhoto($userId, $size) - { - return new Image([ - 'id' => $userId, - 'type' => Image::TYPE_USERPIC, - 'size' => $size, - 'width' => rand(100, 200), - 'height' => rand(100, 200) - ]); - } - - public static function findLatestStory() - { - return array_pop(self::$stories); - } - - public static function findStories($limit, $afterId = null) - { - $start = $afterId ? (int) array_search($afterId, array_keys(self::$stories)) + 1 : 0; - return array_slice(array_values(self::$stories), $start, $limit); - } - - public static function findComments($storyId, $limit = 5, $afterId = null) - { - $storyComments = isset(self::$storyComments[$storyId]) ? self::$storyComments[$storyId] : []; - - $start = isset($after) ? (int) array_search($afterId, $storyComments) + 1 : 0; - $storyComments = array_slice($storyComments, $start, $limit); - - return array_map( - function($commentId) { - return self::$comments[$commentId]; - }, - $storyComments - ); - } - - public static function findReplies($commentId, $limit = 5, $afterId = null) - { - $commentReplies = isset(self::$commentReplies[$commentId]) ? self::$commentReplies[$commentId] : []; - - $start = isset($after) ? (int) array_search($afterId, $commentReplies) + 1: 0; - $commentReplies = array_slice($commentReplies, $start, $limit); - - return array_map( - function($replyId) { - return self::$comments[$replyId]; - }, - $commentReplies - ); - } - - public static function countComments($storyId) - { - return isset(self::$storyComments[$storyId]) ? count(self::$storyComments[$storyId]) : 0; - } - - public static function countReplies($commentId) - { - return isset(self::$commentReplies[$commentId]) ? count(self::$commentReplies[$commentId]) : 0; - } - - public static function findStoryMentions($storyId) - { - return isset(self::$storyMentions[$storyId]) ? self::$storyMentions[$storyId] :[]; - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/Image.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/Image.php deleted file mode 100644 index 68a81ba..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Data/Image.php +++ /dev/null @@ -1,29 +0,0 @@ - 'Comment', - 'fields' => function() { - return [ - 'id' => Types::id(), - 'author' => Types::user(), - 'parent' => Types::comment(), - 'isAnonymous' => Types::boolean(), - 'replies' => [ - 'type' => Types::listOf(Types::comment()), - 'args' => [ - 'after' => Types::int(), - 'limit' => [ - 'type' => Types::int(), - 'defaultValue' => 5 - ] - ] - ], - 'totalReplyCount' => Types::int(), - - Types::htmlField('body') - ]; - }, - 'resolveField' => function($value, $args, $context, ResolveInfo $info) { - $method = 'resolve' . ucfirst($info->fieldName); - if (method_exists($this, $method)) { - return $this->{$method}($value, $args, $context, $info); - } else { - return $value->{$info->fieldName}; - } - } - ]; - parent::__construct($config); - } - - public function resolveAuthor(Comment $comment) - { - if ($comment->isAnonymous) { - return null; - } - return DataSource::findUser($comment->authorId); - } - - public function resolveParent(Comment $comment) - { - if ($comment->parentId) { - return DataSource::findComment($comment->parentId); - } - return null; - } - - public function resolveReplies(Comment $comment, $args) - { - $args += ['after' => null]; - return DataSource::findReplies($comment->id, $args['limit'], $args['after']); - } - - public function resolveTotalReplyCount(Comment $comment) - { - return DataSource::countReplies($comment->id); - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ContentFormatEnum.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ContentFormatEnum.php deleted file mode 100644 index 8825247..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ContentFormatEnum.php +++ /dev/null @@ -1,19 +0,0 @@ - 'ContentFormatEnum', - 'values' => [self::FORMAT_TEXT, self::FORMAT_HTML] - ]; - parent::__construct($config); - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ImageSizeEnumType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ImageSizeEnumType.php deleted file mode 100644 index 5e744a6..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Enum/ImageSizeEnumType.php +++ /dev/null @@ -1,23 +0,0 @@ - [ - 'ICON' => Image::SIZE_ICON, - 'SMALL' => Image::SIZE_SMALL, - 'MEDIUM' => Image::SIZE_MEDIUM, - 'ORIGINAL' => Image::SIZE_ORIGINAL - ] - ]; - - parent::__construct($config); - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Field/HtmlField.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Field/HtmlField.php deleted file mode 100644 index f15ba6b..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Field/HtmlField.php +++ /dev/null @@ -1,52 +0,0 @@ - $name, - 'type' => Types::string(), - 'args' => [ - 'format' => [ - 'type' => Types::contentFormatEnum(), - 'defaultValue' => ContentFormatEnum::FORMAT_HTML - ], - 'maxLength' => Types::int() - ], - 'resolve' => function($object, $args) use ($objectKey) { - $html = $object->{$objectKey}; - $text = strip_tags($html); - - if (!empty($args['maxLength'])) { - $safeText = mb_substr($text, 0, $args['maxLength']); - } else { - $safeText = $text; - } - - switch ($args['format']) { - case ContentFormatEnum::FORMAT_HTML: - if ($safeText !== $text) { - // Text was truncated, so just show what's safe: - return nl2br($safeText); - } else { - return $html; - } - - case ContentFormatEnum::FORMAT_TEXT: - default: - return $safeText; - } - } - ]; - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/ImageType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/ImageType.php deleted file mode 100644 index aef9bff..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/ImageType.php +++ /dev/null @@ -1,62 +0,0 @@ - 'ImageType', - 'fields' => [ - 'id' => Types::id(), - 'type' => new EnumType([ - 'name' => 'ImageTypeEnum', - 'values' => [ - 'USERPIC' => Image::TYPE_USERPIC - ] - ]), - 'size' => Types::imageSizeEnum(), - 'width' => Types::int(), - 'height' => Types::int(), - 'url' => [ - 'type' => Types::url(), - 'resolve' => [$this, 'resolveUrl'] - ], - - // Just for the sake of example - 'fieldWithError' => [ - 'type' => Types::string(), - 'resolve' => function() { - throw new \Exception("Field with exception"); - } - ], - 'nonNullFieldWithError' => [ - 'type' => Types::nonNull(Types::string()), - 'resolve' => function() { - throw new \Exception("Non-null field with exception"); - } - ] - ] - ]; - - parent::__construct($config); - } - - public function resolveUrl(Image $value, $args, AppContext $context) - { - switch ($value->type) { - case Image::TYPE_USERPIC: - $path = "/images/user/{$value->id}-{$value->size}.jpg"; - break; - default: - throw new \UnexpectedValueException("Unexpected image type: " . $value->type); - } - return $context->rootUrl . $path; - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/NodeType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/NodeType.php deleted file mode 100644 index d3be9ed..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/NodeType.php +++ /dev/null @@ -1,34 +0,0 @@ - 'Node', - 'fields' => [ - 'id' => Types::id() - ], - 'resolveType' => [$this, 'resolveNodeType'] - ]; - parent::__construct($config); - } - - public function resolveNodeType($object) - { - if ($object instanceof User) { - return Types::user(); - } else if ($object instanceof Image) { - return Types::image(); - } else if ($object instanceof Story) { - return Types::story(); - } - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/QueryType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/QueryType.php deleted file mode 100644 index ff85577..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/QueryType.php +++ /dev/null @@ -1,97 +0,0 @@ - 'Query', - 'fields' => [ - 'user' => [ - 'type' => Types::user(), - 'description' => 'Returns user by id (in range of 1-5)', - 'args' => [ - 'id' => Types::nonNull(Types::id()) - ] - ], - 'viewer' => [ - 'type' => Types::user(), - 'description' => 'Represents currently logged-in user (for the sake of example - simply returns user with id == 1)' - ], - 'stories' => [ - 'type' => Types::listOf(Types::story()), - 'description' => 'Returns subset of stories posted for this blog', - 'args' => [ - 'after' => [ - 'type' => Types::id(), - 'description' => 'Fetch stories listed after the story with this ID' - ], - 'limit' => [ - 'type' => Types::int(), - 'description' => 'Number of stories to be returned', - 'defaultValue' => 10 - ] - ] - ], - 'lastStoryPosted' => [ - 'type' => Types::story(), - 'description' => 'Returns last story posted for this blog' - ], - 'deprecatedField' => [ - 'type' => Types::string(), - 'deprecationReason' => 'This field is deprecated!' - ], - 'fieldWithException' => [ - 'type' => Types::string(), - 'resolve' => function() { - throw new \Exception("Exception message thrown in field resolver"); - } - ], - 'hello' => Type::string() - ], - 'resolveField' => function($val, $args, $context, ResolveInfo $info) { - return $this->{$info->fieldName}($val, $args, $context, $info); - } - ]; - parent::__construct($config); - } - - public function user($rootValue, $args) - { - return DataSource::findUser($args['id']); - } - - public function viewer($rootValue, $args, AppContext $context) - { - return $context->viewer; - } - - public function stories($rootValue, $args) - { - $args += ['after' => null]; - return DataSource::findStories($args['limit'], $args['after']); - } - - public function lastStoryPosted() - { - return DataSource::findLatestStory(); - } - - public function hello() - { - return 'Your graphql-php endpoint is ready! Use GraphiQL to browse API'; - } - - public function deprecatedField() - { - return 'You can request deprecated field, but it is not displayed in auto-generated documentation by default.'; - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/EmailType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/EmailType.php deleted file mode 100644 index fd78ea7..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/EmailType.php +++ /dev/null @@ -1,70 +0,0 @@ - 'Email', - 'serialize' => [__CLASS__, 'serialize'], - 'parseValue' => [__CLASS__, 'parseValue'], - 'parseLiteral' => [__CLASS__, 'parseLiteral'], - ]); - } - - /** - * Serializes an internal value to include in a response. - * - * @param string $value - * @return string - */ - public static function serialize($value) - { - // Assuming internal representation of email is always correct: - return $value; - - // If it might be incorrect and you want to make sure that only correct values are included in response - - // use following line instead: - // return $this->parseValue($value); - } - - /** - * Parses an externally provided value (query variable) to use as an input - * - * @param mixed $value - * @return mixed - */ - public static function parseValue($value) - { - if (!filter_var($value, FILTER_VALIDATE_EMAIL)) { - throw new \UnexpectedValueException("Cannot represent value as email: " . Utils::printSafe($value)); - } - return $value; - } - - /** - * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input - * - * @param \GraphQL\Language\AST\Node $valueNode - * @return string - * @throws Error - */ - public static function parseLiteral($valueNode) - { - // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL - // error location in query: - if (!$valueNode instanceof StringValueNode) { - throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]); - } - if (!filter_var($valueNode->value, FILTER_VALIDATE_EMAIL)) { - throw new Error("Not a valid email", [$valueNode]); - } - return $valueNode->value; - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/UrlType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/UrlType.php deleted file mode 100644 index 0590546..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/Scalar/UrlType.php +++ /dev/null @@ -1,63 +0,0 @@ -parseValue($value); - } - - /** - * Parses an externally provided value (query variable) to use as an input - * - * @param mixed $value - * @return mixed - * @throws Error - */ - public function parseValue($value) - { - if (!is_string($value) || !filter_var($value, FILTER_VALIDATE_URL)) { // quite naive, but after all this is example - throw new Error("Cannot represent value as URL: " . Utils::printSafe($value)); - } - return $value; - } - - /** - * Parses an externally provided literal value to use as an input (e.g. in Query AST) - * - * @param Node $valueNode - * @param array|null $variables - * @return null|string - * @throws Error - */ - public function parseLiteral($valueNode, array $variables = null) - { - // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL - // error location in query: - if (!($valueNode instanceof StringValueNode)) { - throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, [$valueNode]); - } - if (!is_string($valueNode->value) || !filter_var($valueNode->value, FILTER_VALIDATE_URL)) { - throw new Error('Query error: Not a valid URL', [$valueNode]); - } - return $valueNode->value; - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/SearchResultType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/SearchResultType.php deleted file mode 100644 index d832a26..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/SearchResultType.php +++ /dev/null @@ -1,31 +0,0 @@ - 'SearchResultType', - 'types' => function() { - return [ - Types::story(), - Types::user() - ]; - }, - 'resolveType' => function($value) { - if ($value instanceof Story) { - return Types::story(); - } else if ($value instanceof User) { - return Types::user(); - } - } - ]; - parent::__construct($config); - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/StoryType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/StoryType.php deleted file mode 100644 index 32cea4e..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/StoryType.php +++ /dev/null @@ -1,127 +0,0 @@ - 'Story', - 'fields' => function() { - return [ - 'id' => Types::id(), - 'author' => Types::user(), - 'mentions' => Types::listOf(Types::mention()), - 'totalCommentCount' => Types::int(), - 'comments' => [ - 'type' => Types::listOf(Types::comment()), - 'args' => [ - 'after' => [ - 'type' => Types::id(), - 'description' => 'Load all comments listed after given comment ID' - ], - 'limit' => [ - 'type' => Types::int(), - 'defaultValue' => 5 - ] - ] - ], - 'likes' => [ - 'type' => Types::listOf(Types::user()), - 'args' => [ - 'limit' => [ - 'type' => Types::int(), - 'description' => 'Limit the number of recent likes returned', - 'defaultValue' => 5 - ] - ] - ], - 'likedBy' => [ - 'type' => Types::listOf(Types::user()), - ], - 'affordances' => Types::listOf(new EnumType([ - 'name' => 'StoryAffordancesEnum', - 'values' => [ - self::EDIT, - self::DELETE, - self::LIKE, - self::UNLIKE, - self::REPLY - ] - ])), - 'hasViewerLiked' => Types::boolean(), - - Types::htmlField('body'), - ]; - }, - 'interfaces' => [ - Types::node() - ], - 'resolveField' => function($value, $args, $context, ResolveInfo $info) { - $method = 'resolve' . ucfirst($info->fieldName); - if (method_exists($this, $method)) { - return $this->{$method}($value, $args, $context, $info); - } else { - return $value->{$info->fieldName}; - } - } - ]; - parent::__construct($config); - } - - public function resolveAuthor(Story $story) - { - return DataSource::findUser($story->authorId); - } - - public function resolveAffordances(Story $story, $args, AppContext $context) - { - $isViewer = $context->viewer === DataSource::findUser($story->authorId); - $isLiked = DataSource::isLikedBy($story->id, $context->viewer->id); - - if ($isViewer) { - $affordances[] = self::EDIT; - $affordances[] = self::DELETE; - } - if ($isLiked) { - $affordances[] = self::UNLIKE; - } else { - $affordances[] = self::LIKE; - } - return $affordances; - } - - public function resolveHasViewerLiked(Story $story, $args, AppContext $context) - { - return DataSource::isLikedBy($story->id, $context->viewer->id); - } - - public function resolveTotalCommentCount(Story $story) - { - return DataSource::countComments($story->id); - } - - public function resolveComments(Story $story, $args) - { - $args += ['after' => null]; - return DataSource::findComments($story->id, $args['limit'], $args['after']); - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/UserType.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/UserType.php deleted file mode 100644 index 9960b62..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Type/UserType.php +++ /dev/null @@ -1,68 +0,0 @@ - 'User', - 'description' => 'Our blog authors', - 'fields' => function() { - return [ - 'id' => Types::id(), - 'email' => Types::email(), - 'photo' => [ - 'type' => Types::image(), - 'description' => 'User photo URL', - 'args' => [ - 'size' => Types::nonNull(Types::imageSizeEnum()), - ] - ], - 'firstName' => [ - 'type' => Types::string(), - ], - 'lastName' => [ - 'type' => Types::string(), - ], - 'lastStoryPosted' => Types::story(), - 'fieldWithError' => [ - 'type' => Types::string(), - 'resolve' => function() { - throw new \Exception("This is error field"); - } - ] - ]; - }, - 'interfaces' => [ - Types::node() - ], - 'resolveField' => function($value, $args, $context, ResolveInfo $info) { - $method = 'resolve' . ucfirst($info->fieldName); - if (method_exists($this, $method)) { - return $this->{$method}($value, $args, $context, $info); - } else { - return $value->{$info->fieldName}; - } - } - ]; - parent::__construct($config); - } - - public function resolvePhoto(User $user, $args) - { - return DataSource::getUserPhoto($user->id, $args['size']); - } - - public function resolveLastStoryPosted(User $user) - { - return DataSource::findLastStoryFor($user->id); - } -} diff --git a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Types.php b/vendor/webonyx/graphql-php/examples/01-blog/Blog/Types.php deleted file mode 100644 index 7ffc657..0000000 --- a/vendor/webonyx/graphql-php/examples/01-blog/Blog/Types.php +++ /dev/null @@ -1,209 +0,0 @@ -viewer = DataSource::findUser('1'); // simulated "currently logged-in user" - $appContext->rootUrl = 'http://localhost:8080'; - $appContext->request = $_REQUEST; - - // Parse incoming query and variables - if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) { - $raw = file_get_contents('php://input') ?: ''; - $data = json_decode($raw, true) ?: []; - } else { - $data = $_REQUEST; - } - - $data += ['query' => null, 'variables' => null]; - - if (null === $data['query']) { - $data['query'] = '{hello}'; - } - - // GraphQL schema to be passed to query executor: - $schema = new Schema([ - 'query' => Types::query() - ]); - - $result = GraphQL::executeQuery( - $schema, - $data['query'], - null, - $appContext, - (array) $data['variables'] - ); - $output = $result->toArray($debug); - $httpStatus = 200; -} catch (\Exception $error) { - $httpStatus = 500; - $output['errors'] = [ - FormattedError::createFromException($error, $debug) - ]; -} - -header('Content-Type: application/json', true, $httpStatus); -echo json_encode($output); diff --git a/vendor/webonyx/graphql-php/examples/02-shorthand/README.md b/vendor/webonyx/graphql-php/examples/02-shorthand/README.md deleted file mode 100644 index dd7cfca..0000000 --- a/vendor/webonyx/graphql-php/examples/02-shorthand/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Parsing GraphQL IDL shorthand - -Same as the Hello world example but shows how to build GraphQL schema from shorthand -and wire up some resolvers - -### Run locally -``` -php -S localhost:8080 ./graphql.php -``` - -### Try query -``` -curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }' -``` - -### Try mutation -``` -curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }' -``` diff --git a/vendor/webonyx/graphql-php/examples/02-shorthand/graphql.php b/vendor/webonyx/graphql-php/examples/02-shorthand/graphql.php deleted file mode 100644 index e958955..0000000 --- a/vendor/webonyx/graphql-php/examples/02-shorthand/graphql.php +++ /dev/null @@ -1,31 +0,0 @@ - [ - 'message' => $e->getMessage() - ] - ]; -} -header('Content-Type: application/json; charset=UTF-8'); -echo json_encode($result); - diff --git a/vendor/webonyx/graphql-php/examples/02-shorthand/rootvalue.php b/vendor/webonyx/graphql-php/examples/02-shorthand/rootvalue.php deleted file mode 100644 index 97e0a82..0000000 --- a/vendor/webonyx/graphql-php/examples/02-shorthand/rootvalue.php +++ /dev/null @@ -1,35 +0,0 @@ - function($root, $args, $context) { - $sum = new Addition(); - - return $sum->resolve($root, $args, $context); - }, - 'echo' => function($root, $args, $context) { - $echo = new Echoer(); - - return $echo->resolve($root, $args, $context); - }, - 'prefix' => 'You said: ', -]; diff --git a/vendor/webonyx/graphql-php/examples/02-shorthand/schema.graphqls b/vendor/webonyx/graphql-php/examples/02-shorthand/schema.graphqls deleted file mode 100644 index a8f11d2..0000000 --- a/vendor/webonyx/graphql-php/examples/02-shorthand/schema.graphqls +++ /dev/null @@ -1,13 +0,0 @@ -schema { - query: Query - mutation: Calc -} - -type Calc { - sum(x: Int, y: Int): Int -} - -type Query { - echo(message: String): String -} - diff --git a/vendor/webonyx/graphql-php/examples/03-server/README.md b/vendor/webonyx/graphql-php/examples/03-server/README.md deleted file mode 100644 index 4737d6e..0000000 --- a/vendor/webonyx/graphql-php/examples/03-server/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Hello world -Same example as 01-hello-world, but uses -[Standard Http Server](http://webonyx.github.io/graphql-php/executing-queries/#using-server) -instead of manual parsing of incoming data. - -### Run locally -``` -php -S localhost:8080 ./graphql.php -``` - -### Try query -``` -curl -d '{"query": "query { echo(message: \"Hello World\") }" }' -H "Content-Type: application/json" http://localhost:8080 -``` - -### Try mutation -``` -curl -d '{"query": "mutation { sum(x: 2, y: 2) }" }' -H "Content-Type: application/json" http://localhost:8080 -``` diff --git a/vendor/webonyx/graphql-php/examples/03-server/graphql.php b/vendor/webonyx/graphql-php/examples/03-server/graphql.php deleted file mode 100644 index 0c01195..0000000 --- a/vendor/webonyx/graphql-php/examples/03-server/graphql.php +++ /dev/null @@ -1,61 +0,0 @@ - 'Query', - 'fields' => [ - 'echo' => [ - 'type' => Type::string(), - 'args' => [ - 'message' => ['type' => Type::string()], - ], - 'resolve' => function ($root, $args) { - return $root['prefix'] . $args['message']; - } - ], - ], - ]); - - $mutationType = new ObjectType([ - 'name' => 'Calc', - 'fields' => [ - 'sum' => [ - 'type' => Type::int(), - 'args' => [ - 'x' => ['type' => Type::int()], - 'y' => ['type' => Type::int()], - ], - 'resolve' => function ($root, $args) { - return $args['x'] + $args['y']; - }, - ], - ], - ]); - - // See docs on schema options: - // http://webonyx.github.io/graphql-php/type-system/schema/#configuration-options - $schema = new Schema([ - 'query' => $queryType, - 'mutation' => $mutationType, - ]); - - // See docs on server options: - // http://webonyx.github.io/graphql-php/executing-queries/#server-configuration-options - $server = new StandardServer([ - 'schema' => $schema - ]); - - $server->handleRequest(); -} catch (\Exception $e) { - StandardServer::send500Error($e); -} diff --git a/vendor/webonyx/graphql-php/phpstan-baseline.neon b/vendor/webonyx/graphql-php/phpstan-baseline.neon new file mode 100644 index 0000000..95ca993 --- /dev/null +++ b/vendor/webonyx/graphql-php/phpstan-baseline.neon @@ -0,0 +1,652 @@ +parameters: + ignoreErrors: + - + message: "#^Variable property access on object\\.$#" + count: 2 + path: src/Executor/Executor.php + + - + message: "#^Variable property access on object\\.$#" + count: 2 + path: src/Experimental/Executor/CoroutineExecutor.php + + - + message: "#^Variable property access on mixed\\.$#" + count: 1 + path: src/Experimental/Executor/CoroutineExecutor.php + + - + message: "#^Variable property access on GraphQL\\\\Language\\\\AST\\\\Node\\.$#" + count: 1 + path: src/Language/AST/Node.php + + - + message: "#^Method GraphQL\\\\Language\\\\AST\\\\NodeList\\:\\:splice\\(\\) should return GraphQL\\\\Language\\\\AST\\\\NodeList\\ but returns GraphQL\\\\Language\\\\AST\\\\NodeList\\\\.$#" + count: 1 + path: src/Language/AST/NodeList.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\ given\\.$#" + count: 1 + path: src/Language/Visitor.php + + - + message: "#^Variable property access on GraphQL\\\\Language\\\\AST\\\\Node\\|null\\.$#" + count: 1 + path: src/Language/Visitor.php + + - + message: "#^Variable property access on GraphQL\\\\Language\\\\AST\\\\Node\\.$#" + count: 1 + path: src/Language/Visitor.php + + - + message: "#^Only booleans are allowed in a negated boolean, \\(callable\\)\\|null given\\.$#" + count: 1 + path: src/Language/Visitor.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, \\(callable\\)\\|null given\\.$#" + count: 2 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in an if condition, int given\\.$#" + count: 1 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in a negated boolean, string given\\.$#" + count: 2 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in &&, string given on the left side\\.$#" + count: 1 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in &&, string given on the right side\\.$#" + count: 1 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, string given\\.$#" + count: 1 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in an if condition, \\(callable\\)\\|null given\\.$#" + count: 1 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in \\|\\|, \\(callable\\)\\|null given on the left side\\.$#" + count: 1 + path: src/Server/Helper.php + + - + message: "#^Only booleans are allowed in a negated boolean, ArrayObject\\ given\\.$#" + count: 1 + path: src/Type/Definition/EnumType.php + + - + message: "#^Variable property access on \\$this\\(GraphQL\\\\Type\\\\Definition\\\\FieldDefinition\\)\\.$#" + count: 3 + path: src/Type/Definition/FieldDefinition.php + + - + message: "#^Variable property access on \\$this\\(GraphQL\\\\Type\\\\Definition\\\\InputObjectField\\)\\.$#" + count: 4 + path: src/Type/Definition/InputObjectField.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\SelectionSetNode\\|null given\\.$#" + count: 1 + path: src/Type/Definition/QueryPlan.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\SelectionSetNode\\|null given\\.$#" + count: 1 + path: src/Type/Definition/QueryPlan.php + + - + message: "#^Only booleans are allowed in an if condition, string given\\.$#" + count: 1 + path: src/Type/Definition/Type.php + + - + message: "#^Only booleans are allowed in a negated boolean, string\\|null given\\.$#" + count: 2 + path: src/Type/Introspection.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\\\|\\(callable\\) given\\.$#" + count: 1 + path: src/Type/Schema.php + + - + message: "#^Only booleans are allowed in an if condition, \\(callable\\)\\|null given\\.$#" + count: 1 + path: src/Type/Schema.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\Type\\|null given\\.$#" + count: 1 + path: src/Type/Schema.php + + - + message: "#^Only booleans are allowed in an if condition, array\\ given\\.$#" + count: 1 + path: src/Type/Schema.php + + - + message: "#^Only booleans are allowed in a negated boolean, \\(callable\\)\\|null given\\.$#" + count: 1 + path: src/Type/Schema.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\ObjectType\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in &&, GraphQL\\\\Type\\\\Definition\\\\ObjectType\\|null given on the left side\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in &&, array\\\\|GraphQL\\\\Language\\\\AST\\\\Node\\|GraphQL\\\\Language\\\\AST\\\\TypeDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\TypeNode\\|null given on the left side\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\OperationTypeDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Type\\\\Definition\\\\Type given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Error\\\\Error\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\InputValueDefinitionNode given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\DirectiveDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in &&, array\\ given on the left side\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\DirectiveDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\EnumTypeDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\InputObjectTypeDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\InterfaceTypeDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\ObjectTypeDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\SchemaDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\UnionTypeDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, array\\ given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\InterfaceTypeDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\InterfaceTypeExtensionNode\\|GraphQL\\\\Language\\\\AST\\\\ObjectTypeDefinitionNode\\|GraphQL\\\\Language\\\\AST\\\\ObjectTypeExtensionNode given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\FieldDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in &&, GraphQL\\\\Language\\\\AST\\\\FieldDefinitionNode\\|null given on the left side\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in &&, GraphQL\\\\Language\\\\AST\\\\NodeList\\ given on the right side\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\InputValueDefinitionNode\\|null given\\.$#" + count: 2 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\FieldDefinition\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\FieldArgument\\|null given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in \\|\\|, GraphQL\\\\Type\\\\Definition\\\\FieldArgument\\|null given on the left side\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\ given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\ given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in &&, array\\ given on the left side\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\ given\\.$#" + count: 1 + path: src/Type/SchemaValidationContext.php + + - + message: "#^Variable property access on mixed\\.$#" + count: 2 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\BooleanValueNode\\|GraphQL\\\\Language\\\\AST\\\\EnumValueNode\\|GraphQL\\\\Language\\\\AST\\\\FloatValueNode\\|GraphQL\\\\Language\\\\AST\\\\IntValueNode\\|GraphQL\\\\Language\\\\AST\\\\ListValueNode\\|GraphQL\\\\Language\\\\AST\\\\NullValueNode\\|GraphQL\\\\Language\\\\AST\\\\ObjectValueNode\\|GraphQL\\\\Language\\\\AST\\\\StringValueNode\\|null given\\.$#" + count: 2 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\|null given\\.$#" + count: 1 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\EnumValueDefinition\\|null given\\.$#" + count: 1 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in &&, array\\|null given on the left side\\.$#" + count: 1 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Type\\\\Definition\\\\Type\\|null given\\.$#" + count: 2 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\NodeList\\ given\\.$#" + count: 1 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in a negated boolean, string\\|null given\\.$#" + count: 1 + path: src/Utils/AST.php + + - + message: "#^Only booleans are allowed in an if condition, callable given\\.$#" + count: 1 + path: src/Utils/ASTDefinitionBuilder.php + + - + message: "#^Only booleans are allowed in &&, array\\\\|null given on the left side\\.$#" + count: 1 + path: src/Utils/PairSet.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Type\\\\Definition\\\\Type\\|null given\\.$#" + count: 1 + path: src/Utils/SchemaExtender.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\SchemaDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Utils/SchemaExtender.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\\\|null given\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\Type\\|null given\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in an if condition, \\(GraphQL\\\\Type\\\\Definition\\\\CompositeType&GraphQL\\\\Type\\\\Definition\\\\Type\\)\\|null given\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Type\\\\Definition\\\\FieldDefinition\\|null given\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\NamedTypeNode given\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Type\\\\Definition\\\\Directive\\|GraphQL\\\\Type\\\\Definition\\\\FieldDefinition\\|null given\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in &&, GraphQL\\\\Type\\\\Definition\\\\FieldArgument\\|null given on the left side\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Type\\\\Definition\\\\InputObjectField\\|null given\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Only booleans are allowed in &&, GraphQL\\\\Type\\\\Definition\\\\InputObjectField\\|null given on the left side\\.$#" + count: 1 + path: src/Utils/TypeInfo.php + + - + message: "#^Variable property access on object\\.$#" + count: 1 + path: src/Utils/Utils.php + + - + message: "#^Only booleans are allowed in a negated boolean, string given\\.$#" + count: 1 + path: src/Utils/Utils.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Error\\\\Error\\|null given\\.$#" + count: 1 + path: src/Utils/Utils.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Type\\\\Definition\\\\EnumValueDefinition\\|null given\\.$#" + count: 1 + path: src/Utils/Value.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, array\\ given\\.$#" + count: 2 + path: src/Utils/Value.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, array\\ given\\.$#" + count: 2 + path: src/Utils/Value.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, string given\\.$#" + count: 2 + path: src/Utils/Value.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, string\\|null given\\.$#" + count: 1 + path: src/Utils/Value.php + + - + message: "#^Only booleans are allowed in a negated boolean, \\(GraphQL\\\\Type\\\\Definition\\\\CompositeType&GraphQL\\\\Type\\\\Definition\\\\Type\\)\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/FieldsOnCorrectType.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Type\\\\Definition\\\\FieldDefinition given\\.$#" + count: 1 + path: src/Validator/Rules/FieldsOnCorrectType.php + + - + message: "#^Only booleans are allowed in an if condition, array\\ given\\.$#" + count: 1 + path: src/Validator/Rules/FieldsOnCorrectType.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\NamedTypeNode given\\.$#" + count: 1 + path: src/Validator/Rules/FragmentsOnCompositeTypes.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\Type\\|null given\\.$#" + count: 2 + path: src/Validator/Rules/FragmentsOnCompositeTypes.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Type\\\\Schema\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/KnownDirectives.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/KnownDirectives.php + + - + message: "#^Only booleans are allowed in a negated boolean, string given\\.$#" + count: 1 + path: src/Validator/Rules/KnownDirectives.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\FragmentDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/KnownFragmentNames.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\FragmentDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/NoFragmentCycles.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\NameNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/OverlappingFieldsCanBeMerged.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\NamedTypeNode given\\.$#" + count: 1 + path: src/Validator/Rules/OverlappingFieldsCanBeMerged.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\|null given\\.$#" + count: 2 + path: src/Validator/Rules/OverlappingFieldsCanBeMerged.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\ArgumentNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/OverlappingFieldsCanBeMerged.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\Node given\\.$#" + count: 2 + path: src/Validator/Rules/OverlappingFieldsCanBeMerged.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\FragmentDefinitionNode\\|null given\\.$#" + count: 3 + path: src/Validator/Rules/OverlappingFieldsCanBeMerged.php + + - + message: "#^Only booleans are allowed in a negated boolean, \\(GraphQL\\\\Type\\\\Definition\\\\CompositeType&GraphQL\\\\Type\\\\Definition\\\\Type\\)\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/PossibleFragmentSpreads.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\FragmentDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/PossibleFragmentSpreads.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\FieldDefinition given\\.$#" + count: 1 + path: src/Validator/Rules/ProvidedRequiredArguments.php + + - + message: "#^Only booleans are allowed in \\|\\|, GraphQL\\\\Language\\\\AST\\\\ArgumentNode\\|null given on the left side\\.$#" + count: 1 + path: src/Validator/Rules/ProvidedRequiredArguments.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Type\\\\Schema\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/ProvidedRequiredArgumentsOnDirectives.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/ProvidedRequiredArgumentsOnDirectives.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\FragmentDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/QuerySecurityRule.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Language\\\\AST\\\\NameNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/QuerySecurityRule.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\OutputType\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/ScalarLeafs.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\SelectionSetNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/ScalarLeafs.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\SelectionSetNode\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/ScalarLeafs.php + + - + message: "#^Only booleans are allowed in \\|\\|, GraphQL\\\\Type\\\\Definition\\\\EnumType\\|GraphQL\\\\Type\\\\Definition\\\\InputObjectType\\|GraphQL\\\\Type\\\\Definition\\\\ListOfType\\|GraphQL\\\\Type\\\\Definition\\\\NonNull\\|GraphQL\\\\Type\\\\Definition\\\\ScalarType given on the left side\\.$#" + count: 1 + path: src/Validator/Rules/ValuesOfCorrectType.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\EnumValueDefinition\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/ValuesOfCorrectType.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\EnumType\\|GraphQL\\\\Type\\\\Definition\\\\InputObjectType\\|GraphQL\\\\Type\\\\Definition\\\\ListOfType\\|GraphQL\\\\Type\\\\Definition\\\\NonNull\\|GraphQL\\\\Type\\\\Definition\\\\ScalarType given\\.$#" + count: 1 + path: src/Validator/Rules/ValuesOfCorrectType.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, array\\ given\\.$#" + count: 1 + path: src/Validator/Rules/ValuesOfCorrectType.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\Type\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/VariablesAreInputTypes.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\Type\\|null given\\.$#" + count: 1 + path: src/Validator/Rules/VariablesInAllowedPosition.php + + - + message: "#^Only booleans are allowed in &&, GraphQL\\\\Language\\\\AST\\\\ValueNode\\|null given on the left side\\.$#" + count: 1 + path: src/Validator/Rules/VariablesInAllowedPosition.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Language\\\\AST\\\\FragmentDefinitionNode\\|null given\\.$#" + count: 1 + path: src/Validator/ValidationContext.php + + - + message: "#^Only booleans are allowed in an if condition, GraphQL\\\\Language\\\\AST\\\\SelectionSetNode\\|null given\\.$#" + count: 1 + path: src/Validator/ValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, array\\ given\\.$#" + count: 1 + path: src/Validator/ValidationContext.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Schema given\\.$#" + count: 1 + path: tests/Executor/DirectivesTest.php + + - + message: "#^Anonymous function should have native return typehint \"class@anonymous/tests/Executor/ExecutorTest\\.php\\:1329\"\\.$#" + count: 1 + path: tests/Executor/ExecutorTest.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\InterfaceType given\\.$#" + count: 1 + path: tests/Executor/LazyInterfaceTest.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Definition\\\\ObjectType given\\.$#" + count: 1 + path: tests/Executor/LazyInterfaceTest.php + + - + message: "#^Only booleans are allowed in a negated boolean, GraphQL\\\\Type\\\\Schema given\\.$#" + count: 1 + path: tests/Executor/ValuesTest.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, \\(GraphQL\\\\Type\\\\Definition\\\\CompositeType&GraphQL\\\\Type\\\\Definition\\\\Type\\)\\|null given\\.$#" + count: 4 + path: tests/Language/VisitorTest.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, \\(GraphQL\\\\Type\\\\Definition\\\\OutputType&GraphQL\\\\Type\\\\Definition\\\\Type\\)\\|null given\\.$#" + count: 4 + path: tests/Language/VisitorTest.php + + - + message: "#^Only booleans are allowed in a ternary operator condition, GraphQL\\\\Type\\\\Definition\\\\EnumType\\|GraphQL\\\\Type\\\\Definition\\\\InputObjectType\\|GraphQL\\\\Type\\\\Definition\\\\ListOfType\\|GraphQL\\\\Type\\\\Definition\\\\NonNull\\|GraphQL\\\\Type\\\\Definition\\\\ScalarType\\|null given\\.$#" + count: 4 + path: tests/Language/VisitorTest.php + + - + message: "#^Access to an undefined property GraphQL\\\\Type\\\\Definition\\\\FieldDefinition\\:\\:\\$nonExistentProp\\.$#" + count: 2 + path: tests/Type/DefinitionTest.php + + - + message: "#^Access to an undefined property GraphQL\\\\Type\\\\Definition\\\\InputObjectField\\:\\:\\$nonExistentProp\\.$#" + count: 1 + path: tests/Type/DefinitionTest.php + + - + message: "#^Variable property access on \\$this\\(GraphQL\\\\Tests\\\\Type\\\\TypeLoaderTest\\)\\.$#" + count: 1 + path: tests/Type/TypeLoaderTest.php + + - + message: "#^Only booleans are allowed in a negated boolean, stdClass given\\.$#" + count: 1 + path: tests/Utils/AstFromValueTest.php + diff --git a/vendor/webonyx/graphql-php/phpstan.neon.dist b/vendor/webonyx/graphql-php/phpstan.neon.dist index 02a7a9a..2d8ea20 100644 --- a/vendor/webonyx/graphql-php/phpstan.neon.dist +++ b/vendor/webonyx/graphql-php/phpstan.neon.dist @@ -1,17 +1,47 @@ parameters: - level: 1 + level: 3 + + inferPrivatePropertyTypeFromConstructor: true paths: - %currentWorkingDirectory%/src - %currentWorkingDirectory%/tests + excludes_analyse: + # Ported from dms/phpunit-arraysubset-asserts + - tests/PHPUnit/ArraySubsetAsserts.php + - tests/PHPUnit/Constraint/ArraySubset.php + ignoreErrors: - - "~Construct empty\\(\\) is not allowed\\. Use more strict comparison~" - - "~(Method|Property) .+::.+(\\(\\))? (has parameter \\$\\w+ with no|has no return|has no) typehint specified~" - - "~Variable property access on .+~" - - "~Variable method call on static\\(GraphQL\\\\Server\\\\ServerConfig\\)~" # TODO get rid of + # Since this is a library that is supposed to be flexible, we don't + # want to lock down every possible extension point. + - "~Unsafe usage of new static\\(\\)~" + + # This class uses magic methods to reduce a whole lot of boilerplate required to + # allow partial parsing of language fragments. + - "~Variable method call on GraphQL\\\\Language\\\\Parser\\.~" + + # Those come from graphql-php\tests\Language\VisitorTest.php + - "~Access to an undefined property GraphQL\\\\Language\\\\AST\\\\.+::\\$didEnter~" + - "~Access to an undefined property GraphQL\\\\Language\\\\AST\\\\.+::\\$didLeave~" + - "~Access to an undefined property GraphQL\\\\Language\\\\AST\\\\Node::\\$value~" + + # TODO convert to less magical code + - "~Variable method call on static\\(GraphQL\\\\Server\\\\ServerConfig\\)~" includes: - - vendor/phpstan/phpstan-phpunit/extension.neon - - vendor/phpstan/phpstan-phpunit/rules.neon - - vendor/phpstan/phpstan-strict-rules/rules.neon + - phpstan-baseline.neon + +services: + - + class: GraphQL\Tests\PhpStan\Type\Definition\Type\IsInputTypeStaticMethodTypeSpecifyingExtension + tags: + - phpstan.typeSpecifier.staticMethodTypeSpecifyingExtension + - + class: GraphQL\Tests\PhpStan\Type\Definition\Type\IsOutputTypeStaticMethodTypeSpecifyingExtension + tags: + - phpstan.typeSpecifier.staticMethodTypeSpecifyingExtension + - + class: GraphQL\Tests\PhpStan\Type\Definition\Type\IsCompositeTypeStaticMethodTypeSpecifyingExtension + tags: + - phpstan.typeSpecifier.staticMethodTypeSpecifyingExtension diff --git a/vendor/webonyx/graphql-php/src/Deferred.php b/vendor/webonyx/graphql-php/src/Deferred.php index 6b7bd78..ff79ea6 100644 --- a/vendor/webonyx/graphql-php/src/Deferred.php +++ b/vendor/webonyx/graphql-php/src/Deferred.php @@ -4,62 +4,23 @@ declare(strict_types=1); namespace GraphQL; -use Exception; use GraphQL\Executor\Promise\Adapter\SyncPromise; -use SplQueue; -use Throwable; -class Deferred +class Deferred extends SyncPromise { - /** @var SplQueue|null */ - private static $queue; - - /** @var callable */ - private $callback; - - /** @var SyncPromise */ - public $promise; - - public function __construct(callable $callback) + /** + * @param callable() : mixed $executor + */ + public static function create(callable $executor) : self { - $this->callback = $callback; - $this->promise = new SyncPromise(); - self::getQueue()->enqueue($this); + return new self($executor); } - public static function getQueue() : SplQueue + /** + * @param callable() : mixed $executor + */ + public function __construct(callable $executor) { - if (self::$queue === null) { - self::$queue = new SplQueue(); - } - - return self::$queue; - } - - public static function runQueue() : void - { - $queue = self::getQueue(); - while (! $queue->isEmpty()) { - /** @var self $dequeuedNodeValue */ - $dequeuedNodeValue = $queue->dequeue(); - $dequeuedNodeValue->run(); - } - } - - public function then($onFulfilled = null, $onRejected = null) - { - return $this->promise->then($onFulfilled, $onRejected); - } - - public function run() : void - { - try { - $cb = $this->callback; - $this->promise->resolve($cb()); - } catch (Exception $e) { - $this->promise->reject($e); - } catch (Throwable $e) { - $this->promise->reject($e); - } + parent::__construct($executor); } } diff --git a/vendor/webonyx/graphql-php/src/Error/Debug.php b/vendor/webonyx/graphql-php/src/Error/Debug.php deleted file mode 100644 index a48b81f..0000000 --- a/vendor/webonyx/graphql-php/src/Error/Debug.php +++ /dev/null @@ -1,16 +0,0 @@ -source = $source; $this->positions = $positions; $this->path = $path; - $this->extensions = $extensions ?: ( - $previous && $previous instanceof self + $this->extensions = count($extensions) > 0 ? $extensions : ( + $previous instanceof self ? $previous->extensions : [] ); if ($previous instanceof ClientAware) { $this->isClientSafe = $previous->isClientSafe(); - $this->category = $previous->getCategory() ?: self::CATEGORY_INTERNAL; - } elseif ($previous) { + $cat = $previous->getCategory(); + $this->category = $cat === '' || $cat === null ? self::CATEGORY_INTERNAL: $cat; + } elseif ($previous !== null) { $this->isClientSafe = false; $this->category = self::CATEGORY_INTERNAL; } else { @@ -146,25 +145,27 @@ class Error extends Exception implements JsonSerializable, ClientAware public static function createLocatedError($error, $nodes = null, $path = null) { if ($error instanceof self) { - if ($error->path && $error->nodes) { + if ($error->path !== null && $error->nodes !== null && count($error->nodes) !== 0) { return $error; } - $nodes = $nodes ?: $error->nodes; - $path = $path ?: $error->path; + $nodes = $nodes ?? $error->nodes; + $path = $path ?? $error->path; } - $source = $positions = $originalError = null; - $extensions = []; + $source = null; + $originalError = null; + $positions = []; + $extensions = []; if ($error instanceof self) { $message = $error->getMessage(); $originalError = $error; - $nodes = $error->nodes ?: $nodes; + $nodes = $error->nodes ?? $nodes; $source = $error->source; $positions = $error->positions; $extensions = $error->extensions; - } elseif ($error instanceof Exception || $error instanceof Throwable) { + } elseif ($error instanceof Throwable) { $message = $error->getMessage(); $originalError = $error; } else { @@ -172,7 +173,7 @@ class Error extends Exception implements JsonSerializable, ClientAware } return new static( - $message ?: 'An unknown error occurred.', + $message === '' || $message === null ? 'An unknown error occurred.' : $message, $nodes, $source, $positions, @@ -206,13 +207,10 @@ class Error extends Exception implements JsonSerializable, ClientAware return $this->category; } - /** - * @return Source|null - */ - public function getSource() + public function getSource() : ?Source { if ($this->source === null) { - if (! empty($this->nodes[0]) && ! empty($this->nodes[0]->loc)) { + if (isset($this->nodes[0]) && $this->nodes[0]->loc !== null) { $this->source = $this->nodes[0]->loc->source; } } @@ -223,11 +221,11 @@ class Error extends Exception implements JsonSerializable, ClientAware /** * @return int[] */ - public function getPositions() + public function getPositions() : array { - if ($this->positions === null && ! empty($this->nodes)) { + if (count($this->positions) === 0 && count($this->nodes ?? []) > 0) { $positions = array_map( - static function ($node) { + static function ($node) : ?int { return isset($node->loc) ? $node->loc->start : null; }, $this->nodes @@ -235,7 +233,7 @@ class Error extends Exception implements JsonSerializable, ClientAware $positions = array_filter( $positions, - static function ($p) { + static function ($p) : bool { return $p !== null; } ); @@ -261,27 +259,29 @@ class Error extends Exception implements JsonSerializable, ClientAware * * @api */ - public function getLocations() + public function getLocations() : array { - if ($this->locations === null) { + if (! isset($this->locations)) { $positions = $this->getPositions(); $source = $this->getSource(); $nodes = $this->nodes; - if ($positions && $source) { + if ($source !== null && count($positions) !== 0) { $this->locations = array_map( - static function ($pos) use ($source) { + static function ($pos) use ($source) : SourceLocation { return $source->getLocation($pos); }, $positions ); - } elseif ($nodes) { + } elseif ($nodes !== null && count($nodes) !== 0) { $locations = array_filter( array_map( - static function ($node) { - if ($node->loc && $node->loc->source) { + static function ($node) : ?SourceLocation { + if (isset($node->loc->source)) { return $node->loc->source->getLocation($node->loc->start); } + + return null; }, $nodes ) @@ -330,6 +330,8 @@ class Error extends Exception implements JsonSerializable, ClientAware * @deprecated Use FormattedError::createFromException() instead * * @return mixed[] + * + * @codeCoverageIgnore */ public function toSerializableArray() { @@ -339,18 +341,18 @@ class Error extends Exception implements JsonSerializable, ClientAware $locations = Utils::map( $this->getLocations(), - static function (SourceLocation $loc) { + static function (SourceLocation $loc) : array { return $loc->toSerializableArray(); } ); - if (! empty($locations)) { + if (count($locations) > 0) { $arr['locations'] = $locations; } - if (! empty($this->path)) { + if (count($this->path ?? []) > 0) { $arr['path'] = $this->path; } - if (! empty($this->extensions)) { + if (count($this->extensions ?? []) > 0) { $arr['extensions'] = $this->extensions; } diff --git a/vendor/webonyx/graphql-php/src/Error/FormattedError.php b/vendor/webonyx/graphql-php/src/Error/FormattedError.php index 799ee74..4748b69 100644 --- a/vendor/webonyx/graphql-php/src/Error/FormattedError.php +++ b/vendor/webonyx/graphql-php/src/Error/FormattedError.php @@ -6,7 +6,6 @@ namespace GraphQL\Error; use Countable; use ErrorException; -use Exception; use GraphQL\Language\AST\Node; use GraphQL\Language\Source; use GraphQL\Language\SourceLocation; @@ -67,10 +66,10 @@ class FormattedError public static function printError(Error $error) { $printedLocations = []; - if ($error->nodes) { + if (count($error->nodes ?? []) !== 0) { /** @var Node $node */ foreach ($error->nodes as $node) { - if (! $node->loc) { + if ($node->loc === null) { continue; } @@ -83,14 +82,14 @@ class FormattedError $node->loc->source->getLocation($node->loc->start) ); } - } elseif ($error->getSource() && $error->getLocations()) { + } elseif ($error->getSource() !== null && count($error->getLocations()) !== 0) { $source = $error->getSource(); - foreach ($error->getLocations() as $location) { + foreach (($error->getLocations() ?? []) as $location) { $printedLocations[] = self::highlightSourceAtLocation($source, $location); } } - return ! $printedLocations + return count($printedLocations) === 0 ? $error->getMessage() : implode("\n\n", array_merge([$error->getMessage()], $printedLocations)) . "\n"; } @@ -162,11 +161,9 @@ class FormattedError * This method only exposes exception message when exception implements ClientAware interface * (or when debug flags are passed). * - * For a list of available debug flags see GraphQL\Error\Debug constants. + * For a list of available debug flags @see \GraphQL\Error\DebugFlag constants. * - * @param Throwable $e - * @param bool|int $debug - * @param string $internalErrorMessage + * @param string $internalErrorMessage * * @return mixed[] * @@ -174,21 +171,15 @@ class FormattedError * * @api */ - public static function createFromException($e, $debug = false, $internalErrorMessage = null) + public static function createFromException(Throwable $exception, int $debug = DebugFlag::NONE, $internalErrorMessage = null) : array { - Utils::invariant( - $e instanceof Exception || $e instanceof Throwable, - 'Expected exception, got %s', - Utils::getVariableType($e) - ); + $internalErrorMessage = $internalErrorMessage ?? self::$internalErrorMessage; - $internalErrorMessage = $internalErrorMessage ?: self::$internalErrorMessage; - - if ($e instanceof ClientAware) { + if ($exception instanceof ClientAware) { $formattedError = [ - 'message' => $e->isClientSafe() ? $e->getMessage() : $internalErrorMessage, + 'message' => $exception->isClientSafe() ? $exception->getMessage() : $internalErrorMessage, 'extensions' => [ - 'category' => $e->getCategory(), + 'category' => $exception->getCategory(), ], ]; } else { @@ -200,26 +191,27 @@ class FormattedError ]; } - if ($e instanceof Error) { + if ($exception instanceof Error) { $locations = Utils::map( - $e->getLocations(), - static function (SourceLocation $loc) { + $exception->getLocations(), + static function (SourceLocation $loc) : array { return $loc->toSerializableArray(); } ); - if (! empty($locations)) { + if (count($locations) > 0) { $formattedError['locations'] = $locations; } - if (! empty($e->path)) { - $formattedError['path'] = $e->path; + + if (count($exception->path ?? []) > 0) { + $formattedError['path'] = $exception->path; } - if (! empty($e->getExtensions())) { - $formattedError['extensions'] = $e->getExtensions() + $formattedError['extensions']; + if (count($exception->getExtensions() ?? []) > 0) { + $formattedError['extensions'] = $exception->getExtensions() + $formattedError['extensions']; } } - if ($debug) { - $formattedError = self::addDebugEntries($formattedError, $e, $debug); + if ($debug !== DebugFlag::NONE) { + $formattedError = self::addDebugEntries($formattedError, $exception, $debug); } return $formattedError; @@ -227,54 +219,42 @@ class FormattedError /** * Decorates spec-compliant $formattedError with debug entries according to $debug flags - * (see GraphQL\Error\Debug for available flags) + * (@see \GraphQL\Error\DebugFlag for available flags) * - * @param mixed[] $formattedError - * @param Throwable $e - * @param bool|int $debug + * @param mixed[] $formattedError * * @return mixed[] * * @throws Throwable */ - public static function addDebugEntries(array $formattedError, $e, $debug) + public static function addDebugEntries(array $formattedError, Throwable $e, int $debugFlag) : array { - if (! $debug) { + if ($debugFlag === DebugFlag::NONE) { return $formattedError; } - Utils::invariant( - $e instanceof Exception || $e instanceof Throwable, - 'Expected exception, got %s', - Utils::getVariableType($e) - ); - - $debug = (int) $debug; - - if ($debug & Debug::RETHROW_INTERNAL_EXCEPTIONS) { + if (( $debugFlag & DebugFlag::RETHROW_INTERNAL_EXCEPTIONS) !== 0) { if (! $e instanceof Error) { throw $e; } - if ($e->getPrevious()) { + if ($e->getPrevious() !== null) { throw $e->getPrevious(); } } $isUnsafe = ! $e instanceof ClientAware || ! $e->isClientSafe(); - if (($debug & Debug::RETHROW_UNSAFE_EXCEPTIONS) && $isUnsafe) { - if ($e->getPrevious()) { - throw $e->getPrevious(); - } + if (($debugFlag & DebugFlag::RETHROW_UNSAFE_EXCEPTIONS) !== 0 && $isUnsafe && $e->getPrevious() !== null) { + throw $e->getPrevious(); } - if (($debug & Debug::INCLUDE_DEBUG_MESSAGE) && $isUnsafe) { + if (($debugFlag & DebugFlag::INCLUDE_DEBUG_MESSAGE) !== 0 && $isUnsafe) { // Displaying debugMessage as a first entry: $formattedError = ['debugMessage' => $e->getMessage()] + $formattedError; } - if ($debug & Debug::INCLUDE_TRACE) { + if (($debugFlag & DebugFlag::INCLUDE_TRACE) !== 0) { if ($e instanceof ErrorException || $e instanceof \Error) { $formattedError += [ 'file' => $e->getFile(), @@ -282,10 +262,10 @@ class FormattedError ]; } - $isTrivial = $e instanceof Error && ! $e->getPrevious(); + $isTrivial = $e instanceof Error && $e->getPrevious() === null; if (! $isTrivial) { - $debugging = $e->getPrevious() ?: $e; + $debugging = $e->getPrevious() ?? $e; $formattedError['trace'] = static::toSafeTrace($debugging); } } @@ -296,18 +276,14 @@ class FormattedError /** * Prepares final error formatter taking in account $debug flags. * If initial formatter is not set, FormattedError::createFromException is used - * - * @param bool|int $debug - * - * @return callable|callable */ - public static function prepareFormatter(?callable $formatter = null, $debug) + public static function prepareFormatter(?callable $formatter, int $debug) : callable { - $formatter = $formatter ?: static function ($e) { + $formatter = $formatter ?? static function ($e) : array { return FormattedError::createFromException($e); }; - if ($debug) { - $formatter = static function ($e) use ($formatter, $debug) { + if ($debug !== DebugFlag::NONE) { + $formatter = static function ($e) use ($formatter, $debug) : array { return FormattedError::addDebugEntries($formatter($e), $e, $debug); }; } @@ -338,12 +314,12 @@ class FormattedError } return array_map( - static function ($err) { + static function ($err) : array { $safeErr = array_intersect_key($err, ['file' => true, 'line' => true]); if (isset($err['function'])) { $func = $err['function']; - $args = ! empty($err['args']) ? array_map([self::class, 'printVar'], $err['args']) : []; + $args = array_map([self::class, 'printVar'], $err['args'] ?? []); $funcStr = $func . '(' . implode(', ', $args) . ')'; if (isset($err['class'])) { @@ -412,9 +388,9 @@ class FormattedError { $formatted = ['message' => $error]; - if (! empty($locations)) { + if (count($locations) > 0) { $formatted['locations'] = array_map( - static function ($loc) { + static function ($loc) : array { return $loc->toArray(); }, $locations @@ -428,6 +404,8 @@ class FormattedError * @deprecated as of v0.10.0, use general purpose method createFromException() instead * * @return mixed[] + * + * @codeCoverageIgnore */ public static function createFromPHPError(ErrorException $e) { diff --git a/vendor/webonyx/graphql-php/src/Error/InvariantViolation.php b/vendor/webonyx/graphql-php/src/Error/InvariantViolation.php index 24d6dbc..c3cb8ab 100644 --- a/vendor/webonyx/graphql-php/src/Error/InvariantViolation.php +++ b/vendor/webonyx/graphql-php/src/Error/InvariantViolation.php @@ -13,4 +13,8 @@ use LogicException; */ class InvariantViolation extends LogicException { + public static function shouldNotHappen() : self + { + return new self('This should not have happened'); + } } diff --git a/vendor/webonyx/graphql-php/src/Error/Warning.php b/vendor/webonyx/graphql-php/src/Error/Warning.php index 9157b05..3efd1cf 100644 --- a/vendor/webonyx/graphql-php/src/Error/Warning.php +++ b/vendor/webonyx/graphql-php/src/Error/Warning.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace GraphQL\Error; +use GraphQL\Exception\InvalidArgument; +use function is_int; use function trigger_error; use const E_USER_WARNING; @@ -15,12 +17,12 @@ use const E_USER_WARNING; */ final class Warning { - const WARNING_ASSIGN = 2; - const WARNING_CONFIG = 4; - const WARNING_FULL_SCHEMA_SCAN = 8; - const WARNING_CONFIG_DEPRECATION = 16; - const WARNING_NOT_A_TYPE = 32; - const ALL = 63; + public const WARNING_ASSIGN = 2; + public const WARNING_CONFIG = 4; + public const WARNING_FULL_SCHEMA_SCAN = 8; + public const WARNING_CONFIG_DEPRECATION = 16; + public const WARNING_NOT_A_TYPE = 32; + public const ALL = 63; /** @var int */ private static $enableWarnings = self::ALL; @@ -37,7 +39,7 @@ final class Warning * * @api */ - public static function setWarningHandler(?callable $warningHandler = null) + public static function setWarningHandler(?callable $warningHandler = null) : void { self::$warningHandler = $warningHandler; } @@ -54,14 +56,16 @@ final class Warning * * @api */ - public static function suppress($suppress = true) + public static function suppress($suppress = true) : void { if ($suppress === true) { self::$enableWarnings = 0; } elseif ($suppress === false) { self::$enableWarnings = self::ALL; - } else { + } elseif (is_int($suppress)) { self::$enableWarnings &= ~$suppress; + } else { + throw InvalidArgument::fromExpectedTypeAndArgument('bool|int', $suppress); } } @@ -77,35 +81,41 @@ final class Warning * * @api */ - public static function enable($enable = true) + public static function enable($enable = true) : void { if ($enable === true) { self::$enableWarnings = self::ALL; } elseif ($enable === false) { self::$enableWarnings = 0; - } else { + } elseif (is_int($enable)) { self::$enableWarnings |= $enable; + } else { + throw InvalidArgument::fromExpectedTypeAndArgument('bool|int', $enable); } } - public static function warnOnce($errorMessage, $warningId, $messageLevel = null) + public static function warnOnce(string $errorMessage, int $warningId, ?int $messageLevel = null) : void { - if (self::$warningHandler) { + $messageLevel = $messageLevel ?? E_USER_WARNING; + + if (self::$warningHandler !== null) { $fn = self::$warningHandler; - $fn($errorMessage, $warningId); + $fn($errorMessage, $warningId, $messageLevel); } elseif ((self::$enableWarnings & $warningId) > 0 && ! isset(self::$warned[$warningId])) { self::$warned[$warningId] = true; - trigger_error($errorMessage, $messageLevel ?: E_USER_WARNING); + trigger_error($errorMessage, $messageLevel); } } - public static function warn($errorMessage, $warningId, $messageLevel = null) + public static function warn(string $errorMessage, int $warningId, ?int $messageLevel = null) : void { - if (self::$warningHandler) { + $messageLevel = $messageLevel ?? E_USER_WARNING; + + if (self::$warningHandler !== null) { $fn = self::$warningHandler; - $fn($errorMessage, $warningId); + $fn($errorMessage, $warningId, $messageLevel); } elseif ((self::$enableWarnings & $warningId) > 0) { - trigger_error($errorMessage, $messageLevel ?: E_USER_WARNING); + trigger_error($errorMessage, $messageLevel); } } } diff --git a/vendor/webonyx/graphql-php/src/Exception/InvalidArgument.php b/vendor/webonyx/graphql-php/src/Exception/InvalidArgument.php new file mode 100644 index 0000000..eea34d5 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Exception/InvalidArgument.php @@ -0,0 +1,20 @@ +schema = $schema; $this->fragments = $fragments; - $this->rootValue = $root; + $this->rootValue = $rootValue; $this->contextValue = $contextValue; $this->operation = $operation; - $this->variableValues = $variables; - $this->errors = $errors ?: []; + $this->variableValues = $variableValues; + $this->errors = $errors ?? []; $this->fieldResolver = $fieldResolver; - $this->promises = $promiseAdapter; + $this->promiseAdapter = $promiseAdapter; } public function addError(Error $error) diff --git a/vendor/webonyx/graphql-php/src/Executor/ExecutionResult.php b/vendor/webonyx/graphql-php/src/Executor/ExecutionResult.php index db16dd3..4f53287 100644 --- a/vendor/webonyx/graphql-php/src/Executor/ExecutionResult.php +++ b/vendor/webonyx/graphql-php/src/Executor/ExecutionResult.php @@ -4,10 +4,12 @@ declare(strict_types=1); namespace GraphQL\Executor; +use GraphQL\Error\DebugFlag; use GraphQL\Error\Error; use GraphQL\Error\FormattedError; use JsonSerializable; use function array_map; +use function count; /** * Returned after [query execution](executing-queries.md). @@ -125,35 +127,37 @@ class ExecutionResult implements JsonSerializable * If debug argument is passed, output of error formatter is enriched which debugging information * ("debugMessage", "trace" keys depending on flags). * - * $debug argument must be either bool (only adds "debugMessage" to result) or sum of flags from - * GraphQL\Error\Debug - * - * @param bool|int $debug + * $debug argument must sum of flags from @see \GraphQL\Error\DebugFlag * * @return mixed[] * * @api */ - public function toArray($debug = false) + public function toArray(int $debug = DebugFlag::NONE) : array { $result = []; - if (! empty($this->errors)) { - $errorsHandler = $this->errorsHandler ?: static function (array $errors, callable $formatter) { + if (count($this->errors ?? []) > 0) { + $errorsHandler = $this->errorsHandler ?? static function (array $errors, callable $formatter) : array { return array_map($formatter, $errors); }; - $result['errors'] = $errorsHandler( + $handledErrors = $errorsHandler( $this->errors, FormattedError::prepareFormatter($this->errorFormatter, $debug) ); + + // While we know that there were errors initially, they might have been discarded + if ($handledErrors !== []) { + $result['errors'] = $handledErrors; + } } if ($this->data !== null) { $result['data'] = $this->data; } - if (! empty($this->extensions)) { + if (count($this->extensions ?? []) > 0) { $result['extensions'] = $this->extensions; } diff --git a/vendor/webonyx/graphql-php/src/Executor/Executor.php b/vendor/webonyx/graphql-php/src/Executor/Executor.php index 30ccad4..c6040bd 100644 --- a/vendor/webonyx/graphql-php/src/Executor/Executor.php +++ b/vendor/webonyx/graphql-php/src/Executor/Executor.php @@ -20,7 +20,7 @@ use function is_object; */ class Executor { - /** @var callable|string[] */ + /** @var callable */ private static $defaultFieldResolver = [self::class, 'defaultFieldResolver']; /** @var PromiseAdapter */ @@ -35,7 +35,7 @@ class Executor } /** - * Custom default resolve function. + * Set a custom default resolve function. */ public static function setDefaultFieldResolver(callable $fieldResolver) { @@ -44,9 +44,12 @@ class Executor public static function getPromiseAdapter() : PromiseAdapter { - return self::$defaultPromiseAdapter ?: (self::$defaultPromiseAdapter = new SyncPromiseAdapter()); + return self::$defaultPromiseAdapter ?? (self::$defaultPromiseAdapter = new SyncPromiseAdapter()); } + /** + * Set a custom default promise adapter. + */ public static function setPromiseAdapter(?PromiseAdapter $defaultPromiseAdapter = null) { self::$defaultPromiseAdapter = $defaultPromiseAdapter; @@ -58,9 +61,7 @@ class Executor } /** - * Custom executor implementation factory. - * - * Will be called with as + * Set a custom executor implementation factory. */ public static function setImplementationFactory(callable $implementationFactory) { @@ -70,13 +71,13 @@ class Executor /** * Executes DocumentNode against given $schema. * - * Always returns ExecutionResult and never throws. All errors which occur during operation - * execution are collected in `$result->errors`. + * Always returns ExecutionResult and never throws. + * All errors which occur during operation execution are collected in `$result->errors`. * - * @param mixed|null $rootValue - * @param mixed|null $contextValue - * @param mixed[]|ArrayAccess|null $variableValues - * @param string|null $operationName + * @param mixed|null $rootValue + * @param mixed|null $contextValue + * @param array|ArrayAccess|null $variableValues + * @param string|null $operationName * * @return ExecutionResult|Promise * @@ -119,10 +120,10 @@ class Executor * * Useful for async PHP platforms. * - * @param mixed|null $rootValue - * @param mixed|null $contextValue - * @param mixed[]|null $variableValues - * @param string|null $operationName + * @param mixed|null $rootValue + * @param mixed|null $contextValue + * @param array|null $variableValues + * @param string|null $operationName * * @return Promise * @@ -149,7 +150,7 @@ class Executor $contextValue, $variableValues, $operationName, - $fieldResolver ?: self::$defaultFieldResolver + $fieldResolver ?? self::$defaultFieldResolver ); return $executor->doExecute(); @@ -157,31 +158,33 @@ class Executor /** * If a resolve function is not given, then a default resolve behavior is used - * which takes the property of the source object of the same name as the field + * which takes the property of the root value of the same name as the field * and returns it as the result, or if it's a function, returns the result * of calling that function while passing along args and context. * - * @param mixed $source - * @param mixed[] $args - * @param mixed|null $context + * @param mixed $objectValue + * @param array $args + * @param mixed|null $contextValue * * @return mixed|null */ - public static function defaultFieldResolver($source, $args, $context, ResolveInfo $info) + public static function defaultFieldResolver($objectValue, $args, $contextValue, ResolveInfo $info) { $fieldName = $info->fieldName; $property = null; - if (is_array($source) || $source instanceof ArrayAccess) { - if (isset($source[$fieldName])) { - $property = $source[$fieldName]; + if (is_array($objectValue) || $objectValue instanceof ArrayAccess) { + if (isset($objectValue[$fieldName])) { + $property = $objectValue[$fieldName]; } - } elseif (is_object($source)) { - if (isset($source->{$fieldName})) { - $property = $source->{$fieldName}; + } elseif (is_object($objectValue)) { + if (isset($objectValue->{$fieldName})) { + $property = $objectValue->{$fieldName}; } } - return $property instanceof Closure ? $property($source, $args, $context, $info) : $property; + return $property instanceof Closure + ? $property($objectValue, $args, $contextValue, $info) + : $property; } } diff --git a/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/AmpPromiseAdapter.php b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/AmpPromiseAdapter.php new file mode 100644 index 0000000..e683dae --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/AmpPromiseAdapter.php @@ -0,0 +1,147 @@ +resolve($value); + } elseif ($onRejected !== null) { + self::resolveWithCallable($deferred, $onRejected, $reason); + } else { + $deferred->fail($reason); + } + }; + + /** @var AmpPromise $adoptedPromise */ + $adoptedPromise = $promise->adoptedPromise; + $adoptedPromise->onResolve($onResolve); + + return new Promise($deferred->promise(), $this); + } + + /** + * @inheritdoc + */ + public function create(callable $resolver) : Promise + { + $deferred = new Deferred(); + + $resolver( + static function ($value) use ($deferred) : void { + $deferred->resolve($value); + }, + static function (Throwable $exception) use ($deferred) : void { + $deferred->fail($exception); + } + ); + + return new Promise($deferred->promise(), $this); + } + + /** + * @inheritdoc + */ + public function createFulfilled($value = null) : Promise + { + $promise = new Success($value); + + return new Promise($promise, $this); + } + + /** + * @inheritdoc + */ + public function createRejected($reason) : Promise + { + $promise = new Failure($reason); + + return new Promise($promise, $this); + } + + /** + * @inheritdoc + */ + public function all(array $promisesOrValues) : Promise + { + /** @var AmpPromise[] $promises */ + $promises = []; + foreach ($promisesOrValues as $key => $item) { + if ($item instanceof Promise) { + $promises[$key] = $item->adoptedPromise; + } elseif ($item instanceof AmpPromise) { + $promises[$key] = $item; + } + } + + $deferred = new Deferred(); + + $onResolve = static function (?Throwable $reason, ?array $values) use ($promisesOrValues, $deferred) : void { + if ($reason === null) { + $deferred->resolve(array_replace($promisesOrValues, $values)); + + return; + } + + $deferred->fail($reason); + }; + + all($promises)->onResolve($onResolve); + + return new Promise($deferred->promise(), $this); + } + + private static function resolveWithCallable(Deferred $deferred, callable $callback, $argument) : void + { + try { + $result = $callback($argument); + } catch (Throwable $exception) { + $deferred->fail($exception); + + return; + } + + if ($result instanceof Promise) { + $result = $result->adoptedPromise; + } + + $deferred->resolve($result); + } +} diff --git a/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/ReactPromiseAdapter.php b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/ReactPromiseAdapter.php index 446d904..14ff502 100644 --- a/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/ReactPromiseAdapter.php +++ b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/ReactPromiseAdapter.php @@ -85,7 +85,7 @@ class ReactPromiseAdapter implements PromiseAdapter } ); - $promise = all($promisesOrValues)->then(static function ($values) use ($promisesOrValues) { + $promise = all($promisesOrValues)->then(static function ($values) use ($promisesOrValues) : array { $orderedResults = []; foreach ($promisesOrValues as $key => $value) { diff --git a/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromise.php b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromise.php index 26aecd6..d0b94b1 100644 --- a/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromise.php +++ b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromise.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace GraphQL\Executor\Promise\Adapter; use Exception; -use GraphQL\Executor\ExecutionResult; use GraphQL\Utils\Utils; use SplQueue; use Throwable; @@ -15,6 +14,14 @@ use function method_exists; /** * Simplistic (yet full-featured) implementation of Promises A+ spec for regular PHP `sync` mode * (using queue to defer promises execution) + * + * Note: + * Library users are not supposed to use SyncPromise class in their resolvers. + * Instead they should use GraphQL\Deferred which enforces $executor callback in the constructor. + * + * Root SyncPromise without explicit $executor will never resolve (actually throw while trying). + * The whole point of Deferred is to ensure it never happens and that any resolver creates + * at least one $executor to start the promise chain. */ class SyncPromise { @@ -28,7 +35,7 @@ class SyncPromise /** @var string */ public $state = self::PENDING; - /** @var ExecutionResult|Throwable */ + /** @var mixed */ public $result; /** @@ -38,16 +45,33 @@ class SyncPromise */ private $waiting = []; - public static function runQueue() + public static function runQueue() : void { $q = self::$queue; - while ($q && ! $q->isEmpty()) { + while ($q !== null && ! $q->isEmpty()) { $task = $q->dequeue(); $task(); } } - public function resolve($value) + /** + * @param callable() : mixed $executor + */ + public function __construct(?callable $executor = null) + { + if ($executor === null) { + return; + } + self::getQueue()->enqueue(function () use ($executor) : void { + try { + $this->resolve($executor()); + } catch (Throwable $e) { + $this->reject($e); + } + }); + } + + public function resolve($value) : self { switch ($this->state) { case self::PENDING: @@ -56,10 +80,10 @@ class SyncPromise } if (is_object($value) && method_exists($value, 'then')) { $value->then( - function ($resolvedValue) { + function ($resolvedValue) : void { $this->resolve($resolvedValue); }, - function ($reason) { + function ($reason) : void { $this->reject($reason); } ); @@ -83,9 +107,9 @@ class SyncPromise return $this; } - public function reject($reason) + public function reject($reason) : self { - if (! $reason instanceof Exception && ! $reason instanceof Throwable) { + if (! $reason instanceof Throwable) { throw new Exception('SyncPromise::reject() has to be called with an instance of \Throwable'); } @@ -107,7 +131,7 @@ class SyncPromise return $this; } - private function enqueueWaitingPromises() + private function enqueueWaitingPromises() : void { Utils::invariant( $this->state !== self::PENDING, @@ -115,15 +139,13 @@ class SyncPromise ); foreach ($this->waiting as $descriptor) { - self::getQueue()->enqueue(function () use ($descriptor) { - /** @var $promise self */ + self::getQueue()->enqueue(function () use ($descriptor) : void { + /** @var self $promise */ [$promise, $onFulfilled, $onRejected] = $descriptor; if ($this->state === self::FULFILLED) { try { $promise->resolve($onFulfilled === null ? $this->result : $onFulfilled($this->result)); - } catch (Exception $e) { - $promise->reject($e); } catch (Throwable $e) { $promise->reject($e); } @@ -134,8 +156,6 @@ class SyncPromise } else { $promise->resolve($onRejected($this->result)); } - } catch (Exception $e) { - $promise->reject($e); } catch (Throwable $e) { $promise->reject($e); } @@ -145,17 +165,21 @@ class SyncPromise $this->waiting = []; } - public static function getQueue() + public static function getQueue() : SplQueue { - return self::$queue ?: self::$queue = new SplQueue(); + return self::$queue ?? self::$queue = new SplQueue(); } - public function then(?callable $onFulfilled = null, ?callable $onRejected = null) + /** + * @param callable(mixed) : mixed $onFulfilled + * @param callable(Throwable) : mixed $onRejected + */ + public function then(?callable $onFulfilled = null, ?callable $onRejected = null) : self { - if ($this->state === self::REJECTED && ! $onRejected) { + if ($this->state === self::REJECTED && $onRejected === null) { return $this; } - if ($this->state === self::FULFILLED && ! $onFulfilled) { + if ($this->state === self::FULFILLED && $onFulfilled === null) { return $this; } $tmp = new self(); @@ -167,4 +191,12 @@ class SyncPromise return $tmp; } + + /** + * @param callable(Throwable) : mixed $onRejected + */ + public function catch(callable $onRejected) : self + { + return $this->then(null, $onRejected); + } } diff --git a/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromiseAdapter.php b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromiseAdapter.php index e5900a9..f088aec 100644 --- a/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromiseAdapter.php +++ b/vendor/webonyx/graphql-php/src/Executor/Promise/Adapter/SyncPromiseAdapter.php @@ -4,8 +4,6 @@ declare(strict_types=1); namespace GraphQL\Executor\Promise\Adapter; -use Exception; -use GraphQL\Deferred; use GraphQL\Error\InvariantViolation; use GraphQL\Executor\ExecutionResult; use GraphQL\Executor\Promise\Promise; @@ -25,7 +23,7 @@ class SyncPromiseAdapter implements PromiseAdapter */ public function isThenable($value) { - return $value instanceof Deferred; + return $value instanceof SyncPromise; } /** @@ -33,11 +31,12 @@ class SyncPromiseAdapter implements PromiseAdapter */ public function convertThenable($thenable) { - if (! $thenable instanceof Deferred) { + if (! $thenable instanceof SyncPromise) { + // End-users should always use Deferred (and don't use SyncPromise directly) throw new InvariantViolation('Expected instance of GraphQL\Deferred, got ' . Utils::printSafe($thenable)); } - return new Promise($thenable->promise, $this); + return new Promise($thenable, $this); } /** @@ -69,8 +68,6 @@ class SyncPromiseAdapter implements PromiseAdapter 'reject', ] ); - } catch (Exception $e) { - $promise->reject($e); } catch (Throwable $e) { $promise->reject($e); } @@ -113,7 +110,7 @@ class SyncPromiseAdapter implements PromiseAdapter if ($promiseOrValue instanceof Promise) { $result[$index] = null; $promiseOrValue->then( - static function ($value) use ($index, &$count, $total, &$result, $all) { + static function ($value) use ($index, &$count, $total, &$result, $all) : void { $result[$index] = $value; $count++; if ($count < $total) { @@ -144,13 +141,11 @@ class SyncPromiseAdapter implements PromiseAdapter public function wait(Promise $promise) { $this->beforeWait($promise); - $dfdQueue = Deferred::getQueue(); - $promiseQueue = SyncPromise::getQueue(); + $taskQueue = SyncPromise::getQueue(); while ($promise->adoptedPromise->state === SyncPromise::PENDING && - ! ($dfdQueue->isEmpty() && $promiseQueue->isEmpty()) + ! $taskQueue->isEmpty() ) { - Deferred::runQueue(); SyncPromise::runQueue(); $this->onWait($promise); } diff --git a/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php b/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php index 7b54afc..c29fede 100644 --- a/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php +++ b/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php @@ -17,8 +17,9 @@ use GraphQL\Language\AST\FieldNode; use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\InlineFragmentNode; -use GraphQL\Language\AST\NodeKind; +use GraphQL\Language\AST\Node; use GraphQL\Language\AST\OperationDefinitionNode; +use GraphQL\Language\AST\SelectionNode; use GraphQL\Language\AST\SelectionSetNode; use GraphQL\Type\Definition\AbstractType; use GraphQL\Type\Definition\Directive; @@ -30,6 +31,7 @@ use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\ResolveInfo; use GraphQL\Type\Definition\Type; +use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Introspection; use GraphQL\Type\Schema; use GraphQL\Utils\TypeInfo; @@ -43,32 +45,38 @@ use function array_keys; use function array_merge; use function array_reduce; use function array_values; +use function count; use function get_class; use function is_array; -use function is_object; +use function is_callable; use function is_string; use function sprintf; class ReferenceExecutor implements ExecutorImplementation { /** @var object */ - private static $UNDEFINED; + protected static $UNDEFINED; /** @var ExecutionContext */ - private $exeContext; + protected $exeContext; /** @var SplObjectStorage */ - private $subFieldCache; + protected $subFieldCache; - private function __construct(ExecutionContext $context) + protected function __construct(ExecutionContext $context) { - if (! self::$UNDEFINED) { - self::$UNDEFINED = Utils::undefined(); + if (! static::$UNDEFINED) { + static::$UNDEFINED = Utils::undefined(); } $this->exeContext = $context; $this->subFieldCache = new SplObjectStorage(); } + /** + * @param mixed $rootValue + * @param mixed $contextValue + * @param array|Traversable $variableValues + */ public static function create( PromiseAdapter $promiseAdapter, Schema $schema, @@ -78,8 +86,8 @@ class ReferenceExecutor implements ExecutorImplementation $variableValues, ?string $operationName, callable $fieldResolver - ) { - $exeContext = self::buildExecutionContext( + ) : ExecutorImplementation { + $exeContext = static::buildExecutionContext( $schema, $documentNode, $rootValue, @@ -108,56 +116,55 @@ class ReferenceExecutor implements ExecutorImplementation }; } - return new self($exeContext); + return new static($exeContext); } /** * Constructs an ExecutionContext object from the arguments passed to * execute, which we will pass throughout the other execution methods. * - * @param mixed $rootValue - * @param mixed $contextValue - * @param mixed[]|Traversable $rawVariableValues - * @param string|null $operationName + * @param mixed $rootValue + * @param mixed $contextValue + * @param array|Traversable $rawVariableValues * - * @return ExecutionContext|Error[] + * @return ExecutionContext|array */ - private static function buildExecutionContext( + protected static function buildExecutionContext( Schema $schema, DocumentNode $documentNode, $rootValue, $contextValue, $rawVariableValues, - $operationName = null, + ?string $operationName = null, ?callable $fieldResolver = null, ?PromiseAdapter $promiseAdapter = null ) { $errors = []; $fragments = []; - /** @var OperationDefinitionNode $operation */ + /** @var OperationDefinitionNode|null $operation */ $operation = null; $hasMultipleAssumedOperations = false; foreach ($documentNode->definitions as $definition) { - switch ($definition->kind) { - case NodeKind::OPERATION_DEFINITION: - if (! $operationName && $operation) { + switch (true) { + case $definition instanceof OperationDefinitionNode: + if ($operationName === null && $operation !== null) { $hasMultipleAssumedOperations = true; } - if (! $operationName || + if ($operationName === null || (isset($definition->name) && $definition->name->value === $operationName)) { $operation = $definition; } break; - case NodeKind::FRAGMENT_DEFINITION: + case $definition instanceof FragmentDefinitionNode: $fragments[$definition->name->value] = $definition; break; } } if ($operation === null) { - if ($operationName) { - $errors[] = new Error(sprintf('Unknown operation named "%s".', $operationName)); - } else { + if ($operationName === null) { $errors[] = new Error('Must provide an operation.'); + } else { + $errors[] = new Error(sprintf('Unknown operation named "%s".', $operationName)); } } elseif ($hasMultipleAssumedOperations) { $errors[] = new Error( @@ -168,16 +175,16 @@ class ReferenceExecutor implements ExecutorImplementation if ($operation !== null) { [$coercionErrors, $coercedVariableValues] = Values::getVariableValues( $schema, - $operation->variableDefinitions ?: [], - $rawVariableValues ?: [] + $operation->variableDefinitions ?? [], + $rawVariableValues ?? [] ); - if (empty($coercionErrors)) { + if (count($coercionErrors ?? []) === 0) { $variableValues = $coercedVariableValues; } else { $errors = array_merge($errors, $coercionErrors); } } - if (! empty($errors)) { + if (count($errors) > 0) { return $errors; } Utils::invariant($operation, 'Has operation if no errors.'); @@ -199,7 +206,7 @@ class ReferenceExecutor implements ExecutorImplementation public function doExecute() : Promise { // Return a Promise that will eventually resolve to the data described by - // The "Response" section of the GraphQL specification. + // the "Response" section of the GraphQL specification. // // If errors are encountered while executing a GraphQL field, only that // field and its descendants will be omitted, and sibling fields will still @@ -212,7 +219,7 @@ class ReferenceExecutor implements ExecutorImplementation // But for the "sync" case it is always fulfilled return $this->isPromise($result) ? $result - : $this->exeContext->promises->createFulfilled($result); + : $this->exeContext->promiseAdapter->createFulfilled($result); } /** @@ -220,7 +227,7 @@ class ReferenceExecutor implements ExecutorImplementation * * @return ExecutionResult|Promise */ - private function buildResponse($data) + protected function buildResponse($data) { if ($this->isPromise($data)) { return $data->then(function ($resolved) { @@ -237,11 +244,11 @@ class ReferenceExecutor implements ExecutorImplementation /** * Implements the "Evaluating operations" section of the spec. * - * @param mixed[] $rootValue + * @param mixed $rootValue * - * @return Promise|stdClass|mixed[] + * @return array|Promise|stdClass|null */ - private function executeOperation(OperationDefinitionNode $operation, $rootValue) + protected function executeOperation(OperationDefinitionNode $operation, $rootValue) { $type = $this->getOperationRootType($this->exeContext->schema, $operation); $fields = $this->collectFields($type, $operation->selectionSet, new ArrayObject(), new ArrayObject()); @@ -252,16 +259,20 @@ class ReferenceExecutor implements ExecutorImplementation // // Similar to completeValueCatchingError. try { - $result = $operation->operation === 'mutation' ? - $this->executeFieldsSerially($type, $rootValue, $path, $fields) : - $this->executeFields($type, $rootValue, $path, $fields); + $result = $operation->operation === 'mutation' + ? $this->executeFieldsSerially($type, $rootValue, $path, $fields) + : $this->executeFields($type, $rootValue, $path, $fields); if ($this->isPromise($result)) { return $result->then( null, - function ($error) { - $this->exeContext->addError($error); + function ($error) : ?Promise { + if ($error instanceof Error) { + $this->exeContext->addError($error); - return $this->exeContext->promises->createFulfilled(null); + return $this->exeContext->promiseAdapter->createFulfilled(null); + } + + return null; } ); } @@ -277,16 +288,14 @@ class ReferenceExecutor implements ExecutorImplementation /** * Extracts the root type of the operation from the schema. * - * @return ObjectType - * * @throws Error */ - private function getOperationRootType(Schema $schema, OperationDefinitionNode $operation) + protected function getOperationRootType(Schema $schema, OperationDefinitionNode $operation) : ObjectType { switch ($operation->operation) { case 'query': $queryType = $schema->getQueryType(); - if (! $queryType) { + if ($queryType === null) { throw new Error( 'Schema does not define the required query root type.', [$operation] @@ -296,7 +305,7 @@ class ReferenceExecutor implements ExecutorImplementation return $queryType; case 'mutation': $mutationType = $schema->getMutationType(); - if (! $mutationType) { + if ($mutationType === null) { throw new Error( 'Schema is not configured for mutations.', [$operation] @@ -306,7 +315,7 @@ class ReferenceExecutor implements ExecutorImplementation return $mutationType; case 'subscription': $subscriptionType = $schema->getSubscriptionType(); - if (! $subscriptionType) { + if ($subscriptionType === null) { throw new Error( 'Schema is not configured for subscriptions.', [$operation] @@ -329,32 +338,27 @@ class ReferenceExecutor implements ExecutorImplementation * CollectFields requires the "runtime type" of an object. For a field which * returns an Interface or Union type, the "runtime type" will be the actual * Object type returned by that field. - * - * @param ArrayObject $fields - * @param ArrayObject $visitedFragmentNames - * - * @return ArrayObject */ - private function collectFields( + protected function collectFields( ObjectType $runtimeType, SelectionSetNode $selectionSet, - $fields, - $visitedFragmentNames - ) { + ArrayObject $fields, + ArrayObject $visitedFragmentNames + ) : ArrayObject { $exeContext = $this->exeContext; foreach ($selectionSet->selections as $selection) { - switch ($selection->kind) { - case NodeKind::FIELD: + switch (true) { + case $selection instanceof FieldNode: if (! $this->shouldIncludeNode($selection)) { break; } - $name = self::getFieldEntryKey($selection); + $name = static::getFieldEntryKey($selection); if (! isset($fields[$name])) { $fields[$name] = new ArrayObject(); } $fields[$name][] = $selection; break; - case NodeKind::INLINE_FRAGMENT: + case $selection instanceof InlineFragmentNode: if (! $this->shouldIncludeNode($selection) || ! $this->doesFragmentConditionMatch($selection, $runtimeType) ) { @@ -367,15 +371,16 @@ class ReferenceExecutor implements ExecutorImplementation $visitedFragmentNames ); break; - case NodeKind::FRAGMENT_SPREAD: + case $selection instanceof FragmentSpreadNode: $fragName = $selection->name->value; - if (! empty($visitedFragmentNames[$fragName]) || ! $this->shouldIncludeNode($selection)) { + + if (($visitedFragmentNames[$fragName] ?? false) === true || ! $this->shouldIncludeNode($selection)) { break; } $visitedFragmentNames[$fragName] = true; /** @var FragmentDefinitionNode|null $fragment */ $fragment = $exeContext->fragments[$fragName] ?? null; - if (! $fragment || ! $this->doesFragmentConditionMatch($fragment, $runtimeType)) { + if ($fragment === null || ! $this->doesFragmentConditionMatch($fragment, $runtimeType)) { break; } $this->collectFields( @@ -396,10 +401,8 @@ class ReferenceExecutor implements ExecutorImplementation * directives, where @skip has higher precedence than @include. * * @param FragmentSpreadNode|FieldNode|InlineFragmentNode $node - * - * @return bool */ - private function shouldIncludeNode($node) + protected function shouldIncludeNode(SelectionNode $node) : bool { $variableValues = $this->exeContext->variableValues; $skipDirective = Directive::skipDirective(); @@ -423,25 +426,19 @@ class ReferenceExecutor implements ExecutorImplementation /** * Implements the logic to compute the key of a given fields entry - * - * @return string */ - private static function getFieldEntryKey(FieldNode $node) + protected static function getFieldEntryKey(FieldNode $node) : string { - return $node->alias ? $node->alias->value : $node->name->value; + return $node->alias === null ? $node->name->value : $node->alias->value; } /** * Determines if a fragment is applicable to the given type. * * @param FragmentDefinitionNode|InlineFragmentNode $fragment - * - * @return bool */ - private function doesFragmentConditionMatch( - $fragment, - ObjectType $type - ) { + protected function doesFragmentConditionMatch(Node $fragment, ObjectType $type) : bool + { $typeConditionNode = $fragment->typeCondition; if ($typeConditionNode === null) { return true; @@ -451,7 +448,7 @@ class ReferenceExecutor implements ExecutorImplementation return true; } if ($conditionalType instanceof AbstractType) { - return $this->exeContext->schema->isPossibleType($conditionalType, $type); + return $this->exeContext->schema->isSubType($conditionalType, $type); } return false; @@ -461,26 +458,25 @@ class ReferenceExecutor implements ExecutorImplementation * Implements the "Evaluating selection sets" section of the spec * for "write" mode. * - * @param mixed[] $sourceValue - * @param mixed[] $path - * @param ArrayObject $fields + * @param mixed $rootValue + * @param array $path * - * @return Promise|stdClass|mixed[] + * @return array|Promise|stdClass */ - private function executeFieldsSerially(ObjectType $parentType, $sourceValue, $path, $fields) + protected function executeFieldsSerially(ObjectType $parentType, $rootValue, array $path, ArrayObject $fields) { $result = $this->promiseReduce( array_keys($fields->getArrayCopy()), - function ($results, $responseName) use ($path, $parentType, $sourceValue, $fields) { + function ($results, $responseName) use ($path, $parentType, $rootValue, $fields) { $fieldNodes = $fields[$responseName]; $fieldPath = $path; $fieldPath[] = $responseName; - $result = $this->resolveField($parentType, $sourceValue, $fieldNodes, $fieldPath); - if ($result === self::$UNDEFINED) { + $result = $this->resolveField($parentType, $rootValue, $fieldNodes, $fieldPath); + if ($result === static::$UNDEFINED) { return $results; } $promise = $this->getPromise($result); - if ($promise) { + if ($promise !== null) { return $promise->then(static function ($resolvedResult) use ($responseName, $results) { $results[$responseName] = $resolvedResult; @@ -493,43 +489,46 @@ class ReferenceExecutor implements ExecutorImplementation }, [] ); + if ($this->isPromise($result)) { return $result->then(static function ($resolvedResults) { - return self::fixResultsIfEmptyArray($resolvedResults); + return static::fixResultsIfEmptyArray($resolvedResults); }); } - return self::fixResultsIfEmptyArray($result); + return static::fixResultsIfEmptyArray($result); } /** - * Resolves the field on the given source object. In particular, this - * figures out the value that the field returns by calling its resolve function, - * then calls completeValue to complete promises, serialize scalars, or execute - * the sub-selection-set for objects. + * Resolves the field on the given root value. * - * @param object|null $source - * @param FieldNode[] $fieldNodes - * @param mixed[] $path + * In particular, this figures out the value that the field returns + * by calling its resolve function, then calls completeValue to complete promises, + * serialize scalars, or execute the sub-selection-set for objects. * - * @return mixed[]|Exception|mixed|null + * @param mixed $rootValue + * @param array $path + * + * @return array|Throwable|mixed|null */ - private function resolveField(ObjectType $parentType, $source, $fieldNodes, $path) + protected function resolveField(ObjectType $parentType, $rootValue, ArrayObject $fieldNodes, array $path) { $exeContext = $this->exeContext; $fieldNode = $fieldNodes[0]; $fieldName = $fieldNode->name->value; $fieldDef = $this->getFieldDef($exeContext->schema, $parentType, $fieldName); - if (! $fieldDef) { - return self::$UNDEFINED; + if ($fieldDef === null) { + return static::$UNDEFINED; } $returnType = $fieldDef->getType(); - // The resolve function's optional third argument is a collection of + // The resolve function's optional 3rd argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + // The resolve function's optional 4th argument is a collection of // information about the current execution state. $info = new ResolveInfo( - $fieldName, + $fieldDef, $fieldNodes, - $returnType, $parentType, $path, $exeContext->schema, @@ -545,18 +544,13 @@ class ReferenceExecutor implements ExecutorImplementation } else { $resolveFn = $this->exeContext->fieldResolver; } - // The resolve function's optional third argument is a context value that - // is provided to every resolve function within an execution. It is commonly - // used to represent an authenticated user, or request-specific caches. - $context = $exeContext->contextValue; // Get the resolve function, regardless of if its result is normal // or abrupt (error). - $result = $this->resolveOrError( + $result = $this->resolveFieldValueOrError( $fieldDef, $fieldNode, $resolveFn, - $source, - $context, + $rootValue, $info ); $result = $this->completeValueCatchingError( @@ -572,23 +566,20 @@ class ReferenceExecutor implements ExecutorImplementation /** * This method looks up the field on the given type definition. + * * It has special casing for the two introspection fields, __schema * and __typename. __typename is special because it can always be * queried as a field, even in situations where no other fields * are allowed, like on a Union. __schema could get automatically * added to the query type, but that would require mutating type * definitions, which would cause issues. - * - * @param string $fieldName - * - * @return FieldDefinition */ - private function getFieldDef(Schema $schema, ObjectType $parentType, $fieldName) + protected function getFieldDef(Schema $schema, ObjectType $parentType, string $fieldName) : ?FieldDefinition { static $schemaMetaFieldDef, $typeMetaFieldDef, $typeNameMetaFieldDef; - $schemaMetaFieldDef = $schemaMetaFieldDef ?: Introspection::schemaMetaFieldDef(); - $typeMetaFieldDef = $typeMetaFieldDef ?: Introspection::typeMetaFieldDef(); - $typeNameMetaFieldDef = $typeNameMetaFieldDef ?: Introspection::typeNameMetaFieldDef(); + $schemaMetaFieldDef = $schemaMetaFieldDef ?? Introspection::schemaMetaFieldDef(); + $typeMetaFieldDef = $typeMetaFieldDef ?? Introspection::typeMetaFieldDef(); + $typeNameMetaFieldDef = $typeNameMetaFieldDef ?? Introspection::typeNameMetaFieldDef(); if ($fieldName === $schemaMetaFieldDef->name && $schema->getQueryType() === $parentType) { return $schemaMetaFieldDef; } @@ -600,38 +591,36 @@ class ReferenceExecutor implements ExecutorImplementation if ($fieldName === $typeNameMetaFieldDef->name) { return $typeNameMetaFieldDef; } - $tmp = $parentType->getFields(); - return $tmp[$fieldName] ?? null; + return $parentType->findField($fieldName); } /** - * Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` - * function. Returns the result of resolveFn or the abrupt-return Error object. + * Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` function. + * Returns the result of resolveFn or the abrupt-return Error object. * - * @param FieldDefinition $fieldDef - * @param FieldNode $fieldNode - * @param callable $resolveFn - * @param mixed $source - * @param mixed $context - * @param ResolveInfo $info + * @param mixed $rootValue * * @return Throwable|Promise|mixed */ - private function resolveOrError($fieldDef, $fieldNode, $resolveFn, $source, $context, $info) - { + protected function resolveFieldValueOrError( + FieldDefinition $fieldDef, + FieldNode $fieldNode, + callable $resolveFn, + $rootValue, + ResolveInfo $info + ) { try { - // Build hash of arguments from the field.arguments AST, using the + // Build a map of arguments from the field.arguments AST, using the // variables scope to fulfill any variable references. - $args = Values::getArgumentValues( + $args = Values::getArgumentValues( $fieldDef, $fieldNode, $this->exeContext->variableValues ); + $contextValue = $this->exeContext->contextValue; - return $resolveFn($source, $args, $context, $info); - } catch (Exception $error) { - return $error; + return $resolveFn($rootValue, $args, $contextValue, $info); } catch (Throwable $error) { return $error; } @@ -641,110 +630,67 @@ class ReferenceExecutor implements ExecutorImplementation * This is a small wrapper around completeValue which detects and logs errors * in the execution context. * - * @param FieldNode[] $fieldNodes - * @param string[] $path - * @param mixed $result + * @param array $path + * @param mixed $result * - * @return mixed[]|Promise|null + * @return array|Promise|stdClass|null */ - private function completeValueCatchingError( + protected function completeValueCatchingError( Type $returnType, - $fieldNodes, + ArrayObject $fieldNodes, ResolveInfo $info, - $path, + array $path, $result ) { - $exeContext = $this->exeContext; - // If the field type is non-nullable, then it is resolved without any - // protection from errors. - if ($returnType instanceof NonNull) { - return $this->completeValueWithLocatedError( - $returnType, - $fieldNodes, - $info, - $path, - $result - ); - } // Otherwise, error protection is applied, logging the error and resolving // a null value for this field if one is encountered. try { - $completed = $this->completeValueWithLocatedError( - $returnType, - $fieldNodes, - $info, - $path, - $result - ); - $promise = $this->getPromise($completed); - if ($promise) { - return $promise->then( - null, - function ($error) use ($exeContext) { - $exeContext->addError($error); + $promise = $this->getPromise($result); + if ($promise !== null) { + $completed = $promise->then(function (&$resolved) use ($returnType, $fieldNodes, $info, $path) { + return $this->completeValue($returnType, $fieldNodes, $info, $path, $resolved); + }); + } else { + $completed = $this->completeValue($returnType, $fieldNodes, $info, $path, $result); + } - return $this->exeContext->promises->createFulfilled(null); - } - ); + $promise = $this->getPromise($completed); + if ($promise !== null) { + return $promise->then(null, function ($error) use ($fieldNodes, $path, $returnType) : void { + $this->handleFieldError($error, $fieldNodes, $path, $returnType); + }); } return $completed; - } catch (Error $err) { - // If `completeValueWithLocatedError` returned abruptly (threw an error), log the error - // and return null. - $exeContext->addError($err); + } catch (Throwable $err) { + $this->handleFieldError($err, $fieldNodes, $path, $returnType); return null; } } /** - * This is a small wrapper around completeValue which annotates errors with - * location information. - * - * @param FieldNode[] $fieldNodes - * @param string[] $path - * @param mixed $result - * - * @return mixed[]|mixed|Promise|null + * @param mixed $rawError + * @param array $path * * @throws Error */ - public function completeValueWithLocatedError( - Type $returnType, - $fieldNodes, - ResolveInfo $info, - $path, - $result - ) { - try { - $completed = $this->completeValue( - $returnType, - $fieldNodes, - $info, - $path, - $result - ); - $promise = $this->getPromise($completed); - if ($promise) { - return $promise->then( - null, - function ($error) use ($fieldNodes, $path) { - return $this->exeContext->promises->createRejected(Error::createLocatedError( - $error, - $fieldNodes, - $path - )); - } - ); - } + protected function handleFieldError($rawError, ArrayObject $fieldNodes, array $path, Type $returnType) : void + { + $error = Error::createLocatedError( + $rawError, + $fieldNodes, + $path + ); - return $completed; - } catch (Exception $error) { - throw Error::createLocatedError($error, $fieldNodes, $path); - } catch (Throwable $error) { - throw Error::createLocatedError($error, $fieldNodes, $path); + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if ($returnType instanceof NonNull) { + throw $error; } + // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + $this->exeContext->addError($error); } /** @@ -768,32 +714,26 @@ class ReferenceExecutor implements ExecutorImplementation * Otherwise, the field type expects a sub-selection set, and will complete the * value by evaluating all sub-selections. * - * @param FieldNode[] $fieldNodes - * @param string[] $path - * @param mixed $result + * @param array $path + * @param mixed $result * - * @return mixed[]|mixed|Promise|null + * @return array|mixed|Promise|null * * @throws Error * @throws Throwable */ - private function completeValue( + protected function completeValue( Type $returnType, - $fieldNodes, + ArrayObject $fieldNodes, ResolveInfo $info, - $path, + array $path, &$result ) { - $promise = $this->getPromise($result); - // If result is a Promise, apply-lift over completeValue. - if ($promise) { - return $promise->then(function (&$resolved) use ($returnType, $fieldNodes, $info, $path) { - return $this->completeValue($returnType, $fieldNodes, $info, $path, $resolved); - }); - } - if ($result instanceof Exception || $result instanceof Throwable) { + // If result is an Error, throw a located error. + if ($result instanceof Throwable) { throw $result; } + // If field type is NonNull, complete for inner type, and throw field error // if result is null. if ($returnType instanceof NonNull) { @@ -806,7 +746,7 @@ class ReferenceExecutor implements ExecutorImplementation ); if ($completed === null) { throw new InvariantViolation( - 'Cannot return null for non-nullable field ' . $info->parentType . '.' . $info->fieldName . '.' + sprintf('Cannot return null for non-nullable field "%s.%s".', $info->parentType, $info->fieldName) ); } @@ -824,7 +764,7 @@ class ReferenceExecutor implements ExecutorImplementation // instance than `resolveType` or $field->getType() or $arg->getType() if ($returnType !== $this->exeContext->schema->getType($returnType->name)) { $hint = ''; - if ($this->exeContext->schema->getConfig()->typeLoader) { + if ($this->exeContext->schema->getConfig()->typeLoader !== null) { $hint = sprintf( 'Make sure that type loader returns the same instance as defined in %s.%s', $info->parentType, @@ -857,12 +797,10 @@ class ReferenceExecutor implements ExecutorImplementation /** * @param mixed $value - * - * @return bool */ - private function isPromise($value) + protected function isPromise($value) : bool { - return $value instanceof Promise || $this->exeContext->promises->isThenable($value); + return $value instanceof Promise || $this->exeContext->promiseAdapter->isThenable($value); } /** @@ -870,20 +808,18 @@ class ReferenceExecutor implements ExecutorImplementation * otherwise returns null. * * @param mixed $value - * - * @return Promise|null */ - private function getPromise($value) + protected function getPromise($value) : ?Promise { if ($value === null || $value instanceof Promise) { return $value; } - if ($this->exeContext->promises->isThenable($value)) { - $promise = $this->exeContext->promises->convertThenable($value); + if ($this->exeContext->promiseAdapter->isThenable($value)) { + $promise = $this->exeContext->promiseAdapter->convertThenable($value); if (! $promise instanceof Promise) { throw new InvariantViolation(sprintf( '%s::convertThenable is expected to return instance of GraphQL\Executor\Promise\Promise, got: %s', - get_class($this->exeContext->promises), + get_class($this->exeContext->promiseAdapter), Utils::printSafe($promise) )); } @@ -901,18 +837,18 @@ class ReferenceExecutor implements ExecutorImplementation * If the callback does not return a Promise, then this function will also not * return a Promise. * - * @param mixed[] $values + * @param array $values * @param Promise|mixed|null $initialValue * - * @return mixed[] + * @return Promise|mixed|null */ - private function promiseReduce(array $values, callable $callback, $initialValue) + protected function promiseReduce(array $values, callable $callback, $initialValue) { return array_reduce( $values, function ($previous, $value) use ($callback) { $promise = $this->getPromise($previous); - if ($promise) { + if ($promise !== null) { return $promise->then(static function ($resolved) use ($callback, $value) { return $callback($resolved, $value); }); @@ -925,59 +861,54 @@ class ReferenceExecutor implements ExecutorImplementation } /** - * Complete a list value by completing each item in the list with the - * inner type + * Complete a list value by completing each item in the list with the inner type. * - * @param FieldNode[] $fieldNodes - * @param mixed[] $path - * @param mixed $result + * @param array $path + * @param array|Traversable $results * - * @return mixed[]|Promise + * @return array|Promise|stdClass * * @throws Exception */ - private function completeListValue(ListOfType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) + protected function completeListValue(ListOfType $returnType, ArrayObject $fieldNodes, ResolveInfo $info, array $path, &$results) { $itemType = $returnType->getWrappedType(); Utils::invariant( - is_array($result) || $result instanceof Traversable, + is_array($results) || $results instanceof Traversable, 'User Error: expected iterable, but did not find one for field ' . $info->parentType . '.' . $info->fieldName . '.' ); $containsPromise = false; $i = 0; $completedItems = []; - foreach ($result as $item) { + foreach ($results as $item) { $fieldPath = $path; $fieldPath[] = $i++; + $info->path = $fieldPath; $completedItem = $this->completeValueCatchingError($itemType, $fieldNodes, $info, $fieldPath, $item); - if (! $containsPromise && $this->getPromise($completedItem)) { + if (! $containsPromise && $this->getPromise($completedItem) !== null) { $containsPromise = true; } $completedItems[] = $completedItem; } - return $containsPromise ? $this->exeContext->promises->all($completedItems) : $completedItems; + return $containsPromise + ? $this->exeContext->promiseAdapter->all($completedItems) + : $completedItems; } /** * Complete a Scalar or Enum by serializing to a valid value, throwing if serialization is not possible. * - * @param mixed $result + * @param mixed $result * * @return mixed * * @throws Exception */ - private function completeLeafValue(LeafType $returnType, &$result) + protected function completeLeafValue(LeafType $returnType, &$result) { try { return $returnType->serialize($result); - } catch (Exception $error) { - throw new InvariantViolation( - 'Expected a value of type "' . Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result), - 0, - $error - ); } catch (Throwable $error) { throw new InvariantViolation( 'Expected a value of type "' . Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result), @@ -991,23 +922,32 @@ class ReferenceExecutor implements ExecutorImplementation * Complete a value of an abstract type by determining the runtime object type * of that value, then complete the value for that type. * - * @param FieldNode[] $fieldNodes - * @param mixed[] $path - * @param mixed[] $result + * @param array $path + * @param array $result * - * @return mixed + * @return array|Promise|stdClass * * @throws Error */ - private function completeAbstractValue(AbstractType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) - { - $exeContext = $this->exeContext; - $runtimeType = $returnType->resolveType($result, $exeContext->contextValue, $info); - if ($runtimeType === null) { - $runtimeType = self::defaultTypeResolver($result, $exeContext->contextValue, $info, $returnType); + protected function completeAbstractValue( + AbstractType $returnType, + ArrayObject $fieldNodes, + ResolveInfo $info, + array $path, + &$result + ) { + $exeContext = $this->exeContext; + $typeCandidate = $returnType->resolveType($result, $exeContext->contextValue, $info); + + if ($typeCandidate === null) { + $runtimeType = static::defaultTypeResolver($result, $exeContext->contextValue, $info, $returnType); + } elseif (is_callable($typeCandidate)) { + $runtimeType = Schema::resolveType($typeCandidate); + } else { + $runtimeType = $typeCandidate; } $promise = $this->getPromise($runtimeType); - if ($promise) { + if ($promise !== null) { return $promise->then(function ($resolvedRuntimeType) use ( $returnType, $fieldNodes, @@ -1054,12 +994,13 @@ class ReferenceExecutor implements ExecutorImplementation * Otherwise, test each possible type for the abstract type by calling * isTypeOf for the object being coerced, returning the first type that matches. * - * @param mixed|null $value - * @param mixed|null $context + * @param mixed|null $value + * @param mixed|null $contextValue + * @param InterfaceType|UnionType $abstractType * - * @return ObjectType|Promise|null + * @return Promise|Type|string|null */ - private function defaultTypeResolver($value, $context, ResolveInfo $info, AbstractType $abstractType) + protected function defaultTypeResolver($value, $contextValue, ResolveInfo $info, AbstractType $abstractType) { // First, look for `__typename`. if ($value !== null && @@ -1069,7 +1010,8 @@ class ReferenceExecutor implements ExecutorImplementation ) { return $value['__typename']; } - if ($abstractType instanceof InterfaceType && $info->schema->getConfig()->typeLoader) { + + if ($abstractType instanceof InterfaceType && $info->schema->getConfig()->typeLoader !== null) { Warning::warnOnce( sprintf( 'GraphQL Interface Type `%s` returned `null` from its `resolveType` function ' . @@ -1086,20 +1028,20 @@ class ReferenceExecutor implements ExecutorImplementation $possibleTypes = $info->schema->getPossibleTypes($abstractType); $promisedIsTypeOfResults = []; foreach ($possibleTypes as $index => $type) { - $isTypeOfResult = $type->isTypeOf($value, $context, $info); + $isTypeOfResult = $type->isTypeOf($value, $contextValue, $info); if ($isTypeOfResult === null) { continue; } $promise = $this->getPromise($isTypeOfResult); - if ($promise) { + if ($promise !== null) { $promisedIsTypeOfResults[$index] = $promise; } elseif ($isTypeOfResult) { return $type; } } - if (! empty($promisedIsTypeOfResults)) { - return $this->exeContext->promises->all($promisedIsTypeOfResults) - ->then(static function ($isTypeOfResults) use ($possibleTypes) { + if (count($promisedIsTypeOfResults) > 0) { + return $this->exeContext->promiseAdapter->all($promisedIsTypeOfResults) + ->then(static function ($isTypeOfResults) use ($possibleTypes) : ?ObjectType { foreach ($isTypeOfResults as $index => $result) { if ($result) { return $possibleTypes[$index]; @@ -1116,23 +1058,27 @@ class ReferenceExecutor implements ExecutorImplementation /** * Complete an Object value by executing all sub-selections. * - * @param FieldNode[] $fieldNodes - * @param mixed[] $path - * @param mixed $result + * @param array $path + * @param mixed $result * - * @return mixed[]|Promise|stdClass + * @return array|Promise|stdClass * * @throws Error */ - private function completeObjectValue(ObjectType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) - { + protected function completeObjectValue( + ObjectType $returnType, + ArrayObject $fieldNodes, + ResolveInfo $info, + array $path, + &$result + ) { // If there is an isTypeOf predicate function, call it with the // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. $isTypeOf = $returnType->isTypeOf($result, $this->exeContext->contextValue, $info); if ($isTypeOf !== null) { $promise = $this->getPromise($isTypeOf); - if ($promise) { + if ($promise !== null) { return $promise->then(function ($isTypeOfResult) use ( $returnType, $fieldNodes, @@ -1165,15 +1111,14 @@ class ReferenceExecutor implements ExecutorImplementation } /** - * @param mixed[] $result - * @param FieldNode[] $fieldNodes + * @param array $result * * @return Error */ - private function invalidReturnTypeError( + protected function invalidReturnTypeError( ObjectType $returnType, $result, - $fieldNodes + ArrayObject $fieldNodes ) { return new Error( 'Expected value of type "' . $returnType->name . '" but got: ' . Utils::printSafe($result) . '.', @@ -1182,18 +1127,17 @@ class ReferenceExecutor implements ExecutorImplementation } /** - * @param FieldNode[] $fieldNodes - * @param mixed[] $path - * @param mixed[] $result + * @param array $path + * @param mixed $result * - * @return mixed[]|Promise|stdClass + * @return array|Promise|stdClass * * @throws Error */ - private function collectAndExecuteSubfields( + protected function collectAndExecuteSubfields( ObjectType $returnType, - $fieldNodes, - $path, + ArrayObject $fieldNodes, + array $path, &$result ) { $subFieldNodes = $this->collectSubFields($returnType, $fieldNodes); @@ -1201,7 +1145,12 @@ class ReferenceExecutor implements ExecutorImplementation return $this->executeFields($returnType, $result, $path, $subFieldNodes); } - private function collectSubFields(ObjectType $returnType, $fieldNodes) : ArrayObject + /** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + protected function collectSubFields(ObjectType $returnType, ArrayObject $fieldNodes) : ArrayObject { if (! isset($this->subFieldCache[$returnType])) { $this->subFieldCache[$returnType] = new SplObjectStorage(); @@ -1231,48 +1180,48 @@ class ReferenceExecutor implements ExecutorImplementation * Implements the "Evaluating selection sets" section of the spec * for "read" mode. * - * @param mixed|null $source - * @param mixed[] $path - * @param ArrayObject $fields + * @param mixed $rootValue + * @param array $path * - * @return Promise|stdClass|mixed[] + * @return Promise|stdClass|array */ - private function executeFields(ObjectType $parentType, $source, $path, $fields) + protected function executeFields(ObjectType $parentType, $rootValue, array $path, ArrayObject $fields) { $containsPromise = false; - $finalResults = []; + $results = []; foreach ($fields as $responseName => $fieldNodes) { $fieldPath = $path; $fieldPath[] = $responseName; - $result = $this->resolveField($parentType, $source, $fieldNodes, $fieldPath); - if ($result === self::$UNDEFINED) { + $result = $this->resolveField($parentType, $rootValue, $fieldNodes, $fieldPath); + if ($result === static::$UNDEFINED) { continue; } - if (! $containsPromise && $this->getPromise($result)) { + if (! $containsPromise && $this->isPromise($result)) { $containsPromise = true; } - $finalResults[$responseName] = $result; + $results[$responseName] = $result; } // If there are no promises, we can just return the object if (! $containsPromise) { - return self::fixResultsIfEmptyArray($finalResults); + return static::fixResultsIfEmptyArray($results); } - // Otherwise, results is a map from field name to the result - // of resolving that field, which is possibly a promise. Return - // a promise that will return this same map, but with any - // promises replaced with the values they resolved to. - return $this->promiseForAssocArray($finalResults); + // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + return $this->promiseForAssocArray($results); } /** + * Differentiate empty objects from empty lists. + * * @see https://github.com/webonyx/graphql-php/issues/59 * - * @param mixed[] $results + * @param array|mixed $results * - * @return stdClass|mixed[] + * @return array|stdClass|mixed */ - private static function fixResultsIfEmptyArray($results) + protected static function fixResultsIfEmptyArray($results) { if ($results === []) { return new stdClass(); @@ -1282,21 +1231,16 @@ class ReferenceExecutor implements ExecutorImplementation } /** - * This function transforms a PHP `array` into - * a `Promise>` + * Transform an associative array with Promises to a Promise which resolves to an + * associative array where all Promises were resolved. * - * In other words it returns a promise which resolves to normal PHP associative array which doesn't contain - * any promises. - * - * @param (string|Promise)[] $assoc - * - * @return mixed + * @param array $assoc */ - private function promiseForAssocArray(array $assoc) + protected function promiseForAssocArray(array $assoc) : Promise { $keys = array_keys($assoc); $valuesAndPromises = array_values($assoc); - $promise = $this->exeContext->promises->all($valuesAndPromises); + $promise = $this->exeContext->promiseAdapter->all($valuesAndPromises); return $promise->then(static function ($values) use ($keys) { $resolvedResults = []; @@ -1304,26 +1248,24 @@ class ReferenceExecutor implements ExecutorImplementation $resolvedResults[$keys[$i]] = $value; } - return self::fixResultsIfEmptyArray($resolvedResults); + return static::fixResultsIfEmptyArray($resolvedResults); }); } /** - * @param string|ObjectType|null $runtimeTypeOrName - * @param FieldNode[] $fieldNodes - * @param mixed $result - * - * @return ObjectType + * @param string|ObjectType|null $runtimeTypeOrName + * @param InterfaceType|UnionType $returnType + * @param mixed $result */ - private function ensureValidRuntimeType( + protected function ensureValidRuntimeType( $runtimeTypeOrName, AbstractType $returnType, ResolveInfo $info, &$result - ) { - $runtimeType = is_string($runtimeTypeOrName) ? - $this->exeContext->schema->getType($runtimeTypeOrName) : - $runtimeTypeOrName; + ) : ObjectType { + $runtimeType = is_string($runtimeTypeOrName) + ? $this->exeContext->schema->getType($runtimeTypeOrName) + : $runtimeTypeOrName; if (! $runtimeType instanceof ObjectType) { throw new InvariantViolation( sprintf( @@ -1340,7 +1282,7 @@ class ReferenceExecutor implements ExecutorImplementation ) ); } - if (! $this->exeContext->schema->isPossibleType($returnType, $runtimeType)) { + if (! $this->exeContext->schema->isSubType($returnType, $runtimeType)) { throw new InvariantViolation( sprintf('Runtime Object type "%s" is not a possible type for "%s".', $runtimeType, $returnType) ); diff --git a/vendor/webonyx/graphql-php/src/Executor/Values.php b/vendor/webonyx/graphql-php/src/Executor/Values.php index 5548bcb..ae8d63f 100644 --- a/vendor/webonyx/graphql-php/src/Executor/Values.php +++ b/vendor/webonyx/graphql-php/src/Executor/Values.php @@ -6,22 +6,34 @@ namespace GraphQL\Executor; use GraphQL\Error\Error; use GraphQL\Language\AST\ArgumentNode; +use GraphQL\Language\AST\BooleanValueNode; use GraphQL\Language\AST\DirectiveNode; use GraphQL\Language\AST\EnumValueDefinitionNode; +use GraphQL\Language\AST\EnumValueNode; use GraphQL\Language\AST\FieldDefinitionNode; use GraphQL\Language\AST\FieldNode; +use GraphQL\Language\AST\FloatValueNode; use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\InlineFragmentNode; +use GraphQL\Language\AST\IntValueNode; +use GraphQL\Language\AST\ListValueNode; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeList; +use GraphQL\Language\AST\NullValueNode; +use GraphQL\Language\AST\ObjectValueNode; +use GraphQL\Language\AST\StringValueNode; use GraphQL\Language\AST\ValueNode; use GraphQL\Language\AST\VariableDefinitionNode; use GraphQL\Language\AST\VariableNode; use GraphQL\Language\Printer; use GraphQL\Type\Definition\Directive; +use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\FieldDefinition; +use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InputType; +use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NonNull; +use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema; use GraphQL\Utils\AST; @@ -32,6 +44,7 @@ use stdClass; use Throwable; use function array_key_exists; use function array_map; +use function count; use function sprintf; class Values @@ -55,48 +68,9 @@ class Values /** @var InputType|Type $varType */ $varType = TypeInfo::typeFromAST($schema, $varDefNode->type); - if (Type::isInputType($varType)) { - if (array_key_exists($varName, $inputs)) { - $value = $inputs[$varName]; - $coerced = Value::coerceValue($value, $varType, $varDefNode); - /** @var Error[] $coercionErrors */ - $coercionErrors = $coerced['errors']; - if (empty($coercionErrors)) { - $coercedValues[$varName] = $coerced['value']; - } else { - $messagePrelude = sprintf( - 'Variable "$%s" got invalid value %s; ', - $varName, - Utils::printSafeJson($value) - ); - - foreach ($coercionErrors as $error) { - $errors[] = new Error( - $messagePrelude . $error->getMessage(), - $error->getNodes(), - $error->getSource(), - $error->getPositions(), - $error->getPath(), - $error->getPrevious(), - $error->getExtensions() - ); - } - } - } else { - if ($varType instanceof NonNull) { - $errors[] = new Error( - sprintf( - 'Variable "$%s" of required type "%s" was not provided.', - $varName, - $varType - ), - [$varDefNode] - ); - } elseif ($varDefNode->defaultValue) { - $coercedValues[$varName] = AST::valueFromAST($varDefNode->defaultValue, $varType); - } - } - } else { + if (! Type::isInputType($varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. $errors[] = new Error( sprintf( 'Variable "$%s" expected value of type "%s" which cannot be used as an input type.', @@ -105,10 +79,65 @@ class Values ), [$varDefNode->type] ); + } else { + $hasValue = array_key_exists($varName, $inputs); + $value = $hasValue ? $inputs[$varName] : Utils::undefined(); + + if (! $hasValue && ($varDefNode->defaultValue !== null)) { + // If no value was provided to a variable with a default value, + // use the default value. + $coercedValues[$varName] = AST::valueFromAST($varDefNode->defaultValue, $varType); + } elseif ((! $hasValue || $value === null) && ($varType instanceof NonNull)) { + // If no value or a nullish value was provided to a variable with a + // non-null type (required), produce an error. + $errors[] = new Error( + sprintf( + $hasValue + ? 'Variable "$%s" of non-null type "%s" must not be null.' + : 'Variable "$%s" of required type "%s" was not provided.', + $varName, + Utils::printSafe($varType) + ), + [$varDefNode] + ); + } elseif ($hasValue) { + if ($value === null) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + $coercedValues[$varName] = null; + } else { + // Otherwise, a non-null value was provided, coerce it to the expected + // type or report an error if coercion fails. + $coerced = Value::coerceValue($value, $varType, $varDefNode); + /** @var Error[] $coercionErrors */ + $coercionErrors = $coerced['errors']; + if (count($coercionErrors ?? []) > 0) { + $messagePrelude = sprintf( + 'Variable "$%s" got invalid value %s; ', + $varName, + Utils::printSafeJson($value) + ); + + foreach ($coercionErrors as $error) { + $errors[] = new Error( + $messagePrelude . $error->getMessage(), + $error->getNodes(), + $error->getSource(), + $error->getPositions(), + $error->getPath(), + $error->getPrevious(), + $error->getExtensions() + ); + } + } else { + $coercedValues[$varName] = $coerced['value']; + } + } + } } } - if (! empty($errors)) { + if (count($errors) > 0) { return [$errors, null]; } @@ -132,7 +161,7 @@ class Values if (isset($node->directives) && $node->directives instanceof NodeList) { $directiveNode = Utils::find( $node->directives, - static function (DirectiveNode $directive) use ($directiveDef) { + static function (DirectiveNode $directive) use ($directiveDef) : bool { return $directive->name->value === $directiveDef->name; } ); @@ -159,15 +188,11 @@ class Values */ public static function getArgumentValues($def, $node, $variableValues = null) { - if (empty($def->args)) { - return []; - } - - $argumentNodes = $node->arguments; - if (empty($argumentNodes)) { + if (count($def->args) === 0) { return []; } + $argumentNodes = $node->arguments; $argumentValueMap = []; foreach ($argumentNodes as $argumentNode) { $argumentValueMap[$argumentNode->name->value] = $argumentNode->value; @@ -196,27 +221,32 @@ class Values $argType = $argumentDefinition->getType(); $argumentValueNode = $argumentValueMap[$name] ?? null; - if (! $argumentValueNode) { - if ($argumentDefinition->defaultValueExists()) { - $coercedValues[$name] = $argumentDefinition->defaultValue; - } elseif ($argType instanceof NonNull) { + if ($argumentValueNode instanceof VariableNode) { + $variableName = $argumentValueNode->name->value; + $hasValue = array_key_exists($variableName, $variableValues ?? []); + $isNull = $hasValue ? $variableValues[$variableName] === null : false; + } else { + $hasValue = $argumentValueNode !== null; + $isNull = $argumentValueNode instanceof NullValueNode; + } + + if (! $hasValue && $argumentDefinition->defaultValueExists()) { + // If no argument was provided where the definition has a default value, + // use the default value. + $coercedValues[$name] = $argumentDefinition->defaultValue; + } elseif ((! $hasValue || $isNull) && ($argType instanceof NonNull)) { + // If no argument or a null value was provided to an argument with a + // non-null type (required), produce a field error. + if ($isNull) { throw new Error( - 'Argument "' . $name . '" of required type ' . - '"' . Utils::printSafe($argType) . '" was not provided.', + 'Argument "' . $name . '" of non-null type ' . + '"' . Utils::printSafe($argType) . '" must not be null.', $referenceNode ); } - } elseif ($argumentValueNode instanceof VariableNode) { - $variableName = $argumentValueNode->name->value; - if ($variableValues && array_key_exists($variableName, $variableValues)) { - // Note: this does not check that this variable value is correct. - // This assumes that this query has been validated and the variable - // usage here is of the correct type. - $coercedValues[$name] = $variableValues[$variableName]; - } elseif ($argumentDefinition->defaultValueExists()) { - $coercedValues[$name] = $argumentDefinition->defaultValue; - } elseif ($argType instanceof NonNull) { + if ($argumentValueNode instanceof VariableNode) { + $variableName = $argumentValueNode->name->value; throw new Error( 'Argument "' . $name . '" of required type "' . Utils::printSafe($argType) . '" was ' . 'provided the variable "$' . $variableName . '" which was not provided ' . @@ -224,19 +254,38 @@ class Values [$argumentValueNode] ); } - } else { - $valueNode = $argumentValueNode; - $coercedValue = AST::valueFromAST($valueNode, $argType, $variableValues); - if (Utils::isInvalid($coercedValue)) { - // Note: ValuesOfCorrectType validation should catch this before - // execution. This is a runtime check to ensure execution does not - // continue with an invalid argument value. - throw new Error( - 'Argument "' . $name . '" has invalid value ' . Printer::doPrint($valueNode) . '.', - [$argumentValueNode] - ); + + throw new Error( + 'Argument "' . $name . '" of required type ' . + '"' . Utils::printSafe($argType) . '" was not provided.', + $referenceNode + ); + } elseif ($hasValue) { + if ($argumentValueNode instanceof NullValueNode) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + $coercedValues[$name] = null; + } elseif ($argumentValueNode instanceof VariableNode) { + $variableName = $argumentValueNode->name->value; + Utils::invariant($variableValues !== null, 'Must exist for hasValue to be true.'); + // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + $coercedValues[$name] = $variableValues[$variableName] ?? null; + } else { + $valueNode = $argumentValueNode; + $coercedValue = AST::valueFromAST($valueNode, $argType, $variableValues); + if (Utils::isInvalid($coercedValue)) { + // Note: ValuesOfCorrectType validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new Error( + 'Argument "' . $name . '" has invalid value ' . Printer::doPrint($valueNode) . '.', + [$argumentValueNode] + ); + } + $coercedValues[$name] = $coercedValue; } - $coercedValues[$name] = $coercedValue; } } @@ -246,12 +295,15 @@ class Values /** * @deprecated as of 8.0 (Moved to \GraphQL\Utils\AST::valueFromAST) * - * @param ValueNode $valueNode - * @param mixed[]|null $variables + * @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode $valueNode + * @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type + * @param mixed[]|null $variables * * @return mixed[]|stdClass|null + * + * @codeCoverageIgnore */ - public static function valueFromAST($valueNode, InputType $type, ?array $variables = null) + public static function valueFromAST(ValueNode $valueNode, InputType $type, ?array $variables = null) { return AST::valueFromAST($valueNode, $type, $variables); } @@ -259,9 +311,12 @@ class Values /** * @deprecated as of 0.12 (Use coerceValue() directly for richer information) * - * @param mixed[] $value + * @param mixed[] $value + * @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type * * @return string[] + * + * @codeCoverageIgnore */ public static function isValidPHPValue($value, InputType $type) { @@ -269,10 +324,11 @@ class Values return $errors ? array_map( - static function (Throwable $error) { + static function (Throwable $error) : string { return $error->getMessage(); }, $errors - ) : []; + ) + : []; } } diff --git a/vendor/webonyx/graphql-php/src/Experimental/Executor/Collector.php b/vendor/webonyx/graphql-php/src/Experimental/Executor/Collector.php index 99131ba..dc1b49f 100644 --- a/vendor/webonyx/graphql-php/src/Experimental/Executor/Collector.php +++ b/vendor/webonyx/graphql-php/src/Experimental/Executor/Collector.php @@ -6,23 +6,31 @@ namespace GraphQL\Experimental\Executor; use Generator; use GraphQL\Error\Error; +use GraphQL\Language\AST\BooleanValueNode; use GraphQL\Language\AST\DefinitionNode; use GraphQL\Language\AST\DocumentNode; +use GraphQL\Language\AST\EnumValueNode; use GraphQL\Language\AST\FieldNode; +use GraphQL\Language\AST\FloatValueNode; use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\InlineFragmentNode; +use GraphQL\Language\AST\IntValueNode; +use GraphQL\Language\AST\ListValueNode; use GraphQL\Language\AST\Node; -use GraphQL\Language\AST\NodeKind; +use GraphQL\Language\AST\NullValueNode; +use GraphQL\Language\AST\ObjectValueNode; use GraphQL\Language\AST\OperationDefinitionNode; use GraphQL\Language\AST\SelectionSetNode; -use GraphQL\Language\AST\ValueNode; +use GraphQL\Language\AST\StringValueNode; +use GraphQL\Language\AST\VariableNode; use GraphQL\Type\Definition\AbstractType; use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Introspection; use GraphQL\Type\Schema; +use function count; use function sprintf; /** @@ -48,7 +56,7 @@ class Collector /** @var FieldNode[][] */ private $fields; - /** @var string[] */ + /** @var array */ private $visitedFragments; public function __construct(Schema $schema, Runtime $runtime) @@ -64,8 +72,7 @@ class Collector foreach ($documentNode->definitions as $definitionNode) { /** @var DefinitionNode|Node $definitionNode */ - if ($definitionNode->kind === NodeKind::OPERATION_DEFINITION) { - /** @var OperationDefinitionNode $definitionNode */ + if ($definitionNode instanceof OperationDefinitionNode) { if ($operationName === null && $this->operation !== null) { $hasMultipleAssumedOperations = true; } @@ -74,8 +81,7 @@ class Collector ) { $this->operation = $definitionNode; } - } elseif ($definitionNode->kind === NodeKind::FRAGMENT_DEFINITION) { - /** @var FragmentDefinitionNode $definitionNode */ + } elseif ($definitionNode instanceof FragmentDefinitionNode) { $this->fragments[$definitionNode->name->value] = $definitionNode; } } @@ -122,7 +128,7 @@ class Collector $fieldName = $fieldNode->name->value; $argumentValueMap = null; - if (! empty($fieldNode->arguments)) { + if (count($fieldNode->arguments) > 0) { foreach ($fieldNode->arguments as $argumentNode) { $argumentValueMap = $argumentValueMap ?? []; $argumentValueMap[$argumentNode->name->value] = $argumentNode->value; @@ -149,11 +155,10 @@ class Collector foreach ($selectionSet->selections as $selection) { /** @var FieldNode|FragmentSpreadNode|InlineFragmentNode $selection */ - - if (! empty($selection->directives)) { + if (count($selection->directives) > 0) { foreach ($selection->directives as $directiveNode) { if ($directiveNode->name->value === Directive::SKIP_NAME) { - /** @var ValueNode|null $condition */ + /** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null $condition */ $condition = null; foreach ($directiveNode->arguments as $argumentNode) { if ($argumentNode->name->value === Directive::IF_ARGUMENT_NAME) { @@ -173,7 +178,7 @@ class Collector } } } elseif ($directiveNode->name->value === Directive::INCLUDE_NAME) { - /** @var ValueNode|null $condition */ + /** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null $condition */ $condition = null; foreach ($directiveNode->arguments as $argumentNode) { if ($argumentNode->name->value === Directive::IF_ARGUMENT_NAME) { @@ -196,19 +201,15 @@ class Collector } } - if ($selection->kind === NodeKind::FIELD) { - /** @var FieldNode $selection */ - - $resultName = $selection->alias ? $selection->alias->value : $selection->name->value; + if ($selection instanceof FieldNode) { + $resultName = $selection->alias === null ? $selection->name->value : $selection->alias->value; if (! isset($this->fields[$resultName])) { $this->fields[$resultName] = []; } $this->fields[$resultName][] = $selection; - } elseif ($selection->kind === NodeKind::FRAGMENT_SPREAD) { - /** @var FragmentSpreadNode $selection */ - + } elseif ($selection instanceof FragmentSpreadNode) { $fragmentName = $selection->name->value; if (isset($this->visitedFragments[$fragmentName])) { @@ -243,15 +244,13 @@ class Collector continue; } } elseif ($conditionType instanceof AbstractType) { - if (! $this->schema->isPossibleType($conditionType, $runtimeType)) { + if (! $this->schema->isSubType($conditionType, $runtimeType)) { continue; } } $this->doCollectFields($runtimeType, $fragmentDefinition->selectionSet); - } elseif ($selection->kind === NodeKind::INLINE_FRAGMENT) { - /** @var InlineFragmentNode $selection */ - + } elseif ($selection instanceof InlineFragmentNode) { if ($selection->typeCondition !== null) { $conditionTypeName = $selection->typeCondition->name->value; @@ -270,7 +269,7 @@ class Collector continue; } } elseif ($conditionType instanceof AbstractType) { - if (! $this->schema->isPossibleType($conditionType, $runtimeType)) { + if (! $this->schema->isSubType($conditionType, $runtimeType)) { continue; } } diff --git a/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineContext.php b/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineContext.php index 910b41d..d22ec77 100644 --- a/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineContext.php +++ b/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineContext.php @@ -27,7 +27,7 @@ class CoroutineContext /** @var string[] */ public $path; - /** @var ResolveInfo|null */ + /** @var ResolveInfo */ public $resolveInfo; /** @var string[]|null */ diff --git a/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineExecutor.php b/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineExecutor.php index 91091b4..7498100 100644 --- a/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineExecutor.php +++ b/vendor/webonyx/graphql-php/src/Experimental/Executor/CoroutineExecutor.php @@ -18,6 +18,8 @@ use GraphQL\Language\AST\SelectionSetNode; use GraphQL\Language\AST\ValueNode; use GraphQL\Type\Definition\AbstractType; use GraphQL\Type\Definition\CompositeType; +use GraphQL\Type\Definition\EnumType; +use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InputType; use GraphQL\Type\Definition\InterfaceType; use GraphQL\Type\Definition\LeafType; @@ -25,6 +27,7 @@ use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\ResolveInfo; +use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Introspection; @@ -34,6 +37,7 @@ use GraphQL\Utils\Utils; use SplQueue; use stdClass; use Throwable; +use function count; use function is_array; use function is_string; use function sprintf; @@ -70,10 +74,10 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation /** @var string|null */ private $operationName; - /** @var Collector */ + /** @var Collector|null */ private $collector; - /** @var Error[] */ + /** @var array */ private $errors; /** @var SplQueue */ @@ -82,10 +86,10 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation /** @var SplQueue */ private $schedule; - /** @var stdClass */ + /** @var stdClass|null */ private $rootResult; - /** @var int */ + /** @var int|null */ private $pending; /** @var callable */ @@ -105,6 +109,9 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation self::$undefined = Utils::undefined(); } + $this->errors = []; + $this->queue = new SplQueue(); + $this->schedule = new SplQueue(); $this->schema = $schema; $this->fieldResolver = $fieldResolver; $this->promiseAdapter = $promiseAdapter; @@ -140,11 +147,12 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation private static function resultToArray($value, $emptyObjectAsStdClass = true) { if ($value instanceof stdClass) { - $array = []; - foreach ($value as $propertyName => $propertyValue) { + $array = (array) $value; + foreach ($array as $propertyName => $propertyValue) { $array[$propertyName] = self::resultToArray($propertyValue); } - if ($emptyObjectAsStdClass && empty($array)) { + + if ($emptyObjectAsStdClass && count($array) === 0) { return new stdClass(); } @@ -174,17 +182,17 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation $this->collector = new Collector($this->schema, $this); $this->collector->initialize($this->documentNode, $this->operationName); - if (! empty($this->errors)) { + if (count($this->errors) > 0) { return $this->promiseAdapter->createFulfilled($this->finishExecute(null, $this->errors)); } [$errors, $coercedVariableValues] = Values::getVariableValues( $this->schema, - $this->collector->operation->variableDefinitions ?: [], - $this->rawVariableValues ?: [] + $this->collector->operation->variableDefinitions ?? [], + $this->rawVariableValues ?? [] ); - if (! empty($errors)) { + if (count($errors ?? []) > 0) { return $this->promiseAdapter->createFulfilled($this->finishExecute(null, $errors)); } @@ -219,7 +227,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation $this->run(); if ($this->pending > 0) { - return $this->promiseAdapter->create(function (callable $resolve) { + return $this->promiseAdapter->create(function (callable $resolve) : void { $this->doResolve = $resolve; }); } @@ -234,9 +242,9 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation private function finishExecute($value, array $errors) : ExecutionResult { $this->rootResult = null; - $this->errors = null; - $this->queue = null; - $this->schedule = null; + $this->errors = []; + $this->queue = new SplQueue(); + $this->schedule = new SplQueue(); $this->pending = null; $this->collector = null; $this->variableValues = null; @@ -250,6 +258,8 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation /** * @internal + * + * @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type */ public function evaluate(ValueNode $valueNode, InputType $type) { @@ -304,13 +314,13 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation $this->promiseAdapter ->then( $value, - function ($value) use ($strand) { + function ($value) use ($strand) : void { $strand->success = true; $strand->value = $value; $this->queue->enqueue($strand); $this->done(); }, - function (Throwable $throwable) use ($strand) { + function (Throwable $throwable) use ($strand) : void { $strand->success = false; $strand->value = $throwable; $this->queue->enqueue($strand); @@ -396,9 +406,8 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation $returnType = $fieldDefinition->getType(); $ctx->resolveInfo = new ResolveInfo( - $ctx->shared->fieldName, + $fieldDefinition, $ctx->shared->fieldNodes, - $returnType, $ctx->type, $ctx->path, $this->schema, @@ -498,7 +507,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation if ($type !== $this->schema->getType($type->name)) { $hint = ''; - if ($this->schema->getConfig()->typeLoader) { + if ($this->schema->getConfig()->typeLoader !== null) { $hint = sprintf( 'Make sure that type loader returns the same instance as defined in %s.%s', $ctx->type, @@ -543,7 +552,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation if ($nonNull && $returnValue === null) { $this->addError(Error::createLocatedError( new InvariantViolation(sprintf( - 'Cannot return null for non-nullable field %s.%s.', + 'Cannot return null for non-nullable field "%s.%s".', $ctx->type->name, $ctx->shared->fieldName )), @@ -620,8 +629,9 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation foreach ($value as $itemValue) { ++$index; - $itemPath = $path; - $itemPath[] = $index; // !!! use arrays COW semantics + $itemPath = $path; + $itemPath[] = $index; // !!! use arrays COW semantics + $ctx->resolveInfo->path = $itemPath; try { if (! $this->completeValueFast($ctx, $itemType, $itemValue, $itemPath, $itemReturnValue)) { @@ -646,7 +656,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation } else { if ($type !== $this->schema->getType($type->name)) { $hint = ''; - if ($this->schema->getConfig()->typeLoader) { + if ($this->schema->getConfig()->typeLoader !== null) { $hint = sprintf( 'Make sure that type loader returns the same instance as defined in %s.%s', $ctx->type, @@ -735,7 +745,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation $returnValue = null; goto CHECKED_RETURN; - } elseif (! $this->schema->isPossibleType($type, $objectType)) { + } elseif (! $this->schema->isSubType($type, $objectType)) { $this->addError(Error::createLocatedError( new InvariantViolation(sprintf( 'Runtime Object type "%s" is not a possible type for "%s".', @@ -820,9 +830,16 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation } else { $childContexts = []; - foreach ($this->collector->collectFields($objectType, $ctx->shared->mergedSelectionSet ?? $this->mergeSelectionSets($ctx)) as $childShared) { - /** @var CoroutineContextShared $childShared */ + $fields = []; + if ($this->collector !== null) { + $fields = $this->collector->collectFields( + $objectType, + $ctx->shared->mergedSelectionSet ?? $this->mergeSelectionSets($ctx) + ); + } + /** @var CoroutineContextShared $childShared */ + foreach ($fields as $childShared) { $childPath = $path; $childPath[] = $childShared->resultName; // !!! uses array COW semantics $childCtx = new CoroutineContext( @@ -863,7 +880,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation if ($nonNull && $returnValue === null) { $this->addError(Error::createLocatedError( new InvariantViolation(sprintf( - 'Cannot return null for non-nullable field %s.%s.', + 'Cannot return null for non-nullable field "%s.%s".', $ctx->type->name, $ctx->shared->fieldName )), @@ -894,6 +911,11 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation return $ctx->shared->mergedSelectionSet = new SelectionSetNode(['selections' => $selections]); } + /** + * @param InterfaceType|UnionType $abstractType + * + * @return Generator|ObjectType|Type|null + */ private function resolveTypeSlow(CoroutineContext $ctx, $value, AbstractType $abstractType) { if ($value !== null && @@ -904,7 +926,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation return $this->schema->getType($value['__typename']); } - if ($abstractType instanceof InterfaceType && $this->schema->getConfig()->typeLoader) { + if ($abstractType instanceof InterfaceType && $this->schema->getConfig()->typeLoader !== null) { Warning::warnOnce( sprintf( 'GraphQL Interface Type `%s` returned `null` from its `resolveType` function ' . @@ -926,7 +948,7 @@ class CoroutineExecutor implements Runtime, ExecutorImplementation $selectedType = null; foreach ($possibleTypes as $type) { $typeCheck = yield $type->isTypeOf($value, $this->contextValue, $ctx->resolveInfo); - if ($selectedType !== null || $typeCheck !== true) { + if ($selectedType !== null || ! $typeCheck) { continue; } diff --git a/vendor/webonyx/graphql-php/src/Experimental/Executor/Runtime.php b/vendor/webonyx/graphql-php/src/Experimental/Executor/Runtime.php index f8dc14a..a5c8fa6 100644 --- a/vendor/webonyx/graphql-php/src/Experimental/Executor/Runtime.php +++ b/vendor/webonyx/graphql-php/src/Experimental/Executor/Runtime.php @@ -5,13 +5,21 @@ declare(strict_types=1); namespace GraphQL\Experimental\Executor; use GraphQL\Language\AST\ValueNode; +use GraphQL\Type\Definition\EnumType; +use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InputType; +use GraphQL\Type\Definition\ListOfType; +use GraphQL\Type\Definition\NonNull; +use GraphQL\Type\Definition\ScalarType; /** * @internal */ interface Runtime { + /** + * @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type + */ public function evaluate(ValueNode $valueNode, InputType $type); public function addError($error); diff --git a/vendor/webonyx/graphql-php/src/GraphQL.php b/vendor/webonyx/graphql-php/src/GraphQL.php index a9819be..8f5291c 100644 --- a/vendor/webonyx/graphql-php/src/GraphQL.php +++ b/vendor/webonyx/graphql-php/src/GraphQL.php @@ -16,12 +16,14 @@ use GraphQL\Language\AST\DocumentNode; use GraphQL\Language\Parser; use GraphQL\Language\Source; use GraphQL\Type\Definition\Directive; +use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema as SchemaType; use GraphQL\Validator\DocumentValidator; use GraphQL\Validator\Rules\QueryComplexity; use GraphQL\Validator\Rules\ValidationRule; use function array_values; +use function count; use function trigger_error; use const E_USER_DEPRECATED; @@ -47,9 +49,11 @@ class GraphQL * rootValue: * The value provided as the first argument to resolver functions on the top * level type (e.g. the query object type). - * context: - * The value provided as the third argument to all resolvers. - * Use this to pass current session, user data, etc + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. * variableValues: * A mapping of variable name to runtime value to use for all variables * defined in the requestString. @@ -68,7 +72,7 @@ class GraphQL * * @param string|DocumentNode $source * @param mixed $rootValue - * @param mixed $context + * @param mixed $contextValue * @param mixed[]|null $variableValues * @param ValidationRule[] $validationRules * @@ -78,7 +82,7 @@ class GraphQL SchemaType $schema, $source, $rootValue = null, - $context = null, + $contextValue = null, $variableValues = null, ?string $operationName = null, ?callable $fieldResolver = null, @@ -91,7 +95,7 @@ class GraphQL $schema, $source, $rootValue, - $context, + $contextValue, $variableValues, $operationName, $fieldResolver, @@ -128,11 +132,11 @@ class GraphQL if ($source instanceof DocumentNode) { $documentNode = $source; } else { - $documentNode = Parser::parse(new Source($source ?: '', 'GraphQL')); + $documentNode = Parser::parse(new Source($source ?? '', 'GraphQL')); } // FIXME - if (empty($validationRules)) { + if (count($validationRules ?? []) === 0) { /** @var QueryComplexity $queryComplexity */ $queryComplexity = DocumentValidator::getRule(QueryComplexity::class); $queryComplexity->setRawVariableValues($variableValues); @@ -148,7 +152,7 @@ class GraphQL $validationErrors = DocumentValidator::validate($schema, $documentNode, $validationRules); - if (! empty($validationErrors)) { + if (count($validationErrors) > 0) { return $promiseAdapter->createFulfilled( new ExecutionResult(null, $validationErrors) ); @@ -180,6 +184,8 @@ class GraphQL * @param mixed[]|null $variableValues * * @return Promise|mixed[] + * + * @codeCoverageIgnore */ public static function execute( SchemaType $schema, @@ -208,7 +214,7 @@ class GraphQL if ($promiseAdapter instanceof SyncPromiseAdapter) { $result = $promiseAdapter->wait($result)->toArray(); } else { - $result = $result->then(static function (ExecutionResult $r) { + $result = $result->then(static function (ExecutionResult $r) : array { return $r->toArray(); }); } @@ -225,6 +231,8 @@ class GraphQL * @param mixed[]|null $variableValues * * @return ExecutionResult|Promise + * + * @codeCoverageIgnore */ public static function executeAndReturnResult( SchemaType $schema, @@ -285,7 +293,7 @@ class GraphQL * Replaces standard types with types from this list (matching by name) * Standard types not listed here remain untouched. * - * @param Type[] $types + * @param array $types * * @api */ @@ -326,6 +334,10 @@ class GraphQL */ public static function useExperimentalExecutor() { + trigger_error( + 'Experimental Executor is deprecated and will be removed in the next major version', + E_USER_DEPRECATED + ); Executor::setImplementationFactory([CoroutineExecutor::class, 'create']); } @@ -343,6 +355,8 @@ class GraphQL * @deprecated Renamed to getStandardDirectives * * @return Directive[] + * + * @codeCoverageIgnore */ public static function getInternalDirectives() : array { diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ArgumentNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ArgumentNode.php index 545a855..0abfb6f 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ArgumentNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ArgumentNode.php @@ -9,7 +9,7 @@ class ArgumentNode extends Node /** @var string */ public $kind = NodeKind::ARGUMENT; - /** @var ValueNode */ + /** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode */ public $value; /** @var NameNode */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/DefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/DefinitionNode.php index b3255d4..c331e23 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/DefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/DefinitionNode.php @@ -7,7 +7,7 @@ namespace GraphQL\Language\AST; /** * export type DefinitionNode = * | ExecutableDefinitionNode - * | TypeSystemDefinitionNode; // experimental non-spec addition. + * | TypeSystemDefinitionNode; */ interface DefinitionNode { diff --git a/vendor/webonyx/graphql-php/src/Language/AST/DirectiveDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/DirectiveDefinitionNode.php index 825c7f7..ed75ba2 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/DirectiveDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/DirectiveDefinitionNode.php @@ -12,12 +12,15 @@ class DirectiveDefinitionNode extends Node implements TypeSystemDefinitionNode /** @var NameNode */ public $name; - /** @var ArgumentNode[] */ - public $arguments; - - /** @var NameNode[] */ - public $locations; - /** @var StringValueNode|null */ public $description; + + /** @var NodeList */ + public $arguments; + + /** @var bool */ + public $repeatable; + + /** @var NodeList */ + public $locations; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/DirectiveNode.php b/vendor/webonyx/graphql-php/src/Language/AST/DirectiveNode.php index 09de366..c75aafb 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/DirectiveNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/DirectiveNode.php @@ -12,6 +12,6 @@ class DirectiveNode extends Node /** @var NameNode */ public $name; - /** @var ArgumentNode[] */ + /** @var NodeList */ public $arguments; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/DocumentNode.php b/vendor/webonyx/graphql-php/src/Language/AST/DocumentNode.php index bcf051b..ad421aa 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/DocumentNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/DocumentNode.php @@ -9,6 +9,6 @@ class DocumentNode extends Node /** @var string */ public $kind = NodeKind::DOCUMENT; - /** @var NodeList|DefinitionNode[] */ + /** @var NodeList */ public $definitions; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeDefinitionNode.php index 4ecd8fd..5d8c208 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeDefinitionNode.php @@ -12,10 +12,10 @@ class EnumTypeDefinitionNode extends Node implements TypeDefinitionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; - /** @var EnumValueDefinitionNode[]|NodeList|null */ + /** @var NodeList */ public $values; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeExtensionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeExtensionNode.php index 7812abc..2c90fef 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeExtensionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/EnumTypeExtensionNode.php @@ -12,9 +12,9 @@ class EnumTypeExtensionNode extends Node implements TypeExtensionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var EnumValueDefinitionNode[]|null */ + /** @var NodeList */ public $values; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/EnumValueDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/EnumValueDefinitionNode.php index 1eff6c2..0f9aa8d 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/EnumValueDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/EnumValueDefinitionNode.php @@ -12,7 +12,7 @@ class EnumValueDefinitionNode extends Node /** @var NameNode */ public $name; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/FieldDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/FieldDefinitionNode.php index 9e48f19..9b9f201 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/FieldDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/FieldDefinitionNode.php @@ -12,13 +12,13 @@ class FieldDefinitionNode extends Node /** @var NameNode */ public $name; - /** @var InputValueDefinitionNode[]|NodeList */ + /** @var NodeList */ public $arguments; - /** @var TypeNode */ + /** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */ public $type; - /** @var DirectiveNode[]|NodeList */ + /** @var NodeList */ public $directives; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/FieldNode.php b/vendor/webonyx/graphql-php/src/Language/AST/FieldNode.php index e3c4125..174dbd9 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/FieldNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/FieldNode.php @@ -15,10 +15,10 @@ class FieldNode extends Node implements SelectionNode /** @var NameNode|null */ public $alias; - /** @var ArgumentNode[]|null */ + /** @var NodeList */ public $arguments; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; /** @var SelectionSetNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/FragmentDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/FragmentDefinitionNode.php index 5c53e4a..5cef904 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/FragmentDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/FragmentDefinitionNode.php @@ -16,14 +16,14 @@ class FragmentDefinitionNode extends Node implements ExecutableDefinitionNode, H * Note: fragment variable definitions are experimental and may be changed * or removed in the future. * - * @var VariableDefinitionNode[]|NodeList + * @var NodeList */ public $variableDefinitions; /** @var NamedTypeNode */ public $typeCondition; - /** @var DirectiveNode[]|NodeList */ + /** @var NodeList */ public $directives; /** @var SelectionSetNode */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/FragmentSpreadNode.php b/vendor/webonyx/graphql-php/src/Language/AST/FragmentSpreadNode.php index f6ca72c..2dc693b 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/FragmentSpreadNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/FragmentSpreadNode.php @@ -12,6 +12,6 @@ class FragmentSpreadNode extends Node implements SelectionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/HasSelectionSet.php b/vendor/webonyx/graphql-php/src/Language/AST/HasSelectionSet.php index a80bcae..a412cf7 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/HasSelectionSet.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/HasSelectionSet.php @@ -4,10 +4,12 @@ declare(strict_types=1); namespace GraphQL\Language\AST; +/** + * export type DefinitionNode = OperationDefinitionNode + * | FragmentDefinitionNode + * + * @property SelectionSetNode $selectionSet + */ interface HasSelectionSet { - /** - * export type DefinitionNode = OperationDefinitionNode - * | FragmentDefinitionNode - */ } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/InlineFragmentNode.php b/vendor/webonyx/graphql-php/src/Language/AST/InlineFragmentNode.php index fe22008..0c12e22 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/InlineFragmentNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/InlineFragmentNode.php @@ -12,7 +12,7 @@ class InlineFragmentNode extends Node implements SelectionNode /** @var NamedTypeNode */ public $typeCondition; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; /** @var SelectionSetNode */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeDefinitionNode.php index f761e1f..cc32454 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeDefinitionNode.php @@ -12,10 +12,10 @@ class InputObjectTypeDefinitionNode extends Node implements TypeDefinitionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var InputValueDefinitionNode[]|null */ + /** @var NodeList */ public $fields; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeExtensionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeExtensionNode.php index b9ee90b..e470958 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeExtensionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/InputObjectTypeExtensionNode.php @@ -12,9 +12,9 @@ class InputObjectTypeExtensionNode extends Node implements TypeExtensionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var InputValueDefinitionNode[]|null */ + /** @var NodeList */ public $fields; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/InputValueDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/InputValueDefinitionNode.php index afbaabb..3e5a4aa 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/InputValueDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/InputValueDefinitionNode.php @@ -12,13 +12,13 @@ class InputValueDefinitionNode extends Node /** @var NameNode */ public $name; - /** @var TypeNode */ + /** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */ public $type; - /** @var ValueNode */ + /** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null */ public $defaultValue; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeDefinitionNode.php index b14bd7a..d0cae0e 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeDefinitionNode.php @@ -12,10 +12,13 @@ class InterfaceTypeDefinitionNode extends Node implements TypeDefinitionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var FieldDefinitionNode[]|null */ + /** @var NodeList */ + public $interfaces; + + /** @var NodeList */ public $fields; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeExtensionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeExtensionNode.php index 9528f3d..4b30f3d 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeExtensionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/InterfaceTypeExtensionNode.php @@ -12,9 +12,12 @@ class InterfaceTypeExtensionNode extends Node implements TypeExtensionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var FieldDefinitionNode[]|null */ + /** @var NodeList */ + public $interfaces; + + /** @var NodeList */ public $fields; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ListTypeNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ListTypeNode.php index 104810a..6bb3902 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ListTypeNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ListTypeNode.php @@ -9,6 +9,6 @@ class ListTypeNode extends Node implements TypeNode /** @var string */ public $kind = NodeKind::LIST_TYPE; - /** @var Node */ + /** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */ public $type; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ListValueNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ListValueNode.php index 3720c85..78792c9 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ListValueNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ListValueNode.php @@ -9,6 +9,6 @@ class ListValueNode extends Node implements ValueNode /** @var string */ public $kind = NodeKind::LST; - /** @var ValueNode[]|NodeList */ + /** @var NodeList */ public $values; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/Location.php b/vendor/webonyx/graphql-php/src/Language/AST/Location.php index 72135fc..dfd70b6 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/Location.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/Location.php @@ -30,14 +30,14 @@ class Location /** * The Token at which this Node begins. * - * @var Token + * @var Token|null */ public $startToken; /** * The Token at which this Node ends. * - * @var Token + * @var Token|null */ public $endToken; @@ -69,7 +69,7 @@ class Location $this->endToken = $endToken; $this->source = $source; - if (! $startToken || ! $endToken) { + if ($startToken === null || $endToken === null) { return; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/Node.php b/vendor/webonyx/graphql-php/src/Language/AST/Node.php index 2205d6d..3f2688d 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/Node.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/Node.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace GraphQL\Language\AST; use GraphQL\Utils\Utils; +use function count; use function get_object_vars; use function is_array; use function is_scalar; @@ -36,15 +37,18 @@ use function json_encode; */ abstract class Node { - /** @var Location */ + /** @var Location|null */ public $loc; + /** @var string */ + public $kind; + /** * @param (NameNode|NodeList|SelectionSetNode|Location|string|int|bool|float|null)[] $vars */ public function __construct(array $vars) { - if (empty($vars)) { + if (count($vars) === 0) { return; } @@ -83,10 +87,7 @@ abstract class Node return $cloned; } - /** - * @return string - */ - public function __toString() + public function __toString() : string { $tmp = $this->toArray(true); @@ -94,11 +95,9 @@ abstract class Node } /** - * @param bool $recursive - * * @return mixed[] */ - public function toArray($recursive = false) + public function toArray(bool $recursive = false) : array { if ($recursive) { return $this->recursiveToArray($this); @@ -106,7 +105,7 @@ abstract class Node $tmp = (array) $this; - if ($this->loc) { + if ($this->loc !== null) { $tmp['loc'] = [ 'start' => $this->loc->start, 'end' => $this->loc->end, @@ -125,7 +124,7 @@ abstract class Node 'kind' => $node->kind, ]; - if ($node->loc) { + if ($node->loc !== null) { $result['loc'] = [ 'start' => $node->loc->start, 'end' => $node->loc->end, diff --git a/vendor/webonyx/graphql-php/src/Language/AST/NodeList.php b/vendor/webonyx/graphql-php/src/Language/AST/NodeList.php index 648f68a..c94c40c 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/NodeList.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/NodeList.php @@ -6,31 +6,43 @@ namespace GraphQL\Language\AST; use ArrayAccess; use Countable; -use Generator; use GraphQL\Utils\AST; +use InvalidArgumentException; use IteratorAggregate; +use Traversable; use function array_merge; use function array_splice; use function count; use function is_array; +/** + * @template T of Node + * @phpstan-implements ArrayAccess + * @phpstan-implements IteratorAggregate + */ class NodeList implements ArrayAccess, IteratorAggregate, Countable { - /** @var Node[]|mixed[] */ + /** + * @var Node[] + * @phpstan-var array + */ private $nodes; /** - * @param Node[]|mixed[] $nodes + * @param Node[] $nodes * - * @return static + * @phpstan-param array $nodes + * @phpstan-return self */ - public static function create(array $nodes) + public static function create(array $nodes) : self { return new static($nodes); } /** - * @param Node[]|mixed[] $nodes + * @param Node[] $nodes + * + * @phpstan-param array $nodes */ public function __construct(array $nodes) { @@ -38,59 +50,75 @@ class NodeList implements ArrayAccess, IteratorAggregate, Countable } /** - * @param mixed $offset - * - * @return bool + * @param int|string $offset */ - public function offsetExists($offset) + public function offsetExists($offset) : bool { return isset($this->nodes[$offset]); } /** - * @param mixed $offset + * TODO enable strict typing by changing how the Visitor deals with NodeList. + * Ideally, this function should always return a Node instance. + * However, the Visitor currently allows mutation of the NodeList + * and puts arbitrary values in the NodeList, such as strings. + * We will have to switch to using an array or a less strict + * type instead so we can enable strict typing in this class. * - * @return mixed + * @param int|string $offset + * + * @phpstan-return T */ - public function offsetGet($offset) + public function offsetGet($offset)// : Node { $item = $this->nodes[$offset]; if (is_array($item) && isset($item['kind'])) { - $this->nodes[$offset] = $item = AST::fromArray($item); + /** @phpstan-var T $node */ + $node = AST::fromArray($item); + $this->nodes[$offset] = $node; } - return $item; + return $this->nodes[$offset]; } /** - * @param mixed $offset - * @param mixed $value + * @param int|string|null $offset + * @param Node|mixed[] $value + * + * @phpstan-param T|mixed[] $value */ - public function offsetSet($offset, $value) + public function offsetSet($offset, $value) : void { - if (is_array($value) && isset($value['kind'])) { + if (is_array($value)) { + /** @phpstan-var T $value */ $value = AST::fromArray($value); } + + // Happens when a Node is pushed via []= + if ($offset === null) { + $this->nodes[] = $value; + + return; + } + $this->nodes[$offset] = $value; } /** - * @param mixed $offset + * @param int|string $offset */ - public function offsetUnset($offset) + public function offsetUnset($offset) : void { unset($this->nodes[$offset]); } /** - * @param int $offset - * @param int $length * @param mixed $replacement * - * @return NodeList + * @phpstan-return NodeList */ - public function splice($offset, $length, $replacement = null) + public function splice(int $offset, int $length, $replacement = null) : NodeList { return new NodeList(array_splice($this->nodes, $offset, $length, $replacement)); } @@ -98,9 +126,10 @@ class NodeList implements ArrayAccess, IteratorAggregate, Countable /** * @param NodeList|Node[] $list * - * @return NodeList + * @phpstan-param NodeList|array $list + * @phpstan-return NodeList */ - public function merge($list) + public function merge($list) : NodeList { if ($list instanceof self) { $list = $list->nodes; @@ -109,20 +138,14 @@ class NodeList implements ArrayAccess, IteratorAggregate, Countable return new NodeList(array_merge($this->nodes, $list)); } - /** - * @return Generator - */ - public function getIterator() + public function getIterator() : Traversable { foreach ($this->nodes as $key => $_) { yield $this->offsetGet($key); } } - /** - * @return int - */ - public function count() + public function count() : int { return count($this->nodes); } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/NonNullTypeNode.php b/vendor/webonyx/graphql-php/src/Language/AST/NonNullTypeNode.php index f8b97c0..18dc70e 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/NonNullTypeNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/NonNullTypeNode.php @@ -9,6 +9,6 @@ class NonNullTypeNode extends Node implements TypeNode /** @var string */ public $kind = NodeKind::NON_NULL_TYPE; - /** @var NameNode | ListTypeNode */ + /** @var NamedTypeNode|ListTypeNode */ public $type; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ObjectFieldNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ObjectFieldNode.php index cd458e8..bcced05 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ObjectFieldNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ObjectFieldNode.php @@ -12,6 +12,6 @@ class ObjectFieldNode extends Node /** @var NameNode */ public $name; - /** @var ValueNode */ + /** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode */ public $value; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeDefinitionNode.php index 0339c35..d221a10 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeDefinitionNode.php @@ -12,13 +12,13 @@ class ObjectTypeDefinitionNode extends Node implements TypeDefinitionNode /** @var NameNode */ public $name; - /** @var NamedTypeNode[] */ - public $interfaces = []; + /** @var NodeList */ + public $interfaces; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var FieldDefinitionNode[]|null */ + /** @var NodeList */ public $fields; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeExtensionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeExtensionNode.php index 4522449..b137523 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeExtensionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ObjectTypeExtensionNode.php @@ -12,12 +12,12 @@ class ObjectTypeExtensionNode extends Node implements TypeExtensionNode /** @var NameNode */ public $name; - /** @var NamedTypeNode[] */ - public $interfaces = []; + /** @var NodeList */ + public $interfaces; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; - /** @var FieldDefinitionNode[] */ + /** @var NodeList */ public $fields; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ObjectValueNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ObjectValueNode.php index 7e0d71c..f83d74a 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ObjectValueNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ObjectValueNode.php @@ -9,6 +9,6 @@ class ObjectValueNode extends Node implements ValueNode /** @var string */ public $kind = NodeKind::OBJECT; - /** @var ObjectFieldNode[]|NodeList */ + /** @var NodeList */ public $fields; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/OperationDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/OperationDefinitionNode.php index cef0053..cef2abe 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/OperationDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/OperationDefinitionNode.php @@ -9,16 +9,16 @@ class OperationDefinitionNode extends Node implements ExecutableDefinitionNode, /** @var string */ public $kind = NodeKind::OPERATION_DEFINITION; - /** @var NameNode */ + /** @var NameNode|null */ public $name; - /** @var string (oneOf 'query', 'mutation')) */ + /** @var string (oneOf 'query', 'mutation', 'subscription')) */ public $operation; - /** @var VariableDefinitionNode[] */ + /** @var NodeList */ public $variableDefinitions; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; /** @var SelectionSetNode */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeDefinitionNode.php index 5c90662..f30a282 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeDefinitionNode.php @@ -12,7 +12,7 @@ class ScalarTypeDefinitionNode extends Node implements TypeDefinitionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeExtensionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeExtensionNode.php index fe88316..ea7d16a 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeExtensionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/ScalarTypeExtensionNode.php @@ -12,6 +12,6 @@ class ScalarTypeExtensionNode extends Node implements TypeExtensionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/SchemaDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/SchemaDefinitionNode.php index 20e6a89..f563ec7 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/SchemaDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/SchemaDefinitionNode.php @@ -9,9 +9,9 @@ class SchemaDefinitionNode extends Node implements TypeSystemDefinitionNode /** @var string */ public $kind = NodeKind::SCHEMA_DEFINITION; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; - /** @var OperationTypeDefinitionNode[] */ + /** @var NodeList */ public $operationTypes; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/SchemaTypeExtensionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/SchemaTypeExtensionNode.php index e86177d..c96bcdf 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/SchemaTypeExtensionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/SchemaTypeExtensionNode.php @@ -9,9 +9,9 @@ class SchemaTypeExtensionNode extends Node implements TypeExtensionNode /** @var string */ public $kind = NodeKind::SCHEMA_EXTENSION; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var OperationTypeDefinitionNode[]|null */ + /** @var NodeList */ public $operationTypes; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/SelectionSetNode.php b/vendor/webonyx/graphql-php/src/Language/AST/SelectionSetNode.php index 427674e..ddae648 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/SelectionSetNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/SelectionSetNode.php @@ -9,6 +9,6 @@ class SelectionSetNode extends Node /** @var string */ public $kind = NodeKind::SELECTION_SET; - /** @var SelectionNode[] */ + /** @var NodeList */ public $selections; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/StringValueNode.php b/vendor/webonyx/graphql-php/src/Language/AST/StringValueNode.php index b1fe0df..059a7e3 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/StringValueNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/StringValueNode.php @@ -12,6 +12,6 @@ class StringValueNode extends Node implements ValueNode /** @var string */ public $value; - /** @var bool|null */ + /** @var bool */ public $block; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/TypeSystemDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/TypeSystemDefinitionNode.php index 65553ab..4a31f2e 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/TypeSystemDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/TypeSystemDefinitionNode.php @@ -10,6 +10,8 @@ namespace GraphQL\Language\AST; * | TypeDefinitionNode * | TypeExtensionNode * | DirectiveDefinitionNode + * + * @property NameNode $name */ interface TypeSystemDefinitionNode extends DefinitionNode { diff --git a/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeDefinitionNode.php index 1bfef69..d725d8e 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeDefinitionNode.php @@ -12,10 +12,10 @@ class UnionTypeDefinitionNode extends Node implements TypeDefinitionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[] */ + /** @var NodeList */ public $directives; - /** @var NamedTypeNode[]|null */ + /** @var NodeList */ public $types; /** @var StringValueNode|null */ diff --git a/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeExtensionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeExtensionNode.php index 53bf3ed..b10eebd 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeExtensionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/UnionTypeExtensionNode.php @@ -12,9 +12,9 @@ class UnionTypeExtensionNode extends Node implements TypeExtensionNode /** @var NameNode */ public $name; - /** @var DirectiveNode[]|null */ + /** @var NodeList */ public $directives; - /** @var NamedTypeNode[]|null */ + /** @var NodeList */ public $types; } diff --git a/vendor/webonyx/graphql-php/src/Language/AST/VariableDefinitionNode.php b/vendor/webonyx/graphql-php/src/Language/AST/VariableDefinitionNode.php index eb76b66..1ab87f3 100644 --- a/vendor/webonyx/graphql-php/src/Language/AST/VariableDefinitionNode.php +++ b/vendor/webonyx/graphql-php/src/Language/AST/VariableDefinitionNode.php @@ -12,9 +12,12 @@ class VariableDefinitionNode extends Node implements DefinitionNode /** @var VariableNode */ public $variable; - /** @var TypeNode */ + /** @var NamedTypeNode|ListTypeNode|NonNullTypeNode */ public $type; - /** @var ValueNode|null */ + /** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null */ public $defaultValue; + + /** @var NodeList */ + public $directives; } diff --git a/vendor/webonyx/graphql-php/src/Language/DirectiveLocation.php b/vendor/webonyx/graphql-php/src/Language/DirectiveLocation.php index 5f22537..3a32732 100644 --- a/vendor/webonyx/graphql-php/src/Language/DirectiveLocation.php +++ b/vendor/webonyx/graphql-php/src/Language/DirectiveLocation.php @@ -17,6 +17,7 @@ class DirectiveLocation const FRAGMENT_DEFINITION = 'FRAGMENT_DEFINITION'; const FRAGMENT_SPREAD = 'FRAGMENT_SPREAD'; const INLINE_FRAGMENT = 'INLINE_FRAGMENT'; + const VARIABLE_DEFINITION = 'VARIABLE_DEFINITION'; // Type System Definitions const SCHEMA = 'SCHEMA'; @@ -53,12 +54,7 @@ class DirectiveLocation self::INPUT_FIELD_DEFINITION => self::INPUT_FIELD_DEFINITION, ]; - /** - * @param string $name - * - * @return bool - */ - public static function has($name) + public static function has(string $name) : bool { return isset(self::$locations[$name]); } diff --git a/vendor/webonyx/graphql-php/src/Language/Lexer.php b/vendor/webonyx/graphql-php/src/Language/Lexer.php index 3aad4dd..15563bb 100644 --- a/vendor/webonyx/graphql-php/src/Language/Lexer.php +++ b/vendor/webonyx/graphql-php/src/Language/Lexer.php @@ -9,8 +9,11 @@ use GraphQL\Utils\BlockString; use GraphQL\Utils\Utils; use function chr; use function hexdec; +use function mb_convert_encoding; use function ord; +use function pack; use function preg_match; +use function substr; /** * A Lexer is a stateful stream generator in that every time @@ -118,7 +121,7 @@ class Lexer $token = $this->token; if ($token->kind !== Token::EOF) { do { - $token = $token->next ?: ($token->next = $this->readToken($token)); + $token = $token->next ?? ($token->next = $this->readToken($token)); } while ($token->kind === Token::COMMENT); } @@ -314,11 +317,11 @@ class Lexer $start = $this->position; [$char, $code] = $this->readChar(); - while ($code && ( + while ($code !== null && ( $code === 95 || // _ - $code >= 48 && $code <= 57 || // 0-9 - $code >= 65 && $code <= 90 || // A-Z - $code >= 97 && $code <= 122 // a-z + ($code >= 48 && $code <= 57) || // 0-9 + ($code >= 65 && $code <= 90) || // A-Z + ($code >= 97 && $code <= 122) // a-z )) { $value .= $char; [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); @@ -522,8 +525,27 @@ class Lexer 'Invalid character escape sequence: \\u' . $hex ); } + $code = hexdec($hex); + + // UTF-16 surrogate pair detection and handling. + $highOrderByte = $code >> 8; + if (0xD8 <= $highOrderByte && $highOrderByte <= 0xDF) { + [$utf16Continuation] = $this->readChars(6, true); + if (! preg_match('/^\\\u[0-9a-fA-F]{4}$/', $utf16Continuation)) { + throw new SyntaxError( + $this->source, + $this->position - 5, + 'Invalid UTF-16 trailing surrogate: ' . $utf16Continuation + ); + } + $surrogatePairHex = $hex . substr($utf16Continuation, 2, 4); + $value .= mb_convert_encoding(pack('H*', $surrogatePairHex), 'UTF-8', 'UTF-16'); + break; + } + $this->assertValidStringCharacterCode($code, $position - 2); + $value .= Utils::chr($code); break; default: @@ -695,7 +717,7 @@ class Lexer do { [$char, $code, $bytes] = $this->moveStringCursor(1, $bytes)->readChar(); $value .= $char; - } while ($code && + } while ($code !== null && // SourceCharacter but not LineTerminator ($code > 0x001F || $code === 0x0009) ); @@ -771,7 +793,7 @@ class Lexer { $result = ''; $totalBytes = 0; - $byteOffset = $byteStreamPosition ?: $this->byteStreamPosition; + $byteOffset = $byteStreamPosition ?? $this->byteStreamPosition; for ($i = 0; $i < $charCount; $i++) { [$char, $code, $bytes] = $this->readChar(false, $byteOffset); diff --git a/vendor/webonyx/graphql-php/src/Language/Parser.php b/vendor/webonyx/graphql-php/src/Language/Parser.php index f5c9280..9c0f460 100644 --- a/vendor/webonyx/graphql-php/src/Language/Parser.php +++ b/vendor/webonyx/graphql-php/src/Language/Parser.php @@ -7,6 +7,7 @@ namespace GraphQL\Language; use GraphQL\Error\SyntaxError; use GraphQL\Language\AST\ArgumentNode; use GraphQL\Language\AST\BooleanValueNode; +use GraphQL\Language\AST\DefinitionNode; use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DirectiveNode; use GraphQL\Language\AST\DocumentNode; @@ -32,6 +33,7 @@ use GraphQL\Language\AST\ListValueNode; use GraphQL\Language\AST\Location; use GraphQL\Language\AST\NamedTypeNode; use GraphQL\Language\AST\NameNode; +use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeList; use GraphQL\Language\AST\NonNullTypeNode; use GraphQL\Language\AST\NullValueNode; @@ -45,12 +47,15 @@ use GraphQL\Language\AST\ScalarTypeDefinitionNode; use GraphQL\Language\AST\ScalarTypeExtensionNode; use GraphQL\Language\AST\SchemaDefinitionNode; use GraphQL\Language\AST\SchemaTypeExtensionNode; +use GraphQL\Language\AST\SelectionNode; use GraphQL\Language\AST\SelectionSetNode; use GraphQL\Language\AST\StringValueNode; use GraphQL\Language\AST\TypeExtensionNode; +use GraphQL\Language\AST\TypeNode; use GraphQL\Language\AST\TypeSystemDefinitionNode; use GraphQL\Language\AST\UnionTypeDefinitionNode; use GraphQL\Language\AST\UnionTypeExtensionNode; +use GraphQL\Language\AST\ValueNode; use GraphQL\Language\AST\VariableDefinitionNode; use GraphQL\Language\AST\VariableNode; use function count; @@ -58,6 +63,75 @@ use function sprintf; /** * Parses string containing GraphQL query or [type definition](type-system/type-language.md) to Abstract Syntax Tree. + * + * Those magic functions allow partial parsing: + * + * @method static NameNode name(Source|string $source, bool[] $options = []) + * @method static DocumentNode document(Source|string $source, bool[] $options = []) + * @method static ExecutableDefinitionNode|TypeSystemDefinitionNode definition(Source|string $source, bool[] $options = []) + * @method static ExecutableDefinitionNode executableDefinition(Source|string $source, bool[] $options = []) + * @method static OperationDefinitionNode operationDefinition(Source|string $source, bool[] $options = []) + * @method static string operationType(Source|string $source, bool[] $options = []) + * @method static NodeList variableDefinitions(Source|string $source, bool[] $options = []) + * @method static VariableDefinitionNode variableDefinition(Source|string $source, bool[] $options = []) + * @method static VariableNode variable(Source|string $source, bool[] $options = []) + * @method static SelectionSetNode selectionSet(Source|string $source, bool[] $options = []) + * @method static mixed selection(Source|string $source, bool[] $options = []) + * @method static FieldNode field(Source|string $source, bool[] $options = []) + * @method static NodeList arguments(Source|string $source, bool[] $options = []) + * @method static NodeList constArguments(Source|string $source, bool[] $options = []) + * @method static ArgumentNode argument(Source|string $source, bool[] $options = []) + * @method static ArgumentNode constArgument(Source|string $source, bool[] $options = []) + * @method static FragmentSpreadNode|InlineFragmentNode fragment(Source|string $source, bool[] $options = []) + * @method static FragmentDefinitionNode fragmentDefinition(Source|string $source, bool[] $options = []) + * @method static NameNode fragmentName(Source|string $source, bool[] $options = []) + * @method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|NullValueNode|ObjectValueNode|StringValueNode|VariableNode valueLiteral(Source|string $source, bool[] $options = []) + * @method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|NullValueNode|ObjectValueNode|StringValueNode constValueLiteral(Source|string $source, bool[] $options = []) + * @method static StringValueNode stringLiteral(Source|string $source, bool[] $options = []) + * @method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|StringValueNode constValue(Source|string $source, bool[] $options = []) + * @method static BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode variableValue(Source|string $source, bool[] $options = []) + * @method static ListValueNode array(Source|string $source, bool[] $options = []) + * @method static ListValueNode constArray(Source|string $source, bool[] $options = []) + * @method static ObjectValueNode object(Source|string $source, bool[] $options = []) + * @method static ObjectValueNode constObject(Source|string $source, bool[] $options = []) + * @method static ObjectFieldNode objectField(Source|string $source, bool[] $options = []) + * @method static ObjectFieldNode constObjectField(Source|string $source, bool[] $options = []) + * @method static NodeList directives(Source|string $source, bool[] $options = []) + * @method static NodeList constDirectives(Source|string $source, bool[] $options = []) + * @method static DirectiveNode directive(Source|string $source, bool[] $options = []) + * @method static DirectiveNode constDirective(Source|string $source, bool[] $options = []) + * @method static ListTypeNode|NamedTypeNode|NonNullTypeNode typeReference(Source|string $source, bool[] $options = []) + * @method static NamedTypeNode namedType(Source|string $source, bool[] $options = []) + * @method static TypeSystemDefinitionNode typeSystemDefinition(Source|string $source, bool[] $options = []) + * @method static StringValueNode|null description(Source|string $source, bool[] $options = []) + * @method static SchemaDefinitionNode schemaDefinition(Source|string $source, bool[] $options = []) + * @method static OperationTypeDefinitionNode operationTypeDefinition(Source|string $source, bool[] $options = []) + * @method static ScalarTypeDefinitionNode scalarTypeDefinition(Source|string $source, bool[] $options = []) + * @method static ObjectTypeDefinitionNode objectTypeDefinition(Source|string $source, bool[] $options = []) + * @method static NodeList implementsInterfaces(Source|string $source, bool[] $options = []) + * @method static NodeList fieldsDefinition(Source|string $source, bool[] $options = []) + * @method static FieldDefinitionNode fieldDefinition(Source|string $source, bool[] $options = []) + * @method static NodeList argumentsDefinition(Source|string $source, bool[] $options = []) + * @method static InputValueDefinitionNode inputValueDefinition(Source|string $source, bool[] $options = []) + * @method static InterfaceTypeDefinitionNode interfaceTypeDefinition(Source|string $source, bool[] $options = []) + * @method static UnionTypeDefinitionNode unionTypeDefinition(Source|string $source, bool[] $options = []) + * @method static NodeList unionMemberTypes(Source|string $source, bool[] $options = []) + * @method static EnumTypeDefinitionNode enumTypeDefinition(Source|string $source, bool[] $options = []) + * @method static NodeList enumValuesDefinition(Source|string $source, bool[] $options = []) + * @method static EnumValueDefinitionNode enumValueDefinition(Source|string $source, bool[] $options = []) + * @method static InputObjectTypeDefinitionNode inputObjectTypeDefinition(Source|string $source, bool[] $options = []) + * @method static NodeList inputFieldsDefinition(Source|string $source, bool[] $options = []) + * @method static TypeExtensionNode typeExtension(Source|string $source, bool[] $options = []) + * @method static SchemaTypeExtensionNode schemaTypeExtension(Source|string $source, bool[] $options = []) + * @method static ScalarTypeExtensionNode scalarTypeExtension(Source|string $source, bool[] $options = []) + * @method static ObjectTypeExtensionNode objectTypeExtension(Source|string $source, bool[] $options = []) + * @method static InterfaceTypeExtensionNode interfaceTypeExtension(Source|string $source, bool[] $options = []) + * @method static UnionTypeExtensionNode unionTypeExtension(Source|string $source, bool[] $options = []) + * @method static EnumTypeExtensionNode enumTypeExtension(Source|string $source, bool[] $options = []) + * @method static InputObjectTypeExtensionNode inputObjectTypeExtension(Source|string $source, bool[] $options = []) + * @method static DirectiveDefinitionNode directiveDefinition(Source|string $source, bool[] $options = []) + * @method static NodeList directiveLocations(Source|string $source, bool[] $options = []) + * @method static NameNode directiveLocation(Source|string $source, bool[] $options = []) */ class Parser { @@ -113,8 +187,7 @@ class Parser */ public static function parse($source, array $options = []) { - $sourceObj = $source instanceof Source ? $source : new Source($source); - $parser = new self($sourceObj, $options); + $parser = new self($source, $options); return $parser->parseDocument(); } @@ -138,8 +211,7 @@ class Parser */ public static function parseValue($source, array $options = []) { - $sourceObj = $source instanceof Source ? $source : new Source($source); - $parser = new Parser($sourceObj, $options); + $parser = new Parser($source, $options); $parser->expect(Token::SOF); $value = $parser->parseValueLiteral(false); $parser->expect(Token::EOF); @@ -160,14 +232,13 @@ class Parser * @param Source|string $source * @param bool[] $options * - * @return ListTypeNode|NameNode|NonNullTypeNode + * @return ListTypeNode|NamedTypeNode|NonNullTypeNode * * @api */ public static function parseType($source, array $options = []) { - $sourceObj = $source instanceof Source ? $source : new Source($source); - $parser = new Parser($sourceObj, $options); + $parser = new Parser($source, $options); $parser->expect(Token::SOF); $type = $parser->parseTypeReference(); $parser->expect(Token::EOF); @@ -175,26 +246,78 @@ class Parser return $type; } + /** + * Parse partial source by delegating calls to the internal parseX methods. + * + * @param bool[] $arguments + * + * @throws SyntaxError + */ + public static function __callStatic(string $name, array $arguments) + { + $parser = new Parser(...$arguments); + $parser->expect(Token::SOF); + + switch ($name) { + case 'arguments': + case 'valueLiteral': + case 'array': + case 'object': + case 'objectField': + case 'directives': + case 'directive': + $type = $parser->{'parse' . $name}(false); + break; + case 'constArguments': + $type = $parser->parseArguments(true); + break; + case 'constValueLiteral': + $type = $parser->parseValueLiteral(true); + break; + case 'constArray': + $type = $parser->parseArray(true); + break; + case 'constObject': + $type = $parser->parseObject(true); + break; + case 'constObjectField': + $type = $parser->parseObjectField(true); + break; + case 'constDirectives': + $type = $parser->parseDirectives(true); + break; + case 'constDirective': + $type = $parser->parseDirective(true); + break; + default: + $type = $parser->{'parse' . $name}(); + } + + $parser->expect(Token::EOF); + + return $type; + } + /** @var Lexer */ private $lexer; /** - * @param bool[] $options + * @param Source|string $source + * @param bool[] $options */ - public function __construct(Source $source, array $options = []) + public function __construct($source, array $options = []) { - $this->lexer = new Lexer($source, $options); + $sourceObj = $source instanceof Source ? $source : new Source($source); + $this->lexer = new Lexer($sourceObj, $options); } /** * Returns a location object, used to identify the place in * the source that created a given parsed object. - * - * @return Location|null */ - private function loc(Token $startToken) + private function loc(Token $startToken) : ?Location { - if (empty($this->lexer->options['noLocation'])) { + if (! ($this->lexer->options['noLocation'] ?? false)) { return new Location($startToken, $this->lexer->lastToken, $this->lexer->source); } @@ -203,12 +326,8 @@ class Parser /** * Determines if the next token is of a given kind - * - * @param string $kind - * - * @return bool */ - private function peek($kind) + private function peek(string $kind) : bool { return $this->lexer->token->kind === $kind; } @@ -216,12 +335,8 @@ class Parser /** * If the next token is of the given kind, return true after advancing * the parser. Otherwise, do not change the parser state and return false. - * - * @param string $kind - * - * @return bool */ - private function skip($kind) + private function skip(string $kind) : bool { $match = $this->lexer->token->kind === $kind; @@ -236,13 +351,9 @@ class Parser * If the next token is of the given kind, return that token after advancing * the parser. Otherwise, do not change the parser state and return false. * - * @param string $kind - * - * @return Token - * * @throws SyntaxError */ - private function expect($kind) + private function expect(string $kind) : Token { $token = $this->lexer->token; @@ -260,38 +371,44 @@ class Parser } /** - * If the next token is a keyword with the given value, return that token after - * advancing the parser. Otherwise, do not change the parser state and return - * false. - * - * @param string $value - * - * @return Token + * If the next token is a keyword with the given value, advance the lexer. + * Otherwise, throw an error. * * @throws SyntaxError */ - private function expectKeyword($value) + private function expectKeyword(string $value) : void { $token = $this->lexer->token; - - if ($token->kind === Token::NAME && $token->value === $value) { - $this->lexer->advance(); - - return $token; + if ($token->kind !== Token::NAME || $token->value !== $value) { + throw new SyntaxError( + $this->lexer->source, + $token->start, + 'Expected "' . $value . '", found ' . $token->getDescription() + ); } - throw new SyntaxError( - $this->lexer->source, - $token->start, - 'Expected "' . $value . '", found ' . $token->getDescription() - ); + + $this->lexer->advance(); } /** - * @return SyntaxError + * If the next token is a given keyword, return "true" after advancing + * the lexer. Otherwise, do not change the parser state and return "false". */ - private function unexpected(?Token $atToken = null) + private function expectOptionalKeyword(string $value) : bool { - $token = $atToken ?: $this->lexer->token; + $token = $this->lexer->token; + if ($token->kind === Token::NAME && $token->value === $value) { + $this->lexer->advance(); + + return true; + } + + return false; + } + + private function unexpected(?Token $atToken = null) : SyntaxError + { + $token = $atToken ?? $this->lexer->token; return new SyntaxError($this->lexer->source, $token->start, 'Unexpected ' . $token->getDescription()); } @@ -302,15 +419,9 @@ class Parser * and ends with a lex token of closeKind. Advances the parser * to the next lex token after the closing token. * - * @param string $openKind - * @param callable $parseFn - * @param string $closeKind - * - * @return NodeList - * * @throws SyntaxError */ - private function any($openKind, $parseFn, $closeKind) + private function any(string $openKind, callable $parseFn, string $closeKind) : NodeList { $this->expect($openKind); @@ -328,15 +439,9 @@ class Parser * and ends with a lex token of closeKind. Advances the parser * to the next lex token after the closing token. * - * @param string $openKind - * @param callable $parseFn - * @param string $closeKind - * - * @return NodeList - * * @throws SyntaxError */ - private function many($openKind, $parseFn, $closeKind) + private function many(string $openKind, callable $parseFn, string $closeKind) : NodeList { $this->expect($openKind); @@ -351,11 +456,9 @@ class Parser /** * Converts a name lex token into a name parse node. * - * @return NameNode - * * @throws SyntaxError */ - private function parseName() + private function parseName() : NameNode { $token = $this->expect(Token::NAME); @@ -368,22 +471,20 @@ class Parser /** * Implements the parsing rules in the Document section. * - * @return DocumentNode - * * @throws SyntaxError */ - private function parseDocument() + private function parseDocument() : DocumentNode { $start = $this->lexer->token; - $this->expect(Token::SOF); - - $definitions = []; - do { - $definitions[] = $this->parseDefinition(); - } while (! $this->skip(Token::EOF)); return new DocumentNode([ - 'definitions' => new NodeList($definitions), + 'definitions' => $this->many( + Token::SOF, + function () { + return $this->parseDefinition(); + }, + Token::EOF + ), 'loc' => $this->loc($start), ]); } @@ -393,7 +494,7 @@ class Parser * * @throws SyntaxError */ - private function parseDefinition() + private function parseDefinition() : DefinitionNode { if ($this->peek(Token::NAME)) { switch ($this->lexer->token->value) { @@ -427,11 +528,9 @@ class Parser } /** - * @return ExecutableDefinitionNode - * * @throws SyntaxError */ - private function parseExecutableDefinition() + private function parseExecutableDefinition() : ExecutableDefinitionNode { if ($this->peek(Token::NAME)) { switch ($this->lexer->token->value) { @@ -452,11 +551,9 @@ class Parser // Implements the parsing rules in the Operations section. /** - * @return OperationDefinitionNode - * * @throws SyntaxError */ - private function parseOperationDefinition() + private function parseOperationDefinition() : OperationDefinitionNode { $start = $this->lexer->token; if ($this->peek(Token::BRACE_L)) { @@ -488,11 +585,9 @@ class Parser } /** - * @return string - * * @throws SyntaxError */ - private function parseOperationType() + private function parseOperationType() : string { $operationToken = $this->expect(Token::NAME); switch ($operationToken->value) { @@ -507,28 +602,23 @@ class Parser throw $this->unexpected($operationToken); } - /** - * @return VariableDefinitionNode[]|NodeList - */ - private function parseVariableDefinitions() + private function parseVariableDefinitions() : NodeList { - return $this->peek(Token::PAREN_L) ? - $this->many( + return $this->peek(Token::PAREN_L) + ? $this->many( Token::PAREN_L, - function () { + function () : VariableDefinitionNode { return $this->parseVariableDefinition(); }, Token::PAREN_R - ) : - new NodeList([]); + ) + : new NodeList([]); } /** - * @return VariableDefinitionNode - * * @throws SyntaxError */ - private function parseVariableDefinition() + private function parseVariableDefinition() : VariableDefinitionNode { $start = $this->lexer->token; $var = $this->parseVariable(); @@ -539,18 +629,18 @@ class Parser return new VariableDefinitionNode([ 'variable' => $var, 'type' => $type, - 'defaultValue' => - ($this->skip(Token::EQUALS) ? $this->parseValueLiteral(true) : null), + 'defaultValue' => $this->skip(Token::EQUALS) + ? $this->parseValueLiteral(true) + : null, + 'directives' => $this->parseDirectives(true), 'loc' => $this->loc($start), ]); } /** - * @return VariableNode - * * @throws SyntaxError */ - private function parseVariable() + private function parseVariable() : VariableNode { $start = $this->lexer->token; $this->expect(Token::DOLLAR); @@ -561,10 +651,7 @@ class Parser ]); } - /** - * @return SelectionSetNode - */ - private function parseSelectionSet() + private function parseSelectionSet() : SelectionSetNode { $start = $this->lexer->token; @@ -572,7 +659,7 @@ class Parser [ 'selections' => $this->many( Token::BRACE_L, - function () { + function () : SelectionNode { return $this->parseSelection(); }, Token::BRACE_R @@ -587,22 +674,18 @@ class Parser * - Field * - FragmentSpread * - InlineFragment - * - * @return mixed */ - private function parseSelection() + private function parseSelection() : SelectionNode { - return $this->peek(Token::SPREAD) ? - $this->parseFragment() : - $this->parseField(); + return $this->peek(Token::SPREAD) + ? $this->parseFragment() + : $this->parseField(); } /** - * @return FieldNode - * * @throws SyntaxError */ - private function parseField() + private function parseField() : FieldNode { $start = $this->lexer->token; $nameOrAlias = $this->parseName(); @@ -626,33 +709,27 @@ class Parser } /** - * @param bool $isConst - * - * @return ArgumentNode[]|NodeList - * * @throws SyntaxError */ - private function parseArguments($isConst) + private function parseArguments(bool $isConst) : NodeList { - $parseFn = $isConst ? - function () { + $parseFn = $isConst + ? function () : ArgumentNode { return $this->parseConstArgument(); - } : - function () { + } + : function () : ArgumentNode { return $this->parseArgument(); }; - return $this->peek(Token::PAREN_L) ? - $this->many(Token::PAREN_L, $parseFn, Token::PAREN_R) : - new NodeList([]); + return $this->peek(Token::PAREN_L) + ? $this->many(Token::PAREN_L, $parseFn, Token::PAREN_R) + : new NodeList([]); } /** - * @return ArgumentNode - * * @throws SyntaxError */ - private function parseArgument() + private function parseArgument() : ArgumentNode { $start = $this->lexer->token; $name = $this->parseName(); @@ -668,11 +745,9 @@ class Parser } /** - * @return ArgumentNode - * * @throws SyntaxError */ - private function parseConstArgument() + private function parseConstArgument() : ArgumentNode { $start = $this->lexer->token; $name = $this->parseName(); @@ -694,12 +769,13 @@ class Parser * * @throws SyntaxError */ - private function parseFragment() + private function parseFragment() : SelectionNode { $start = $this->lexer->token; $this->expect(Token::SPREAD); - if ($this->peek(Token::NAME) && $this->lexer->token->value !== 'on') { + $hasTypeCondition = $this->expectOptionalKeyword('on'); + if (! $hasTypeCondition && $this->peek(Token::NAME)) { return new FragmentSpreadNode([ 'name' => $this->parseFragmentName(), 'directives' => $this->parseDirectives(false), @@ -707,14 +783,8 @@ class Parser ]); } - $typeCondition = null; - if ($this->lexer->token->value === 'on') { - $this->lexer->advance(); - $typeCondition = $this->parseNamedType(); - } - return new InlineFragmentNode([ - 'typeCondition' => $typeCondition, + 'typeCondition' => $hasTypeCondition ? $this->parseNamedType() : null, 'directives' => $this->parseDirectives(false), 'selectionSet' => $this->parseSelectionSet(), 'loc' => $this->loc($start), @@ -722,11 +792,9 @@ class Parser } /** - * @return FragmentDefinitionNode - * * @throws SyntaxError */ - private function parseFragmentDefinition() + private function parseFragmentDefinition() : FragmentDefinitionNode { $start = $this->lexer->token; $this->expectKeyword('fragment'); @@ -754,11 +822,9 @@ class Parser } /** - * @return NameNode - * * @throws SyntaxError */ - private function parseFragmentName() + private function parseFragmentName() : NameNode { if ($this->lexer->token->value === 'on') { throw $this->unexpected(); @@ -787,13 +853,11 @@ class Parser * * EnumValue : Name but not `true`, `false` or `null` * - * @param bool $isConst - * * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|StringValueNode|VariableNode|ListValueNode|ObjectValueNode|NullValueNode * * @throws SyntaxError */ - private function parseValueLiteral($isConst) + private function parseValueLiteral(bool $isConst) : ValueNode { $token = $this->lexer->token; switch ($token->kind) { @@ -853,10 +917,7 @@ class Parser throw $this->unexpected(); } - /** - * @return StringValueNode - */ - private function parseStringLiteral() + private function parseStringLiteral() : StringValueNode { $token = $this->lexer->token; $this->lexer->advance(); @@ -873,7 +934,7 @@ class Parser * * @throws SyntaxError */ - private function parseConstValue() + private function parseConstValue() : ValueNode { return $this->parseValueLiteral(true); } @@ -881,24 +942,21 @@ class Parser /** * @return BooleanValueNode|EnumValueNode|FloatValueNode|IntValueNode|ListValueNode|ObjectValueNode|StringValueNode|VariableNode */ - private function parseVariableValue() + private function parseVariableValue() : ValueNode { return $this->parseValueLiteral(false); } - /** - * @param bool $isConst - * - * @return ListValueNode - */ - private function parseArray($isConst) + private function parseArray(bool $isConst) : ListValueNode { $start = $this->lexer->token; - $parseFn = $isConst ? function () { - return $this->parseConstValue(); - } : function () { - return $this->parseVariableValue(); - }; + $parseFn = $isConst + ? function () { + return $this->parseConstValue(); + } + : function () { + return $this->parseVariableValue(); + }; return new ListValueNode( [ @@ -908,12 +966,7 @@ class Parser ); } - /** - * @param bool $isConst - * - * @return ObjectValueNode - */ - private function parseObject($isConst) + private function parseObject(bool $isConst) : ObjectValueNode { $start = $this->lexer->token; $this->expect(Token::BRACE_L); @@ -928,12 +981,7 @@ class Parser ]); } - /** - * @param bool $isConst - * - * @return ObjectFieldNode - */ - private function parseObjectField($isConst) + private function parseObjectField(bool $isConst) : ObjectFieldNode { $start = $this->lexer->token; $name = $this->parseName(); @@ -950,13 +998,9 @@ class Parser // Implements the parsing rules in the Directives section. /** - * @param bool $isConst - * - * @return DirectiveNode[]|NodeList - * * @throws SyntaxError */ - private function parseDirectives($isConst) + private function parseDirectives(bool $isConst) : NodeList { $directives = []; while ($this->peek(Token::AT)) { @@ -967,13 +1011,9 @@ class Parser } /** - * @param bool $isConst - * - * @return DirectiveNode - * * @throws SyntaxError */ - private function parseDirective($isConst) + private function parseDirective(bool $isConst) : DirectiveNode { $start = $this->lexer->token; $this->expect(Token::AT); @@ -990,11 +1030,11 @@ class Parser /** * Handles the Type: TypeName, ListType, and NonNullType parsing rules. * - * @return ListTypeNode|NameNode|NonNullTypeNode + * @return ListTypeNode|NamedTypeNode|NonNullTypeNode * * @throws SyntaxError */ - private function parseTypeReference() + private function parseTypeReference() : TypeNode { $start = $this->lexer->token; @@ -1018,7 +1058,7 @@ class Parser return $type; } - private function parseNamedType() + private function parseNamedType() : NamedTypeNode { $start = $this->lexer->token; @@ -1045,11 +1085,9 @@ class Parser * - EnumTypeDefinition * - InputObjectTypeDefinition * - * @return TypeSystemDefinitionNode - * * @throws SyntaxError */ - private function parseTypeSystemDefinition() + private function parseTypeSystemDefinition() : TypeSystemDefinitionNode { // Many definitions begin with a description and require a lookahead. $keywordToken = $this->peekDescription() @@ -1082,30 +1120,24 @@ class Parser throw $this->unexpected($keywordToken); } - /** - * @return bool - */ - private function peekDescription() + private function peekDescription() : bool { return $this->peek(Token::STRING) || $this->peek(Token::BLOCK_STRING); } - /** - * @return StringValueNode|null - */ - private function parseDescription() + private function parseDescription() : ?StringValueNode { if ($this->peekDescription()) { return $this->parseStringLiteral(); } + + return null; } /** - * @return SchemaDefinitionNode - * * @throws SyntaxError */ - private function parseSchemaDefinition() + private function parseSchemaDefinition() : SchemaDefinitionNode { $start = $this->lexer->token; $this->expectKeyword('schema'); @@ -1113,7 +1145,7 @@ class Parser $operationTypes = $this->many( Token::BRACE_L, - function () { + function () : OperationTypeDefinitionNode { return $this->parseOperationTypeDefinition(); }, Token::BRACE_R @@ -1127,11 +1159,9 @@ class Parser } /** - * @return OperationTypeDefinitionNode - * * @throws SyntaxError */ - private function parseOperationTypeDefinition() + private function parseOperationTypeDefinition() : OperationTypeDefinitionNode { $start = $this->lexer->token; $operation = $this->parseOperationType(); @@ -1146,11 +1176,9 @@ class Parser } /** - * @return ScalarTypeDefinitionNode - * * @throws SyntaxError */ - private function parseScalarTypeDefinition() + private function parseScalarTypeDefinition() : ScalarTypeDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); @@ -1167,11 +1195,9 @@ class Parser } /** - * @return ObjectTypeDefinitionNode - * * @throws SyntaxError */ - private function parseObjectTypeDefinition() + private function parseObjectTypeDefinition() : ObjectTypeDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); @@ -1195,67 +1221,64 @@ class Parser * ImplementsInterfaces : * - implements `&`? NamedType * - ImplementsInterfaces & NamedType - * - * @return NamedTypeNode[] */ - private function parseImplementsInterfaces() + private function parseImplementsInterfaces() : NodeList { $types = []; - if ($this->lexer->token->value === 'implements') { - $this->lexer->advance(); + if ($this->expectOptionalKeyword('implements')) { // Optional leading ampersand $this->skip(Token::AMP); do { $types[] = $this->parseNamedType(); } while ($this->skip(Token::AMP) || - // Legacy support for the SDL? - (! empty($this->lexer->options['allowLegacySDLImplementsInterfaces']) && $this->peek(Token::NAME)) + // Legacy support for the SDL? + (($this->lexer->options['allowLegacySDLImplementsInterfaces'] ?? false) && $this->peek(Token::NAME)) ); } - return $types; + return new NodeList($types); } /** - * @return FieldDefinitionNode[]|NodeList - * * @throws SyntaxError */ - private function parseFieldsDefinition() + private function parseFieldsDefinition() : NodeList { // Legacy support for the SDL? - if (! empty($this->lexer->options['allowLegacySDLEmptyFields']) && - $this->peek(Token::BRACE_L) && - $this->lexer->lookahead()->kind === Token::BRACE_R + if (($this->lexer->options['allowLegacySDLEmptyFields'] ?? false) + && $this->peek(Token::BRACE_L) + && $this->lexer->lookahead()->kind === Token::BRACE_R ) { $this->lexer->advance(); $this->lexer->advance(); - return []; + /** @phpstan-var NodeList $nodeList */ + $nodeList = new NodeList([]); + } else { + /** @phpstan-var NodeList $nodeList */ + $nodeList = $this->peek(Token::BRACE_L) + ? $this->many( + Token::BRACE_L, + function () : FieldDefinitionNode { + return $this->parseFieldDefinition(); + }, + Token::BRACE_R + ) + : new NodeList([]); } - return $this->peek(Token::BRACE_L) - ? $this->many( - Token::BRACE_L, - function () { - return $this->parseFieldDefinition(); - }, - Token::BRACE_R - ) - : new NodeList([]); + return $nodeList; } /** - * @return FieldDefinitionNode - * * @throws SyntaxError */ - private function parseFieldDefinition() + private function parseFieldDefinition() : FieldDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); $name = $this->parseName(); - $args = $this->parseArgumentDefs(); + $args = $this->parseArgumentsDefinition(); $this->expect(Token::COLON); $type = $this->parseTypeReference(); $directives = $this->parseDirectives(true); @@ -1271,31 +1294,28 @@ class Parser } /** - * @return InputValueDefinitionNode[]|NodeList - * * @throws SyntaxError */ - private function parseArgumentDefs() + private function parseArgumentsDefinition() : NodeList { - if (! $this->peek(Token::PAREN_L)) { - return new NodeList([]); - } + /** @var NodeList $nodeList */ + $nodeList = $this->peek(Token::PAREN_L) + ? $this->many( + Token::PAREN_L, + function () : InputValueDefinitionNode { + return $this->parseInputValueDefinition(); + }, + Token::PAREN_R + ) + : new NodeList([]); - return $this->many( - Token::PAREN_L, - function () { - return $this->parseInputValueDef(); - }, - Token::PAREN_R - ); + return $nodeList; } /** - * @return InputValueDefinitionNode - * * @throws SyntaxError */ - private function parseInputValueDef() + private function parseInputValueDefinition() : InputValueDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); @@ -1319,22 +1339,22 @@ class Parser } /** - * @return InterfaceTypeDefinitionNode - * * @throws SyntaxError */ - private function parseInterfaceTypeDefinition() + private function parseInterfaceTypeDefinition() : InterfaceTypeDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); $this->expectKeyword('interface'); $name = $this->parseName(); + $interfaces = $this->parseImplementsInterfaces(); $directives = $this->parseDirectives(true); $fields = $this->parseFieldsDefinition(); return new InterfaceTypeDefinitionNode([ 'name' => $name, 'directives' => $directives, + 'interfaces' => $interfaces, 'fields' => $fields, 'loc' => $this->loc($start), 'description' => $description, @@ -1345,11 +1365,9 @@ class Parser * UnionTypeDefinition : * - Description? union Name Directives[Const]? UnionMemberTypes? * - * @return UnionTypeDefinitionNode - * * @throws SyntaxError */ - private function parseUnionTypeDefinition() + private function parseUnionTypeDefinition() : UnionTypeDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); @@ -1371,10 +1389,8 @@ class Parser * UnionMemberTypes : * - = `|`? NamedType * - UnionMemberTypes | NamedType - * - * @return NamedTypeNode[] */ - private function parseUnionMemberTypes() + private function parseUnionMemberTypes() : NodeList { $types = []; if ($this->skip(Token::EQUALS)) { @@ -1385,15 +1401,13 @@ class Parser } while ($this->skip(Token::PIPE)); } - return $types; + return new NodeList($types); } /** - * @return EnumTypeDefinitionNode - * * @throws SyntaxError */ - private function parseEnumTypeDefinition() + private function parseEnumTypeDefinition() : EnumTypeDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); @@ -1412,29 +1426,28 @@ class Parser } /** - * @return EnumValueDefinitionNode[]|NodeList - * * @throws SyntaxError */ - private function parseEnumValuesDefinition() + private function parseEnumValuesDefinition() : NodeList { - return $this->peek(Token::BRACE_L) + /** @var NodeList $nodeList */ + $nodeList = $this->peek(Token::BRACE_L) ? $this->many( Token::BRACE_L, - function () { + function () : EnumValueDefinitionNode { return $this->parseEnumValueDefinition(); }, Token::BRACE_R ) : new NodeList([]); + + return $nodeList; } /** - * @return EnumValueDefinitionNode - * * @throws SyntaxError */ - private function parseEnumValueDefinition() + private function parseEnumValueDefinition() : EnumValueDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); @@ -1450,11 +1463,9 @@ class Parser } /** - * @return InputObjectTypeDefinitionNode - * * @throws SyntaxError */ - private function parseInputObjectTypeDefinition() + private function parseInputObjectTypeDefinition() : InputObjectTypeDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); @@ -1473,21 +1484,22 @@ class Parser } /** - * @return InputValueDefinitionNode[]|NodeList - * * @throws SyntaxError */ - private function parseInputFieldsDefinition() + private function parseInputFieldsDefinition() : NodeList { - return $this->peek(Token::BRACE_L) + /** @var NodeList $nodeList */ + $nodeList = $this->peek(Token::BRACE_L) ? $this->many( Token::BRACE_L, - function () { - return $this->parseInputValueDef(); + function () : InputValueDefinitionNode { + return $this->parseInputValueDefinition(); }, Token::BRACE_R ) : new NodeList([]); + + return $nodeList; } /** @@ -1499,11 +1511,9 @@ class Parser * - EnumTypeExtension * - InputObjectTypeDefinition * - * @return TypeExtensionNode - * * @throws SyntaxError */ - private function parseTypeExtension() + private function parseTypeExtension() : TypeExtensionNode { $keywordToken = $this->lexer->lookahead(); @@ -1530,11 +1540,9 @@ class Parser } /** - * @return SchemaTypeExtensionNode - * * @throws SyntaxError */ - private function parseSchemaTypeExtension() + private function parseSchemaTypeExtension() : SchemaTypeExtensionNode { $start = $this->lexer->token; $this->expectKeyword('extend'); @@ -1545,7 +1553,8 @@ class Parser Token::BRACE_L, [$this, 'parseOperationTypeDefinition'], Token::BRACE_R - ) : []; + ) + : new NodeList([]); if (count($directives) === 0 && count($operationTypes) === 0) { $this->unexpected(); } @@ -1558,11 +1567,9 @@ class Parser } /** - * @return ScalarTypeExtensionNode - * * @throws SyntaxError */ - private function parseScalarTypeExtension() + private function parseScalarTypeExtension() : ScalarTypeExtensionNode { $start = $this->lexer->token; $this->expectKeyword('extend'); @@ -1581,11 +1588,9 @@ class Parser } /** - * @return ObjectTypeExtensionNode - * * @throws SyntaxError */ - private function parseObjectTypeExtension() + private function parseObjectTypeExtension() : ObjectTypeExtensionNode { $start = $this->lexer->token; $this->expectKeyword('extend'); @@ -1612,20 +1617,20 @@ class Parser } /** - * @return InterfaceTypeExtensionNode - * * @throws SyntaxError */ - private function parseInterfaceTypeExtension() + private function parseInterfaceTypeExtension() : InterfaceTypeExtensionNode { $start = $this->lexer->token; $this->expectKeyword('extend'); $this->expectKeyword('interface'); $name = $this->parseName(); + $interfaces = $this->parseImplementsInterfaces(); $directives = $this->parseDirectives(true); $fields = $this->parseFieldsDefinition(); - if (count($directives) === 0 && - count($fields) === 0 + if (count($interfaces) === 0 + && count($directives) === 0 + && count($fields) === 0 ) { throw $this->unexpected(); } @@ -1633,6 +1638,7 @@ class Parser return new InterfaceTypeExtensionNode([ 'name' => $name, 'directives' => $directives, + 'interfaces' => $interfaces, 'fields' => $fields, 'loc' => $this->loc($start), ]); @@ -1643,11 +1649,9 @@ class Parser * - extend union Name Directives[Const]? UnionMemberTypes * - extend union Name Directives[Const] * - * @return UnionTypeExtensionNode - * * @throws SyntaxError */ - private function parseUnionTypeExtension() + private function parseUnionTypeExtension() : UnionTypeExtensionNode { $start = $this->lexer->token; $this->expectKeyword('extend'); @@ -1655,9 +1659,7 @@ class Parser $name = $this->parseName(); $directives = $this->parseDirectives(true); $types = $this->parseUnionMemberTypes(); - if (count($directives) === 0 && - ! $types - ) { + if (count($directives) === 0 && count($types) === 0) { throw $this->unexpected(); } @@ -1670,11 +1672,9 @@ class Parser } /** - * @return EnumTypeExtensionNode - * * @throws SyntaxError */ - private function parseEnumTypeExtension() + private function parseEnumTypeExtension() : EnumTypeExtensionNode { $start = $this->lexer->token; $this->expectKeyword('extend'); @@ -1697,11 +1697,9 @@ class Parser } /** - * @return InputObjectTypeExtensionNode - * * @throws SyntaxError */ - private function parseInputObjectTypeExtension() + private function parseInputObjectTypeExtension() : InputObjectTypeExtensionNode { $start = $this->lexer->token; $this->expectKeyword('extend'); @@ -1725,38 +1723,36 @@ class Parser /** * DirectiveDefinition : - * - directive @ Name ArgumentsDefinition? on DirectiveLocations - * - * @return DirectiveDefinitionNode + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations * * @throws SyntaxError */ - private function parseDirectiveDefinition() + private function parseDirectiveDefinition() : DirectiveDefinitionNode { $start = $this->lexer->token; $description = $this->parseDescription(); $this->expectKeyword('directive'); $this->expect(Token::AT); - $name = $this->parseName(); - $args = $this->parseArgumentDefs(); + $name = $this->parseName(); + $args = $this->parseArgumentsDefinition(); + $repeatable = $this->expectOptionalKeyword('repeatable'); $this->expectKeyword('on'); $locations = $this->parseDirectiveLocations(); return new DirectiveDefinitionNode([ 'name' => $name, + 'description' => $description, 'arguments' => $args, + 'repeatable' => $repeatable, 'locations' => $locations, 'loc' => $this->loc($start), - 'description' => $description, ]); } /** - * @return NameNode[] - * * @throws SyntaxError */ - private function parseDirectiveLocations() + private function parseDirectiveLocations() : NodeList { // Optional leading pipe $this->skip(Token::PIPE); @@ -1765,15 +1761,13 @@ class Parser $locations[] = $this->parseDirectiveLocation(); } while ($this->skip(Token::PIPE)); - return $locations; + return new NodeList($locations); } /** - * @return NameNode - * * @throws SyntaxError */ - private function parseDirectiveLocation() + private function parseDirectiveLocation() : NameNode { $start = $this->lexer->token; $name = $this->parseName(); diff --git a/vendor/webonyx/graphql-php/src/Language/Printer.php b/vendor/webonyx/graphql-php/src/Language/Printer.php index ae96222..0a95efc 100644 --- a/vendor/webonyx/graphql-php/src/Language/Printer.php +++ b/vendor/webonyx/graphql-php/src/Language/Printer.php @@ -28,6 +28,7 @@ use GraphQL\Language\AST\IntValueNode; use GraphQL\Language\AST\ListTypeNode; use GraphQL\Language\AST\ListValueNode; use GraphQL\Language\AST\NamedTypeNode; +use GraphQL\Language\AST\NameNode; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\NonNullTypeNode; @@ -47,6 +48,7 @@ use GraphQL\Language\AST\StringValueNode; use GraphQL\Language\AST\UnionTypeDefinitionNode; use GraphQL\Language\AST\UnionTypeExtensionNode; use GraphQL\Language\AST\VariableDefinitionNode; +use GraphQL\Language\AST\VariableNode; use GraphQL\Utils\Utils; use function count; use function implode; @@ -54,6 +56,7 @@ use function json_encode; use function preg_replace; use function sprintf; use function str_replace; +use function strlen; use function strpos; /** @@ -82,7 +85,7 @@ class Printer public static function doPrint($ast) { static $instance; - $instance = $instance ?: new static(); + $instance = $instance ?? new static(); return $instance->printAST($ast); } @@ -91,25 +94,31 @@ class Printer { } + /** + * Traverse an AST bottom-up, converting all nodes to strings. + * + * That means the AST is manipulated in such a way that it no longer + * resembles the well-formed result of parsing. + */ public function printAST($ast) { return Visitor::visit( $ast, [ 'leave' => [ - NodeKind::NAME => static function (Node $node) { - return '' . $node->value; + NodeKind::NAME => static function (NameNode $node) : string { + return $node->value; }, - NodeKind::VARIABLE => static function ($node) { + NodeKind::VARIABLE => static function (VariableNode $node) : string { return '$' . $node->name; }, - NodeKind::DOCUMENT => function (DocumentNode $node) { + NodeKind::DOCUMENT => function (DocumentNode $node) : string { return $this->join($node->definitions, "\n\n") . "\n"; }, - NodeKind::OPERATION_DEFINITION => function (OperationDefinitionNode $node) { + NodeKind::OPERATION_DEFINITION => function (OperationDefinitionNode $node) : string { $op = $node->operation; $name = $node->name; $varDefs = $this->wrap('(', $this->join($node->variableDefinitions, ', '), ')'); @@ -118,20 +127,24 @@ class Printer // Anonymous queries with no directives or variable definitions can use // the query short form. - return ! $name && ! $directives && ! $varDefs && $op === 'query' + return $name === null && strlen($directives ?? '') === 0 && ! $varDefs && $op === 'query' ? $selectionSet : $this->join([$op, $this->join([$name, $varDefs]), $directives, $selectionSet], ' '); }, - NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $node) { - return $node->variable . ': ' . $node->type . $this->wrap(' = ', $node->defaultValue); + NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $node) : string { + return $node->variable + . ': ' + . $node->type + . $this->wrap(' = ', $node->defaultValue) + . $this->wrap(' ', $this->join($node->directives, ' ')); }, NodeKind::SELECTION_SET => function (SelectionSetNode $node) { return $this->block($node->selections); }, - NodeKind::FIELD => function (FieldNode $node) { + NodeKind::FIELD => function (FieldNode $node) : string { return $this->join( [ $this->wrap('', $node->alias, ': ') . $node->name . $this->wrap( @@ -146,15 +159,17 @@ class Printer ); }, - NodeKind::ARGUMENT => static function (ArgumentNode $node) { + NodeKind::ARGUMENT => static function (ArgumentNode $node) : string { return $node->name . ': ' . $node->value; }, - NodeKind::FRAGMENT_SPREAD => function (FragmentSpreadNode $node) { - return '...' . $node->name . $this->wrap(' ', $this->join($node->directives, ' ')); + NodeKind::FRAGMENT_SPREAD => function (FragmentSpreadNode $node) : string { + return '...' + . $node->name + . $this->wrap(' ', $this->join($node->directives, ' ')); }, - NodeKind::INLINE_FRAGMENT => function (InlineFragmentNode $node) { + NodeKind::INLINE_FRAGMENT => function (InlineFragmentNode $node) : string { return $this->join( [ '...', @@ -166,7 +181,7 @@ class Printer ); }, - NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) { + NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) : string { // Note: fragment variable definitions are experimental and may be changed or removed in the future. return sprintf('fragment %s', $node->name) . $this->wrap('(', $this->join($node->variableDefinitions, ', '), ')') @@ -175,15 +190,15 @@ class Printer . $node->selectionSet; }, - NodeKind::INT => static function (IntValueNode $node) { + NodeKind::INT => static function (IntValueNode $node) : string { return $node->value; }, - NodeKind::FLOAT => static function (FloatValueNode $node) { + NodeKind::FLOAT => static function (FloatValueNode $node) : string { return $node->value; }, - NodeKind::STRING => function (StringValueNode $node, $key) { + NodeKind::STRING => function (StringValueNode $node, $key) : string { if ($node->block) { return $this->printBlockString($node->value, $key === 'description'); } @@ -191,47 +206,48 @@ class Printer return json_encode($node->value); }, - NodeKind::BOOLEAN => static function (BooleanValueNode $node) { + NodeKind::BOOLEAN => static function (BooleanValueNode $node) : string { return $node->value ? 'true' : 'false'; }, - NodeKind::NULL => static function (NullValueNode $node) { + NodeKind::NULL => static function (NullValueNode $node) : string { return 'null'; }, - NodeKind::ENUM => static function (EnumValueNode $node) { + NodeKind::ENUM => static function (EnumValueNode $node) : string { return $node->value; }, - NodeKind::LST => function (ListValueNode $node) { + NodeKind::LST => function (ListValueNode $node) : string { return '[' . $this->join($node->values, ', ') . ']'; }, - NodeKind::OBJECT => function (ObjectValueNode $node) { + NodeKind::OBJECT => function (ObjectValueNode $node) : string { return '{' . $this->join($node->fields, ', ') . '}'; }, - NodeKind::OBJECT_FIELD => static function (ObjectFieldNode $node) { + NodeKind::OBJECT_FIELD => static function (ObjectFieldNode $node) : string { return $node->name . ': ' . $node->value; }, - NodeKind::DIRECTIVE => function (DirectiveNode $node) { + NodeKind::DIRECTIVE => function (DirectiveNode $node) : string { return '@' . $node->name . $this->wrap('(', $this->join($node->arguments, ', '), ')'); }, - NodeKind::NAMED_TYPE => static function (NamedTypeNode $node) { + NodeKind::NAMED_TYPE => static function (NamedTypeNode $node) : string { + // @phpstan-ignore-next-line the printer works bottom up, so this is already a string here return $node->name; }, - NodeKind::LIST_TYPE => static function (ListTypeNode $node) { + NodeKind::LIST_TYPE => static function (ListTypeNode $node) : string { return '[' . $node->type . ']'; }, - NodeKind::NON_NULL_TYPE => static function (NonNullTypeNode $node) { + NodeKind::NON_NULL_TYPE => static function (NonNullTypeNode $node) : string { return $node->type . '!'; }, - NodeKind::SCHEMA_DEFINITION => function (SchemaDefinitionNode $def) { + NodeKind::SCHEMA_DEFINITION => function (SchemaDefinitionNode $def) : string { return $this->join( [ 'schema', @@ -242,15 +258,15 @@ class Printer ); }, - NodeKind::OPERATION_TYPE_DEFINITION => static function (OperationTypeDefinitionNode $def) { + NodeKind::OPERATION_TYPE_DEFINITION => static function (OperationTypeDefinitionNode $def) : string { return $def->operation . ': ' . $def->type; }, - NodeKind::SCALAR_TYPE_DEFINITION => $this->addDescription(function (ScalarTypeDefinitionNode $def) { + NodeKind::SCALAR_TYPE_DEFINITION => $this->addDescription(function (ScalarTypeDefinitionNode $def) : string { return $this->join(['scalar', $def->name, $this->join($def->directives, ' ')], ' '); }), - NodeKind::OBJECT_TYPE_DEFINITION => $this->addDescription(function (ObjectTypeDefinitionNode $def) { + NodeKind::OBJECT_TYPE_DEFINITION => $this->addDescription(function (ObjectTypeDefinitionNode $def) : string { return $this->join( [ 'type', @@ -263,8 +279,8 @@ class Printer ); }), - NodeKind::FIELD_DEFINITION => $this->addDescription(function (FieldDefinitionNode $def) { - $noIndent = Utils::every($def->arguments, static function (string $arg) { + NodeKind::FIELD_DEFINITION => $this->addDescription(function (FieldDefinitionNode $def) : string { + $noIndent = Utils::every($def->arguments, static function (string $arg) : bool { return strpos($arg, "\n") === false; }); @@ -276,7 +292,7 @@ class Printer . $this->wrap(' ', $this->join($def->directives, ' ')); }), - NodeKind::INPUT_VALUE_DEFINITION => $this->addDescription(function (InputValueDefinitionNode $def) { + NodeKind::INPUT_VALUE_DEFINITION => $this->addDescription(function (InputValueDefinitionNode $def) : string { return $this->join( [ $def->name . ': ' . $def->type, @@ -288,11 +304,12 @@ class Printer }), NodeKind::INTERFACE_TYPE_DEFINITION => $this->addDescription( - function (InterfaceTypeDefinitionNode $def) { + function (InterfaceTypeDefinitionNode $def) : string { return $this->join( [ 'interface', $def->name, + $this->wrap('implements ', $this->join($def->interfaces, ' & ')), $this->join($def->directives, ' '), $this->block($def->fields), ], @@ -301,13 +318,13 @@ class Printer } ), - NodeKind::UNION_TYPE_DEFINITION => $this->addDescription(function (UnionTypeDefinitionNode $def) { + NodeKind::UNION_TYPE_DEFINITION => $this->addDescription(function (UnionTypeDefinitionNode $def) : string { return $this->join( [ 'union', $def->name, $this->join($def->directives, ' '), - $def->types + count($def->types ?? []) > 0 ? '= ' . $this->join($def->types, ' | ') : '', ], @@ -315,7 +332,7 @@ class Printer ); }), - NodeKind::ENUM_TYPE_DEFINITION => $this->addDescription(function (EnumTypeDefinitionNode $def) { + NodeKind::ENUM_TYPE_DEFINITION => $this->addDescription(function (EnumTypeDefinitionNode $def) : string { return $this->join( [ 'enum', @@ -327,13 +344,13 @@ class Printer ); }), - NodeKind::ENUM_VALUE_DEFINITION => $this->addDescription(function (EnumValueDefinitionNode $def) { + NodeKind::ENUM_VALUE_DEFINITION => $this->addDescription(function (EnumValueDefinitionNode $def) : string { return $this->join([$def->name, $this->join($def->directives, ' ')], ' '); }), NodeKind::INPUT_OBJECT_TYPE_DEFINITION => $this->addDescription(function ( InputObjectTypeDefinitionNode $def - ) { + ) : string { return $this->join( [ 'input', @@ -345,7 +362,7 @@ class Printer ); }), - NodeKind::SCHEMA_EXTENSION => function (SchemaTypeExtensionNode $def) { + NodeKind::SCHEMA_EXTENSION => function (SchemaTypeExtensionNode $def) : string { return $this->join( [ 'extend schema', @@ -356,7 +373,7 @@ class Printer ); }, - NodeKind::SCALAR_TYPE_EXTENSION => function (ScalarTypeExtensionNode $def) { + NodeKind::SCALAR_TYPE_EXTENSION => function (ScalarTypeExtensionNode $def) : string { return $this->join( [ 'extend scalar', @@ -367,7 +384,7 @@ class Printer ); }, - NodeKind::OBJECT_TYPE_EXTENSION => function (ObjectTypeExtensionNode $def) { + NodeKind::OBJECT_TYPE_EXTENSION => function (ObjectTypeExtensionNode $def) : string { return $this->join( [ 'extend type', @@ -380,11 +397,12 @@ class Printer ); }, - NodeKind::INTERFACE_TYPE_EXTENSION => function (InterfaceTypeExtensionNode $def) { + NodeKind::INTERFACE_TYPE_EXTENSION => function (InterfaceTypeExtensionNode $def) : string { return $this->join( [ 'extend interface', $def->name, + $this->wrap('implements ', $this->join($def->interfaces, ' & ')), $this->join($def->directives, ' '), $this->block($def->fields), ], @@ -392,13 +410,13 @@ class Printer ); }, - NodeKind::UNION_TYPE_EXTENSION => function (UnionTypeExtensionNode $def) { + NodeKind::UNION_TYPE_EXTENSION => function (UnionTypeExtensionNode $def) : string { return $this->join( [ 'extend union', $def->name, $this->join($def->directives, ' '), - $def->types + count($def->types ?? []) > 0 ? '= ' . $this->join($def->types, ' | ') : '', ], @@ -406,7 +424,7 @@ class Printer ); }, - NodeKind::ENUM_TYPE_EXTENSION => function (EnumTypeExtensionNode $def) { + NodeKind::ENUM_TYPE_EXTENSION => function (EnumTypeExtensionNode $def) : string { return $this->join( [ 'extend enum', @@ -418,7 +436,7 @@ class Printer ); }, - NodeKind::INPUT_OBJECT_TYPE_EXTENSION => function (InputObjectTypeExtensionNode $def) { + NodeKind::INPUT_OBJECT_TYPE_EXTENSION => function (InputObjectTypeExtensionNode $def) : string { return $this->join( [ 'extend input', @@ -430,8 +448,8 @@ class Printer ); }, - NodeKind::DIRECTIVE_DEFINITION => $this->addDescription(function (DirectiveDefinitionNode $def) { - $noIndent = Utils::every($def->arguments, static function (string $arg) { + NodeKind::DIRECTIVE_DEFINITION => $this->addDescription(function (DirectiveDefinitionNode $def) : string { + $noIndent = Utils::every($def->arguments, static function (string $arg) : bool { return strpos($arg, "\n") === false; }); @@ -440,6 +458,7 @@ class Printer . ($noIndent ? $this->wrap('(', $this->join($def->arguments, ', '), ')') : $this->wrap("(\n", $this->indent($this->join($def->arguments, "\n")), "\n")) + . ($def->repeatable ? ' repeatable' : '') . ' on ' . $this->join($def->locations, ' | '); }), ], @@ -449,7 +468,7 @@ class Printer public function addDescription(callable $cb) { - return function ($node) use ($cb) { + return function ($node) use ($cb) : string { return $this->join([$node->description, $cb($node)], "\n"); }; } @@ -489,14 +508,14 @@ class Printer return $maybeArray ? count($maybeArray) : 0; } - public function join($maybeArray, $separator = '') + public function join($maybeArray, $separator = '') : string { return $maybeArray ? implode( $separator, Utils::filter( $maybeArray, - static function ($x) { + static function ($x) : bool { return (bool) $x; } ) diff --git a/vendor/webonyx/graphql-php/src/Language/Source.php b/vendor/webonyx/graphql-php/src/Language/Source.php index 7e94030..bd87940 100644 --- a/vendor/webonyx/graphql-php/src/Language/Source.php +++ b/vendor/webonyx/graphql-php/src/Language/Source.php @@ -46,8 +46,8 @@ class Source $this->body = $body; $this->length = mb_strlen($body, 'UTF-8'); - $this->name = $name ?: 'GraphQL request'; - $this->locationOffset = $location ?: new SourceLocation(1, 1); + $this->name = $name === '' || $name === null ? 'GraphQL request' : $name; + $this->locationOffset = $location ?? new SourceLocation(1, 1); Utils::invariant( $this->locationOffset->line > 0, diff --git a/vendor/webonyx/graphql-php/src/Language/Token.php b/vendor/webonyx/graphql-php/src/Language/Token.php index 831b3ad..1618103 100644 --- a/vendor/webonyx/graphql-php/src/Language/Token.php +++ b/vendor/webonyx/graphql-php/src/Language/Token.php @@ -11,28 +11,28 @@ namespace GraphQL\Language; class Token { // Each kind of token. - const SOF = ''; - const EOF = ''; - const BANG = '!'; - const DOLLAR = '$'; - const AMP = '&'; - const PAREN_L = '('; - const PAREN_R = ')'; - const SPREAD = '...'; - const COLON = ':'; - const EQUALS = '='; - const AT = '@'; - const BRACKET_L = '['; - const BRACKET_R = ']'; - const BRACE_L = '{'; - const PIPE = '|'; - const BRACE_R = '}'; - const NAME = 'Name'; - const INT = 'Int'; - const FLOAT = 'Float'; - const STRING = 'String'; - const BLOCK_STRING = 'BlockString'; - const COMMENT = 'Comment'; + public const SOF = ''; + public const EOF = ''; + public const BANG = '!'; + public const DOLLAR = '$'; + public const AMP = '&'; + public const PAREN_L = '('; + public const PAREN_R = ')'; + public const SPREAD = '...'; + public const COLON = ':'; + public const EQUALS = '='; + public const AT = '@'; + public const BRACKET_L = '['; + public const BRACKET_R = ']'; + public const BRACE_L = '{'; + public const PIPE = '|'; + public const BRACE_R = '}'; + public const NAME = 'Name'; + public const INT = 'Int'; + public const FLOAT = 'Float'; + public const STRING = 'String'; + public const BLOCK_STRING = 'BlockString'; + public const COMMENT = 'Comment'; /** * The kind of Token (see one of constants above). @@ -81,18 +81,13 @@ class Token */ public $prev; - /** @var Token */ + /** @var Token|null */ public $next; /** - * @param string $kind - * @param int $start - * @param int $end - * @param int $line - * @param int $column - * @param mixed|null $value + * @param mixed $value */ - public function __construct($kind, $start, $end, $line, $column, ?Token $previous = null, $value = null) + public function __construct(string $kind, int $start, int $end, int $line, int $column, ?Token $previous = null, $value = null) { $this->kind = $kind; $this->start = $start; @@ -104,18 +99,15 @@ class Token $this->value = $value; } - /** - * @return string - */ - public function getDescription() + public function getDescription() : string { - return $this->kind . ($this->value ? ' "' . $this->value . '"' : ''); + return $this->kind . ($this->value === null ? '' : ' "' . $this->value . '"'); } /** * @return (string|int|null)[] */ - public function toArray() + public function toArray() : array { return [ 'kind' => $this->kind, diff --git a/vendor/webonyx/graphql-php/src/Language/Visitor.php b/vendor/webonyx/graphql-php/src/Language/Visitor.php index 45f8fff..95031e8 100644 --- a/vendor/webonyx/graphql-php/src/Language/Visitor.php +++ b/vendor/webonyx/graphql-php/src/Language/Visitor.php @@ -14,8 +14,6 @@ use SplFixedArray; use stdClass; use function array_pop; use function array_splice; -use function call_user_func; -use function call_user_func_array; use function count; use function func_get_args; use function is_array; @@ -116,7 +114,7 @@ class Visitor NodeKind::NAME => [], NodeKind::DOCUMENT => ['definitions'], NodeKind::OPERATION_DEFINITION => ['name', 'variableDefinitions', 'directives', 'selectionSet'], - NodeKind::VARIABLE_DEFINITION => ['variable', 'type', 'defaultValue'], + NodeKind::VARIABLE_DEFINITION => ['variable', 'type', 'defaultValue', 'directives'], NodeKind::VARIABLE => ['name'], NodeKind::SELECTION_SET => ['selections'], NodeKind::FIELD => ['alias', 'name', 'arguments', 'directives', 'selectionSet'], @@ -153,7 +151,7 @@ class Visitor NodeKind::OBJECT_TYPE_DEFINITION => ['description', 'name', 'interfaces', 'directives', 'fields'], NodeKind::FIELD_DEFINITION => ['description', 'name', 'arguments', 'type', 'directives'], NodeKind::INPUT_VALUE_DEFINITION => ['description', 'name', 'type', 'defaultValue', 'directives'], - NodeKind::INTERFACE_TYPE_DEFINITION => ['description', 'name', 'directives', 'fields'], + NodeKind::INTERFACE_TYPE_DEFINITION => ['description', 'name', 'interfaces', 'directives', 'fields'], NodeKind::UNION_TYPE_DEFINITION => ['description', 'name', 'directives', 'types'], NodeKind::ENUM_TYPE_DEFINITION => ['description', 'name', 'directives', 'values'], NodeKind::ENUM_VALUE_DEFINITION => ['description', 'name', 'directives'], @@ -161,7 +159,7 @@ class Visitor NodeKind::SCALAR_TYPE_EXTENSION => ['name', 'directives'], NodeKind::OBJECT_TYPE_EXTENSION => ['name', 'interfaces', 'directives', 'fields'], - NodeKind::INTERFACE_TYPE_EXTENSION => ['name', 'directives', 'fields'], + NodeKind::INTERFACE_TYPE_EXTENSION => ['name', 'interfaces', 'directives', 'fields'], NodeKind::UNION_TYPE_EXTENSION => ['name', 'directives', 'types'], NodeKind::ENUM_TYPE_EXTENSION => ['name', 'directives', 'values'], NodeKind::INPUT_OBJECT_TYPE_EXTENSION => ['name', 'directives', 'fields'], @@ -186,7 +184,7 @@ class Visitor */ public static function visit($root, $visitor, $keyMap = null) { - $visitorKeys = $keyMap ?: self::$visitorKeys; + $visitorKeys = $keyMap ?? self::$visitorKeys; $stack = null; $inArray = $root instanceof NodeList || is_array($root); @@ -205,7 +203,7 @@ class Visitor $isLeaving = $index === count($keys); $key = null; $node = null; - $isEdited = $isLeaving && count($edits) !== 0; + $isEdited = $isLeaving && count($edits) > 0; if ($isLeaving) { $key = ! $ancestors ? $UNDEFINED : $path[count($path) - 1]; @@ -230,11 +228,7 @@ class Visitor $editKey -= $editOffset; } if ($inArray && $editValue === null) { - if ($node instanceof NodeList) { - $node->splice($editKey, 1); - } else { - array_splice($node, $editKey, 1); - } + $node->splice($editKey, 1); $editOffset++; } else { if ($node instanceof NodeList || is_array($node)) { @@ -251,8 +245,18 @@ class Visitor $inArray = $stack['inArray']; $stack = $stack['prev']; } else { - $key = $parent !== null ? ($inArray ? $index : $keys[$index]) : $UNDEFINED; - $node = $parent !== null ? ($parent instanceof NodeList || is_array($parent) ? $parent[$key] : $parent->{$key}) : $newRoot; + $key = $parent !== null + ? ($inArray + ? $index + : $keys[$index] + ) + : $UNDEFINED; + $node = $parent !== null + ? ($parent instanceof NodeList || is_array($parent) + ? $parent[$key] + : $parent->{$key} + ) + : $newRoot; if ($node === null || $node === $UNDEFINED) { continue; } @@ -269,8 +273,8 @@ class Visitor $visitFn = self::getVisitFn($visitor, $node->kind, $isLeaving); - if ($visitFn) { - $result = call_user_func($visitFn, $node, $key, $parent, $path, $ancestors); + if ($visitFn !== null) { + $result = $visitFn($node, $key, $parent, $path, $ancestors); $editValue = null; if ($result !== null) { @@ -318,7 +322,7 @@ class Visitor ]; $inArray = $node instanceof NodeList || is_array($node); - $keys = ($inArray ? $node : $visitorKeys[$node->kind]) ?: []; + $keys = ($inArray ? $node : $visitorKeys[$node->kind]) ?? []; $index = -1; $edits = []; if ($parent !== null) { @@ -328,7 +332,7 @@ class Visitor } } while ($stack); - if (count($edits) !== 0) { + if (count($edits) > 0) { $newRoot = $edits[0][1]; } @@ -383,7 +387,7 @@ class Visitor /** * @param callable[][] $visitors * - * @return callable[][] + * @return array */ public static function visitInParallel($visitors) { @@ -393,7 +397,7 @@ class Visitor return [ 'enter' => static function (Node $node) use ($visitors, $skipping, $visitorsCount) { for ($i = 0; $i < $visitorsCount; $i++) { - if (! empty($skipping[$i])) { + if ($skipping[$i] !== null) { continue; } @@ -407,7 +411,7 @@ class Visitor continue; } - $result = call_user_func_array($fn, func_get_args()); + $result = $fn(...func_get_args()); if ($result instanceof VisitorOperation) { if ($result->doContinue) { @@ -424,15 +428,15 @@ class Visitor }, 'leave' => static function (Node $node) use ($visitors, $skipping, $visitorsCount) { for ($i = 0; $i < $visitorsCount; $i++) { - if (empty($skipping[$i])) { + if ($skipping[$i] === null) { $fn = self::getVisitFn( $visitors[$i], $node->kind, /* isLeaving */ true ); - if ($fn) { - $result = call_user_func_array($fn, func_get_args()); + if (isset($fn)) { + $result = $fn(...func_get_args()); if ($result instanceof VisitorOperation) { if ($result->doBreak) { $skipping[$i] = $result; @@ -462,8 +466,8 @@ class Visitor $typeInfo->enter($node); $fn = self::getVisitFn($visitor, $node->kind, false); - if ($fn) { - $result = call_user_func_array($fn, func_get_args()); + if (isset($fn)) { + $result = $fn(...func_get_args()); if ($result !== null) { $typeInfo->leave($node); if ($result instanceof Node) { @@ -478,7 +482,10 @@ class Visitor }, 'leave' => static function (Node $node) use ($typeInfo, $visitor) { $fn = self::getVisitFn($visitor, $node->kind, true); - $result = $fn ? call_user_func_array($fn, func_get_args()) : null; + $result = $fn !== null + ? $fn(...func_get_args()) + : null; + $typeInfo->leave($node); return $result; @@ -490,10 +497,8 @@ class Visitor * @param callable[]|null $visitor * @param string $kind * @param bool $isLeaving - * - * @return callable|null */ - public static function getVisitFn($visitor, $kind, $isLeaving) + public static function getVisitFn($visitor, $kind, $isLeaving) : ?callable { if ($visitor === null) { return null; @@ -501,11 +506,6 @@ class Visitor $kindVisitor = $visitor[$kind] ?? null; - if (! $isLeaving && is_callable($kindVisitor)) { - // { Kind() {} } - return $kindVisitor; - } - if (is_array($kindVisitor)) { if ($isLeaving) { $kindSpecificVisitor = $kindVisitor['leave'] ?? null; @@ -513,29 +513,24 @@ class Visitor $kindSpecificVisitor = $kindVisitor['enter'] ?? null; } - if ($kindSpecificVisitor && is_callable($kindSpecificVisitor)) { - // { Kind: { enter() {}, leave() {} } } - return $kindSpecificVisitor; - } + return $kindSpecificVisitor; + } - return null; + if ($kindVisitor !== null && ! $isLeaving) { + return $kindVisitor; } $visitor += ['leave' => null, 'enter' => null]; $specificVisitor = $isLeaving ? $visitor['leave'] : $visitor['enter']; - if ($specificVisitor) { - if (is_callable($specificVisitor)) { + if (isset($specificVisitor)) { + if (! is_array($specificVisitor)) { // { enter() {}, leave() {} } return $specificVisitor; } - $specificKindVisitor = $specificVisitor[$kind] ?? null; - if (is_callable($specificKindVisitor)) { - // { enter: { Kind() {} }, leave: { Kind() {} } } - return $specificKindVisitor; - } + return $specificVisitor[$kind] ?? null; } return null; diff --git a/vendor/webonyx/graphql-php/src/Schema.php b/vendor/webonyx/graphql-php/src/Schema.php deleted file mode 100644 index 351047a..0000000 --- a/vendor/webonyx/graphql-php/src/Schema.php +++ /dev/null @@ -1,22 +0,0 @@ -readRawBody(); - $bodyParams = ['query' => $rawBody ?: '']; + $rawBody = $readRawBodyFn + ? $readRawBodyFn() + : $this->readRawBody(); + $bodyParams = ['query' => $rawBody ?? '']; } elseif (stripos($contentType, 'application/json') !== false) { - $rawBody = $readRawBodyFn ? $readRawBodyFn() : $this->readRawBody(); - $bodyParams = json_decode($rawBody ?: '', true); + $rawBody = $readRawBodyFn ? + $readRawBodyFn() + : $this->readRawBody(); + $bodyParams = json_decode($rawBody ?? '', true); if (json_last_error()) { throw new RequestError('Could not parse JSON: ' . json_last_error_msg()); @@ -142,7 +151,7 @@ class Helper * Checks validity of OperationParams extracted from HTTP request and returns an array of errors * if params are invalid (or empty array when params are valid) * - * @return Error[] + * @return array * * @api */ @@ -157,21 +166,21 @@ class Helper $errors[] = new RequestError('GraphQL Request parameters "query" and "queryId" are mutually exclusive'); } - if ($params->query !== null && (! is_string($params->query) || empty($params->query))) { + if ($params->query !== null && ! is_string($params->query)) { $errors[] = new RequestError( 'GraphQL Request parameter "query" must be string, but got ' . Utils::printSafeJson($params->query) ); } - if ($params->queryId !== null && (! is_string($params->queryId) || empty($params->queryId))) { + if ($params->queryId !== null && ! is_string($params->queryId)) { $errors[] = new RequestError( 'GraphQL Request parameter "queryId" must be string, but got ' . Utils::printSafeJson($params->queryId) ); } - if ($params->operation !== null && (! is_string($params->operation) || empty($params->operation))) { + if ($params->operation !== null && ! is_string($params->operation)) { $errors[] = new RequestError( 'GraphQL Request parameter "operation" must be string, but got ' . Utils::printSafeJson($params->operation) @@ -198,7 +207,7 @@ class Helper */ public function executeOperation(ServerConfig $config, OperationParams $op) { - $promiseAdapter = $config->getPromiseAdapter() ?: Executor::getPromiseAdapter(); + $promiseAdapter = $config->getPromiseAdapter() ?? Executor::getPromiseAdapter(); $result = $this->promiseToExecuteOperation($promiseAdapter, $config, $op); if ($promiseAdapter instanceof SyncPromiseAdapter) { @@ -220,7 +229,7 @@ class Helper */ public function executeBatch(ServerConfig $config, array $operations) { - $promiseAdapter = $config->getPromiseAdapter() ?: Executor::getPromiseAdapter(); + $promiseAdapter = $config->getPromiseAdapter() ?? Executor::getPromiseAdapter(); $result = []; foreach ($operations as $operation) { @@ -249,7 +258,7 @@ class Helper $isBatch = false ) { try { - if (! $config->getSchema()) { + if ($config->getSchema() === null) { throw new InvariantViolation('Schema is required for the server'); } @@ -259,10 +268,10 @@ class Helper $errors = $this->validateOperationParams($op); - if (! empty($errors)) { + if (count($errors) > 0) { $errors = Utils::map( $errors, - static function (RequestError $err) { + static function (RequestError $err) : Error { return Error::createLocatedError($err, null, null); } ); @@ -272,13 +281,20 @@ class Helper ); } - $doc = $op->queryId ? $this->loadPersistedQuery($config, $op) : $op->query; + $doc = $op->queryId + ? $this->loadPersistedQuery($config, $op) + : $op->query; if (! $doc instanceof DocumentNode) { $doc = Parser::parse($doc); } $operationType = AST::getOperation($doc, $op->operation); + + if ($operationType === false) { + throw new RequestError('Failed to determine operation type'); + } + if ($operationType !== 'query' && $op->isReadOnly()) { throw new RequestError('GET supports only query operation'); } @@ -304,15 +320,15 @@ class Helper ); } - $applyErrorHandling = static function (ExecutionResult $result) use ($config) { + $applyErrorHandling = static function (ExecutionResult $result) use ($config) : ExecutionResult { if ($config->getErrorsHandler()) { $result->setErrorsHandler($config->getErrorsHandler()); } - if ($config->getErrorFormatter() || $config->getDebug()) { + if ($config->getErrorFormatter() || $config->getDebugFlag() !== DebugFlag::NONE) { $result->setErrorFormatter( FormattedError::prepareFormatter( $config->getErrorFormatter(), - $config->getDebug() + $config->getDebugFlag() ) ); } @@ -333,7 +349,7 @@ class Helper // Load query if we got persisted query id: $loader = $config->getPersistentQueryLoader(); - if (! $loader) { + if ($loader === null) { throw new RequestError('Persisted queries are not supported by this server'); } @@ -379,19 +395,17 @@ class Helper } /** - * @param string $operationType - * * @return mixed */ - private function resolveRootValue(ServerConfig $config, OperationParams $params, DocumentNode $doc, $operationType) + private function resolveRootValue(ServerConfig $config, OperationParams $params, DocumentNode $doc, string $operationType) { - $root = $config->getRootValue(); + $rootValue = $config->getRootValue(); - if (is_callable($root)) { - $root = $root($params, $doc, $operationType); + if (is_callable($rootValue)) { + $rootValue = $rootValue($params, $doc, $operationType); } - return $root; + return $rootValue; } /** @@ -425,7 +439,7 @@ class Helper public function sendResponse($result, $exitWhenDone = false) { if ($result instanceof Promise) { - $result->then(function ($actualResult) use ($exitWhenDone) { + $result->then(function ($actualResult) use ($exitWhenDone) : void { $this->doSendResponse($actualResult, $exitWhenDone); }); } else { @@ -473,7 +487,7 @@ class Helper if (is_array($result) && isset($result[0])) { Utils::each( $result, - static function ($executionResult, $index) { + static function ($executionResult, $index) : void { if (! $executionResult instanceof ExecutionResult) { throw new InvariantViolation(sprintf( 'Expecting every entry of batched query result to be instance of %s but entry at position %d is %s', @@ -493,7 +507,7 @@ class Helper Utils::printSafe($result) )); } - if ($result->data === null && ! empty($result->errors)) { + if ($result->data === null && count($result->errors) > 0) { $httpStatus = 400; } else { $httpStatus = 200; @@ -512,7 +526,7 @@ class Helper * * @api */ - public function parsePsrRequest(ServerRequestInterface $request) + public function parsePsrRequest(RequestInterface $request) { if ($request->getMethod() === 'GET') { $bodyParams = []; @@ -524,13 +538,17 @@ class Helper } if (stripos($contentType[0], 'application/graphql') !== false) { - $bodyParams = ['query' => $request->getBody()->getContents()]; + $bodyParams = ['query' => (string) $request->getBody()]; } elseif (stripos($contentType[0], 'application/json') !== false) { - $bodyParams = $request->getParsedBody(); + $bodyParams = $request instanceof ServerRequestInterface + ? $request->getParsedBody() + : json_decode((string) $request->getBody(), true); if ($bodyParams === null) { throw new InvariantViolation( - 'PSR-7 request is expected to provide parsed body for "application/json" requests but got null' + $request instanceof ServerRequestInterface + ? 'Expected to receive a parsed body for "application/json" PSR-7 request but got null' + : 'Expected to receive a JSON array in body for "application/json" PSR-7 request' ); } @@ -541,7 +559,7 @@ class Helper ); } } else { - $bodyParams = $request->getParsedBody(); + parse_str((string) $request->getBody(), $bodyParams); if (! is_array($bodyParams)) { throw new RequestError('Unexpected content type: ' . Utils::printSafeJson($contentType[0])); @@ -549,10 +567,12 @@ class Helper } } + parse_str(html_entity_decode($request->getUri()->getQuery()), $queryParams); + return $this->parseRequestParams( $request->getMethod(), $bodyParams, - $request->getQueryParams() + $queryParams ); } diff --git a/vendor/webonyx/graphql-php/src/Server/OperationParams.php b/vendor/webonyx/graphql-php/src/Server/OperationParams.php index 3ab12de..5490ca4 100644 --- a/vendor/webonyx/graphql-php/src/Server/OperationParams.php +++ b/vendor/webonyx/graphql-php/src/Server/OperationParams.php @@ -8,7 +8,9 @@ use function array_change_key_case; use function is_string; use function json_decode; use function json_last_error; +use function strlen; use const CASE_LOWER; +use const JSON_ERROR_NONE; /** * Structure representing parsed HTTP parameters for GraphQL operation @@ -93,7 +95,7 @@ class OperationParams } $tmp = json_decode($params[$param], true); - if (json_last_error()) { + if (json_last_error() !== JSON_ERROR_NONE) { continue; } @@ -101,14 +103,14 @@ class OperationParams } $instance->query = $params['query']; - $instance->queryId = $params['queryid'] ?: $params['documentid'] ?: $params['id']; + $instance->queryId = $params['queryid'] ?? $params['documentid'] ?? $params['id']; $instance->operation = $params['operationname']; $instance->variables = $params['variables']; $instance->extensions = $params['extensions']; $instance->readOnly = $readonly; // Apollo server/client compatibility: look for the queryid in extensions - if (isset($instance->extensions['persistedQuery']['sha256Hash']) && empty($instance->query) && empty($instance->queryId)) { + if (isset($instance->extensions['persistedQuery']['sha256Hash']) && strlen($instance->query ?? '') === 0 && strlen($instance->queryId ?? '') === 0) { $instance->queryId = $instance->extensions['persistedQuery']['sha256Hash']; } diff --git a/vendor/webonyx/graphql-php/src/Server/ServerConfig.php b/vendor/webonyx/graphql-php/src/Server/ServerConfig.php index cb36ceb..2c44dea 100644 --- a/vendor/webonyx/graphql-php/src/Server/ServerConfig.php +++ b/vendor/webonyx/graphql-php/src/Server/ServerConfig.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Server; +use GraphQL\Error\DebugFlag; use GraphQL\Error\InvariantViolation; use GraphQL\Executor\Promise\PromiseAdapter; use GraphQL\Type\Schema; @@ -54,7 +55,7 @@ class ServerConfig return $instance; } - /** @var Schema */ + /** @var Schema|null */ private $schema; /** @var mixed|callable */ @@ -69,22 +70,22 @@ class ServerConfig /** @var callable|null */ private $errorsHandler; - /** @var bool */ - private $debug = false; + /** @var int */ + private $debugFlag = DebugFlag::NONE; /** @var bool */ private $queryBatching = false; - /** @var ValidationRule[]|callable */ + /** @var ValidationRule[]|callable|null */ private $validationRules; - /** @var callable */ + /** @var callable|null */ private $fieldResolver; - /** @var PromiseAdapter */ + /** @var PromiseAdapter|null */ private $promiseAdapter; - /** @var callable */ + /** @var callable|null */ private $persistentQueryLoader; /** @@ -158,7 +159,7 @@ class ServerConfig /** * Set validation rules for this server. * - * @param ValidationRule[]|callable $validationRules + * @param ValidationRule[]|callable|null $validationRules * * @return self * @@ -207,17 +208,13 @@ class ServerConfig } /** - * Set response debug flags. See GraphQL\Error\Debug class for a list of all available flags - * - * @param bool|int $set - * - * @return self + * Set response debug flags. @see \GraphQL\Error\DebugFlag class for a list of all available flags * * @api */ - public function setDebug($set = true) + public function setDebugFlag(int $debugFlag = DebugFlag::INCLUDE_DEBUG_MESSAGE) : self { - $this->debug = $set; + $this->debugFlag = $debugFlag; return $this; } @@ -263,7 +260,7 @@ class ServerConfig } /** - * @return Schema + * @return Schema|null */ public function getSchema() { @@ -287,7 +284,7 @@ class ServerConfig } /** - * @return PromiseAdapter + * @return PromiseAdapter|null */ public function getPromiseAdapter() { @@ -295,7 +292,7 @@ class ServerConfig } /** - * @return ValidationRule[]|callable + * @return ValidationRule[]|callable|null */ public function getValidationRules() { @@ -303,7 +300,7 @@ class ServerConfig } /** - * @return callable + * @return callable|null */ public function getFieldResolver() { @@ -311,19 +308,16 @@ class ServerConfig } /** - * @return callable + * @return callable|null */ public function getPersistentQueryLoader() { return $this->persistentQueryLoader; } - /** - * @return bool - */ - public function getDebug() + public function getDebugFlag() : int { - return $this->debug; + return $this->debugFlag; } /** diff --git a/vendor/webonyx/graphql-php/src/Server/StandardServer.php b/vendor/webonyx/graphql-php/src/Server/StandardServer.php index 7b7e627..bb128ea 100644 --- a/vendor/webonyx/graphql-php/src/Server/StandardServer.php +++ b/vendor/webonyx/graphql-php/src/Server/StandardServer.php @@ -4,13 +4,14 @@ declare(strict_types=1); namespace GraphQL\Server; +use GraphQL\Error\DebugFlag; use GraphQL\Error\FormattedError; use GraphQL\Error\InvariantViolation; use GraphQL\Executor\ExecutionResult; use GraphQL\Executor\Promise\Promise; use GraphQL\Utils\Utils; +use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; use Throwable; use function is_array; @@ -50,12 +51,12 @@ class StandardServer * (e.g. during schema instantiation). * * @param Throwable $error - * @param bool $debug + * @param int $debug * @param bool $exitWhenDone * * @api */ - public static function send500Error($error, $debug = false, $exitWhenDone = false) + public static function send500Error($error, $debug = DebugFlag::NONE, $exitWhenDone = false) { $response = [ 'errors' => [FormattedError::createFromException($error, $debug)], @@ -146,7 +147,7 @@ class StandardServer * @api */ public function processPsrRequest( - ServerRequestInterface $request, + RequestInterface $request, ResponseInterface $response, StreamInterface $writableBodyStream ) { @@ -163,7 +164,7 @@ class StandardServer * * @api */ - public function executePsrRequest(ServerRequestInterface $request) + public function executePsrRequest(RequestInterface $request) { $parsedBody = $this->helper->parsePsrRequest($request); diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/AbstractType.php b/vendor/webonyx/graphql-php/src/Type/Definition/AbstractType.php index 356dceb..e025715 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/AbstractType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/AbstractType.php @@ -4,12 +4,11 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; -/* -export type GraphQLAbstractType = -GraphQLInterfaceType | -GraphQLUnionType; -*/ - +/** +export type AbstractType = +InterfaceType | +UnionType; + */ interface AbstractType { /** diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/BooleanType.php b/vendor/webonyx/graphql-php/src/Type/Definition/BooleanType.php index 56b5f0f..46dd943 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/BooleanType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/BooleanType.php @@ -20,11 +20,14 @@ class BooleanType extends ScalarType public $description = 'The `Boolean` scalar type represents `true` or `false`.'; /** - * @param mixed $value + * Serialize the given value to a boolean. * - * @return bool + * The GraphQL spec leaves this up to the implementations, so we just do what + * PHP does natively to make this intuitive for developers. + * + * @param mixed $value */ - public function serialize($value) + public function serialize($value) : bool { return (bool) $value; } @@ -42,22 +45,19 @@ class BooleanType extends ScalarType return $value; } - throw new Error('Cannot represent value as boolean: ' . Utils::printSafe($value)); + throw new Error('Boolean cannot represent a non boolean value: ' . Utils::printSafe($value)); } /** - * @param Node $valueNode * @param mixed[]|null $variables * - * @return bool|null - * * @throws Exception */ - public function parseLiteral($valueNode, ?array $variables = null) + public function parseLiteral(Node $valueNode, ?array $variables = null) { if (! $valueNode instanceof BooleanValueNode) { // Intentionally without message, as all information already in wrapped Exception - throw new Exception(); + throw new Error(); } return $valueNode->value; diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/CustomScalarType.php b/vendor/webonyx/graphql-php/src/Type/Definition/CustomScalarType.php index 50b28ce..8a82530 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/CustomScalarType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/CustomScalarType.php @@ -8,7 +8,6 @@ use Exception; use GraphQL\Language\AST\Node; use GraphQL\Utils\AST; use GraphQL\Utils\Utils; -use function call_user_func; use function is_callable; use function sprintf; @@ -21,7 +20,7 @@ class CustomScalarType extends ScalarType */ public function serialize($value) { - return call_user_func($this->config['serialize'], $value); + return $this->config['serialize']($value); } /** @@ -32,26 +31,23 @@ class CustomScalarType extends ScalarType public function parseValue($value) { if (isset($this->config['parseValue'])) { - return call_user_func($this->config['parseValue'], $value); + return $this->config['parseValue']($value); } return $value; } /** - * @param Node $valueNode * @param mixed[]|null $variables * * @return mixed * * @throws Exception */ - public function parseLiteral(/* GraphQL\Language\AST\ValueNode */ - $valueNode, - ?array $variables = null - ) { + public function parseLiteral(Node $valueNode, ?array $variables = null) + { if (isset($this->config['parseLiteral'])) { - return call_user_func($this->config['parseLiteral'], $valueNode, $variables); + return $this->config['parseLiteral']($valueNode, $variables); } return AST::valueFromASTUntyped($valueNode, $variables); diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/Directive.php b/vendor/webonyx/graphql-php/src/Type/Definition/Directive.php index 0ffe496..10878e9 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/Directive.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/Directive.php @@ -4,25 +4,23 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\DirectiveLocation; -use GraphQL\Utils\Utils; use function array_key_exists; -use function array_keys; -use function in_array; use function is_array; class Directive { public const DEFAULT_DEPRECATION_REASON = 'No longer supported'; - const INCLUDE_NAME = 'include'; - const IF_ARGUMENT_NAME = 'if'; - const SKIP_NAME = 'skip'; - const DEPRECATED_NAME = 'deprecated'; - const REASON_ARGUMENT_NAME = 'reason'; + public const INCLUDE_NAME = 'include'; + public const IF_ARGUMENT_NAME = 'if'; + public const SKIP_NAME = 'skip'; + public const DEPRECATED_NAME = 'deprecated'; + public const REASON_ARGUMENT_NAME = 'reason'; - /** @var Directive[] */ + /** @var Directive[]|null */ public static $internalDirectives; // Schema Definitions @@ -33,12 +31,15 @@ class Directive /** @var string|null */ public $description; - /** @var string[] */ - public $locations; - /** @var FieldArgument[] */ public $args = []; + /** @var bool */ + public $isRepeatable; + + /** @var string[] */ + public $locations; + /** @var DirectiveDefinitionNode|null */ public $astNode; @@ -50,6 +51,13 @@ class Directive */ public function __construct(array $config) { + if (! isset($config['name'])) { + throw new InvariantViolation('Directive must be named.'); + } + $this->name = $config['name']; + + $this->description = $config['description'] ?? null; + if (isset($config['args'])) { $args = []; foreach ($config['args'] as $name => $arg) { @@ -60,14 +68,16 @@ class Directive } } $this->args = $args; - unset($config['args']); - } - foreach ($config as $key => $value) { - $this->{$key} = $value; } - Utils::invariant($this->name, 'Directive must be named.'); - Utils::invariant(is_array($this->locations), 'Must provide locations for directive.'); + if (! isset($config['locations']) || ! is_array($config['locations'])) { + throw new InvariantViolation('Must provide locations for directive.'); + } + $this->locations = $config['locations']; + + $this->isRepeatable = $config['isRepeatable'] ?? false; + $this->astNode = $config['astNode'] ?? null; + $this->config = $config; } @@ -84,9 +94,9 @@ class Directive /** * @return Directive[] */ - public static function getInternalDirectives() + public static function getInternalDirectives() : array { - if (! self::$internalDirectives) { + if (self::$internalDirectives === null) { self::$internalDirectives = [ 'include' => new self([ 'name' => self::INCLUDE_NAME, @@ -130,8 +140,8 @@ class Directive 'type' => Type::string(), 'description' => 'Explains why this element was deprecated, usually also including a ' . - 'suggestion for how to access supported similar data. Formatted ' . - 'in [Markdown](https://daringfireball.net/projects/markdown/).', + 'suggestion for how to access supported similar data. Formatted using ' . + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).', 'defaultValue' => self::DEFAULT_DEPRECATION_REASON, ]), ], diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/EnumType.php b/vendor/webonyx/graphql-php/src/Type/Definition/EnumType.php index dc83d69..9451ec7 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/EnumType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/EnumType.php @@ -24,10 +24,20 @@ class EnumType extends Type implements InputType, OutputType, LeafType, Nullable /** @var EnumTypeDefinitionNode|null */ public $astNode; - /** @var EnumValueDefinition[] */ + /** + * Lazily initialized. + * + * @var EnumValueDefinition[] + */ private $values; - /** @var MixedStore */ + /** + * Lazily initialized. + * + * Actually a MixedStore, PHPStan won't let us type it that way. + * + * @var MixedStore + */ private $valueLookup; /** @var ArrayObject */ @@ -67,12 +77,10 @@ class EnumType extends Type implements InputType, OutputType, LeafType, Nullable return $lookup[$name] ?? null; } - /** - * @return ArrayObject - */ - private function getNameLookup() + private function getNameLookup() : ArrayObject { if (! $this->nameLookup) { + /** @var ArrayObject $lookup */ $lookup = new ArrayObject(); foreach ($this->getValues() as $value) { $lookup[$value->name] = $value; @@ -86,9 +94,9 @@ class EnumType extends Type implements InputType, OutputType, LeafType, Nullable /** * @return EnumValueDefinition[] */ - public function getValues() + public function getValues() : array { - if ($this->values === null) { + if (! isset($this->values)) { $this->values = []; $config = $this->config; @@ -139,11 +147,11 @@ class EnumType extends Type implements InputType, OutputType, LeafType, Nullable } /** - * @return MixedStore + * Actually returns a MixedStore, PHPStan won't let us type it that way */ - private function getValueLookup() + private function getValueLookup() : MixedStore { - if ($this->valueLookup === null) { + if (! isset($this->valueLookup)) { $this->valueLookup = new MixedStore(); foreach ($this->getValues() as $valueName => $value) { @@ -172,14 +180,13 @@ class EnumType extends Type implements InputType, OutputType, LeafType, Nullable } /** - * @param Node $valueNode * @param mixed[]|null $variables * * @return null * * @throws Exception */ - public function parseLiteral($valueNode, ?array $variables = null) + public function parseLiteral(Node $valueNode, ?array $variables = null) { if ($valueNode instanceof EnumValueNode) { $lookup = $this->getNameLookup(); @@ -192,7 +199,7 @@ class EnumType extends Type implements InputType, OutputType, LeafType, Nullable } // Intentionally without message, as all information already in wrapped Exception - throw new Exception(); + throw new Error(); } /** diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/FieldArgument.php b/vendor/webonyx/graphql-php/src/Type/Definition/FieldArgument.php index 3bffe57..f6a8f38 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/FieldArgument.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/FieldArgument.php @@ -6,7 +6,9 @@ namespace GraphQL\Type\Definition; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\InputValueDefinitionNode; +use GraphQL\Type\Schema; use GraphQL\Utils\Utils; +use function array_key_exists; use function is_array; use function is_string; use function sprintf; @@ -28,28 +30,19 @@ class FieldArgument /** @var mixed[] */ public $config; - /** @var InputType */ + /** @var Type&InputType */ private $type; - /** @var bool */ - private $defaultValueExists = false; - - /** - * @param mixed[] $def - */ + /** @param mixed[] $def */ public function __construct(array $def) { foreach ($def as $key => $value) { switch ($key) { - case 'type': - $this->type = $value; - break; case 'name': $this->name = $value; break; case 'defaultValue': - $this->defaultValue = $value; - $this->defaultValueExists = true; + $this->defaultValue = $value; break; case 'description': $this->description = $value; @@ -67,7 +60,7 @@ class FieldArgument * * @return FieldArgument[] */ - public static function createMap(array $config) + public static function createMap(array $config) : array { $map = []; foreach ($config as $name => $argConfig) { @@ -80,20 +73,29 @@ class FieldArgument return $map; } - /** - * @return InputType - */ - public function getType() + public function getType() : Type { + if (! isset($this->type)) { + /** + * TODO: replace this phpstan cast with native assert + * + * @var Type&InputType + */ + $type = Schema::resolveType($this->config['type']); + $this->type = $type; + } + return $this->type; } - /** - * @return bool - */ - public function defaultValueExists() + public function defaultValueExists() : bool { - return $this->defaultValueExists; + return array_key_exists('defaultValue', $this->config); + } + + public function isRequired() : bool + { + return $this->getType() instanceof NonNull && ! $this->defaultValueExists(); } public function assertValid(FieldDefinition $parentField, Type $parentType) @@ -105,7 +107,7 @@ class FieldArgument sprintf('%s.%s(%s:) %s', $parentType->name, $parentField->name, $this->name, $e->getMessage()) ); } - $type = $this->type; + $type = $this->getType(); if ($type instanceof WrappingType) { $type = $type->getWrappedType(true); } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/FieldDefinition.php b/vendor/webonyx/graphql-php/src/Type/Definition/FieldDefinition.php index 8f409bf..7d4ee38 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/FieldDefinition.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/FieldDefinition.php @@ -6,7 +6,9 @@ namespace GraphQL\Type\Definition; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; +use GraphQL\Error\Warning; use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Type\Schema; use GraphQL\Utils\Utils; use function is_array; use function is_callable; @@ -30,7 +32,7 @@ class FieldDefinition * Callback for resolving field value given parent value. * Mutually exclusive with `map` * - * @var callable + * @var callable|null */ public $resolveFn; @@ -38,7 +40,7 @@ class FieldDefinition * Callback for mapping list of parent values to list of field values. * Mutually exclusive with `resolve` * - * @var callable + * @var callable|null */ public $mapFn; @@ -58,8 +60,8 @@ class FieldDefinition */ public $config; - /** @var OutputType */ - public $type; + /** @var OutputType&Type */ + private $type; /** @var callable|string */ private $complexityFn; @@ -70,7 +72,6 @@ class FieldDefinition protected function __construct(array $config) { $this->name = $config['name']; - $this->type = $config['type']; $this->resolveFn = $config['resolve'] ?? null; $this->mapFn = $config['map'] ?? null; $this->args = isset($config['args']) ? FieldArgument::createMap($config['args']) : []; @@ -84,7 +85,12 @@ class FieldDefinition $this->complexityFn = $config['complexity'] ?? self::DEFAULT_COMPLEXITY_FN; } - public static function defineFieldMap(Type $type, $fields) + /** + * @param (callable():mixed[])|mixed[] $fields + * + * @return array + */ + public static function defineFieldMap(Type $type, $fields) : array { if (is_callable($fields)) { $fields = $fields(); @@ -117,6 +123,17 @@ class FieldDefinition $fieldDef = self::create($field); } elseif ($field instanceof self) { $fieldDef = $field; + } elseif (is_callable($field)) { + if (! is_string($name)) { + throw new InvariantViolation( + sprintf( + '%s lazy fields must be an associative array with field names as keys.', + $type->name + ) + ); + } + + $fieldDef = new UnresolvedFieldDefinition($type, $name, $field); } else { if (! is_string($name) || ! $field) { throw new InvariantViolation( @@ -131,7 +148,8 @@ class FieldDefinition $fieldDef = self::create(['name' => $name, 'type' => $field]); } - $map[$fieldDef->name] = $fieldDef; + + $map[$fieldDef->getName()] = $fieldDef; } return $map; @@ -164,7 +182,7 @@ class FieldDefinition */ public function getArg($name) { - foreach ($this->args ?: [] as $arg) { + foreach ($this->args ?? [] as $arg) { /** @var FieldArgument $arg */ if ($arg->name === $name) { return $arg; @@ -174,14 +192,78 @@ class FieldDefinition return null; } - /** - * @return Type - */ - public function getType() + public function getName() : string { + return $this->name; + } + + public function getType() : Type + { + if (! isset($this->type)) { + /** + * TODO: replace this phpstan cast with native assert + * + * @var Type&OutputType + */ + $type = Schema::resolveType($this->config['type']); + $this->type = $type; + } + return $this->type; } + public function __isset(string $name) : bool + { + switch ($name) { + case 'type': + Warning::warnOnce( + "The public getter for 'type' on FieldDefinition has been deprecated and will be removed" . + " in the next major version. Please update your code to use the 'getType' method.", + Warning::WARNING_CONFIG_DEPRECATION + ); + + return isset($this->type); + } + + return isset($this->$name); + } + + public function __get(string $name) + { + switch ($name) { + case 'type': + Warning::warnOnce( + "The public getter for 'type' on FieldDefinition has been deprecated and will be removed" . + " in the next major version. Please update your code to use the 'getType' method.", + Warning::WARNING_CONFIG_DEPRECATION + ); + + return $this->getType(); + default: + return $this->$name; + } + + return null; + } + + public function __set(string $name, $value) + { + switch ($name) { + case 'type': + Warning::warnOnce( + "The public setter for 'type' on FieldDefinition has been deprecated and will be removed" . + ' in the next major version.', + Warning::WARNING_CONFIG_DEPRECATION + ); + $this->type = $value; + break; + + default: + $this->$name = $value; + break; + } + } + /** * @return bool */ @@ -217,7 +299,7 @@ class FieldDefinition ) ); - $type = $this->type; + $type = $this->getType(); if ($type instanceof WrappingType) { $type = $type->getWrappedType(true); } @@ -239,5 +321,9 @@ class FieldDefinition Utils::printSafe($this->resolveFn) ) ); + + foreach ($this->args as $fieldArgument) { + $fieldArgument->assertValid($this, $type); + } } } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/FloatType.php b/vendor/webonyx/graphql-php/src/Type/Definition/FloatType.php index e8923ca..4ce723c 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/FloatType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/FloatType.php @@ -10,6 +10,11 @@ use GraphQL\Language\AST\FloatValueNode; use GraphQL\Language\AST\IntValueNode; use GraphQL\Language\AST\Node; use GraphQL\Utils\Utils; +use function floatval; +use function is_bool; +use function is_finite; +use function is_float; +use function is_int; use function is_numeric; class FloatType extends ScalarType @@ -26,60 +31,59 @@ values as specified by /** * @param mixed $value * - * @return float|null - * * @throws Error */ - public function serialize($value) + public function serialize($value) : float { - return $this->coerceFloat($value); - } + $float = is_numeric($value) || is_bool($value) + ? (float) $value + : null; - private function coerceFloat($value) - { - if ($value === '') { - throw new Error( - 'Float cannot represent non numeric value: (empty string)' - ); - } - - if (! is_numeric($value) && $value !== true && $value !== false) { + if ($float === null || ! is_finite($float)) { throw new Error( 'Float cannot represent non numeric value: ' . Utils::printSafe($value) ); } - return (float) $value; + return $float; } /** * @param mixed $value * - * @return float|null - * * @throws Error */ - public function parseValue($value) + public function parseValue($value) : float { - return $this->coerceFloat($value); + $float = is_float($value) || is_int($value) + ? (float) $value + : null; + + if ($float === null || ! is_finite($float)) { + throw new Error( + 'Float cannot represent non numeric value: ' . + Utils::printSafe($value) + ); + } + + return $float; } /** - * @param Node $valueNode * @param mixed[]|null $variables * - * @return float|null + * @return float * * @throws Exception */ - public function parseLiteral($valueNode, ?array $variables = null) + public function parseLiteral(Node $valueNode, ?array $variables = null) { if ($valueNode instanceof FloatValueNode || $valueNode instanceof IntValueNode) { return (float) $valueNode->value; } // Intentionally without message, as all information already in wrapped Exception - throw new Exception(); + throw new Error(); } } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/HasFieldsType.php b/vendor/webonyx/graphql-php/src/Type/Definition/HasFieldsType.php new file mode 100644 index 0000000..d77e61f --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Type/Definition/HasFieldsType.php @@ -0,0 +1,33 @@ + + * + * @throws InvariantViolation + */ + public function getFields() : array; + + /** + * @return array + * + * @throws InvariantViolation + */ + public function getFieldNames() : array; +} diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/IDType.php b/vendor/webonyx/graphql-php/src/Type/Definition/IDType.php index 8077393..d5a214d 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/IDType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/IDType.php @@ -12,7 +12,6 @@ use GraphQL\Language\AST\StringValueNode; use GraphQL\Utils\Utils; use function is_int; use function is_object; -use function is_scalar; use function is_string; use function method_exists; @@ -38,17 +37,12 @@ When expected as an input type, any string (such as `"4"`) or integer */ public function serialize($value) { - if ($value === true) { - return 'true'; - } - if ($value === false) { - return 'false'; - } - if ($value === null) { - return 'null'; - } - if (! is_scalar($value) && (! is_object($value) || ! method_exists($value, '__toString'))) { - throw new Error('ID type cannot represent non scalar value: ' . Utils::printSafe($value)); + $canCast = is_string($value) + || is_int($value) + || (is_object($value) && method_exists($value, '__toString')); + + if (! $canCast) { + throw new Error('ID cannot represent value: ' . Utils::printSafe($value)); } return (string) $value; @@ -57,34 +51,30 @@ When expected as an input type, any string (such as `"4"`) or integer /** * @param mixed $value * - * @return string - * * @throws Error */ - public function parseValue($value) + public function parseValue($value) : string { if (is_string($value) || is_int($value)) { return (string) $value; } - - throw new Error('Cannot represent value as ID: ' . Utils::printSafe($value)); + throw new Error('ID cannot represent value: ' . Utils::printSafe($value)); } /** - * @param Node $valueNode * @param mixed[]|null $variables * - * @return string|null + * @return string * * @throws Exception */ - public function parseLiteral($valueNode, ?array $variables = null) + public function parseLiteral(Node $valueNode, ?array $variables = null) { if ($valueNode instanceof StringValueNode || $valueNode instanceof IntValueNode) { return $valueNode->value; } // Intentionally without message, as all information already in wrapped Exception - throw new Exception(); + throw new Error(); } } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/ImplementingType.php b/vendor/webonyx/graphql-php/src/Type/Definition/ImplementingType.php new file mode 100644 index 0000000..94bf771 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Type/Definition/ImplementingType.php @@ -0,0 +1,20 @@ + + */ + public function getInterfaces() : array; +} diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectField.php b/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectField.php index 82fa570..e2578ef 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectField.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectField.php @@ -6,8 +6,11 @@ namespace GraphQL\Type\Definition; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; +use GraphQL\Error\Warning; use GraphQL\Language\AST\InputValueDefinitionNode; +use GraphQL\Type\Schema; use GraphQL\Utils\Utils; +use function array_key_exists; use function sprintf; class InputObjectField @@ -21,8 +24,8 @@ class InputObjectField /** @var string|null */ public $description; - /** @var mixed */ - public $type; + /** @var Type&InputType */ + private $type; /** @var InputValueDefinitionNode|null */ public $astNode; @@ -30,13 +33,6 @@ class InputObjectField /** @var mixed[] */ public $config; - /** - * Helps to differentiate when `defaultValue` is `null` and when it was not even set initially - * - * @var bool - */ - private $defaultValueExists = false; - /** * @param mixed[] $opts */ @@ -45,11 +41,13 @@ class InputObjectField foreach ($opts as $k => $v) { switch ($k) { case 'defaultValue': - $this->defaultValue = $v; - $this->defaultValueExists = true; + $this->defaultValue = $v; break; case 'defaultValueExists': break; + case 'type': + // do nothing; type is lazy loaded in getType + break; default: $this->{$k} = $v; } @@ -57,20 +55,84 @@ class InputObjectField $this->config = $opts; } - /** - * @return mixed - */ - public function getType() + public function __isset(string $name) : bool { - return $this->type; + switch ($name) { + case 'type': + Warning::warnOnce( + "The public getter for 'type' on InputObjectField has been deprecated and will be removed" . + " in the next major version. Please update your code to use the 'getType' method.", + Warning::WARNING_CONFIG_DEPRECATION + ); + + return isset($this->type); + } + + return isset($this->$name); + } + + public function __get(string $name) + { + switch ($name) { + case 'type': + Warning::warnOnce( + "The public getter for 'type' on InputObjectField has been deprecated and will be removed" . + " in the next major version. Please update your code to use the 'getType' method.", + Warning::WARNING_CONFIG_DEPRECATION + ); + + return $this->getType(); + default: + return $this->$name; + } + + return null; + } + + public function __set(string $name, $value) + { + switch ($name) { + case 'type': + Warning::warnOnce( + "The public setter for 'type' on InputObjectField has been deprecated and will be removed" . + ' in the next major version.', + Warning::WARNING_CONFIG_DEPRECATION + ); + $this->type = $value; + break; + + default: + $this->$name = $value; + break; + } } /** - * @return bool + * @return Type&InputType */ - public function defaultValueExists() + public function getType() : Type { - return $this->defaultValueExists; + if (! isset($this->type)) { + /** + * TODO: replace this phpstan cast with native assert + * + * @var Type&InputType + */ + $type = Schema::resolveType($this->config['type']); + $this->type = $type; + } + + return $this->type; + } + + public function defaultValueExists() : bool + { + return array_key_exists('defaultValue', $this->config); + } + + public function isRequired() : bool + { + return $this->getType() instanceof NonNull && ! $this->defaultValueExists(); } /** @@ -83,7 +145,7 @@ class InputObjectField } catch (Error $e) { throw new InvariantViolation(sprintf('%s.%s: %s', $parentType->name, $this->name, $e->getMessage())); } - $type = $this->type; + $type = $this->getType(); if ($type instanceof WrappingType) { $type = $type->getWrappedType(true); } @@ -97,9 +159,9 @@ class InputObjectField ) ); Utils::invariant( - empty($this->config['resolve']), + ! array_key_exists('resolve', $this->config), sprintf( - '%s.%s field type has a resolve property, but Input Types cannot define resolvers.', + '%s.%s field has a resolve property, but Input Types cannot define resolvers.', $parentType->name, $this->name ) diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectType.php b/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectType.php index c921dda..b55755d 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/InputObjectType.php @@ -4,12 +4,11 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; -use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\InputObjectTypeDefinitionNode; use GraphQL\Language\AST\InputObjectTypeExtensionNode; use GraphQL\Utils\Utils; -use function call_user_func; +use function count; use function is_array; use function is_callable; use function is_string; @@ -20,7 +19,11 @@ class InputObjectType extends Type implements InputType, NullableType, NamedType /** @var InputObjectTypeDefinitionNode|null */ public $astNode; - /** @var InputObjectField[] */ + /** + * Lazily initialized. + * + * @var InputObjectField[] + */ private $fields; /** @var InputObjectTypeExtensionNode[] */ @@ -45,16 +48,12 @@ class InputObjectType extends Type implements InputType, NullableType, NamedType } /** - * @param string $name - * - * @return InputObjectField - * - * @throws Exception + * @throws InvariantViolation */ - public function getField($name) + public function getField(string $name) : InputObjectField { - if ($this->fields === null) { - $this->getFields(); + if (! isset($this->fields)) { + $this->initializeFields(); } Utils::invariant(isset($this->fields[$name]), "Field '%s' is not defined for type '%s'", $name, $this->name); @@ -64,43 +63,50 @@ class InputObjectType extends Type implements InputType, NullableType, NamedType /** * @return InputObjectField[] */ - public function getFields() + public function getFields() : array { - if ($this->fields === null) { - $this->fields = []; - $fields = $this->config['fields'] ?? []; - $fields = is_callable($fields) ? call_user_func($fields) : $fields; - - if (! is_array($fields)) { - throw new InvariantViolation( - sprintf('%s fields must be an array or a callable which returns such an array.', $this->name) - ); - } - - foreach ($fields as $name => $field) { - if ($field instanceof Type) { - $field = ['type' => $field]; - } - $field = new InputObjectField($field + ['name' => $name]); - $this->fields[$field->name] = $field; - } + if (! isset($this->fields)) { + $this->initializeFields(); } return $this->fields; } + protected function initializeFields() : void + { + $this->fields = []; + $fields = $this->config['fields'] ?? []; + if (is_callable($fields)) { + $fields = $fields(); + } + + if (! is_array($fields)) { + throw new InvariantViolation( + sprintf('%s fields must be an array or a callable which returns such an array.', $this->name) + ); + } + + foreach ($fields as $name => $field) { + if ($field instanceof Type || is_callable($field)) { + $field = ['type' => $field]; + } + $field = new InputObjectField($field + ['name' => $name]); + $this->fields[$field->name] = $field; + } + } + /** * Validates type config and throws if one of type options is invalid. * Note: this method is shallow, it won't validate object fields and their arguments. * * @throws InvariantViolation */ - public function assertValid() + public function assertValid() : void { parent::assertValid(); Utils::invariant( - ! empty($this->getFields()), + count($this->getFields()) > 0, sprintf( '%s fields must be an associative array with field names as keys or a callable which returns such an array.', $this->name diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/InputType.php b/vendor/webonyx/graphql-php/src/Type/Definition/InputType.php index 0437657..d970bff 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/InputType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/InputType.php @@ -4,20 +4,19 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; -/* -export type GraphQLInputType = - | GraphQLScalarType - | GraphQLEnumType - | GraphQLInputObjectType - | GraphQLList - | GraphQLNonNull< - | GraphQLScalarType - | GraphQLEnumType - | GraphQLInputObjectType - | GraphQLList, +/** +export type InputType = + | ScalarType + | EnumType + | InputObjectType + | ListOfType + | NonNull< + | ScalarType + | EnumType + | InputObjectType + | ListOfType, >; */ - interface InputType { } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/IntType.php b/vendor/webonyx/graphql-php/src/Type/Definition/IntType.php index e6176c3..e2180df 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/IntType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/IntType.php @@ -10,8 +10,11 @@ use GraphQL\Language\AST\IntValueNode; use GraphQL\Language\AST\Node; use GraphQL\Utils\Utils; use function floatval; +use function floor; use function intval; use function is_bool; +use function is_float; +use function is_int; use function is_numeric; class IntType extends ScalarType @@ -41,63 +44,66 @@ values. Int can represent values between -(2^31) and 2^31 - 1. '; */ public function serialize($value) { - return $this->coerceInt($value); - } - - /** - * @param mixed $value - * - * @return int - */ - private function coerceInt($value) - { - if ($value === '') { - throw new Error( - 'Int cannot represent non 32-bit signed integer value: (empty string)' - ); + // Fast path for 90+% of cases: + if (is_int($value) && $value <= self::MAX_INT && $value >= self::MIN_INT) { + return $value; } - $num = floatval($value); - if ((! is_numeric($value) && ! is_bool($value)) || $num > self::MAX_INT || $num < self::MIN_INT) { - throw new Error( - 'Int cannot represent non 32-bit signed integer value: ' . - Utils::printSafe($value) - ); - } - $int = intval($num); - // int cast with == used for performance reasons - // phpcs:ignore - if ($int != $num) { + $float = is_numeric($value) || is_bool($value) + ? (float) $value + : null; + + if ($float === null || floor($float) !== $float) { throw new Error( 'Int cannot represent non-integer value: ' . Utils::printSafe($value) ); } - return $int; + if ($float > self::MAX_INT || $float < self::MIN_INT) { + throw new Error( + 'Int cannot represent non 32-bit signed integer value: ' . + Utils::printSafe($value) + ); + } + + return (int) $float; } /** * @param mixed $value * - * @return int|null - * * @throws Error */ - public function parseValue($value) + public function parseValue($value) : int { - return $this->coerceInt($value); + $isInt = is_int($value) || (is_float($value) && floor($value) === $value); + + if (! $isInt) { + throw new Error( + 'Int cannot represent non-integer value: ' . + Utils::printSafe($value) + ); + } + + if ($value > self::MAX_INT || $value < self::MIN_INT) { + throw new Error( + 'Int cannot represent non 32-bit signed integer value: ' . + Utils::printSafe($value) + ); + } + + return (int) $value; } /** - * @param Node $valueNode * @param mixed[]|null $variables * - * @return int|null + * @return int * * @throws Exception */ - public function parseLiteral($valueNode, ?array $variables = null) + public function parseLiteral(Node $valueNode, ?array $variables = null) { if ($valueNode instanceof IntValueNode) { $val = (int) $valueNode->value; @@ -107,6 +113,6 @@ values. Int can represent values between -(2^31) and 2^31 - 1. '; } // Intentionally without message, as all information already in wrapped Exception - throw new Exception(); + throw new Error(); } } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/InterfaceType.php b/vendor/webonyx/graphql-php/src/Type/Definition/InterfaceType.php index c13d7fb..578580c 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/InterfaceType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/InterfaceType.php @@ -7,21 +7,35 @@ namespace GraphQL\Type\Definition; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\InterfaceTypeDefinitionNode; use GraphQL\Language\AST\InterfaceTypeExtensionNode; +use GraphQL\Type\Schema; use GraphQL\Utils\Utils; +use function array_map; +use function is_array; use function is_callable; use function is_string; use function sprintf; -class InterfaceType extends Type implements AbstractType, OutputType, CompositeType, NullableType, NamedType +class InterfaceType extends TypeWithFields implements AbstractType, OutputType, CompositeType, NullableType, NamedType, ImplementingType { /** @var InterfaceTypeDefinitionNode|null */ public $astNode; - /** @var InterfaceTypeExtensionNode[] */ + /** @var array */ public $extensionASTNodes; - /** @var FieldDefinition[] */ - private $fields; + /** + * Lazily initialized. + * + * @var array + */ + private $interfaces; + + /** + * Lazily initialized. + * + * @var array + */ + private $interfaceMap; /** * @param mixed[] $config @@ -44,9 +58,11 @@ class InterfaceType extends Type implements AbstractType, OutputType, CompositeT /** * @param mixed $type * - * @return self + * @return $this + * + * @throws InvariantViolation */ - public static function assertInterfaceType($type) + public static function assertInterfaceType($type) : self { Utils::invariant( $type instanceof self, @@ -56,53 +72,53 @@ class InterfaceType extends Type implements AbstractType, OutputType, CompositeT return $type; } - /** - * @param string $name - * - * @return FieldDefinition - */ - public function getField($name) + public function implementsInterface(InterfaceType $interfaceType) : bool { - if ($this->fields === null) { - $this->getFields(); + if (! isset($this->interfaceMap)) { + $this->interfaceMap = []; + foreach ($this->getInterfaces() as $interface) { + /** @var Type&InterfaceType $interface */ + $interface = Schema::resolveType($interface); + $this->interfaceMap[$interface->name] = $interface; + } } - Utils::invariant(isset($this->fields[$name]), 'Field "%s" is not defined for type "%s"', $name, $this->name); - return $this->fields[$name]; + return isset($this->interfaceMap[$interfaceType->name]); } /** - * @param string $name - * - * @return bool + * @return array */ - public function hasField($name) + public function getInterfaces() : array { - if ($this->fields === null) { - $this->getFields(); + if (! isset($this->interfaces)) { + $interfaces = $this->config['interfaces'] ?? []; + if (is_callable($interfaces)) { + $interfaces = $interfaces(); + } + + if ($interfaces !== null && ! is_array($interfaces)) { + throw new InvariantViolation( + sprintf('%s interfaces must be an Array or a callable which returns an Array.', $this->name) + ); + } + + /** @var array $interfaces */ + $interfaces = $interfaces === null + ? [] + : array_map([Schema::class, 'resolveType'], $interfaces); + + $this->interfaces = $interfaces; } - return isset($this->fields[$name]); - } - - /** - * @return FieldDefinition[] - */ - public function getFields() - { - if ($this->fields === null) { - $fields = $this->config['fields'] ?? []; - $this->fields = FieldDefinition::defineFieldMap($this, $fields); - } - - return $this->fields; + return $this->interfaces; } /** * Resolves concrete ObjectType for given object value * - * @param object $objectValue - * @param mixed[] $context + * @param object $objectValue + * @param mixed $context * * @return Type|null */ @@ -120,7 +136,7 @@ class InterfaceType extends Type implements AbstractType, OutputType, CompositeT /** * @throws InvariantViolation */ - public function assertValid() + public function assertValid() : void { parent::assertValid(); diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/LeafType.php b/vendor/webonyx/graphql-php/src/Type/Definition/LeafType.php index ece7355..b913823 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/LeafType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/LeafType.php @@ -6,7 +6,12 @@ namespace GraphQL\Type\Definition; use Exception; use GraphQL\Error\Error; +use GraphQL\Language\AST\BooleanValueNode; +use GraphQL\Language\AST\FloatValueNode; +use GraphQL\Language\AST\IntValueNode; use GraphQL\Language\AST\Node; +use GraphQL\Language\AST\NullValueNode; +use GraphQL\Language\AST\StringValueNode; /* export type GraphQLLeafType = @@ -45,12 +50,12 @@ interface LeafType * * In the case of an invalid node or value this method must throw an Exception * - * @param Node $valueNode - * @param mixed[]|null $variables + * @param IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|NullValueNode $valueNode + * @param mixed[]|null $variables * * @return mixed * * @throws Exception */ - public function parseLiteral($valueNode, ?array $variables = null); + public function parseLiteral(Node $valueNode, ?array $variables = null); } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/ListOfType.php b/vendor/webonyx/graphql-php/src/Type/Definition/ListOfType.php index eb8200d..c771766 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/ListOfType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/ListOfType.php @@ -4,33 +4,38 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; +use GraphQL\Type\Schema; +use function is_callable; + class ListOfType extends Type implements WrappingType, OutputType, NullableType, InputType { - /** @var ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType */ + /** @var callable():Type|Type */ public $ofType; /** - * @param callable|Type $type + * @param callable():Type|Type $type */ public function __construct($type) { - $this->ofType = Type::assertType($type); + $this->ofType = is_callable($type) ? $type : Type::assertType($type); } public function toString() : string { - return '[' . $this->ofType->toString() . ']'; + return '[' . $this->getOfType()->toString() . ']'; } - /** - * @param bool $recurse - * - * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType - */ - public function getWrappedType($recurse = false) + public function getOfType() { - $type = $this->ofType; + return Schema::resolveType($this->ofType); + } - return $recurse && $type instanceof WrappingType ? $type->getWrappedType($recurse) : $type; + public function getWrappedType(bool $recurse = false) : Type + { + $type = $this->getOfType(); + + return $recurse && $type instanceof WrappingType + ? $type->getWrappedType($recurse) + : $type; } } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/NamedType.php b/vendor/webonyx/graphql-php/src/Type/Definition/NamedType.php index 372bcc5..d36dff5 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/NamedType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/NamedType.php @@ -4,16 +4,15 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; -/* -export type GraphQLNamedType = - | GraphQLScalarType - | GraphQLObjectType - | GraphQLInterfaceType - | GraphQLUnionType - | GraphQLEnumType - | GraphQLInputObjectType; +/** +export type NamedType = + | ScalarType + | ObjectType + | InterfaceType + | UnionType + | EnumType + | InputObjectType; */ - interface NamedType { } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/NonNull.php b/vendor/webonyx/graphql-php/src/Type/Definition/NonNull.php index 6799523..25ba1c9 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/NonNull.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/NonNull.php @@ -4,68 +4,42 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; -use GraphQL\Utils\Utils; +use GraphQL\Type\Schema; class NonNull extends Type implements WrappingType, OutputType, InputType { - /** @var NullableType */ + /** @var callable():(NullableType&Type)|(NullableType&Type) */ private $ofType; /** - * @param NullableType $type + * code sniffer doesn't understand this syntax. Pr with a fix here: waiting on https://github.com/squizlabs/PHP_CodeSniffer/pull/2919 + * phpcs:disable Squiz.Commenting.FunctionComment.SpacingAfterParamType + * @param callable():(NullableType&Type)|(NullableType&Type) $type */ public function __construct($type) { - $this->ofType = self::assertNullableType($type); + $this->ofType = $type; } - /** - * @param mixed $type - * - * @return NullableType - */ - public static function assertNullableType($type) - { - Utils::invariant( - Type::isType($type) && ! $type instanceof self, - 'Expected ' . Utils::printSafe($type) . ' to be a GraphQL nullable type.' - ); - - return $type; - } - - /** - * @param mixed $type - * - * @return self - */ - public static function assertNullType($type) - { - Utils::invariant( - $type instanceof self, - 'Expected ' . Utils::printSafe($type) . ' to be a GraphQL Non-Null type.' - ); - - return $type; - } - - /** - * @return string - */ - public function toString() + public function toString() : string { return $this->getWrappedType()->toString() . '!'; } - /** - * @param bool $recurse - * - * @return Type - */ - public function getWrappedType($recurse = false) + public function getOfType() { - $type = $this->ofType; + return Schema::resolveType($this->ofType); + } - return $recurse && $type instanceof WrappingType ? $type->getWrappedType($recurse) : $type; + /** + * @return (NullableType&Type) + */ + public function getWrappedType(bool $recurse = false) : Type + { + $type = $this->getOfType(); + + return $recurse && $type instanceof WrappingType + ? $type->getWrappedType($recurse) + : $type; } } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/ObjectType.php b/vendor/webonyx/graphql-php/src/Type/Definition/ObjectType.php index f509293..1a1cf79 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/ObjectType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/ObjectType.php @@ -4,12 +4,13 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; -use Exception; +use GraphQL\Deferred; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\ObjectTypeDefinitionNode; use GraphQL\Language\AST\ObjectTypeExtensionNode; +use GraphQL\Type\Schema; use GraphQL\Utils\Utils; -use function call_user_func; +use function array_map; use function is_array; use function is_callable; use function is_string; @@ -54,7 +55,7 @@ use function sprintf; * } * ]); */ -class ObjectType extends Type implements OutputType, CompositeType, NullableType, NamedType +class ObjectType extends TypeWithFields implements OutputType, CompositeType, NullableType, NamedType, ImplementingType { /** @var ObjectTypeDefinitionNode|null */ public $astNode; @@ -62,16 +63,21 @@ class ObjectType extends Type implements OutputType, CompositeType, NullableType /** @var ObjectTypeExtensionNode[] */ public $extensionASTNodes; - /** @var callable */ + /** @var ?callable */ public $resolveFieldFn; - /** @var FieldDefinition[] */ - private $fields; - - /** @var InterfaceType[] */ + /** + * Lazily initialized. + * + * @var array + */ private $interfaces; - /** @var InterfaceType[]|null */ + /** + * Lazily initialized. + * + * @var array + */ private $interfaceMap; /** @@ -96,9 +102,11 @@ class ObjectType extends Type implements OutputType, CompositeType, NullableType /** * @param mixed $type * - * @return self + * @return $this + * + * @throws InvariantViolation */ - public static function assertObjectType($type) + public static function assertObjectType($type) : self { Utils::invariant( $type instanceof self, @@ -108,84 +116,30 @@ class ObjectType extends Type implements OutputType, CompositeType, NullableType return $type; } - /** - * @param string $name - * - * @return FieldDefinition - * - * @throws Exception - */ - public function getField($name) + public function implementsInterface(InterfaceType $interfaceType) : bool { - if ($this->fields === null) { - $this->getFields(); - } - Utils::invariant(isset($this->fields[$name]), 'Field "%s" is not defined for type "%s"', $name, $this->name); - - return $this->fields[$name]; - } - - /** - * @param string $name - * - * @return bool - */ - public function hasField($name) - { - if ($this->fields === null) { - $this->getFields(); - } - - return isset($this->fields[$name]); - } - - /** - * @return FieldDefinition[] - * - * @throws InvariantViolation - */ - public function getFields() - { - if ($this->fields === null) { - $fields = $this->config['fields'] ?? []; - $this->fields = FieldDefinition::defineFieldMap($this, $fields); - } - - return $this->fields; - } - - /** - * @param InterfaceType $iface - * - * @return bool - */ - public function implementsInterface($iface) - { - $map = $this->getInterfaceMap(); - - return isset($map[$iface->name]); - } - - private function getInterfaceMap() - { - if (! $this->interfaceMap) { + if (! isset($this->interfaceMap)) { $this->interfaceMap = []; foreach ($this->getInterfaces() as $interface) { + /** @var Type&InterfaceType $interface */ + $interface = Schema::resolveType($interface); $this->interfaceMap[$interface->name] = $interface; } } - return $this->interfaceMap; + return isset($this->interfaceMap[$interfaceType->name]); } /** - * @return InterfaceType[] + * @return array */ - public function getInterfaces() + public function getInterfaces() : array { - if ($this->interfaces === null) { + if (! isset($this->interfaces)) { $interfaces = $this->config['interfaces'] ?? []; - $interfaces = is_callable($interfaces) ? call_user_func($interfaces) : $interfaces; + if (is_callable($interfaces)) { + $interfaces = $interfaces(); + } if ($interfaces !== null && ! is_array($interfaces)) { throw new InvariantViolation( @@ -193,26 +147,30 @@ class ObjectType extends Type implements OutputType, CompositeType, NullableType ); } - $this->interfaces = $interfaces ?: []; + /** @var InterfaceType[] $interfaces */ + $interfaces = array_map([Schema::class, 'resolveType'], $interfaces ?? []); + + $this->interfaces = $interfaces; } return $this->interfaces; } /** - * @param mixed[] $value - * @param mixed[]|null $context + * @param mixed $value + * @param mixed $context * - * @return bool|null + * @return bool|Deferred|null */ public function isTypeOf($value, $context, ResolveInfo $info) { - return isset($this->config['isTypeOf']) ? call_user_func( - $this->config['isTypeOf'], - $value, - $context, - $info - ) : null; + return isset($this->config['isTypeOf']) + ? $this->config['isTypeOf']( + $value, + $context, + $info + ) + : null; } /** @@ -221,7 +179,7 @@ class ObjectType extends Type implements OutputType, CompositeType, NullableType * * @throws InvariantViolation */ - public function assertValid() + public function assertValid() : void { parent::assertValid(); diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/QueryPlan.php b/vendor/webonyx/graphql-php/src/Type/Definition/QueryPlan.php index 641686d..a4ad1a0 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/QueryPlan.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/QueryPlan.php @@ -11,8 +11,11 @@ use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\InlineFragmentNode; use GraphQL\Language\AST\SelectionSetNode; +use GraphQL\Type\Introspection; use GraphQL\Type\Schema; +use function array_diff_key; use function array_filter; +use function array_intersect_key; use function array_key_exists; use function array_keys; use function array_merge; @@ -32,7 +35,7 @@ class QueryPlan /** @var Schema */ private $schema; - /** @var mixed[] */ + /** @var array */ private $queryPlan = []; /** @var mixed[] */ @@ -41,16 +44,21 @@ class QueryPlan /** @var FragmentDefinitionNode[] */ private $fragments; + /** @var bool */ + private $groupImplementorFields; + /** * @param FieldNode[] $fieldNodes * @param mixed[] $variableValues * @param FragmentDefinitionNode[] $fragments + * @param mixed[] $options */ - public function __construct(ObjectType $parentType, Schema $schema, iterable $fieldNodes, array $variableValues, array $fragments) + public function __construct(ObjectType $parentType, Schema $schema, iterable $fieldNodes, array $variableValues, array $fragments, array $options = []) { - $this->schema = $schema; - $this->variableValues = $variableValues; - $this->fragments = $fragments; + $this->schema = $schema; + $this->variableValues = $variableValues; + $this->fragments = $fragments; + $this->groupImplementorFields = in_array('group-implementor-fields', $options, true); $this->analyzeQueryPlan($parentType, $fieldNodes); } @@ -72,7 +80,7 @@ class QueryPlan public function hasType(string $type) : bool { - return count(array_filter($this->getReferencedTypes(), static function (string $referencedType) use ($type) { + return count(array_filter($this->getReferencedTypes(), static function (string $referencedType) use ($type) : bool { return $type === $referencedType; })) > 0; } @@ -87,7 +95,7 @@ class QueryPlan public function hasField(string $field) : bool { - return count(array_filter($this->getReferencedFields(), static function (string $referencedField) use ($field) { + return count(array_filter($this->getReferencedFields(), static function (string $referencedField) use ($field) : bool { return $field === $referencedField; })) > 0; } @@ -109,7 +117,8 @@ class QueryPlan */ private function analyzeQueryPlan(ObjectType $parentType, iterable $fieldNodes) : void { - $queryPlan = []; + $queryPlan = []; + $implementors = []; /** @var FieldNode $fieldNode */ foreach ($fieldNodes as $fieldNode) { if (! $fieldNode->selectionSet) { @@ -118,10 +127,10 @@ class QueryPlan $type = $parentType->getField($fieldNode->name->value)->getType(); if ($type instanceof WrappingType) { - $type = $type->getWrappedType(); + $type = $type->getWrappedType(true); } - $subfields = $this->analyzeSelectionSet($fieldNode->selectionSet, $type); + $subfields = $this->analyzeSelectionSet($fieldNode->selectionSet, $type, $implementors); $this->types[$type->name] = array_unique(array_merge( array_key_exists($type->name, $this->types) ? $this->types[$type->name] : [], @@ -134,28 +143,44 @@ class QueryPlan ); } - $this->queryPlan = $queryPlan; + if ($this->groupImplementorFields) { + $this->queryPlan = ['fields' => $queryPlan]; + + if ($implementors) { + $this->queryPlan['implementors'] = $implementors; + } + } else { + $this->queryPlan = $queryPlan; + } } /** - * @return mixed[] + * @param InterfaceType|ObjectType $parentType + * @param mixed[] $implementors * - * $parentType InterfaceType|ObjectType. + * @return mixed[] * * @throws Error */ - private function analyzeSelectionSet(SelectionSetNode $selectionSet, Type $parentType) : array + private function analyzeSelectionSet(SelectionSetNode $selectionSet, Type $parentType, array &$implementors) : array { - $fields = []; + $fields = []; + $implementors = []; foreach ($selectionSet->selections as $selectionNode) { if ($selectionNode instanceof FieldNode) { - $fieldName = $selectionNode->name->value; + $fieldName = $selectionNode->name->value; + + if ($fieldName === Introspection::TYPE_NAME_FIELD_NAME) { + continue; + } + $type = $parentType->getField($fieldName); $selectionType = $type->getType(); - $subfields = []; + $subfields = []; + $subImplementors = []; if ($selectionNode->selectionSet) { - $subfields = $this->analyzeSubFields($selectionType, $selectionNode->selectionSet); + $subfields = $this->analyzeSubFields($selectionType, $selectionNode->selectionSet, $subImplementors); } $fields[$fieldName] = [ @@ -163,26 +188,21 @@ class QueryPlan 'fields' => $subfields ?? [], 'args' => Values::getArgumentValues($type, $selectionNode, $this->variableValues), ]; + if ($this->groupImplementorFields && $subImplementors) { + $fields[$fieldName]['implementors'] = $subImplementors; + } } elseif ($selectionNode instanceof FragmentSpreadNode) { $spreadName = $selectionNode->name->value; if (isset($this->fragments[$spreadName])) { $fragment = $this->fragments[$spreadName]; $type = $this->schema->getType($fragment->typeCondition->name->value); $subfields = $this->analyzeSubFields($type, $fragment->selectionSet); - - $fields = $this->arrayMergeDeep( - $subfields, - $fields - ); + $fields = $this->mergeFields($parentType, $type, $fields, $subfields, $implementors); } } elseif ($selectionNode instanceof InlineFragmentNode) { $type = $this->schema->getType($selectionNode->typeCondition->name->value); $subfields = $this->analyzeSubFields($type, $selectionNode->selectionSet); - - $fields = $this->arrayMergeDeep( - $subfields, - $fields - ); + $fields = $this->mergeFields($parentType, $type, $fields, $subfields, $implementors); } } @@ -190,17 +210,19 @@ class QueryPlan } /** + * @param mixed[] $implementors + * * @return mixed[] */ - private function analyzeSubFields(Type $type, SelectionSetNode $selectionSet) : array + private function analyzeSubFields(Type $type, SelectionSetNode $selectionSet, array &$implementors = []) : array { if ($type instanceof WrappingType) { - $type = $type->getWrappedType(); + $type = $type->getWrappedType(true); } $subfields = []; - if ($type instanceof ObjectType) { - $subfields = $this->analyzeSelectionSet($selectionSet, $type); + if ($type instanceof ObjectType || $type instanceof AbstractType) { + $subfields = $this->analyzeSelectionSet($selectionSet, $type, $implementors); $this->types[$type->name] = array_unique(array_merge( array_key_exists($type->name, $this->types) ? $this->types[$type->name] : [], array_keys($subfields) @@ -210,6 +232,38 @@ class QueryPlan return $subfields; } + /** + * @param mixed[] $fields + * @param mixed[] $subfields + * @param mixed[] $implementors + * + * @return mixed[] + */ + private function mergeFields(Type $parentType, Type $type, array $fields, array $subfields, array &$implementors) : array + { + if ($this->groupImplementorFields && $parentType instanceof AbstractType && ! $type instanceof AbstractType) { + $implementors[$type->name] = [ + 'type' => $type, + 'fields' => $this->arrayMergeDeep( + $implementors[$type->name]['fields'] ?? [], + array_diff_key($subfields, $fields) + ), + ]; + + $fields = $this->arrayMergeDeep( + $fields, + array_intersect_key($subfields, $fields) + ); + } else { + $fields = $this->arrayMergeDeep( + $subfields, + $fields + ); + } + + return $fields; + } + /** * similar to array_merge_recursive this merges nested arrays, but handles non array values differently * while array_merge_recursive tries to merge non array values, in this implementation they will be overwritten diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/ResolveInfo.php b/vendor/webonyx/graphql-php/src/Type/Definition/ResolveInfo.php index 822a0fa..6c118c2 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/ResolveInfo.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/ResolveInfo.php @@ -20,6 +20,14 @@ use function array_merge_recursive; */ class ResolveInfo { + /** + * The definition of the field being resolved. + * + * @api + * @var FieldDefinition + */ + public $fieldDefinition; + /** * The name of the field being resolved. * @@ -28,6 +36,14 @@ class ResolveInfo */ public $fieldName; + /** + * Expected return type of the field being resolved. + * + * @api + * @var Type + */ + public $returnType; + /** * AST of all nodes referencing this field in the query. * @@ -36,14 +52,6 @@ class ResolveInfo */ public $fieldNodes = []; - /** - * Expected return type of the field being resolved. - * - * @api - * @var ScalarType|ObjectType|InterfaceType|UnionType|EnumType|ListOfType|NonNull - */ - public $returnType; - /** * Parent type of the field being resolved. * @@ -56,7 +64,7 @@ class ResolveInfo * Path to this field from the very root value. * * @api - * @var string[][] + * @var string[] */ public $path; @@ -100,21 +108,23 @@ class ResolveInfo */ public $variableValues = []; - /** @var QueryPlan */ + /** + * Lazily initialized. + * + * @var QueryPlan + */ private $queryPlan; /** - * @param FieldNode[] $fieldNodes - * @param ScalarType|ObjectType|InterfaceType|UnionType|EnumType|ListOfType|NonNull $returnType - * @param string[][] $path - * @param FragmentDefinitionNode[] $fragments - * @param mixed|null $rootValue - * @param mixed[] $variableValues + * @param FieldNode[] $fieldNodes + * @param string[] $path + * @param FragmentDefinitionNode[] $fragments + * @param mixed|null $rootValue + * @param mixed[] $variableValues */ public function __construct( - string $fieldName, + FieldDefinition $fieldDefinition, iterable $fieldNodes, - $returnType, ObjectType $parentType, array $path, Schema $schema, @@ -123,16 +133,17 @@ class ResolveInfo ?OperationDefinitionNode $operation, array $variableValues ) { - $this->fieldName = $fieldName; - $this->fieldNodes = $fieldNodes; - $this->returnType = $returnType; - $this->parentType = $parentType; - $this->path = $path; - $this->schema = $schema; - $this->fragments = $fragments; - $this->rootValue = $rootValue; - $this->operation = $operation; - $this->variableValues = $variableValues; + $this->fieldDefinition = $fieldDefinition; + $this->fieldName = $fieldDefinition->name; + $this->returnType = $fieldDefinition->getType(); + $this->fieldNodes = $fieldNodes; + $this->parentType = $parentType; + $this->path = $path; + $this->schema = $schema; + $this->fragments = $fragments; + $this->rootValue = $rootValue; + $this->operation = $operation; + $this->variableValues = $variableValues; } /** @@ -168,7 +179,7 @@ class ResolveInfo * * @param int $depth How many levels to include in output * - * @return bool[] + * @return array * * @api */ @@ -191,15 +202,19 @@ class ResolveInfo return $fields; } - public function lookAhead() : QueryPlan + /** + * @param mixed[] $options + */ + public function lookAhead(array $options = []) : QueryPlan { - if ($this->queryPlan === null) { + if (! isset($this->queryPlan)) { $this->queryPlan = new QueryPlan( $this->parentType, $this->schema, $this->fieldNodes, $this->variableValues, - $this->fragments + $this->fragments, + $options ); } @@ -214,7 +229,7 @@ class ResolveInfo $fields = []; foreach ($selectionSet->selections as $selectionNode) { if ($selectionNode instanceof FieldNode) { - $fields[$selectionNode->name->value] = $descend > 0 && ! empty($selectionNode->selectionSet) + $fields[$selectionNode->name->value] = $descend > 0 && $selectionNode->selectionSet !== null ? $this->foldSelectionSet($selectionNode->selectionSet, $descend - 1) : true; } elseif ($selectionNode instanceof FragmentSpreadNode) { diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/StringType.php b/vendor/webonyx/graphql-php/src/Type/Definition/StringType.php index 533298f..4a26b78 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/StringType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/StringType.php @@ -9,9 +9,9 @@ use GraphQL\Error\Error; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\StringValueNode; use GraphQL\Utils\Utils; -use function is_array; use function is_object; use function is_scalar; +use function is_string; use function method_exists; class StringType extends ScalarType @@ -34,31 +34,13 @@ represent free-form human-readable text.'; */ public function serialize($value) { - if ($value === true) { - return 'true'; - } - if ($value === false) { - return 'false'; - } - if ($value === null) { - return 'null'; - } - if (is_object($value) && method_exists($value, '__toString')) { - return (string) $value; - } - if (! is_scalar($value)) { - throw new Error('String cannot represent non scalar value: ' . Utils::printSafe($value)); - } + $canCast = is_scalar($value) + || (is_object($value) && method_exists($value, '__toString')) + || $value === null; - return $this->coerceString($value); - } - - private function coerceString($value) - { - if (is_array($value)) { + if (! $canCast) { throw new Error( - 'String cannot represent an array value: ' . - Utils::printSafe($value) + 'String cannot represent value: ' . Utils::printSafe($value) ); } @@ -74,24 +56,29 @@ represent free-form human-readable text.'; */ public function parseValue($value) { - return $this->coerceString($value); + if (! is_string($value)) { + throw new Error( + 'String cannot represent a non string value: ' . Utils::printSafe($value) + ); + } + + return $value; } /** - * @param Node $valueNode * @param mixed[]|null $variables * - * @return string|null + * @return string * * @throws Exception */ - public function parseLiteral($valueNode, ?array $variables = null) + public function parseLiteral(Node $valueNode, ?array $variables = null) { if ($valueNode instanceof StringValueNode) { return $valueNode->value; } // Intentionally without message, as all information already in wrapped Exception - throw new Exception(); + throw new Error(); } } diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/Type.php b/vendor/webonyx/graphql-php/src/Type/Definition/Type.php index 69faa1c..864bcfe 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/Type.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/Type.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace GraphQL\Type\Definition; -use Exception; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\TypeDefinitionNode; use GraphQL\Language\AST\TypeExtensionNode; @@ -12,9 +11,9 @@ use GraphQL\Type\Introspection; use GraphQL\Utils\Utils; use JsonSerializable; use ReflectionClass; -use Throwable; use function array_keys; use function array_merge; +use function assert; use function implode; use function in_array; use function preg_replace; @@ -33,8 +32,8 @@ abstract class Type implements JsonSerializable public const FLOAT = 'Float'; public const ID = 'ID'; - /** @var Type[] */ - private static $standardTypes; + /** @var array */ + protected static $standardTypes; /** @var Type[] */ private static $builtInTypes; @@ -55,105 +54,87 @@ abstract class Type implements JsonSerializable public $extensionASTNodes; /** - * @return IDType - * * @api */ - public static function id() + public static function id() : ScalarType { - return self::getStandardType(self::ID); - } - - /** - * @param string $name - * - * @return (IDType|StringType|FloatType|IntType|BooleanType)[]|IDType|StringType|FloatType|IntType|BooleanType - */ - private static function getStandardType($name = null) - { - if (self::$standardTypes === null) { - self::$standardTypes = [ - self::ID => new IDType(), - self::STRING => new StringType(), - self::FLOAT => new FloatType(), - self::INT => new IntType(), - self::BOOLEAN => new BooleanType(), - ]; + if (! isset(static::$standardTypes[self::ID])) { + static::$standardTypes[self::ID] = new IDType(); } - return $name ? self::$standardTypes[$name] : self::$standardTypes; + return static::$standardTypes[self::ID]; } /** - * @return StringType - * * @api */ - public static function string() + public static function string() : ScalarType { - return self::getStandardType(self::STRING); + if (! isset(static::$standardTypes[self::STRING])) { + static::$standardTypes[self::STRING] = new StringType(); + } + + return static::$standardTypes[self::STRING]; } /** - * @return BooleanType - * * @api */ - public static function boolean() + public static function boolean() : ScalarType { - return self::getStandardType(self::BOOLEAN); + if (! isset(static::$standardTypes[self::BOOLEAN])) { + static::$standardTypes[self::BOOLEAN] = new BooleanType(); + } + + return static::$standardTypes[self::BOOLEAN]; } /** - * @return IntType - * * @api */ - public static function int() + public static function int() : ScalarType { - return self::getStandardType(self::INT); + if (! isset(static::$standardTypes[self::INT])) { + static::$standardTypes[self::INT] = new IntType(); + } + + return static::$standardTypes[self::INT]; } /** - * @return FloatType - * * @api */ - public static function float() + public static function float() : ScalarType { - return self::getStandardType(self::FLOAT); + if (! isset(static::$standardTypes[self::FLOAT])) { + static::$standardTypes[self::FLOAT] = new FloatType(); + } + + return static::$standardTypes[self::FLOAT]; } /** - * @param Type|ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType|ListOfType|NonNull $wrappedType - * - * @return ListOfType - * * @api */ - public static function listOf($wrappedType) + public static function listOf(Type $wrappedType) : ListOfType { return new ListOfType($wrappedType); } /** - * @param NullableType $wrappedType - * - * @return NonNull + * @param callable|NullableType $wrappedType * * @api */ - public static function nonNull($wrappedType) + public static function nonNull($wrappedType) : NonNull { return new NonNull($wrappedType); } /** * Checks if the type is a builtin type - * - * @return bool */ - public static function isBuiltInType(Type $type) + public static function isBuiltInType(Type $type) : bool { return in_array($type->name, array_keys(self::getAllBuiltInTypes()), true); } @@ -179,17 +160,25 @@ abstract class Type implements JsonSerializable /** * Returns all builtin scalar types * - * @return Type[] + * @return ScalarType[] */ public static function getStandardTypes() { - return self::getStandardType(); + return [ + self::ID => static::id(), + self::STRING => static::string(), + self::FLOAT => static::float(), + self::INT => static::int(), + self::BOOLEAN => static::boolean(), + ]; } /** * @deprecated Use method getStandardTypes() instead * * @return Type[] + * + * @codeCoverageIgnore */ public static function getInternalTypes() { @@ -199,7 +188,7 @@ abstract class Type implements JsonSerializable } /** - * @param Type[] $types + * @param array $types */ public static function overrideStandardTypes(array $types) { @@ -217,35 +206,26 @@ abstract class Type implements JsonSerializable implode(', ', array_keys($standardTypes)), Utils::printSafe($type->name ?? null) ); - $standardTypes[$type->name] = $type; + static::$standardTypes[$type->name] = $type; } - self::$standardTypes = $standardTypes; } /** * @param Type $type * - * @return bool - * * @api */ - public static function isInputType($type) + public static function isInputType($type) : bool { - return $type instanceof InputType && - ( - ! $type instanceof WrappingType || - self::getNamedType($type) instanceof InputType - ); + return self::getNamedType($type) instanceof InputType; } /** * @param Type $type * - * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType - * * @api */ - public static function getNamedType($type) + public static function getNamedType($type) : ?Type { if ($type === null) { return null; @@ -260,27 +240,19 @@ abstract class Type implements JsonSerializable /** * @param Type $type * - * @return bool - * * @api */ - public static function isOutputType($type) + public static function isOutputType($type) : bool { - return $type instanceof OutputType && - ( - ! $type instanceof WrappingType || - self::getNamedType($type) instanceof OutputType - ); + return self::getNamedType($type) instanceof OutputType; } /** * @param Type $type * - * @return bool - * * @api */ - public static function isLeafType($type) + public static function isLeafType($type) : bool { return $type instanceof LeafType; } @@ -288,11 +260,9 @@ abstract class Type implements JsonSerializable /** * @param Type $type * - * @return bool - * * @api */ - public static function isCompositeType($type) + public static function isCompositeType($type) : bool { return $type instanceof CompositeType; } @@ -300,52 +270,31 @@ abstract class Type implements JsonSerializable /** * @param Type $type * - * @return bool - * * @api */ - public static function isAbstractType($type) + public static function isAbstractType($type) : bool { return $type instanceof AbstractType; } /** * @param mixed $type - * - * @return mixed */ - public static function assertType($type) + public static function assertType($type) : Type { - Utils::invariant( - self::isType($type), - 'Expected ' . Utils::printSafe($type) . ' to be a GraphQL type.' - ); + assert($type instanceof Type, new InvariantViolation('Expected ' . Utils::printSafe($type) . ' to be a GraphQL type.')); return $type; } /** - * @param Type $type - * - * @return bool - * * @api */ - public static function isType($type) + public static function getNullableType(Type $type) : Type { - return $type instanceof Type; - } - - /** - * @param Type $type - * - * @return NullableType - * - * @api - */ - public static function getNullableType($type) - { - return $type instanceof NonNull ? $type->getWrappedType() : $type; + return $type instanceof NonNull + ? $type->getWrappedType() + : $type; } /** @@ -377,13 +326,7 @@ abstract class Type implements JsonSerializable */ public function __toString() { - try { - return $this->toString(); - } catch (Exception $e) { - echo $e; - } catch (Throwable $e) { - echo $e; - } + return $this->toString(); } /** diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/TypeWithFields.php b/vendor/webonyx/graphql-php/src/Type/Definition/TypeWithFields.php new file mode 100644 index 0000000..1d0cd92 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Type/Definition/TypeWithFields.php @@ -0,0 +1,81 @@ + + */ + private $fields; + + private function initializeFields() : void + { + if (isset($this->fields)) { + return; + } + + $fields = $this->config['fields'] ?? []; + $this->fields = FieldDefinition::defineFieldMap($this, $fields); + } + + public function getField(string $name) : FieldDefinition + { + Utils::invariant($this->hasField($name), 'Field "%s" is not defined for type "%s"', $name, $this->name); + + return $this->findField($name); + } + + public function findField(string $name) : ?FieldDefinition + { + $this->initializeFields(); + + if (! isset($this->fields[$name])) { + return null; + } + + if ($this->fields[$name] instanceof UnresolvedFieldDefinition) { + $this->fields[$name] = $this->fields[$name]->resolve(); + } + + return $this->fields[$name]; + } + + public function hasField(string $name) : bool + { + $this->initializeFields(); + + return isset($this->fields[$name]); + } + + /** @inheritDoc */ + public function getFields() : array + { + $this->initializeFields(); + + foreach ($this->fields as $name => $field) { + if (! ($field instanceof UnresolvedFieldDefinition)) { + continue; + } + + $this->fields[$name] = $field->resolve(); + } + + return $this->fields; + } + + /** @inheritDoc */ + public function getFieldNames() : array + { + $this->initializeFields(); + + return array_keys($this->fields); + } +} diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/UnionType.php b/vendor/webonyx/graphql-php/src/Type/Definition/UnionType.php index 3229df4..6301e60 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/UnionType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/UnionType.php @@ -7,8 +7,8 @@ namespace GraphQL\Type\Definition; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\UnionTypeDefinitionNode; use GraphQL\Language\AST\UnionTypeExtensionNode; +use GraphQL\Type\Schema; use GraphQL\Utils\Utils; -use function call_user_func; use function is_array; use function is_callable; use function is_string; @@ -19,16 +19,27 @@ class UnionType extends Type implements AbstractType, OutputType, CompositeType, /** @var UnionTypeDefinitionNode */ public $astNode; - /** @var ObjectType[] */ + /** + * Lazily initialized. + * + * @var ObjectType[] + */ private $types; - /** @var ObjectType[] */ + /** + * Lazily initialized. + * + * @var array + */ private $possibleTypeNames; /** @var UnionTypeExtensionNode[] */ public $extensionASTNodes; - public function __construct($config) + /** + * @param mixed[] $config + */ + public function __construct(array $config) { if (! isset($config['name'])) { $config['name'] = $this->tryInferName(); @@ -38,7 +49,7 @@ class UnionType extends Type implements AbstractType, OutputType, CompositeType, /** * Optionally provide a custom type resolver function. If one is not provided, - * the default implemenation will call `isTypeOf` on each implementing + * the default implementation will call `isTypeOf` on each implementing * Object type. */ $this->name = $config['name']; @@ -54,7 +65,7 @@ class UnionType extends Type implements AbstractType, OutputType, CompositeType, return false; } - if ($this->possibleTypeNames === null) { + if (! isset($this->possibleTypeNames)) { $this->possibleTypeNames = []; foreach ($this->getTypes() as $possibleType) { $this->possibleTypeNames[$possibleType->name] = true; @@ -66,16 +77,15 @@ class UnionType extends Type implements AbstractType, OutputType, CompositeType, /** * @return ObjectType[] + * + * @throws InvariantViolation */ - public function getTypes() + public function getTypes() : array { - if ($this->types === null) { - if (! isset($this->config['types'])) { - $types = null; - } elseif (is_callable($this->config['types'])) { - $types = call_user_func($this->config['types']); - } else { - $types = $this->config['types']; + if (! isset($this->types)) { + $types = $this->config['types'] ?? null; + if (is_callable($types)) { + $types = $types(); } if (! is_array($types)) { @@ -87,7 +97,12 @@ class UnionType extends Type implements AbstractType, OutputType, CompositeType, ); } - $this->types = $types; + $rawTypes = $types; + foreach ($rawTypes as $i => $rawType) { + $rawTypes[$i] = Schema::resolveType($rawType); + } + + $this->types = $rawTypes; } return $this->types; @@ -115,7 +130,7 @@ class UnionType extends Type implements AbstractType, OutputType, CompositeType, /** * @throws InvariantViolation */ - public function assertValid() + public function assertValid() : void { parent::assertValid(); diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/UnresolvedFieldDefinition.php b/vendor/webonyx/graphql-php/src/Type/Definition/UnresolvedFieldDefinition.php new file mode 100644 index 0000000..20eae8a --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Type/Definition/UnresolvedFieldDefinition.php @@ -0,0 +1,71 @@ +|Type) $resolver */ + private $resolver; + + /** + * @param callable(): (FieldDefinition|array|Type) $resolver + */ + public function __construct(Type $type, string $name, callable $resolver) + { + $this->type = $type; + $this->name = $name; + $this->resolver = $resolver; + } + + public function getName() : string + { + return $this->name; + } + + public function resolve() : FieldDefinition + { + $field = ($this->resolver)(); + + if ($field instanceof FieldDefinition) { + if ($field->name !== $this->name) { + throw new InvariantViolation( + sprintf('%s.%s should not dynamically change its name when resolved lazily.', $this->type->name, $this->name) + ); + } + + return $field; + } + + if (! is_array($field)) { + return FieldDefinition::create(['name' => $this->name, 'type' => $field]); + } + + if (! isset($field['name'])) { + $field['name'] = $this->name; + } elseif ($field['name'] !== $this->name) { + throw new InvariantViolation( + sprintf('%s.%s should not dynamically change its name when resolved lazily.', $this->type->name, $this->name) + ); + } + + if (isset($field['args']) && ! is_array($field['args'])) { + throw new InvariantViolation( + sprintf('%s.%s args must be an array.', $this->type->name, $this->name) + ); + } + + return FieldDefinition::create($field); + } +} diff --git a/vendor/webonyx/graphql-php/src/Type/Definition/WrappingType.php b/vendor/webonyx/graphql-php/src/Type/Definition/WrappingType.php index 8bff768..26fbe85 100644 --- a/vendor/webonyx/graphql-php/src/Type/Definition/WrappingType.php +++ b/vendor/webonyx/graphql-php/src/Type/Definition/WrappingType.php @@ -6,10 +6,5 @@ namespace GraphQL\Type\Definition; interface WrappingType { - /** - * @param bool $recurse - * - * @return ObjectType|InterfaceType|UnionType|ScalarType|InputObjectType|EnumType - */ - public function getWrappedType($recurse = false); + public function getWrappedType(bool $recurse = false) : Type; } diff --git a/vendor/webonyx/graphql-php/src/Type/Introspection.php b/vendor/webonyx/graphql-php/src/Type/Introspection.php index 66271e0..626a528 100644 --- a/vendor/webonyx/graphql-php/src/Type/Introspection.php +++ b/vendor/webonyx/graphql-php/src/Type/Introspection.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace GraphQL\Type; use Exception; +use GraphQL\GraphQL; use GraphQL\Language\DirectiveLocation; use GraphQL\Language\Printer; use GraphQL\Type\Definition\Directive; @@ -26,8 +27,8 @@ use GraphQL\Utils\AST; use GraphQL\Utils\Utils; use function array_filter; use function array_key_exists; +use function array_merge; use function array_values; -use function in_array; use function is_bool; use function method_exists; use function trigger_error; @@ -39,32 +40,32 @@ class Introspection const TYPE_FIELD_NAME = '__type'; const TYPE_NAME_FIELD_NAME = '__typename'; - /** @var Type[] */ + /** @var array */ private static $map = []; /** - * Options: - * - descriptions - * Whether to include descriptions in the introspection result. - * Default: true - * - * @param bool[]|bool $options + * @param array $options + * Available options: + * - descriptions + * Whether to include descriptions in the introspection result. + * Default: true + * - directiveIsRepeatable + * Whether to include `isRepeatable` flag on directives. + * Default: false * * @return string + * + * @api */ - public static function getIntrospectionQuery($options = []) + public static function getIntrospectionQuery(array $options = []) { - if (is_bool($options)) { - trigger_error( - 'Calling Introspection::getIntrospectionQuery(boolean) is deprecated. ' . - 'Please use Introspection::getIntrospectionQuery(["descriptions" => boolean]).', - E_USER_DEPRECATED - ); - $descriptions = $options; - } else { - $descriptions = ! array_key_exists('descriptions', $options) || $options['descriptions'] === true; - } - $descriptionField = $descriptions ? 'description' : ''; + $optionsWithDefaults = array_merge([ + 'descriptions' => true, + 'directiveIsRepeatable' => false, + ], $options); + + $descriptions = $optionsWithDefaults['descriptions'] ? 'description' : ''; + $directiveIsRepeatable = $optionsWithDefaults['directiveIsRepeatable'] ? 'isRepeatable' : ''; return << $options + * Available options: + * - descriptions + * Whether to include `isRepeatable` flag on directives. + * Default: true + * - directiveIsRepeatable + * Whether to include descriptions in the introspection result. + * Default: true + * + * @return array>|null + * + * @api + */ + public static function fromSchema(Schema $schema, array $options = []) : ?array + { + $optionsWithDefaults = array_merge(['directiveIsRepeatable' => true], $options); + + $result = GraphQL::executeQuery( + $schema, + self::getIntrospectionQuery($optionsWithDefaults) + ); + + return $result->data; + } + public static function _schema() { if (! isset(self::$map['__Schema'])) { @@ -200,14 +236,14 @@ EOD; 'types' => [ 'description' => 'A list of all types supported by this server.', 'type' => new NonNull(new ListOfType(new NonNull(self::_type()))), - 'resolve' => static function (Schema $schema) { + 'resolve' => static function (Schema $schema) : array { return array_values($schema->getTypeMap()); }, ], 'queryType' => [ 'description' => 'The type that query operations will be rooted at.', 'type' => new NonNull(self::_type()), - 'resolve' => static function (Schema $schema) { + 'resolve' => static function (Schema $schema) : ?ObjectType { return $schema->getQueryType(); }, ], @@ -216,21 +252,21 @@ EOD; 'If this server supports mutation, the type that ' . 'mutation operations will be rooted at.', 'type' => self::_type(), - 'resolve' => static function (Schema $schema) { + 'resolve' => static function (Schema $schema) : ?ObjectType { return $schema->getMutationType(); }, ], 'subscriptionType' => [ 'description' => 'If this server support subscription, the type that subscription operations will be rooted at.', 'type' => self::_type(), - 'resolve' => static function (Schema $schema) { + 'resolve' => static function (Schema $schema) : ?ObjectType { return $schema->getSubscriptionType(); }, ], 'directives' => [ 'description' => 'A list of all directives supported by this server.', 'type' => Type::nonNull(Type::listOf(Type::nonNull(self::_directive()))), - 'resolve' => static function (Schema $schema) { + 'resolve' => static function (Schema $schema) : array { return $schema->getDirectives(); }, ], @@ -257,14 +293,14 @@ EOD; 'Object and Interface types provide the fields they describe. Abstract ' . 'types, Union and Interface, provide the Object types possible ' . 'at runtime. List and NonNull types compose other types.', - 'fields' => static function () { + 'fields' => static function () : array { return [ 'kind' => [ 'type' => Type::nonNull(self::_typeKind()), 'resolve' => static function (Type $type) { switch (true) { case $type instanceof ListOfType: - return TypeKind::LIST_KIND; + return TypeKind::LIST; case $type instanceof NonNull: return TypeKind::NON_NULL; case $type instanceof ScalarType: @@ -276,7 +312,7 @@ EOD; case $type instanceof InputObjectType: return TypeKind::INPUT_OBJECT; case $type instanceof InterfaceType: - return TypeKind::INTERFACE_KIND; + return TypeKind::INTERFACE; case $type instanceof UnionType: return TypeKind::UNION; default: @@ -301,14 +337,14 @@ EOD; 'args' => [ 'includeDeprecated' => ['type' => Type::boolean(), 'defaultValue' => false], ], - 'resolve' => static function (Type $type, $args) { + 'resolve' => static function (Type $type, $args) : ?array { if ($type instanceof ObjectType || $type instanceof InterfaceType) { $fields = $type->getFields(); - if (empty($args['includeDeprecated'])) { + if (! ($args['includeDeprecated'] ?? false)) { $fields = array_filter( $fields, - static function (FieldDefinition $field) { + static function (FieldDefinition $field) : bool { return ! $field->deprecationReason; } ); @@ -322,8 +358,8 @@ EOD; ], 'interfaces' => [ 'type' => Type::listOf(Type::nonNull(self::_type())), - 'resolve' => static function ($type) { - if ($type instanceof ObjectType) { + 'resolve' => static function ($type) : ?array { + if ($type instanceof ObjectType || $type instanceof InterfaceType) { return $type->getInterfaces(); } @@ -332,7 +368,7 @@ EOD; ], 'possibleTypes' => [ 'type' => Type::listOf(Type::nonNull(self::_type())), - 'resolve' => static function ($type, $args, $context, ResolveInfo $info) { + 'resolve' => static function ($type, $args, $context, ResolveInfo $info) : ?array { if ($type instanceof InterfaceType || $type instanceof UnionType) { return $info->schema->getPossibleTypes($type); } @@ -345,14 +381,14 @@ EOD; 'args' => [ 'includeDeprecated' => ['type' => Type::boolean(), 'defaultValue' => false], ], - 'resolve' => static function ($type, $args) { + 'resolve' => static function ($type, $args) : ?array { if ($type instanceof EnumType) { $values = array_values($type->getValues()); - if (empty($args['includeDeprecated'])) { + if (! ($args['includeDeprecated'] ?? false)) { $values = array_filter( $values, - static function ($value) { + static function ($value) : bool { return ! $value->deprecationReason; } ); @@ -366,7 +402,7 @@ EOD; ], 'inputFields' => [ 'type' => Type::listOf(Type::nonNull(self::_inputValue())), - 'resolve' => static function ($type) { + 'resolve' => static function ($type) : ?array { if ($type instanceof InputObjectType) { return array_values($type->getFields()); } @@ -376,7 +412,7 @@ EOD; ], 'ofType' => [ 'type' => self::_type(), - 'resolve' => static function ($type) { + 'resolve' => static function ($type) : ?Type { if ($type instanceof WrappingType) { return $type->getWrappedType(); } @@ -409,8 +445,8 @@ EOD; 'description' => 'Indicates this type is an object. `fields` and `interfaces` are valid fields.', ], 'INTERFACE' => [ - 'value' => TypeKind::INTERFACE_KIND, - 'description' => 'Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.', + 'value' => TypeKind::INTERFACE, + 'description' => 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.', ], 'UNION' => [ 'value' => TypeKind::UNION, @@ -425,7 +461,7 @@ EOD; 'description' => 'Indicates this type is an input object. `inputFields` is a valid field.', ], 'LIST' => [ - 'value' => TypeKind::LIST_KIND, + 'value' => TypeKind::LIST, 'description' => 'Indicates this type is a list. `ofType` is a valid field.', ], 'NON_NULL' => [ @@ -448,41 +484,41 @@ EOD; 'description' => 'Object and Interface types are described by a list of Fields, each of ' . 'which has a name, potentially a list of arguments, and a return type.', - 'fields' => static function () { + 'fields' => static function () : array { return [ 'name' => [ 'type' => Type::nonNull(Type::string()), - 'resolve' => static function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) : string { return $field->name; }, ], 'description' => [ 'type' => Type::string(), - 'resolve' => static function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) : ?string { return $field->description; }, ], 'args' => [ 'type' => Type::nonNull(Type::listOf(Type::nonNull(self::_inputValue()))), - 'resolve' => static function (FieldDefinition $field) { - return empty($field->args) ? [] : $field->args; + 'resolve' => static function (FieldDefinition $field) : array { + return $field->args ?? []; }, ], 'type' => [ 'type' => Type::nonNull(self::_type()), - 'resolve' => static function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) : Type { return $field->getType(); }, ], 'isDeprecated' => [ 'type' => Type::nonNull(Type::boolean()), - 'resolve' => static function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) : bool { return (bool) $field->deprecationReason; }, ], 'deprecationReason' => [ 'type' => Type::string(), - 'resolve' => static function (FieldDefinition $field) { + 'resolve' => static function (FieldDefinition $field) : ?string { return $field->deprecationReason; }, ], @@ -504,34 +540,42 @@ EOD; 'Arguments provided to Fields or Directives and the input fields of an ' . 'InputObject are represented as Input Values which describe their type ' . 'and optionally a default value.', - 'fields' => static function () { + 'fields' => static function () : array { return [ 'name' => [ 'type' => Type::nonNull(Type::string()), - 'resolve' => static function ($inputValue) { + 'resolve' => static function ($inputValue) : string { /** @var FieldArgument|InputObjectField $inputValue */ + $inputValue = $inputValue; + return $inputValue->name; }, ], 'description' => [ 'type' => Type::string(), - 'resolve' => static function ($inputValue) { + 'resolve' => static function ($inputValue) : ?string { /** @var FieldArgument|InputObjectField $inputValue */ + $inputValue = $inputValue; + return $inputValue->description; }, ], 'type' => [ 'type' => Type::nonNull(self::_type()), 'resolve' => static function ($value) { - return method_exists($value, 'getType') ? $value->getType() : $value->type; + return method_exists($value, 'getType') + ? $value->getType() + : $value->type; }, ], 'defaultValue' => [ 'type' => Type::string(), 'description' => 'A GraphQL-formatted string representing the default value for this input value.', - 'resolve' => static function ($inputValue) { + 'resolve' => static function ($inputValue) : ?string { /** @var FieldArgument|InputObjectField $inputValue */ + $inputValue = $inputValue; + return ! $inputValue->defaultValueExists() ? null : Printer::doPrint(AST::astFromValue( @@ -573,7 +617,7 @@ EOD; ], 'isDeprecated' => [ 'type' => Type::nonNull(Type::boolean()), - 'resolve' => static function ($enumValue) { + 'resolve' => static function ($enumValue) : bool { return (bool) $enumValue->deprecationReason; }, ], @@ -615,6 +659,18 @@ EOD; return $obj->description; }, ], + 'args' => [ + 'type' => Type::nonNull(Type::listOf(Type::nonNull(self::_inputValue()))), + 'resolve' => static function (Directive $directive) : array { + return $directive->args ?? []; + }, + ], + 'isRepeatable' => [ + 'type' => Type::nonNull(Type::boolean()), + 'resolve' => static function (Directive $directive) : bool { + return $directive->isRepeatable; + }, + ], 'locations' => [ 'type' => Type::nonNull(Type::listOf(Type::nonNull( self::_directiveLocation() @@ -623,40 +679,6 @@ EOD; return $obj->locations; }, ], - 'args' => [ - 'type' => Type::nonNull(Type::listOf(Type::nonNull(self::_inputValue()))), - 'resolve' => static function (Directive $directive) { - return $directive->args ?: []; - }, - ], - - // NOTE: the following three fields are deprecated and are no longer part - // of the GraphQL specification. - 'onOperation' => [ - 'deprecationReason' => 'Use `locations`.', - 'type' => Type::nonNull(Type::boolean()), - 'resolve' => static function ($d) { - return in_array(DirectiveLocation::QUERY, $d->locations, true) || - in_array(DirectiveLocation::MUTATION, $d->locations, true) || - in_array(DirectiveLocation::SUBSCRIPTION, $d->locations, true); - }, - ], - 'onFragment' => [ - 'deprecationReason' => 'Use `locations`.', - 'type' => Type::nonNull(Type::boolean()), - 'resolve' => static function ($d) { - return in_array(DirectiveLocation::FRAGMENT_SPREAD, $d->locations, true) || - in_array(DirectiveLocation::INLINE_FRAGMENT, $d->locations, true) || - in_array(DirectiveLocation::FRAGMENT_DEFINITION, $d->locations, true); - }, - ], - 'onField' => [ - 'deprecationReason' => 'Use `locations`.', - 'type' => Type::nonNull(Type::boolean()), - 'resolve' => static function ($d) { - return in_array(DirectiveLocation::FIELD, $d->locations, true); - }, - ], ], ]); } @@ -702,6 +724,10 @@ EOD; 'value' => DirectiveLocation::INLINE_FRAGMENT, 'description' => 'Location adjacent to an inline fragment.', ], + 'VARIABLE_DEFINITION' => [ + 'value' => DirectiveLocation::VARIABLE_DEFINITION, + 'description' => 'Location adjacent to a variable definition.', + ], 'SCHEMA' => [ 'value' => DirectiveLocation::SCHEMA, 'description' => 'Location adjacent to a schema definition.', @@ -754,7 +780,7 @@ EOD; return self::$map['__DirectiveLocation']; } - public static function schemaMetaFieldDef() + public static function schemaMetaFieldDef() : FieldDefinition { if (! isset(self::$map[self::SCHEMA_FIELD_NAME])) { self::$map[self::SCHEMA_FIELD_NAME] = FieldDefinition::create([ @@ -767,7 +793,7 @@ EOD; $args, $context, ResolveInfo $info - ) { + ) : Schema { return $info->schema; }, ]); @@ -776,7 +802,7 @@ EOD; return self::$map[self::SCHEMA_FIELD_NAME]; } - public static function typeMetaFieldDef() + public static function typeMetaFieldDef() : FieldDefinition { if (! isset(self::$map[self::TYPE_FIELD_NAME])) { self::$map[self::TYPE_FIELD_NAME] = FieldDefinition::create([ @@ -786,7 +812,7 @@ EOD; 'args' => [ ['name' => 'name', 'type' => Type::nonNull(Type::string())], ], - 'resolve' => static function ($source, $args, $context, ResolveInfo $info) { + 'resolve' => static function ($source, $args, $context, ResolveInfo $info) : Type { return $info->schema->getType($args['name']); }, ]); @@ -795,7 +821,7 @@ EOD; return self::$map[self::TYPE_FIELD_NAME]; } - public static function typeNameMetaFieldDef() + public static function typeNameMetaFieldDef() : FieldDefinition { if (! isset(self::$map[self::TYPE_NAME_FIELD_NAME])) { self::$map[self::TYPE_NAME_FIELD_NAME] = FieldDefinition::create([ @@ -808,7 +834,7 @@ EOD; $args, $context, ResolveInfo $info - ) { + ) : string { return $info->parentType->name; }, ]); diff --git a/vendor/webonyx/graphql-php/src/Type/Schema.php b/vendor/webonyx/graphql-php/src/Type/Schema.php index 7e480e8..c2cf0d5 100644 --- a/vendor/webonyx/graphql-php/src/Type/Schema.php +++ b/vendor/webonyx/graphql-php/src/Type/Schema.php @@ -12,14 +12,18 @@ use GraphQL\Language\AST\SchemaDefinitionNode; use GraphQL\Language\AST\SchemaTypeExtensionNode; use GraphQL\Type\Definition\AbstractType; use GraphQL\Type\Definition\Directive; +use GraphQL\Type\Definition\ImplementingType; use GraphQL\Type\Definition\InterfaceType; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; +use GraphQL\Utils\InterfaceImplementations; use GraphQL\Utils\TypeInfo; use GraphQL\Utils\Utils; +use InvalidArgumentException; use Traversable; -use function array_values; +use function array_map; +use function get_class; use function implode; use function is_array; use function is_callable; @@ -57,8 +61,12 @@ class Schema */ private $resolvedTypes = []; - /** @var Type[][]|null */ - private $possibleTypeMap; + /** + * Lazily initialised. + * + * @var array + */ + private $implementationsMap; /** * True when $resolvedTypes contain all possible schema types @@ -67,11 +75,11 @@ class Schema */ private $fullyLoaded = false; - /** @var InvariantViolation[]|null */ + /** @var Error[] */ private $validationErrors; /** @var SchemaTypeExtensionNode[] */ - public $extensionASTNodes; + public $extensionASTNodes = []; /** * @param mixed[]|SchemaConfig $config @@ -112,7 +120,7 @@ class Schema '"types" must be array or callable if provided but got: ' . Utils::getVariableType($config->types) ); Utils::invariant( - ! $config->directives || is_array($config->directives), + $config->directives === null || is_array($config->directives), '"directives" must be Array if provided but got: ' . Utils::getVariableType($config->directives) ); } @@ -120,13 +128,13 @@ class Schema $this->config = $config; $this->extensionASTNodes = $config->extensionASTNodes; - if ($config->query) { + if ($config->query !== null) { $this->resolvedTypes[$config->query->name] = $config->query; } - if ($config->mutation) { + if ($config->mutation !== null) { $this->resolvedTypes[$config->mutation->name] = $config->mutation; } - if ($config->subscription) { + if ($config->subscription !== null) { $this->resolvedTypes[$config->subscription->name] = $config->subscription; } if (is_array($this->config->types)) { @@ -158,7 +166,7 @@ class Schema */ private function resolveAdditionalTypes() { - $types = $this->config->types ?: []; + $types = $this->config->types ?? []; if (is_callable($types)) { $types = $types(); @@ -172,6 +180,7 @@ class Schema } foreach ($types as $index => $type) { + $type = self::resolveType($type); if (! $type instanceof Type) { throw new InvariantViolation(sprintf( 'Each entry of schema types must be instance of GraphQL\Type\Definition\Type but entry at %s is %s', @@ -189,11 +198,11 @@ class Schema * * This operation requires full schema scan. Do not use in production environment. * - * @return Type[] + * @return array * * @api */ - public function getTypeMap() + public function getTypeMap() : array { if (! $this->fullyLoaded) { $this->resolvedTypes = $this->collectAllTypes(); @@ -238,7 +247,26 @@ class Schema */ public function getDirectives() { - return $this->config->directives ?: GraphQL::getStandardDirectives(); + return $this->config->directives ?? GraphQL::getStandardDirectives(); + } + + /** + * @param string $operation + * + * @return ObjectType|null + */ + public function getOperationType($operation) + { + switch ($operation) { + case 'query': + return $this->getQueryType(); + case 'mutation': + return $this->getMutationType(); + case 'subscription': + return $this->getSubscriptionType(); + default: + return null; + } } /** @@ -248,7 +276,7 @@ class Schema * * @api */ - public function getQueryType() + public function getQueryType() : ?Type { return $this->config->query; } @@ -260,7 +288,7 @@ class Schema * * @api */ - public function getMutationType() + public function getMutationType() : ?Type { return $this->config->mutation; } @@ -272,7 +300,7 @@ class Schema * * @api */ - public function getSubscriptionType() + public function getSubscriptionType() : ?Type { return $this->config->subscription; } @@ -288,61 +316,56 @@ class Schema } /** - * Returns type by it's name - * - * @param string $name - * - * @return Type|null + * Returns type by its name * * @api */ - public function getType($name) + public function getType(string $name) : ?Type { if (! isset($this->resolvedTypes[$name])) { $type = $this->loadType($name); + if (! $type) { return null; } - $this->resolvedTypes[$name] = $type; + $this->resolvedTypes[$name] = self::resolveType($type); } return $this->resolvedTypes[$name]; } - /** - * @param string $name - * - * @return bool - */ - public function hasType($name) + public function hasType(string $name) : bool { return $this->getType($name) !== null; } - /** - * @param string $typeName - * - * @return Type - */ - private function loadType($typeName) + private function loadType(string $typeName) : ?Type { $typeLoader = $this->config->typeLoader; - if (! $typeLoader) { + if (! isset($typeLoader)) { return $this->defaultTypeLoader($typeName); } $type = $typeLoader($typeName); if (! $type instanceof Type) { - throw new InvariantViolation( - sprintf( - 'Type loader is expected to return valid type "%s", but it returned %s', - $typeName, - Utils::printSafe($type) - ) - ); + // Unless you know what you're doing, kindly resist the temptation to refactor or simplify this block. The + // twisty logic here is tuned for performance, and meant to prioritize the "happy path" (the result returned + // from the type loader is already a Type), and only checks for callable if that fails. If the result is + // neither a Type nor a callable, then we throw an exception. + + if (is_callable($type)) { + $type = $type(); + + if (! $type instanceof Type) { + $this->throwNotAType($type, $typeName); + } + } else { + $this->throwNotAType($type, $typeName); + } } + if ($type->name !== $typeName) { throw new InvariantViolation( sprintf('Type loader is expected to return type "%s", but it returned "%s"', $typeName, $type->name) @@ -352,91 +375,149 @@ class Schema return $type; } - /** - * @param string $typeName - * - * @return Type - */ - private function defaultTypeLoader($typeName) + protected function throwNotAType($type, string $typeName) { - // Default type loader simply fallbacks to collecting all types + throw new InvariantViolation( + sprintf( + 'Type loader is expected to return a callable or valid type "%s", but it returned %s', + $typeName, + Utils::printSafe($type) + ) + ); + } + + private function defaultTypeLoader(string $typeName) : ?Type + { + // Default type loader simply falls back to collecting all types $typeMap = $this->getTypeMap(); return $typeMap[$typeName] ?? null; } + /** + * @param Type|callable():Type $type + */ + public static function resolveType($type) : Type + { + if ($type instanceof Type) { + return $type; + } + + return $type(); + } + /** * Returns all possible concrete types for given abstract type * (implementations for interfaces and members of union type for unions) * * This operation requires full schema scan. Do not use in production environment. * - * @return ObjectType[] + * @param InterfaceType|UnionType $abstractType + * + * @return array * * @api */ - public function getPossibleTypes(AbstractType $abstractType) + public function getPossibleTypes(Type $abstractType) : array { - $possibleTypeMap = $this->getPossibleTypeMap(); - - return isset($possibleTypeMap[$abstractType->name]) ? array_values($possibleTypeMap[$abstractType->name]) : []; + return $abstractType instanceof UnionType + ? $abstractType->getTypes() + : $this->getImplementations($abstractType)->objects(); } /** - * @return Type[][] + * Returns all types that implement a given interface type. + * + * This operations requires full schema scan. Do not use in production environment. + * + * @api */ - private function getPossibleTypeMap() + public function getImplementations(InterfaceType $abstractType) : InterfaceImplementations { - if ($this->possibleTypeMap === null) { - $this->possibleTypeMap = []; - foreach ($this->getTypeMap() as $type) { - if ($type instanceof ObjectType) { - foreach ($type->getInterfaces() as $interface) { - if (! ($interface instanceof InterfaceType)) { - continue; - } + return $this->collectImplementations()[$abstractType->name]; + } - $this->possibleTypeMap[$interface->name][$type->name] = $type; + /** + * @return array + */ + private function collectImplementations() : array + { + if (! isset($this->implementationsMap)) { + /** @var array> $foundImplementations */ + $foundImplementations = []; + foreach ($this->getTypeMap() as $type) { + if ($type instanceof InterfaceType) { + if (! isset($foundImplementations[$type->name])) { + $foundImplementations[$type->name] = ['objects' => [], 'interfaces' => []]; } - } elseif ($type instanceof UnionType) { - foreach ($type->getTypes() as $innerType) { - $this->possibleTypeMap[$type->name][$innerType->name] = $innerType; + + foreach ($type->getInterfaces() as $iface) { + if (! isset($foundImplementations[$iface->name])) { + $foundImplementations[$iface->name] = ['objects' => [], 'interfaces' => []]; + } + $foundImplementations[$iface->name]['interfaces'][] = $type; + } + } elseif ($type instanceof ObjectType) { + foreach ($type->getInterfaces() as $iface) { + if (! isset($foundImplementations[$iface->name])) { + $foundImplementations[$iface->name] = ['objects' => [], 'interfaces' => []]; + } + $foundImplementations[$iface->name]['objects'][] = $type; } } } + $this->implementationsMap = array_map( + static function (array $implementations) : InterfaceImplementations { + return new InterfaceImplementations($implementations['objects'], $implementations['interfaces']); + }, + $foundImplementations + ); } - return $this->possibleTypeMap; + return $this->implementationsMap; } /** + * @deprecated as of 14.4.0 use isSubType instead, will be removed in 15.0.0. + * * Returns true if object type is concrete type of given abstract type * (implementation for interfaces and members of union type for unions) * - * @return bool + * @api + * @codeCoverageIgnore + */ + public function isPossibleType(AbstractType $abstractType, ObjectType $possibleType) : bool + { + return $this->isSubType($abstractType, $possibleType); + } + + /** + * Returns true if the given type is a sub type of the given abstract type. + * + * @param UnionType|InterfaceType $abstractType + * @param ObjectType|InterfaceType $maybeSubType * * @api */ - public function isPossibleType(AbstractType $abstractType, ObjectType $possibleType) + public function isSubType(AbstractType $abstractType, ImplementingType $maybeSubType) : bool { if ($abstractType instanceof InterfaceType) { - return $possibleType->implementsInterface($abstractType); + return $maybeSubType->implementsInterface($abstractType); } - /** @var UnionType $abstractType */ - return $abstractType->isPossibleType($possibleType); + if ($abstractType instanceof UnionType) { + return $abstractType->isPossibleType($maybeSubType); + } + + throw new InvalidArgumentException(sprintf('$abstractType must be of type UnionType|InterfaceType got: %s.', get_class($abstractType))); } /** * Returns instance of directive by name * - * @param string $name - * - * @return Directive - * * @api */ - public function getDirective($name) + public function getDirective(string $name) : ?Directive { foreach ($this->getDirectives() as $directive) { if ($directive->name === $name) { @@ -447,10 +528,7 @@ class Schema return null; } - /** - * @return SchemaDefinitionNode - */ - public function getAstNode() + public function getAstNode() : ?SchemaDefinitionNode { return $this->config->getAstNode(); } diff --git a/vendor/webonyx/graphql-php/src/Type/SchemaConfig.php b/vendor/webonyx/graphql-php/src/Type/SchemaConfig.php index 9f33626..f3511d7 100644 --- a/vendor/webonyx/graphql-php/src/Type/SchemaConfig.php +++ b/vendor/webonyx/graphql-php/src/Type/SchemaConfig.php @@ -10,6 +10,7 @@ use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Utils\Utils; +use function count; use function is_callable; /** @@ -27,32 +28,32 @@ use function is_callable; */ class SchemaConfig { - /** @var ObjectType */ + /** @var ObjectType|null */ public $query; - /** @var ObjectType */ + /** @var ObjectType|null */ public $mutation; - /** @var ObjectType */ + /** @var ObjectType|null */ public $subscription; /** @var Type[]|callable */ - public $types; + public $types = []; - /** @var Directive[] */ + /** @var Directive[]|null */ public $directives; - /** @var callable */ + /** @var callable|null */ public $typeLoader; - /** @var SchemaDefinitionNode */ + /** @var SchemaDefinitionNode|null */ public $astNode; /** @var bool */ - public $assumeValid; + public $assumeValid = false; /** @var SchemaTypeExtensionNode[] */ - public $extensionASTNodes; + public $extensionASTNodes = []; /** * Converts an array of options to instance of SchemaConfig @@ -68,7 +69,7 @@ class SchemaConfig { $config = new static(); - if (! empty($options)) { + if (count($options) > 0) { if (isset($options['query'])) { $config->setQuery($options['query']); } @@ -115,7 +116,7 @@ class SchemaConfig } /** - * @return SchemaDefinitionNode + * @return SchemaDefinitionNode|null */ public function getAstNode() { @@ -133,7 +134,7 @@ class SchemaConfig } /** - * @return ObjectType + * @return ObjectType|null * * @api */ @@ -143,7 +144,7 @@ class SchemaConfig } /** - * @param ObjectType $query + * @param ObjectType|null $query * * @return SchemaConfig * @@ -157,7 +158,7 @@ class SchemaConfig } /** - * @return ObjectType + * @return ObjectType|null * * @api */ @@ -167,7 +168,7 @@ class SchemaConfig } /** - * @param ObjectType $mutation + * @param ObjectType|null $mutation * * @return SchemaConfig * @@ -181,7 +182,7 @@ class SchemaConfig } /** - * @return ObjectType + * @return ObjectType|null * * @api */ @@ -191,7 +192,7 @@ class SchemaConfig } /** - * @param ObjectType $subscription + * @param ObjectType|null $subscription * * @return SchemaConfig * @@ -205,13 +206,13 @@ class SchemaConfig } /** - * @return Type[] + * @return Type[]|callable * * @api */ public function getTypes() { - return $this->types ?: []; + return $this->types; } /** @@ -229,13 +230,13 @@ class SchemaConfig } /** - * @return Directive[] + * @return Directive[]|null * * @api */ public function getDirectives() { - return $this->directives ?: []; + return $this->directives; } /** @@ -253,7 +254,7 @@ class SchemaConfig } /** - * @return callable + * @return callable|null * * @api */ diff --git a/vendor/webonyx/graphql-php/src/Type/SchemaValidationContext.php b/vendor/webonyx/graphql-php/src/Type/SchemaValidationContext.php index 63f54dd..fb64bd5 100644 --- a/vendor/webonyx/graphql-php/src/Type/SchemaValidationContext.php +++ b/vendor/webonyx/graphql-php/src/Type/SchemaValidationContext.php @@ -5,39 +5,48 @@ declare(strict_types=1); namespace GraphQL\Type; use GraphQL\Error\Error; +use GraphQL\Language\AST\DirectiveDefinitionNode; +use GraphQL\Language\AST\DirectiveNode; use GraphQL\Language\AST\EnumValueDefinitionNode; use GraphQL\Language\AST\FieldDefinitionNode; use GraphQL\Language\AST\InputValueDefinitionNode; use GraphQL\Language\AST\InterfaceTypeDefinitionNode; use GraphQL\Language\AST\InterfaceTypeExtensionNode; +use GraphQL\Language\AST\ListTypeNode; use GraphQL\Language\AST\NamedTypeNode; use GraphQL\Language\AST\Node; +use GraphQL\Language\AST\NodeList; +use GraphQL\Language\AST\NonNullTypeNode; use GraphQL\Language\AST\ObjectTypeDefinitionNode; use GraphQL\Language\AST\ObjectTypeExtensionNode; use GraphQL\Language\AST\SchemaDefinitionNode; use GraphQL\Language\AST\TypeDefinitionNode; use GraphQL\Language\AST\TypeNode; +use GraphQL\Language\DirectiveLocation; use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\EnumValueDefinition; use GraphQL\Type\Definition\FieldDefinition; +use GraphQL\Type\Definition\ImplementingType; use GraphQL\Type\Definition\InputObjectField; use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InterfaceType; use GraphQL\Type\Definition\NamedType; use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; +use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; +use GraphQL\Type\Validation\InputObjectCircularRefs; use GraphQL\Utils\TypeComparators; use GraphQL\Utils\Utils; use function array_filter; use function array_key_exists; use function array_merge; use function count; +use function in_array; use function is_array; use function is_object; -use function iterator_to_array; use function sprintf; class SchemaValidationContext @@ -48,9 +57,13 @@ class SchemaValidationContext /** @var Schema */ private $schema; + /** @var InputObjectCircularRefs */ + private $inputObjectCircularRefs; + public function __construct(Schema $schema) { - $this->schema = $schema; + $this->schema = $schema; + $this->inputObjectCircularRefs = new InputObjectCircularRefs($this); } /** @@ -61,7 +74,7 @@ class SchemaValidationContext return $this->errors; } - public function validateRootTypes() + public function validateRootTypes() : void { $queryType = $this->schema->getQueryType(); if (! $queryType) { @@ -85,7 +98,7 @@ class SchemaValidationContext } $subscriptionType = $this->schema->getSubscriptionType(); - if (! $subscriptionType || $subscriptionType instanceof ObjectType) { + if ($subscriptionType === null || $subscriptionType instanceof ObjectType) { return; } @@ -99,7 +112,7 @@ class SchemaValidationContext * @param string $message * @param Node[]|Node|TypeNode|TypeDefinitionNode|null $nodes */ - private function reportError($message, $nodes = null) + public function reportError($message, $nodes = null) { $nodes = array_filter($nodes && is_array($nodes) ? $nodes : [$nodes]); $this->addError(new Error($message, $nodes)); @@ -117,7 +130,7 @@ class SchemaValidationContext * @param Type $type * @param string $operation * - * @return TypeNode|TypeDefinitionNode + * @return NamedTypeNode|ListTypeNode|NonNullTypeNode|TypeDefinitionNode */ private function getOperationTypeNode($type, $operation) { @@ -140,16 +153,36 @@ class SchemaValidationContext public function validateDirectives() { + $this->validateDirectiveDefinitions(); + + // Validate directives that are used on the schema + $this->validateDirectivesAtLocation( + $this->getDirectives($this->schema), + DirectiveLocation::SCHEMA + ); + } + + public function validateDirectiveDefinitions() + { + $directiveDefinitions = []; + $directives = $this->schema->getDirectives(); foreach ($directives as $directive) { // Ensure all directives are in fact GraphQL directives. if (! $directive instanceof Directive) { + $nodes = is_object($directive) + ? $directive->astNode + : null; + $this->reportError( 'Expected directive but got: ' . Utils::printSafe($directive) . '.', - is_object($directive) ? $directive->astNode : null + $nodes ); continue; } + $existingDefinitions = $directiveDefinitions[$directive->name] ?? []; + $existingDefinitions[] = $directive; + $directiveDefinitions[$directive->name] = $existingDefinitions; // Ensure they are named correctly. $this->validateName($directive); @@ -189,6 +222,22 @@ class SchemaValidationContext ); } } + foreach ($directiveDefinitions as $directiveName => $directiveList) { + if (count($directiveList) <= 1) { + continue; + } + + $nodes = Utils::map( + $directiveList, + static function (Directive $directive) : ?DirectiveDefinitionNode { + return $directive->astNode; + } + ); + $this->reportError( + sprintf('Directive @%s defined multiple times.', $directiveName), + array_filter($nodes) + ); + } } /** @@ -212,34 +261,34 @@ class SchemaValidationContext */ private function getAllDirectiveArgNodes(Directive $directive, $argName) { - $argNodes = []; - $directiveNode = $directive->astNode; - if ($directiveNode && $directiveNode->arguments) { - foreach ($directiveNode->arguments as $node) { - if ($node->name->value !== $argName) { - continue; - } - - $argNodes[] = $node; + $subNodes = $this->getAllSubNodes( + $directive, + static function ($directiveNode) { + return $directiveNode->arguments; } - } + ); - return $argNodes; + return Utils::filter( + $subNodes, + static function ($argNode) use ($argName) : bool { + return $argNode->name->value === $argName; + } + ); } /** * @param string $argName * - * @return TypeNode|null + * @return NamedTypeNode|ListTypeNode|NonNullTypeNode|null */ - private function getDirectiveArgTypeNode(Directive $directive, $argName) + private function getDirectiveArgTypeNode(Directive $directive, $argName) : ?TypeNode { $argNode = $this->getAllDirectiveArgNodes($directive, $argName)[0]; return $argNode ? $argNode->type : null; } - public function validateTypes() + public function validateTypes() : void { $typeMap = $this->schema->getTypeMap(); foreach ($typeMap as $typeName => $type) { @@ -247,7 +296,7 @@ class SchemaValidationContext if (! $type instanceof NamedType) { $this->reportError( 'Expected GraphQL named type but got: ' . Utils::printSafe($type) . '.', - is_object($type) ? $type->astNode : null + $type instanceof Type ? $type->astNode : null ); continue; } @@ -259,26 +308,123 @@ class SchemaValidationContext $this->validateFields($type); // Ensure objects implement the interfaces they claim to. - $this->validateObjectInterfaces($type); + $this->validateInterfaces($type); + + // Ensure directives are valid + $this->validateDirectivesAtLocation( + $this->getDirectives($type), + DirectiveLocation::OBJECT + ); } elseif ($type instanceof InterfaceType) { // Ensure fields are valid. $this->validateFields($type); - // Ensure Interfaces include at least 1 Object type. + // Ensure interfaces implement the interfaces they claim to. $this->validateInterfaces($type); + + // Ensure directives are valid + $this->validateDirectivesAtLocation( + $this->getDirectives($type), + DirectiveLocation::IFACE + ); } elseif ($type instanceof UnionType) { // Ensure Unions include valid member types. $this->validateUnionMembers($type); + + // Ensure directives are valid + $this->validateDirectivesAtLocation( + $this->getDirectives($type), + DirectiveLocation::UNION + ); } elseif ($type instanceof EnumType) { // Ensure Enums have valid values. $this->validateEnumValues($type); + + // Ensure directives are valid + $this->validateDirectivesAtLocation( + $this->getDirectives($type), + DirectiveLocation::ENUM + ); } elseif ($type instanceof InputObjectType) { // Ensure Input Object fields are valid. $this->validateInputFields($type); + + // Ensure directives are valid + $this->validateDirectivesAtLocation( + $this->getDirectives($type), + DirectiveLocation::INPUT_OBJECT + ); + + // Ensure Input Objects do not contain non-nullable circular references + $this->inputObjectCircularRefs->validate($type); + } elseif ($type instanceof ScalarType) { + // Ensure directives are valid + $this->validateDirectivesAtLocation( + $this->getDirectives($type), + DirectiveLocation::SCALAR + ); } } } + /** + * @param NodeList $directives + */ + private function validateDirectivesAtLocation($directives, string $location) + { + /** @var array> $potentiallyDuplicateDirectives */ + $potentiallyDuplicateDirectives = []; + $schema = $this->schema; + foreach ($directives as $directive) { + $directiveName = $directive->name->value; + + // Ensure directive used is also defined + $schemaDirective = $schema->getDirective($directiveName); + if ($schemaDirective === null) { + $this->reportError( + sprintf('No directive @%s defined.', $directiveName), + $directive + ); + continue; + } + + $includes = Utils::some( + $schemaDirective->locations, + static function ($schemaLocation) use ($location) : bool { + return $schemaLocation === $location; + } + ); + if (! $includes) { + $errorNodes = $schemaDirective->astNode + ? [$directive, $schemaDirective->astNode] + : [$directive]; + $this->reportError( + sprintf('Directive @%s not allowed at %s location.', $directiveName, $location), + $errorNodes + ); + } + + if ($schemaDirective->isRepeatable) { + continue; + } + + $existingNodes = $potentiallyDuplicateDirectives[$directiveName] ?? []; + $existingNodes[] = $directive; + $potentiallyDuplicateDirectives[$directiveName] = $existingNodes; + } + + foreach ($potentiallyDuplicateDirectives as $directiveName => $directiveList) { + if (count($directiveList) <= 1) { + continue; + } + + $this->reportError( + sprintf('Non-repeatable directive @%s used more than once at the same location.', $directiveName), + $directiveList + ); + } + } + /** * @param ObjectType|InterfaceType $type */ @@ -287,10 +433,10 @@ class SchemaValidationContext $fieldMap = $type->getFields(); // Objects and Interfaces both must define one or more fields. - if (! $fieldMap) { + if ($fieldMap === []) { $this->reportError( sprintf('Type %s must define one or more fields.', $type->name), - $this->getAllObjectOrInterfaceNodes($type) + $this->getAllNodes($type) ); } @@ -343,36 +489,84 @@ class SchemaValidationContext $argNames[$argName] = true; // Ensure the type is an input type - if (Type::isInputType($arg->getType())) { + if (! Type::isInputType($arg->getType())) { + $this->reportError( + sprintf( + 'The type of %s.%s(%s:) must be Input Type but got: %s.', + $type->name, + $fieldName, + $argName, + Utils::printSafe($arg->getType()) + ), + $this->getFieldArgTypeNode($type, $fieldName, $argName) + ); + } + + // Ensure argument definition directives are valid + if (! isset($arg->astNode, $arg->astNode->directives)) { continue; } - $this->reportError( - sprintf( - 'The type of %s.%s(%s:) must be Input Type but got: %s.', - $type->name, - $fieldName, - $argName, - Utils::printSafe($arg->getType()) - ), - $this->getFieldArgTypeNode($type, $fieldName, $argName) + $this->validateDirectivesAtLocation( + $arg->astNode->directives, + DirectiveLocation::ARGUMENT_DEFINITION ); } + + // Ensure any directives are valid + if (! isset($field->astNode, $field->astNode->directives)) { + continue; + } + + $this->validateDirectivesAtLocation( + $field->astNode->directives, + DirectiveLocation::FIELD_DEFINITION + ); } } /** - * @param ObjectType|InterfaceType $type + * @param Schema|ObjectType|InterfaceType|UnionType|EnumType|InputObjectType|Directive $obj * * @return ObjectTypeDefinitionNode[]|ObjectTypeExtensionNode[]|InterfaceTypeDefinitionNode[]|InterfaceTypeExtensionNode[] */ - private function getAllObjectOrInterfaceNodes($type) + private function getAllNodes($obj) { - return $type->astNode - ? ($type->extensionASTNodes - ? array_merge([$type->astNode], $type->extensionASTNodes) - : [$type->astNode]) - : ($type->extensionASTNodes ?: []); + if ($obj instanceof Schema) { + $astNode = $obj->getAstNode(); + $extensionNodes = $obj->extensionASTNodes; + } else { + $astNode = $obj->astNode; + $extensionNodes = $obj->extensionASTNodes; + } + + return $astNode + ? ($extensionNodes + ? array_merge([$astNode], $extensionNodes) + : [$astNode]) + : ($extensionNodes ?? []); + } + + /** + * @param Schema|ObjectType|InterfaceType|UnionType|EnumType|Directive $obj + */ + private function getAllSubNodes($obj, callable $getter) : NodeList + { + $result = new NodeList([]); + foreach ($this->getAllNodes($obj) as $astNode) { + if (! $astNode) { + continue; + } + + $subNodes = $getter($astNode); + if (! $subNodes) { + continue; + } + + $result = $result->merge($subNodes); + } + + return $result; } /** @@ -383,32 +577,22 @@ class SchemaValidationContext */ private function getAllFieldNodes($type, $fieldName) { - $fieldNodes = []; - $astNodes = $this->getAllObjectOrInterfaceNodes($type); - foreach ($astNodes as $astNode) { - if (! $astNode || ! $astNode->fields) { - continue; - } + $subNodes = $this->getAllSubNodes($type, static function ($typeNode) { + return $typeNode->fields; + }); - foreach ($astNode->fields as $node) { - if ($node->name->value !== $fieldName) { - continue; - } - - $fieldNodes[] = $node; - } - } - - return $fieldNodes; + return Utils::filter($subNodes, static function ($fieldNode) use ($fieldName) : bool { + return $fieldNode->name->value === $fieldName; + }); } /** * @param ObjectType|InterfaceType $type * @param string $fieldName * - * @return TypeNode|null + * @return NamedTypeNode|ListTypeNode|NonNullTypeNode|null */ - private function getFieldTypeNode($type, $fieldName) + private function getFieldTypeNode($type, $fieldName) : ?TypeNode { $fieldNode = $this->getFieldNode($type, $fieldName); @@ -457,9 +641,9 @@ class SchemaValidationContext * @param string $fieldName * @param string $argName * - * @return TypeNode|null + * @return NamedTypeNode|ListTypeNode|NonNullTypeNode|null */ - private function getFieldArgTypeNode($type, $fieldName, $argName) + private function getFieldArgTypeNode($type, $fieldName, $argName) : ?TypeNode { $fieldArgNode = $this->getFieldArgNode($type, $fieldName, $argName); @@ -480,122 +664,125 @@ class SchemaValidationContext return $nodes[0] ?? null; } - private function validateObjectInterfaces(ObjectType $object) + /** + * @param ObjectType|InterfaceType $type + */ + private function validateInterfaces(ImplementingType $type) : void { - $implementedTypeNames = []; - foreach ($object->getInterfaces() as $iface) { + $ifaceTypeNames = []; + foreach ($type->getInterfaces() as $iface) { if (! $iface instanceof InterfaceType) { $this->reportError( sprintf( 'Type %s must only implement Interface types, it cannot implement %s.', - $object->name, + $type->name, Utils::printSafe($iface) ), - $this->getImplementsInterfaceNode($object, $iface) + $this->getImplementsInterfaceNode($type, $iface) ); continue; } - if (isset($implementedTypeNames[$iface->name])) { + + if ($type === $iface) { $this->reportError( - sprintf('Type %s can only implement %s once.', $object->name, $iface->name), - $this->getAllImplementsInterfaceNodes($object, $iface) + sprintf( + 'Type %s cannot implement itself because it would create a circular reference.', + $type->name + ), + $this->getImplementsInterfaceNode($type, $iface) ); continue; } - $implementedTypeNames[$iface->name] = true; - $this->validateObjectImplementsInterface($object, $iface); + + if (isset($ifaceTypeNames[$iface->name])) { + $this->reportError( + sprintf('Type %s can only implement %s once.', $type->name, $iface->name), + $this->getAllImplementsInterfaceNodes($type, $iface) + ); + continue; + } + $ifaceTypeNames[$iface->name] = true; + + $this->validateTypeImplementsAncestors($type, $iface); + $this->validateTypeImplementsInterface($type, $iface); } } - private function validateInterfaces(InterfaceType $iface) - { - $possibleTypes = $this->schema->getPossibleTypes($iface); - - if (count($possibleTypes) !== 0) { - return; - } - - $this->reportError( - sprintf( - 'Interface %s must be implemented by at least one Object type.', - $iface->name - ), - $iface->astNode - ); - } - /** - * @param InterfaceType $iface + * @param Schema|Type $object * - * @return NamedTypeNode|null + * @return NodeList */ - private function getImplementsInterfaceNode(ObjectType $type, $iface) + private function getDirectives($object) { - $nodes = $this->getAllImplementsInterfaceNodes($type, $iface); + return $this->getAllSubNodes($object, static function ($node) { + return $node->directives; + }); + } + + /** + * @param ObjectType|InterfaceType $type + */ + private function getImplementsInterfaceNode(ImplementingType $type, Type $shouldBeInterface) : ?NamedTypeNode + { + $nodes = $this->getAllImplementsInterfaceNodes($type, $shouldBeInterface); return $nodes[0] ?? null; } /** - * @param InterfaceType $iface + * @param ObjectType|InterfaceType $type * - * @return NamedTypeNode[] + * @return array */ - private function getAllImplementsInterfaceNodes(ObjectType $type, $iface) + private function getAllImplementsInterfaceNodes(ImplementingType $type, Type $shouldBeInterface) : array { - $implementsNodes = []; - $astNodes = $this->getAllObjectOrInterfaceNodes($type); + $subNodes = $this->getAllSubNodes($type, static function (Node $typeNode) : NodeList { + /** @var ObjectTypeDefinitionNode|ObjectTypeExtensionNode|InterfaceTypeDefinitionNode|InterfaceTypeExtensionNode $typeNode */ + return $typeNode->interfaces; + }); - foreach ($astNodes as $astNode) { - if (! $astNode || ! $astNode->interfaces) { - continue; - } - - foreach ($astNode->interfaces as $node) { - if ($node->name->value !== $iface->name) { - continue; - } - - $implementsNodes[] = $node; - } - } - - return $implementsNodes; + return Utils::filter($subNodes, static function (NamedTypeNode $ifaceNode) use ($shouldBeInterface) : bool { + return $ifaceNode->name->value === $shouldBeInterface->name; + }); } /** - * @param InterfaceType $iface + * @param ObjectType|InterfaceType $type */ - private function validateObjectImplementsInterface(ObjectType $object, $iface) + private function validateTypeImplementsInterface(ImplementingType $type, InterfaceType $iface) { - $objectFieldMap = $object->getFields(); - $ifaceFieldMap = $iface->getFields(); + $typeFieldMap = $type->getFields(); + $ifaceFieldMap = $iface->getFields(); // Assert each interface field is implemented. foreach ($ifaceFieldMap as $fieldName => $ifaceField) { - $objectField = array_key_exists($fieldName, $objectFieldMap) - ? $objectFieldMap[$fieldName] + $typeField = array_key_exists($fieldName, $typeFieldMap) + ? $typeFieldMap[$fieldName] : null; - // Assert interface field exists on object. - if (! $objectField) { + // Assert interface field exists on type. + if (! $typeField) { $this->reportError( sprintf( 'Interface field %s.%s expected but %s does not provide it.', $iface->name, $fieldName, - $object->name + $type->name ), - [$this->getFieldNode($iface, $fieldName), $object->astNode] + array_merge( + [$this->getFieldNode($iface, $fieldName)], + $this->getAllNodes($type) + ) ); continue; } - // Assert interface field type is satisfied by object field type, by being + // Assert interface field type is satisfied by type field type, by being // a valid subtype. (covariant) if (! TypeComparators::isTypeSubTypeOf( $this->schema, - $objectField->getType(), + $typeField->getType(), $ifaceField->getType() ) ) { @@ -605,52 +792,52 @@ class SchemaValidationContext $iface->name, $fieldName, $ifaceField->getType(), - $object->name, + $type->name, $fieldName, - Utils::printSafe($objectField->getType()) + Utils::printSafe($typeField->getType()) ), [ $this->getFieldTypeNode($iface, $fieldName), - $this->getFieldTypeNode($object, $fieldName), + $this->getFieldTypeNode($type, $fieldName), ] ); } // Assert each interface field arg is implemented. foreach ($ifaceField->args as $ifaceArg) { - $argName = $ifaceArg->name; - $objectArg = null; + $argName = $ifaceArg->name; + $typeArg = null; - foreach ($objectField->args as $arg) { + foreach ($typeField->args as $arg) { if ($arg->name === $argName) { - $objectArg = $arg; + $typeArg = $arg; break; } } - // Assert interface field arg exists on object field. - if (! $objectArg) { + // Assert interface field arg exists on type field. + if (! $typeArg) { $this->reportError( sprintf( 'Interface field argument %s.%s(%s:) expected but %s.%s does not provide it.', $iface->name, $fieldName, $argName, - $object->name, + $type->name, $fieldName ), [ $this->getFieldArgNode($iface, $fieldName, $argName), - $this->getFieldNode($object, $fieldName), + $this->getFieldNode($type, $fieldName), ] ); continue; } - // Assert interface field arg type matches object field arg type. + // Assert interface field arg type matches type field arg type. // (invariant) // TODO: change to contravariant? - if (! TypeComparators::isEqualType($ifaceArg->getType(), $objectArg->getType())) { + if (! TypeComparators::isEqualType($ifaceArg->getType(), $typeArg->getType())) { $this->reportError( sprintf( 'Interface field argument %s.%s(%s:) expects type %s but %s.%s(%s:) is type %s.', @@ -658,14 +845,14 @@ class SchemaValidationContext $fieldName, $argName, Utils::printSafe($ifaceArg->getType()), - $object->name, + $type->name, $fieldName, $argName, - Utils::printSafe($objectArg->getType()) + Utils::printSafe($typeArg->getType()) ), [ $this->getFieldArgTypeNode($iface, $fieldName, $argName), - $this->getFieldArgTypeNode($object, $fieldName, $argName), + $this->getFieldArgTypeNode($type, $fieldName, $argName), ] ); } @@ -673,8 +860,8 @@ class SchemaValidationContext } // Assert additional arguments must not be required. - foreach ($objectField->args as $objectArg) { - $argName = $objectArg->name; + foreach ($typeField->args as $typeArg) { + $argName = $typeArg->name; $ifaceArg = null; foreach ($ifaceField->args as $arg) { @@ -684,22 +871,21 @@ class SchemaValidationContext } } - if ($ifaceArg || ! ($objectArg->getType() instanceof NonNull)) { + if ($ifaceArg || ! $typeArg->isRequired()) { continue; } $this->reportError( sprintf( - 'Object field argument %s.%s(%s:) is of required type %s but is not also provided by the Interface field %s.%s.', - $object->name, + 'Object field %s.%s includes required argument %s that is missing from the Interface field %s.%s.', + $type->name, $fieldName, $argName, - Utils::printSafe($objectArg->getType()), $iface->name, $fieldName ), [ - $this->getFieldArgTypeNode($object, $fieldName, $argName), + $this->getFieldArgNode($type, $fieldName, $argName), $this->getFieldNode($iface, $fieldName), ] ); @@ -707,6 +893,39 @@ class SchemaValidationContext } } + /** + * @param ObjectType|InterfaceType $type + */ + private function validateTypeImplementsAncestors(ImplementingType $type, InterfaceType $iface) : void + { + $typeInterfaces = $type->getInterfaces(); + foreach ($iface->getInterfaces() as $transitive) { + if (in_array($transitive, $typeInterfaces, true)) { + continue; + } + + $error = $transitive === $type ? + sprintf( + 'Type %s cannot implement %s because it would create a circular reference.', + $type->name, + $iface->name + ) : + sprintf( + 'Type %s must implement %s because it is implemented by %s.', + $type->name, + $transitive->name, + $iface->name + ); + $this->reportError( + $error, + array_merge( + $this->getAllImplementsInterfaceNodes($iface, $transitive), + $this->getAllImplementsInterfaceNodes($type, $iface) + ) + ); + } + } + private function validateUnionMembers(UnionType $union) { $memberTypes = $union->getTypes(); @@ -714,7 +933,7 @@ class SchemaValidationContext if (! $memberTypes) { $this->reportError( sprintf('Union type %s must define one or more member types.', $union->name), - $union->astNode + $this->getAllNodes($union) ); } @@ -751,17 +970,13 @@ class SchemaValidationContext */ private function getUnionMemberTypeNodes(UnionType $union, $typeName) { - if ($union->astNode && $union->astNode->types) { - return array_filter( - $union->astNode->types, - static function (NamedTypeNode $value) use ($typeName) { - return $value->name->value === $typeName; - } - ); - } + $subNodes = $this->getAllSubNodes($union, static function ($unionNode) { + return $unionNode->types; + }); - return $union->astNode ? - $union->astNode->types : null; + return Utils::filter($subNodes, static function ($typeNode) use ($typeName) : bool { + return $typeNode->name->value === $typeName; + }); } private function validateEnumValues(EnumType $enumType) @@ -771,7 +986,7 @@ class SchemaValidationContext if (! $enumValues) { $this->reportError( sprintf('Enum type %s must define one or more values.', $enumType->name), - $enumType->astNode + $this->getAllNodes($enumType) ); } @@ -789,13 +1004,21 @@ class SchemaValidationContext // Ensure valid name. $this->validateName($enumValue); - if ($valueName !== 'true' && $valueName !== 'false' && $valueName !== 'null') { + if ($valueName === 'true' || $valueName === 'false' || $valueName === 'null') { + $this->reportError( + sprintf('Enum type %s cannot include value: %s.', $enumType->name, $valueName), + $enumValue->astNode + ); + } + + // Ensure valid directives + if (! isset($enumValue->astNode, $enumValue->astNode->directives)) { continue; } - $this->reportError( - sprintf('Enum type %s cannot include value: %s.', $enumType->name, $valueName), - $enumValue->astNode + $this->validateDirectivesAtLocation( + $enumValue->astNode->directives, + DirectiveLocation::ENUM_VALUE ); } } @@ -807,17 +1030,13 @@ class SchemaValidationContext */ private function getEnumValueNodes(EnumType $enum, $valueName) { - if ($enum->astNode && $enum->astNode->values) { - return array_filter( - iterator_to_array($enum->astNode->values), - static function (EnumValueDefinitionNode $value) use ($valueName) { - return $value->name->value === $valueName; - } - ); - } + $subNodes = $this->getAllSubNodes($enum, static function ($enumNode) { + return $enumNode->values; + }); - return $enum->astNode ? - $enum->astNode->values : null; + return Utils::filter($subNodes, static function ($valueNode) use ($valueName) : bool { + return $valueNode->name->value === $valueName; + }); } private function validateInputFields(InputObjectType $inputObj) @@ -827,7 +1046,7 @@ class SchemaValidationContext if (! $fieldMap) { $this->reportError( sprintf('Input Object type %s must define one or more fields.', $inputObj->name), - $inputObj->astNode + $this->getAllNodes($inputObj) ); } @@ -839,18 +1058,26 @@ class SchemaValidationContext // TODO: Ensure they are unique per field. // Ensure the type is an input type - if (Type::isInputType($field->getType())) { + if (! Type::isInputType($field->getType())) { + $this->reportError( + sprintf( + 'The type of %s.%s must be Input Type but got: %s.', + $inputObj->name, + $fieldName, + Utils::printSafe($field->getType()) + ), + $field->astNode ? $field->astNode->type : null + ); + } + + // Ensure valid directives + if (! isset($field->astNode, $field->astNode->directives)) { continue; } - $this->reportError( - sprintf( - 'The type of %s.%s must be Input Type but got: %s.', - $inputObj->name, - $fieldName, - Utils::printSafe($field->getType()) - ), - $field->astNode ? $field->astNode->type : null + $this->validateDirectivesAtLocation( + $field->astNode->directives, + DirectiveLocation::INPUT_FIELD_DEFINITION ); } } diff --git a/vendor/webonyx/graphql-php/src/Type/TypeKind.php b/vendor/webonyx/graphql-php/src/Type/TypeKind.php index 7cd38ff..69cdf2e 100644 --- a/vendor/webonyx/graphql-php/src/Type/TypeKind.php +++ b/vendor/webonyx/graphql-php/src/Type/TypeKind.php @@ -6,12 +6,12 @@ namespace GraphQL\Type; class TypeKind { - const SCALAR = 0; - const OBJECT = 1; - const INTERFACE_KIND = 2; - const UNION = 3; - const ENUM = 4; - const INPUT_OBJECT = 5; - const LIST_KIND = 6; - const NON_NULL = 7; + const SCALAR = 'SCALAR'; + const OBJECT = 'OBJECT'; + const INTERFACE = 'INTERFACE'; + const UNION = 'UNION'; + const ENUM = 'ENUM'; + const INPUT_OBJECT = 'INPUT_OBJECT'; + const LIST = 'LIST'; + const NON_NULL = 'NON_NULL'; } diff --git a/vendor/webonyx/graphql-php/src/Type/Validation/InputObjectCircularRefs.php b/vendor/webonyx/graphql-php/src/Type/Validation/InputObjectCircularRefs.php new file mode 100644 index 0000000..7291ae4 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Type/Validation/InputObjectCircularRefs.php @@ -0,0 +1,105 @@ + + */ + private $visitedTypes = []; + + /** @var InputObjectField[] */ + private $fieldPath = []; + + /** + * Position in the type path. + * + * [string $typeName => int $index] + * + * @var int[] + */ + private $fieldPathIndexByTypeName = []; + + public function __construct(SchemaValidationContext $schemaValidationContext) + { + $this->schemaValidationContext = $schemaValidationContext; + } + + /** + * This does a straight-forward DFS to find cycles. + * It does not terminate when a cycle was found but continues to explore + * the graph to find all possible cycles. + */ + public function validate(InputObjectType $inputObj) : void + { + if (isset($this->visitedTypes[$inputObj->name])) { + return; + } + + $this->visitedTypes[$inputObj->name] = true; + $this->fieldPathIndexByTypeName[$inputObj->name] = count($this->fieldPath); + + $fieldMap = $inputObj->getFields(); + foreach ($fieldMap as $fieldName => $field) { + $type = $field->getType(); + + if ($type instanceof NonNull) { + $fieldType = $type->getWrappedType(); + + // If the type of the field is anything else then a non-nullable input object, + // there is no chance of an unbreakable cycle + if ($fieldType instanceof InputObjectType) { + $this->fieldPath[] = $field; + + if (! isset($this->fieldPathIndexByTypeName[$fieldType->name])) { + $this->validate($fieldType); + } else { + $cycleIndex = $this->fieldPathIndexByTypeName[$fieldType->name]; + $cyclePath = array_slice($this->fieldPath, $cycleIndex); + $fieldNames = array_map( + static function (InputObjectField $field) : string { + return $field->name; + }, + $cyclePath + ); + + $this->schemaValidationContext->reportError( + 'Cannot reference Input Object "' . $fieldType->name . '" within itself ' + . 'through a series of non-null fields: "' . implode('.', $fieldNames) . '".', + array_map( + static function (InputObjectField $field) : ?InputValueDefinitionNode { + return $field->astNode; + }, + $cyclePath + ) + ); + } + } + } + + array_pop($this->fieldPath); + } + + unset($this->fieldPathIndexByTypeName[$inputObj->name]); + } +} diff --git a/vendor/webonyx/graphql-php/src/Utils/AST.php b/vendor/webonyx/graphql-php/src/Utils/AST.php index ae01ac5..5b5e2d5 100644 --- a/vendor/webonyx/graphql-php/src/Utils/AST.php +++ b/vendor/webonyx/graphql-php/src/Utils/AST.php @@ -6,6 +6,7 @@ namespace GraphQL\Utils; use ArrayAccess; use Exception; +use GraphQL\Error\DebugFlag; use GraphQL\Error\Error; use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\BooleanValueNode; @@ -105,7 +106,7 @@ class AST continue; } if (is_array($value)) { - if (isset($value[0]) || empty($value)) { + if (isset($value[0]) || count($value) === 0) { $value = new NodeList($value); } else { $value = self::fromArray($value); @@ -124,7 +125,7 @@ class AST * * @api */ - public static function toArray(Node $node) + public static function toArray(Node $node) : array { return $node->toArray(true); } @@ -149,7 +150,7 @@ class AST * * @param Type|mixed|null $value * - * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode + * @return ObjectValueNode|ListValueNode|BooleanValueNode|IntValueNode|FloatValueNode|EnumValueNode|StringValueNode|NullValueNode|null * * @api */ @@ -183,7 +184,7 @@ class AST $valuesNodes[] = $itemNode; } - return new ListValueNode(['values' => $valuesNodes]); + return new ListValueNode(['values' => new NodeList($valuesNodes)]); } return self::astFromValue($value, $itemType); @@ -213,7 +214,6 @@ class AST } elseif ($isArray) { $fieldExists = array_key_exists($fieldName, $value); } elseif ($isArrayLike) { - /** @var ArrayAccess $value */ $fieldExists = $value->offsetExists($fieldName); } else { $fieldExists = property_exists($value, $fieldName); @@ -235,7 +235,7 @@ class AST ]); } - return new ObjectValueNode(['fields' => $fieldNodes]); + return new ObjectValueNode(['fields' => new NodeList($fieldNodes)]); } if ($type instanceof ScalarType || $type instanceof EnumType) { @@ -243,11 +243,6 @@ class AST // to an externally represented value before converting into an AST. try { $serialized = $type->serialize($value); - } catch (Exception $error) { - if ($error instanceof Error && $type instanceof EnumType) { - return null; - } - throw $error; } catch (Throwable $error) { if ($error instanceof Error && $type instanceof EnumType) { return null; @@ -260,16 +255,16 @@ class AST return new BooleanValueNode(['value' => $serialized]); } if (is_int($serialized)) { - return new IntValueNode(['value' => $serialized]); + return new IntValueNode(['value' => (string) $serialized]); } if (is_float($serialized)) { // int cast with == used for performance reasons // phpcs:ignore if ((int) $serialized == $serialized) { - return new IntValueNode(['value' => $serialized]); + return new IntValueNode(['value' => (string) $serialized]); } - return new FloatValueNode(['value' => $serialized]); + return new FloatValueNode(['value' => (string) $serialized]); } if (is_string($serialized)) { // Enum types use Enum literals. @@ -313,8 +308,8 @@ class AST * | Enum Value | Mixed | * | Null Value | null | * - * @param ValueNode|null $valueNode - * @param mixed[]|null $variables + * @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode|null $valueNode + * @param mixed[]|null $variables * * @return mixed[]|stdClass|null * @@ -322,7 +317,7 @@ class AST * * @api */ - public static function valueFromAST($valueNode, InputType $type, ?array $variables = null) + public static function valueFromAST(?ValueNode $valueNode, Type $type, ?array $variables = null) { $undefined = Utils::undefined(); @@ -354,9 +349,14 @@ class AST return $undefined; } - // Note: we're not doing any checking that this variable is correct. We're - // assuming that this query has been validated and the variable usage here - // is of the correct type. + $variableValue = $variables[$variableName] ?? null; + if ($variableValue === null && $type instanceof NonNull) { + return $undefined; // Invalid: intentionally return no value. + } + + // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. return $variables[$variableName]; } @@ -411,8 +411,8 @@ class AST } ); foreach ($fields as $field) { - /** @var ValueNode $fieldNode */ $fieldName = $field->name; + /** @var VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode $fieldNode */ $fieldNode = $fieldNodes[$fieldName] ?? null; if ($fieldNode === null || self::isMissingVariable($fieldNode->value, $variables)) { @@ -459,8 +459,6 @@ class AST // no value is returned. try { return $type->parseLiteral($valueNode, $variables); - } catch (Exception $error) { - return $undefined; } catch (Throwable $error) { return $undefined; } @@ -473,12 +471,12 @@ class AST * Returns true if the provided valueNode is a variable which is not defined * in the set of variables. * - * @param ValueNode $valueNode - * @param mixed[] $variables + * @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode $valueNode + * @param mixed[] $variables * * @return bool */ - private static function isMissingVariable($valueNode, $variables) + private static function isMissingVariable(ValueNode $valueNode, $variables) { return $valueNode instanceof VariableNode && (count($variables) === 0 || ! array_key_exists($valueNode->name->value, $variables)); @@ -515,9 +513,9 @@ class AST case $valueNode instanceof NullValueNode: return null; case $valueNode instanceof IntValueNode: - return intval($valueNode->value, 10); + return (int) $valueNode->value; case $valueNode instanceof FloatValueNode: - return floatval($valueNode->value); + return (float) $valueNode->value; case $valueNode instanceof StringValueNode: case $valueNode instanceof EnumValueNode: case $valueNode instanceof BooleanValueNode: @@ -532,7 +530,7 @@ class AST case $valueNode instanceof ObjectValueNode: return array_combine( array_map( - static function ($field) { + static function ($field) : string { return $field->name->value; }, iterator_to_array($valueNode->fields) @@ -586,11 +584,13 @@ class AST } /** + * @deprecated use getOperationAST instead. + * * Returns operation type ("query", "mutation" or "subscription") given a document and operation name * * @param string $operationName * - * @return bool + * @return bool|string * * @api */ @@ -610,4 +610,33 @@ class AST return false; } + + /** + * Returns the operation within a document by name. + * + * If a name is not provided, an operation is only returned if the document has exactly one. + * + * @api + */ + public static function getOperationAST(DocumentNode $document, ?string $operationName = null) : ?OperationDefinitionNode + { + $operation = null; + foreach ($document->definitions->getIterator() as $node) { + if (! $node instanceof OperationDefinitionNode) { + continue; + } + + if ($operationName === null) { + // We found a second operation, so we bail instead of returning an ambiguous result. + if ($operation !== null) { + return null; + } + $operation = $node; + } elseif ($node->name instanceof NameNode && $node->name->value === $operationName) { + return $node; + } + } + + return $operation; + } } diff --git a/vendor/webonyx/graphql-php/src/Utils/ASTDefinitionBuilder.php b/vendor/webonyx/graphql-php/src/Utils/ASTDefinitionBuilder.php index 95f8d5a..92e7d27 100644 --- a/vendor/webonyx/graphql-php/src/Utils/ASTDefinitionBuilder.php +++ b/vendor/webonyx/graphql-php/src/Utils/ASTDefinitionBuilder.php @@ -8,7 +8,6 @@ use GraphQL\Error\Error; use GraphQL\Executor\Values; use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\EnumTypeDefinitionNode; -use GraphQL\Language\AST\EnumTypeExtensionNode; use GraphQL\Language\AST\EnumValueDefinitionNode; use GraphQL\Language\AST\FieldDefinitionNode; use GraphQL\Language\AST\InputObjectTypeDefinitionNode; @@ -16,11 +15,13 @@ use GraphQL\Language\AST\InputValueDefinitionNode; use GraphQL\Language\AST\InterfaceTypeDefinitionNode; use GraphQL\Language\AST\ListTypeNode; use GraphQL\Language\AST\NamedTypeNode; +use GraphQL\Language\AST\NameNode; use GraphQL\Language\AST\Node; -use GraphQL\Language\AST\NodeKind; +use GraphQL\Language\AST\NodeList; use GraphQL\Language\AST\NonNullTypeNode; use GraphQL\Language\AST\ObjectTypeDefinitionNode; use GraphQL\Language\AST\ScalarTypeDefinitionNode; +use GraphQL\Language\AST\TypeDefinitionNode; use GraphQL\Language\AST\TypeNode; use GraphQL\Language\AST\UnionTypeDefinitionNode; use GraphQL\Language\Token; @@ -29,9 +30,7 @@ use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\FieldArgument; use GraphQL\Type\Definition\InputObjectType; -use GraphQL\Type\Definition\InputType; use GraphQL\Type\Definition\InterfaceType; -use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; @@ -44,28 +43,30 @@ use function sprintf; class ASTDefinitionBuilder { - /** @var Node[] */ + /** @var array */ private $typeDefinitionsMap; /** @var callable */ private $typeConfigDecorator; - /** @var bool[] */ + /** @var array */ private $options; /** @var callable */ private $resolveType; - /** @var Type[] */ + /** @var array */ private $cache; /** - * @param Node[] $typeDefinitionsMap - * @param bool[] $options + * code sniffer doesn't understand this syntax. Pr with a fix here: waiting on https://github.com/squizlabs/PHP_CodeSniffer/pull/2919 + * phpcs:disable Squiz.Commenting.FunctionComment.SpacingAfterParamType + * @param array $typeDefinitionsMap + * @param array $options */ public function __construct( array $typeDefinitionsMap, - $options, + array $options, callable $resolveType, ?callable $typeConfigDecorator = null ) { @@ -77,30 +78,32 @@ class ASTDefinitionBuilder $this->cache = Type::getAllBuiltInTypes(); } - public function buildDirective(DirectiveDefinitionNode $directiveNode) + public function buildDirective(DirectiveDefinitionNode $directiveNode) : Directive { return new Directive([ - 'name' => $directiveNode->name->value, - 'description' => $this->getDescription($directiveNode), - 'locations' => Utils::map( + 'name' => $directiveNode->name->value, + 'description' => $this->getDescription($directiveNode), + 'args' => FieldArgument::createMap($this->makeInputValues($directiveNode->arguments)), + 'isRepeatable' => $directiveNode->repeatable, + 'locations' => Utils::map( $directiveNode->locations, - static function ($node) { + static function (NameNode $node) : string { return $node->value; } ), - 'args' => $directiveNode->arguments ? FieldArgument::createMap($this->makeInputValues($directiveNode->arguments)) : null, - 'astNode' => $directiveNode, + 'astNode' => $directiveNode, ]); } /** * Given an ast node, returns its string description. */ - private function getDescription($node) + private function getDescription(Node $node) : ?string { - if ($node->description) { + if (isset($node->description)) { return $node->description->value; } + if (isset($this->options['commentDescriptions'])) { $rawValue = $this->getLeadingCommentBlock($node); if ($rawValue !== null) { @@ -111,19 +114,21 @@ class ASTDefinitionBuilder return null; } - private function getLeadingCommentBlock($node) + private function getLeadingCommentBlock(Node $node) : ?string { $loc = $node->loc; - if (! $loc || ! $loc->startToken) { + if ($loc === null || $loc->startToken === null) { return null; } + $comments = []; $token = $loc->startToken->prev; - while ($token && - $token->kind === Token::COMMENT && - $token->next && $token->prev && - $token->line + 1 === $token->next->line && - $token->line !== $token->prev->line + while ($token !== null + && $token->kind === Token::COMMENT + && $token->next !== null + && $token->prev !== null + && $token->line + 1 === $token->next->line + && $token->line !== $token->prev->line ) { $value = $token->value; $comments[] = $value; @@ -133,18 +138,21 @@ class ASTDefinitionBuilder return implode("\n", array_reverse($comments)); } - private function makeInputValues($values) + /** + * @return array> + */ + private function makeInputValues(NodeList $values) : array { return Utils::keyValMap( $values, - static function ($value) { + static function (InputValueDefinitionNode $value) : string { return $value->name->value; }, - function ($value) { + function (InputValueDefinitionNode $value) : array { // Note: While this could make assertions to get the correctly typed // value, that would throw immediately while type system validation // with validateSchema() will produce more actionable results. - $type = $this->internalBuildWrappedType($value->type); + $type = $this->buildWrappedType($value->type); $config = [ 'name' => $value->name->value, @@ -161,26 +169,23 @@ class ASTDefinitionBuilder ); } - /** - * @return Type|InputType - * - * @throws Error - */ - private function internalBuildWrappedType(TypeNode $typeNode) + private function buildWrappedType(TypeNode $typeNode) : Type { - $typeDef = $this->buildType($this->getNamedTypeNode($typeNode)); + if ($typeNode instanceof ListTypeNode) { + return Type::listOf($this->buildWrappedType($typeNode->type)); + } - return $this->buildWrappedType($typeDef, $typeNode); + if ($typeNode instanceof NonNullTypeNode) { + return Type::nonNull($this->buildWrappedType($typeNode->type)); + } + + return $this->buildType($typeNode); } /** - * @param string|NamedTypeNode $ref - * - * @return Type - * - * @throws Error + * @param string|(Node &NamedTypeNode)|(Node&TypeDefinitionNode) $ref */ - public function buildType($ref) + public function buildType($ref) : Type { if (is_string($ref)) { return $this->internalBuildType($ref); @@ -190,14 +195,11 @@ class ASTDefinitionBuilder } /** - * @param string $typeName - * @param NamedTypeNode|null $typeNode - * - * @return Type + * @param (Node &NamedTypeNode)|(Node&TypeDefinitionNode)|null $typeNode * * @throws Error */ - private function internalBuildType($typeName, $typeNode = null) + private function internalBuildType(string $typeName, ?Node $typeNode = null) : Type { if (! isset($this->cache[$typeName])) { if (isset($this->typeDefinitionsMap[$typeName])) { @@ -212,7 +214,7 @@ class ASTDefinitionBuilder sprintf('when building %s type: %s', $typeName, $e->getMessage()), null, null, - null, + [], null, $e ); @@ -245,70 +247,71 @@ class ASTDefinitionBuilder * * @throws Error */ - private function makeSchemaDef($def) + private function makeSchemaDef(Node $def) : Type { - if (! $def) { - throw new Error('def must be defined.'); - } - switch ($def->kind) { - case NodeKind::OBJECT_TYPE_DEFINITION: + switch (true) { + case $def instanceof ObjectTypeDefinitionNode: return $this->makeTypeDef($def); - case NodeKind::INTERFACE_TYPE_DEFINITION: + case $def instanceof InterfaceTypeDefinitionNode: return $this->makeInterfaceDef($def); - case NodeKind::ENUM_TYPE_DEFINITION: + case $def instanceof EnumTypeDefinitionNode: return $this->makeEnumDef($def); - case NodeKind::UNION_TYPE_DEFINITION: + case $def instanceof UnionTypeDefinitionNode: return $this->makeUnionDef($def); - case NodeKind::SCALAR_TYPE_DEFINITION: + case $def instanceof ScalarTypeDefinitionNode: return $this->makeScalarDef($def); - case NodeKind::INPUT_OBJECT_TYPE_DEFINITION: + case $def instanceof InputObjectTypeDefinitionNode: return $this->makeInputObjectDef($def); default: throw new Error(sprintf('Type kind of %s not supported.', $def->kind)); } } - private function makeTypeDef(ObjectTypeDefinitionNode $def) + private function makeTypeDef(ObjectTypeDefinitionNode $def) : ObjectType { - $typeName = $def->name->value; - return new ObjectType([ - 'name' => $typeName, + 'name' => $def->name->value, 'description' => $this->getDescription($def), - 'fields' => function () use ($def) { + 'fields' => function () use ($def) : array { return $this->makeFieldDefMap($def); }, - 'interfaces' => function () use ($def) { + 'interfaces' => function () use ($def) : array { return $this->makeImplementedInterfaces($def); }, 'astNode' => $def, ]); } - private function makeFieldDefMap($def) + /** + * @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode $def + * + * @return array> + */ + private function makeFieldDefMap(Node $def) : array { - return $def->fields - ? Utils::keyValMap( - $def->fields, - static function ($field) { - return $field->name->value; - }, - function ($field) { - return $this->buildField($field); - } - ) - : []; + return Utils::keyValMap( + $def->fields, + static function (FieldDefinitionNode $field) : string { + return $field->name->value; + }, + function (FieldDefinitionNode $field) : array { + return $this->buildField($field); + } + ); } - public function buildField(FieldDefinitionNode $field) + /** + * @return array + */ + public function buildField(FieldDefinitionNode $field) : array { return [ // Note: While this could make assertions to get the correctly typed // value, that would throw immediately while type system validation // with validateSchema() will produce more actionable results. - 'type' => $this->internalBuildWrappedType($field->type), + 'type' => $this->buildWrappedType($field->type), 'description' => $this->getDescription($field), - 'args' => $field->arguments ? $this->makeInputValues($field->arguments) : null, + 'args' => $this->makeInputValues($field->arguments), 'deprecationReason' => $this->getDeprecationReason($field), 'astNode' => $field, ]; @@ -318,73 +321,74 @@ class ASTDefinitionBuilder * Given a collection of directives, returns the string value for the * deprecation reason. * - * @param EnumValueDefinitionNode | FieldDefinitionNode $node - * - * @return string + * @param EnumValueDefinitionNode|FieldDefinitionNode $node */ - private function getDeprecationReason($node) + private function getDeprecationReason(Node $node) : ?string { - $deprecated = Values::getDirectiveValues(Directive::deprecatedDirective(), $node); + $deprecated = Values::getDirectiveValues( + Directive::deprecatedDirective(), + $node + ); return $deprecated['reason'] ?? null; } - private function makeImplementedInterfaces(ObjectTypeDefinitionNode $def) + /** + * @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode $def + * + * @return array + */ + private function makeImplementedInterfaces($def) : array { - if ($def->interfaces) { - // Note: While this could make early assertions to get the correctly - // typed values, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - return Utils::map( - $def->interfaces, - function ($iface) { - return $this->buildType($iface); - } - ); - } - - return null; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return Utils::map( + $def->interfaces, + function (NamedTypeNode $iface) : Type { + return $this->buildType($iface); + } + ); } - private function makeInterfaceDef(InterfaceTypeDefinitionNode $def) + private function makeInterfaceDef(InterfaceTypeDefinitionNode $def) : InterfaceType { - $typeName = $def->name->value; - return new InterfaceType([ - 'name' => $typeName, + 'name' => $def->name->value, 'description' => $this->getDescription($def), - 'fields' => function () use ($def) { + 'fields' => function () use ($def) : array { return $this->makeFieldDefMap($def); }, + 'interfaces' => function () use ($def) : array { + return $this->makeImplementedInterfaces($def); + }, 'astNode' => $def, ]); } - private function makeEnumDef(EnumTypeDefinitionNode $def) + private function makeEnumDef(EnumTypeDefinitionNode $def) : EnumType { return new EnumType([ 'name' => $def->name->value, 'description' => $this->getDescription($def), - 'values' => $def->values - ? Utils::keyValMap( - $def->values, - static function ($enumValue) { - return $enumValue->name->value; - }, - function ($enumValue) { - return [ - 'description' => $this->getDescription($enumValue), - 'deprecationReason' => $this->getDeprecationReason($enumValue), - 'astNode' => $enumValue, - ]; - } - ) - : [], + 'values' => Utils::keyValMap( + $def->values, + static function ($enumValue) { + return $enumValue->name->value; + }, + function ($enumValue) : array { + return [ + 'description' => $this->getDescription($enumValue), + 'deprecationReason' => $this->getDeprecationReason($enumValue), + 'astNode' => $enumValue, + ]; + } + ), 'astNode' => $def, ]); } - private function makeUnionDef(UnionTypeDefinitionNode $def) + private function makeUnionDef(UnionTypeDefinitionNode $def) : UnionType { return new UnionType([ 'name' => $def->name->value, @@ -392,19 +396,19 @@ class ASTDefinitionBuilder // Note: While this could make assertions to get the correctly typed // values below, that would throw immediately while type system // validation with validateSchema() will produce more actionable results. - 'types' => $def->types - ? Utils::map( + 'types' => function () use ($def) : array { + return Utils::map( $def->types, - function ($typeNode) { + function ($typeNode) : Type { return $this->buildType($typeNode); } - ) : - [], + ); + }, 'astNode' => $def, ]); } - private function makeScalarDef(ScalarTypeDefinitionNode $def) + private function makeScalarDef(ScalarTypeDefinitionNode $def) : CustomScalarType { return new CustomScalarType([ 'name' => $def->name->value, @@ -416,45 +420,39 @@ class ASTDefinitionBuilder ]); } - private function makeInputObjectDef(InputObjectTypeDefinitionNode $def) + private function makeInputObjectDef(InputObjectTypeDefinitionNode $def) : InputObjectType { return new InputObjectType([ 'name' => $def->name->value, 'description' => $this->getDescription($def), - 'fields' => function () use ($def) { - return $def->fields - ? $this->makeInputValues($def->fields) - : []; + 'fields' => function () use ($def) : array { + return $this->makeInputValues($def->fields); }, 'astNode' => $def, ]); } /** - * @param ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|EnumTypeExtensionNode|ScalarTypeDefinitionNode|InputObjectTypeDefinitionNode $def - * @param mixed[] $config + * @param array $config * * @return CustomScalarType|EnumType|InputObjectType|InterfaceType|ObjectType|UnionType * * @throws Error */ - private function makeSchemaDefFromConfig($def, array $config) + private function makeSchemaDefFromConfig(Node $def, array $config) : Type { - if (! $def) { - throw new Error('def must be defined.'); - } - switch ($def->kind) { - case NodeKind::OBJECT_TYPE_DEFINITION: + switch (true) { + case $def instanceof ObjectTypeDefinitionNode: return new ObjectType($config); - case NodeKind::INTERFACE_TYPE_DEFINITION: + case $def instanceof InterfaceTypeDefinitionNode: return new InterfaceType($config); - case NodeKind::ENUM_TYPE_DEFINITION: + case $def instanceof EnumTypeDefinitionNode: return new EnumType($config); - case NodeKind::UNION_TYPE_DEFINITION: + case $def instanceof UnionTypeDefinitionNode: return new UnionType($config); - case NodeKind::SCALAR_TYPE_DEFINITION: + case $def instanceof ScalarTypeDefinitionNode: return new CustomScalarType($config); - case NodeKind::INPUT_OBJECT_TYPE_DEFINITION: + case $def instanceof InputObjectTypeDefinitionNode: return new InputObjectType($config); default: throw new Error(sprintf('Type kind of %s not supported.', $def->kind)); @@ -462,45 +460,11 @@ class ASTDefinitionBuilder } /** - * @param TypeNode|ListTypeNode|NonNullTypeNode $typeNode - * - * @return TypeNode - */ - private function getNamedTypeNode(TypeNode $typeNode) - { - $namedType = $typeNode; - while ($namedType->kind === NodeKind::LIST_TYPE || $namedType->kind === NodeKind::NON_NULL_TYPE) { - $namedType = $namedType->type; - } - - return $namedType; - } - - /** - * @param TypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode - * - * @return Type - */ - private function buildWrappedType(Type $innerType, TypeNode $inputTypeNode) - { - if ($inputTypeNode->kind === NodeKind::LIST_TYPE) { - return Type::listOf($this->buildWrappedType($innerType, $inputTypeNode->type)); - } - if ($inputTypeNode->kind === NodeKind::NON_NULL_TYPE) { - $wrappedType = $this->buildWrappedType($innerType, $inputTypeNode->type); - - return Type::nonNull(NonNull::assertNullableType($wrappedType)); - } - - return $innerType; - } - - /** - * @return mixed[] + * @return array */ public function buildInputField(InputValueDefinitionNode $value) : array { - $type = $this->internalBuildWrappedType($value->type); + $type = $this->buildWrappedType($value->type); $config = [ 'name' => $value->name->value, @@ -509,7 +473,7 @@ class ASTDefinitionBuilder 'astNode' => $value, ]; - if ($value->defaultValue) { + if ($value->defaultValue !== null) { $config['defaultValue'] = $value->defaultValue; } @@ -517,7 +481,7 @@ class ASTDefinitionBuilder } /** - * @return mixed[] + * @return array */ public function buildEnumValue(EnumValueDefinitionNode $value) : array { diff --git a/vendor/webonyx/graphql-php/src/Utils/BreakingChangesFinder.php b/vendor/webonyx/graphql-php/src/Utils/BreakingChangesFinder.php index 533abf6..234f114 100644 --- a/vendor/webonyx/graphql-php/src/Utils/BreakingChangesFinder.php +++ b/vendor/webonyx/graphql-php/src/Utils/BreakingChangesFinder.php @@ -11,6 +11,7 @@ namespace GraphQL\Utils; use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\FieldArgument; +use GraphQL\Type\Definition\ImplementingType; use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InterfaceType; use GraphQL\Type\Definition\ListOfType; @@ -39,19 +40,23 @@ class BreakingChangesFinder public const BREAKING_CHANGE_VALUE_REMOVED_FROM_ENUM = 'VALUE_REMOVED_FROM_ENUM'; public const BREAKING_CHANGE_ARG_REMOVED = 'ARG_REMOVED'; public const BREAKING_CHANGE_ARG_CHANGED_KIND = 'ARG_CHANGED_KIND'; - public const BREAKING_CHANGE_NON_NULL_ARG_ADDED = 'NON_NULL_ARG_ADDED'; - public const BREAKING_CHANGE_NON_NULL_INPUT_FIELD_ADDED = 'NON_NULL_INPUT_FIELD_ADDED'; - public const BREAKING_CHANGE_INTERFACE_REMOVED_FROM_OBJECT = 'INTERFACE_REMOVED_FROM_OBJECT'; + public const BREAKING_CHANGE_REQUIRED_ARG_ADDED = 'REQUIRED_ARG_ADDED'; + public const BREAKING_CHANGE_REQUIRED_INPUT_FIELD_ADDED = 'REQUIRED_INPUT_FIELD_ADDED'; + public const BREAKING_CHANGE_IMPLEMENTED_INTERFACE_REMOVED = 'IMPLEMENTED_INTERFACE_REMOVED'; public const BREAKING_CHANGE_DIRECTIVE_REMOVED = 'DIRECTIVE_REMOVED'; public const BREAKING_CHANGE_DIRECTIVE_ARG_REMOVED = 'DIRECTIVE_ARG_REMOVED'; public const BREAKING_CHANGE_DIRECTIVE_LOCATION_REMOVED = 'DIRECTIVE_LOCATION_REMOVED'; - public const BREAKING_CHANGE_NON_NULL_DIRECTIVE_ARG_ADDED = 'NON_NULL_DIRECTIVE_ARG_ADDED'; + public const BREAKING_CHANGE_REQUIRED_DIRECTIVE_ARG_ADDED = 'REQUIRED_DIRECTIVE_ARG_ADDED'; public const DANGEROUS_CHANGE_ARG_DEFAULT_VALUE_CHANGED = 'ARG_DEFAULT_VALUE_CHANGE'; public const DANGEROUS_CHANGE_VALUE_ADDED_TO_ENUM = 'VALUE_ADDED_TO_ENUM'; - public const DANGEROUS_CHANGE_INTERFACE_ADDED_TO_OBJECT = 'INTERFACE_ADDED_TO_OBJECT'; + public const DANGEROUS_CHANGE_IMPLEMENTED_INTERFACE_ADDED = 'IMPLEMENTED_INTERFACE_ADDED'; public const DANGEROUS_CHANGE_TYPE_ADDED_TO_UNION = 'TYPE_ADDED_TO_UNION'; - public const DANGEROUS_CHANGE_NULLABLE_INPUT_FIELD_ADDED = 'NULLABLE_INPUT_FIELD_ADDED'; - public const DANGEROUS_CHANGE_NULLABLE_ARG_ADDED = 'NULLABLE_ARG_ADDED'; + public const DANGEROUS_CHANGE_OPTIONAL_INPUT_FIELD_ADDED = 'OPTIONAL_INPUT_FIELD_ADDED'; + public const DANGEROUS_CHANGE_OPTIONAL_ARG_ADDED = 'OPTIONAL_ARG_ADDED'; + /** @deprecated use BREAKING_CHANGE_IMPLEMENTED_INTERFACE_REMOVED instead, will be removed in v15.0.0. */ + public const BREAKING_CHANGE_INTERFACE_REMOVED_FROM_OBJECT = 'IMPLEMENTED_INTERFACE_REMOVED'; + /** @deprecated use DANGEROUS_CHANGE_IMPLEMENTED_INTERFACE_ADDED instead, will be removed in v15.0.0. */ + public const DANGEROUS_CHANGE_INTERFACE_ADDED_TO_OBJECT = 'IMPLEMENTED_INTERFACE_ADDED'; /** * Given two schemas, returns an Array containing descriptions of all the types @@ -214,10 +219,10 @@ class BreakingChangesFinder $newFieldType ); if (! $isSafe) { - $oldFieldTypeString = $oldFieldType instanceof NamedType + $oldFieldTypeString = $oldFieldType instanceof NamedType && $oldFieldType instanceof Type ? $oldFieldType->name : $oldFieldType; - $newFieldTypeString = $newFieldType instanceof NamedType + $newFieldTypeString = $newFieldType instanceof NamedType && $newFieldType instanceof Type ? $newFieldType->name : $newFieldType; $breakingChanges[] = [ @@ -270,7 +275,7 @@ class BreakingChangesFinder } /** - * @return string[][] + * @return array>> */ public static function findFieldsThatChangedTypeOnInputObjectTypes( Schema $oldSchema, @@ -304,13 +309,17 @@ class BreakingChangesFinder $newFieldType ); if (! $isSafe) { - $oldFieldTypeString = $oldFieldType instanceof NamedType - ? $oldFieldType->name - : $oldFieldType; - $newFieldTypeString = $newFieldType instanceof NamedType - ? $newFieldType->name - : $newFieldType; - $breakingChanges[] = [ + if ($oldFieldType instanceof NamedType) { + $oldFieldTypeString = $oldFieldType->name; + } else { + $oldFieldTypeString = $oldFieldType; + } + if ($newFieldType instanceof NamedType) { + $newFieldTypeString = $newFieldType->name; + } else { + $newFieldTypeString = $newFieldType; + } + $breakingChanges[] = [ 'type' => self::BREAKING_CHANGE_FIELD_CHANGED_KIND, 'description' => "${typeName}.${fieldName} changed type from ${oldFieldTypeString} to ${newFieldTypeString}.", ]; @@ -324,15 +333,15 @@ class BreakingChangesFinder } $newTypeName = $newType->name; - if ($fieldDef->getType() instanceof NonNull) { + if ($fieldDef->isRequired()) { $breakingChanges[] = [ - 'type' => self::BREAKING_CHANGE_NON_NULL_INPUT_FIELD_ADDED, - 'description' => "A non-null field ${fieldName} on input type ${newTypeName} was added.", + 'type' => self::BREAKING_CHANGE_REQUIRED_INPUT_FIELD_ADDED, + 'description' => "A required field ${fieldName} on input type ${newTypeName} was added.", ]; } else { $dangerousChanges[] = [ - 'type' => self::DANGEROUS_CHANGE_NULLABLE_INPUT_FIELD_ADDED, - 'description' => "A nullable field ${fieldName} on input type ${newTypeName} was added.", + 'type' => self::DANGEROUS_CHANGE_OPTIONAL_INPUT_FIELD_ADDED, + 'description' => "An optional field ${fieldName} on input type ${newTypeName} was added.", ]; } } @@ -352,8 +361,12 @@ class BreakingChangesFinder Type $newType ) { if ($oldType instanceof NamedType) { + if (! $newType instanceof NamedType) { + return false; + } + // if they're both named types, see if their names are equivalent - return $newType instanceof NamedType && $oldType->name === $newType->name; + return $oldType->name === $newType->name; } if ($oldType instanceof ListOfType) { @@ -463,7 +476,7 @@ class BreakingChangesFinder * (such as removal or change of type of an argument, or a change in an * argument's default value). * - * @return string[][] + * @return array>> */ public static function findArgChanges( Schema $oldSchema, @@ -496,15 +509,16 @@ class BreakingChangesFinder $newArgs = $newTypeFields[$fieldName]->args; $newArgDef = Utils::find( $newArgs, - static function ($arg) use ($oldArgDef) { + static function ($arg) use ($oldArgDef) : bool { return $arg->name === $oldArgDef->name; } ); if ($newArgDef !== null) { - $isSafe = self::isChangeSafeForInputObjectFieldOrFieldArg( + $isSafe = self::isChangeSafeForInputObjectFieldOrFieldArg( $oldArgDef->getType(), $newArgDef->getType() ); + /** @var ScalarType|EnumType|InputObjectType|ListOfType|NonNull $oldArgType */ $oldArgType = $oldArgDef->getType(); $oldArgName = $oldArgDef->name; if (! $isSafe) { @@ -530,12 +544,12 @@ class BreakingChangesFinder ), ]; } - // Check if a non-null arg was added to the field + // Check if arg was added to the field foreach ($newTypeFields[$fieldName]->args as $newTypeFieldArgDef) { $oldArgs = $oldTypeFields[$fieldName]->args; $oldArgDef = Utils::find( $oldArgs, - static function ($arg) use ($newTypeFieldArgDef) { + static function ($arg) use ($newTypeFieldArgDef) : bool { return $arg->name === $newTypeFieldArgDef->name; } ); @@ -546,15 +560,15 @@ class BreakingChangesFinder $newTypeName = $newType->name; $newArgName = $newTypeFieldArgDef->name; - if ($newTypeFieldArgDef->getType() instanceof NonNull) { + if ($newTypeFieldArgDef->isRequired()) { $breakingChanges[] = [ - 'type' => self::BREAKING_CHANGE_NON_NULL_ARG_ADDED, - 'description' => "A non-null arg ${newArgName} on ${newTypeName}.${fieldName} was added", + 'type' => self::BREAKING_CHANGE_REQUIRED_ARG_ADDED, + 'description' => "A required arg ${newArgName} on ${newTypeName}.${fieldName} was added", ]; } else { $dangerousChanges[] = [ - 'type' => self::DANGEROUS_CHANGE_NULLABLE_ARG_ADDED, - 'description' => "A nullable arg ${newArgName} on ${newTypeName}.${fieldName} was added", + 'type' => self::DANGEROUS_CHANGE_OPTIONAL_ARG_ADDED, + 'description' => "An optional arg ${newArgName} on ${newTypeName}.${fieldName} was added", ]; } } @@ -581,7 +595,7 @@ class BreakingChangesFinder foreach ($oldTypeMap as $typeName => $oldType) { $newType = $newTypeMap[$typeName] ?? null; - if (! ($oldType instanceof ObjectType) || ! ($newType instanceof ObjectType)) { + if (! ($oldType instanceof ImplementingType) || ! ($newType instanceof ImplementingType)) { continue; } @@ -599,7 +613,7 @@ class BreakingChangesFinder } $breakingChanges[] = [ - 'type' => self::BREAKING_CHANGE_INTERFACE_REMOVED_FROM_OBJECT, + 'type' => self::BREAKING_CHANGE_IMPLEMENTED_INTERFACE_REMOVED, 'description' => sprintf('%s no longer implements interface %s.', $typeName, $oldInterface->name), ]; } @@ -682,7 +696,7 @@ class BreakingChangesFinder private static function getArgumentMapForDirective(Directive $directive) { return Utils::keyMap( - $directive->args ?: [], + $directive->args ?? [], static function ($arg) { return $arg->name; } @@ -703,13 +717,13 @@ class BreakingChangesFinder $oldSchemaDirectiveMap[$newDirective->name], $newDirective ) as $arg) { - if (! $arg->getType() instanceof NonNull) { + if (! $arg->isRequired()) { continue; } $addedNonNullableArgs[] = [ - 'type' => self::BREAKING_CHANGE_NON_NULL_DIRECTIVE_ARG_ADDED, + 'type' => self::BREAKING_CHANGE_REQUIRED_DIRECTIVE_ARG_ADDED, 'description' => sprintf( - 'A non-null arg %s on directive %s was added', + 'A required arg %s on directive %s was added', $arg->name, $newDirective->name ), @@ -848,7 +862,8 @@ class BreakingChangesFinder foreach ($newTypeMap as $typeName => $newType) { $oldType = $oldTypeMap[$typeName] ?? null; - if (! ($oldType instanceof ObjectType) || ! ($newType instanceof ObjectType)) { + if (! ($oldType instanceof ObjectType || $oldType instanceof InterfaceType) + || ! ($newType instanceof ObjectType || $newType instanceof InterfaceType)) { continue; } @@ -867,7 +882,7 @@ class BreakingChangesFinder } $interfacesAddedToObjectTypes[] = [ - 'type' => self::DANGEROUS_CHANGE_INTERFACE_ADDED_TO_OBJECT, + 'type' => self::DANGEROUS_CHANGE_IMPLEMENTED_INTERFACE_ADDED, 'description' => sprintf( '%s added to interfaces implemented by %s.', $newInterface->name, diff --git a/vendor/webonyx/graphql-php/src/Utils/BuildClientSchema.php b/vendor/webonyx/graphql-php/src/Utils/BuildClientSchema.php new file mode 100644 index 0000000..060f523 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Utils/BuildClientSchema.php @@ -0,0 +1,496 @@ + */ + private $introspection; + + /** @var array */ + private $options; + + /** @var array */ + private $typeMap; + + /** + * @param array $introspectionQuery + * @param array $options + */ + public function __construct(array $introspectionQuery, array $options = []) + { + $this->introspection = $introspectionQuery; + $this->options = $options; + } + + /** + * Build a schema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a \GraphQL\Type\Schema instance which can be then used with all graphql-php + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + * + * Accepts options as a third argument: + * + * - assumeValid: + * When building a schema from a GraphQL service's introspection result, it + * might be safe to assume the schema is valid. Set to true to assume the + * produced schema is valid. + * + * Default: false + * + * @param array $introspectionQuery + * @param array $options + * + * @api + */ + public static function build(array $introspectionQuery, array $options = []) : Schema + { + $builder = new self($introspectionQuery, $options); + + return $builder->buildSchema(); + } + + public function buildSchema() : Schema + { + if (! array_key_exists('__schema', $this->introspection)) { + throw new InvariantViolation('Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ' . json_encode($this->introspection) . '.'); + } + + $schemaIntrospection = $this->introspection['__schema']; + + $this->typeMap = Utils::keyValMap( + $schemaIntrospection['types'], + static function (array $typeIntrospection) { + return $typeIntrospection['name']; + }, + function (array $typeIntrospection) : NamedType { + return $this->buildType($typeIntrospection); + } + ); + + $builtInTypes = array_merge( + Type::getStandardTypes(), + Introspection::getTypes() + ); + foreach ($builtInTypes as $name => $type) { + if (! isset($this->typeMap[$name])) { + continue; + } + + $this->typeMap[$name] = $type; + } + + $queryType = isset($schemaIntrospection['queryType']) + ? $this->getObjectType($schemaIntrospection['queryType']) + : null; + + $mutationType = isset($schemaIntrospection['mutationType']) + ? $this->getObjectType($schemaIntrospection['mutationType']) + : null; + + $subscriptionType = isset($schemaIntrospection['subscriptionType']) + ? $this->getObjectType($schemaIntrospection['subscriptionType']) + : null; + + $directives = isset($schemaIntrospection['directives']) + ? array_map( + [$this, 'buildDirective'], + $schemaIntrospection['directives'] + ) + : []; + + $schemaConfig = new SchemaConfig(); + $schemaConfig->setQuery($queryType) + ->setMutation($mutationType) + ->setSubscription($subscriptionType) + ->setTypes($this->typeMap) + ->setDirectives($directives) + ->setAssumeValid( + isset($this->options) + && isset($this->options['assumeValid']) + && $this->options['assumeValid'] + ); + + return new Schema($schemaConfig); + } + + /** + * @param array $typeRef + */ + private function getType(array $typeRef) : Type + { + if (isset($typeRef['kind'])) { + if ($typeRef['kind'] === TypeKind::LIST) { + if (! isset($typeRef['ofType'])) { + throw new InvariantViolation('Decorated type deeper than introspection query.'); + } + + return new ListOfType($this->getType($typeRef['ofType'])); + } + + if ($typeRef['kind'] === TypeKind::NON_NULL) { + if (! isset($typeRef['ofType'])) { + throw new InvariantViolation('Decorated type deeper than introspection query.'); + } + /** @var NullableType $nullableType */ + $nullableType = $this->getType($typeRef['ofType']); + + return new NonNull($nullableType); + } + } + + if (! isset($typeRef['name'])) { + throw new InvariantViolation('Unknown type reference: ' . json_encode($typeRef) . '.'); + } + + return $this->getNamedType($typeRef['name']); + } + + /** + * @return NamedType&Type + */ + private function getNamedType(string $typeName) : NamedType + { + if (! isset($this->typeMap[$typeName])) { + throw new InvariantViolation( + "Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema." + ); + } + + return $this->typeMap[$typeName]; + } + + /** + * @param array $typeRef + */ + private function getInputType(array $typeRef) : InputType + { + $type = $this->getType($typeRef); + + if ($type instanceof InputType) { + return $type; + } + + throw new InvariantViolation('Introspection must provide input type for arguments, but received: ' . json_encode($type) . '.'); + } + + /** + * @param array $typeRef + */ + private function getOutputType(array $typeRef) : OutputType + { + $type = $this->getType($typeRef); + + if ($type instanceof OutputType) { + return $type; + } + + throw new InvariantViolation('Introspection must provide output type for fields, but received: ' . json_encode($type) . '.'); + } + + /** + * @param array $typeRef + */ + private function getObjectType(array $typeRef) : ObjectType + { + $type = $this->getType($typeRef); + + return ObjectType::assertObjectType($type); + } + + /** + * @param array $typeRef + */ + public function getInterfaceType(array $typeRef) : InterfaceType + { + $type = $this->getType($typeRef); + + return InterfaceType::assertInterfaceType($type); + } + + /** + * @param array $type + */ + private function buildType(array $type) : NamedType + { + if (array_key_exists('name', $type) && array_key_exists('kind', $type)) { + switch ($type['kind']) { + case TypeKind::SCALAR: + return $this->buildScalarDef($type); + case TypeKind::OBJECT: + return $this->buildObjectDef($type); + case TypeKind::INTERFACE: + return $this->buildInterfaceDef($type); + case TypeKind::UNION: + return $this->buildUnionDef($type); + case TypeKind::ENUM: + return $this->buildEnumDef($type); + case TypeKind::INPUT_OBJECT: + return $this->buildInputObjectDef($type); + } + } + + throw new InvariantViolation( + 'Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ' . json_encode($type) . '.' + ); + } + + /** + * @param array $scalar + */ + private function buildScalarDef(array $scalar) : ScalarType + { + return new CustomScalarType([ + 'name' => $scalar['name'], + 'description' => $scalar['description'], + 'serialize' => static function ($value) : string { + return (string) $value; + }, + ]); + } + + /** + * @param array $implementingIntrospection + * + * @return array + */ + private function buildImplementationsList(array $implementingIntrospection) : array + { + // TODO: Temporary workaround until GraphQL ecosystem will fully support 'interfaces' on interface types. + if (array_key_exists('interfaces', $implementingIntrospection) && + $implementingIntrospection['interfaces'] === null && + $implementingIntrospection['kind'] === TypeKind::INTERFACE) { + return []; + } + + if (! array_key_exists('interfaces', $implementingIntrospection)) { + throw new InvariantViolation('Introspection result missing interfaces: ' . json_encode($implementingIntrospection) . '.'); + } + + return array_map([$this, 'getInterfaceType'], $implementingIntrospection['interfaces']); + } + + /** + * @param array $object + */ + private function buildObjectDef(array $object) : ObjectType + { + return new ObjectType([ + 'name' => $object['name'], + 'description' => $object['description'], + 'interfaces' => function () use ($object) : array { + return $this->buildImplementationsList($object); + }, + 'fields' => function () use ($object) { + return $this->buildFieldDefMap($object); + }, + ]); + } + + /** + * @param array $interface + */ + private function buildInterfaceDef(array $interface) : InterfaceType + { + return new InterfaceType([ + 'name' => $interface['name'], + 'description' => $interface['description'], + 'fields' => function () use ($interface) { + return $this->buildFieldDefMap($interface); + }, + 'interfaces' => function () use ($interface) : array { + return $this->buildImplementationsList($interface); + }, + ]); + } + + /** + * @param array> $union + */ + private function buildUnionDef(array $union) : UnionType + { + if (! array_key_exists('possibleTypes', $union)) { + throw new InvariantViolation('Introspection result missing possibleTypes: ' . json_encode($union) . '.'); + } + + return new UnionType([ + 'name' => $union['name'], + 'description' => $union['description'], + 'types' => function () use ($union) : array { + return array_map( + [$this, 'getObjectType'], + $union['possibleTypes'] + ); + }, + ]); + } + + /** + * @param array> $enum + */ + private function buildEnumDef(array $enum) : EnumType + { + if (! array_key_exists('enumValues', $enum)) { + throw new InvariantViolation('Introspection result missing enumValues: ' . json_encode($enum) . '.'); + } + + return new EnumType([ + 'name' => $enum['name'], + 'description' => $enum['description'], + 'values' => Utils::keyValMap( + $enum['enumValues'], + static function (array $enumValue) : string { + return $enumValue['name']; + }, + static function (array $enumValue) : array { + return [ + 'description' => $enumValue['description'], + 'deprecationReason' => $enumValue['deprecationReason'], + ]; + } + ), + ]); + } + + /** + * @param array $inputObject + */ + private function buildInputObjectDef(array $inputObject) : InputObjectType + { + if (! array_key_exists('inputFields', $inputObject)) { + throw new InvariantViolation('Introspection result missing inputFields: ' . json_encode($inputObject) . '.'); + } + + return new InputObjectType([ + 'name' => $inputObject['name'], + 'description' => $inputObject['description'], + 'fields' => function () use ($inputObject) : array { + return $this->buildInputValueDefMap($inputObject['inputFields']); + }, + ]); + } + + /** + * @param array $typeIntrospection + */ + private function buildFieldDefMap(array $typeIntrospection) + { + if (! array_key_exists('fields', $typeIntrospection)) { + throw new InvariantViolation('Introspection result missing fields: ' . json_encode($typeIntrospection) . '.'); + } + + return Utils::keyValMap( + $typeIntrospection['fields'], + static function (array $fieldIntrospection) : string { + return $fieldIntrospection['name']; + }, + function (array $fieldIntrospection) : array { + if (! array_key_exists('args', $fieldIntrospection)) { + throw new InvariantViolation('Introspection result missing field args: ' . json_encode($fieldIntrospection) . '.'); + } + + return [ + 'description' => $fieldIntrospection['description'], + 'deprecationReason' => $fieldIntrospection['deprecationReason'], + 'type' => $this->getOutputType($fieldIntrospection['type']), + 'args' => $this->buildInputValueDefMap($fieldIntrospection['args']), + ]; + } + ); + } + + /** + * @param array> $inputValueIntrospections + * + * @return array> + */ + private function buildInputValueDefMap(array $inputValueIntrospections) : array + { + return Utils::keyValMap( + $inputValueIntrospections, + static function (array $inputValue) : string { + return $inputValue['name']; + }, + [$this, 'buildInputValue'] + ); + } + + /** + * @param array $inputValueIntrospection + * + * @return array + */ + public function buildInputValue(array $inputValueIntrospection) : array + { + $type = $this->getInputType($inputValueIntrospection['type']); + + $inputValue = [ + 'description' => $inputValueIntrospection['description'], + 'type' => $type, + ]; + + if (isset($inputValueIntrospection['defaultValue'])) { + $inputValue['defaultValue'] = AST::valueFromAST( + Parser::parseValue($inputValueIntrospection['defaultValue']), + $type + ); + } + + return $inputValue; + } + + /** + * @param array $directive + */ + public function buildDirective(array $directive) : Directive + { + if (! array_key_exists('args', $directive)) { + throw new InvariantViolation('Introspection result missing directive args: ' . json_encode($directive) . '.'); + } + if (! array_key_exists('locations', $directive)) { + throw new InvariantViolation('Introspection result missing directive locations: ' . json_encode($directive) . '.'); + } + + return new Directive([ + 'name' => $directive['name'], + 'description' => $directive['description'], + 'args' => $this->buildInputValueDefMap($directive['args']), + 'isRepeatable' => $directive['isRepeatable'] ?? false, + 'locations' => $directive['locations'], + ]); + } +} diff --git a/vendor/webonyx/graphql-php/src/Utils/BuildSchema.php b/vendor/webonyx/graphql-php/src/Utils/BuildSchema.php index 8b5a654..3e05775 100644 --- a/vendor/webonyx/graphql-php/src/Utils/BuildSchema.php +++ b/vendor/webonyx/graphql-php/src/Utils/BuildSchema.php @@ -5,16 +5,23 @@ declare(strict_types=1); namespace GraphQL\Utils; use GraphQL\Error\Error; +use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DocumentNode; -use GraphQL\Language\AST\Node; -use GraphQL\Language\AST\NodeKind; +use GraphQL\Language\AST\EnumTypeDefinitionNode; +use GraphQL\Language\AST\InputObjectTypeDefinitionNode; +use GraphQL\Language\AST\InterfaceTypeDefinitionNode; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Language\AST\ScalarTypeDefinitionNode; use GraphQL\Language\AST\SchemaDefinitionNode; +use GraphQL\Language\AST\TypeDefinitionNode; +use GraphQL\Language\AST\UnionTypeDefinitionNode; use GraphQL\Language\Parser; use GraphQL\Language\Source; use GraphQL\Type\Definition\Directive; +use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema; +use GraphQL\Validator\DocumentValidator; use function array_map; -use function array_reduce; use function sprintf; /** @@ -26,17 +33,17 @@ class BuildSchema /** @var DocumentNode */ private $ast; - /** @var Node[] */ + /** @var array */ private $nodeMap; /** @var callable|null */ private $typeConfigDecorator; - /** @var bool[] */ + /** @var array */ private $options; /** - * @param bool[] $options + * @param array $options */ public function __construct(DocumentNode $ast, ?callable $typeConfigDecorator = null, array $options = []) { @@ -50,7 +57,7 @@ class BuildSchema * document. * * @param DocumentNode|Source|string $source - * @param bool[] $options + * @param array $options * * @return Schema * @@ -58,7 +65,9 @@ class BuildSchema */ public static function build($source, ?callable $typeConfigDecorator = null, array $options = []) { - $doc = $source instanceof DocumentNode ? $source : Parser::parse($source); + $doc = $source instanceof DocumentNode + ? $source + : Parser::parse($source); return self::buildAST($doc, $typeConfigDecorator, $options); } @@ -77,8 +86,9 @@ class BuildSchema * * - commentDescriptions: * Provide true to use preceding comments as the description. + * This option is provided to ease adoption and will be removed in v16. * - * @param bool[] $options + * @param array $options * * @return Schema * @@ -95,39 +105,36 @@ class BuildSchema public function buildSchema() { - /** @var SchemaDefinitionNode $schemaDef */ + $options = $this->options; + if (! ($options['assumeValid'] ?? false) && ! ($options['assumeValidSDL'] ?? false)) { + DocumentValidator::assertValidSDL($this->ast); + } + $schemaDef = null; $typeDefs = []; $this->nodeMap = []; + /** @var array $directiveDefs */ $directiveDefs = []; - foreach ($this->ast->definitions as $d) { - switch ($d->kind) { - case NodeKind::SCHEMA_DEFINITION: - if ($schemaDef) { - throw new Error('Must provide only one schema definition.'); - } - $schemaDef = $d; + foreach ($this->ast->definitions as $definition) { + switch (true) { + case $definition instanceof SchemaDefinitionNode: + $schemaDef = $definition; break; - case NodeKind::SCALAR_TYPE_DEFINITION: - case NodeKind::OBJECT_TYPE_DEFINITION: - case NodeKind::INTERFACE_TYPE_DEFINITION: - case NodeKind::ENUM_TYPE_DEFINITION: - case NodeKind::UNION_TYPE_DEFINITION: - case NodeKind::INPUT_OBJECT_TYPE_DEFINITION: - $typeName = $d->name->value; - if (! empty($this->nodeMap[$typeName])) { + case $definition instanceof TypeDefinitionNode: + $typeName = $definition->name->value; + if (isset($this->nodeMap[$typeName])) { throw new Error(sprintf('Type "%s" was defined more than once.', $typeName)); } - $typeDefs[] = $d; - $this->nodeMap[$typeName] = $d; + $typeDefs[] = $definition; + $this->nodeMap[$typeName] = $definition; break; - case NodeKind::DIRECTIVE_DEFINITION: - $directiveDefs[] = $d; + case $definition instanceof DirectiveDefinitionNode: + $directiveDefs[] = $definition; break; } } - $operationTypes = $schemaDef + $operationTypes = $schemaDef !== null ? $this->getOperationTypes($schemaDef) : [ 'query' => isset($this->nodeMap['Query']) ? 'Query' : null, @@ -138,47 +145,33 @@ class BuildSchema $DefinitionBuilder = new ASTDefinitionBuilder( $this->nodeMap, $this->options, - static function ($typeName) { + static function ($typeName) : void { throw new Error('Type "' . $typeName . '" not found in document.'); }, $this->typeConfigDecorator ); $directives = array_map( - static function ($def) use ($DefinitionBuilder) { + static function (DirectiveDefinitionNode $def) use ($DefinitionBuilder) : Directive { return $DefinitionBuilder->buildDirective($def); }, $directiveDefs ); // If specified directives were not explicitly declared, add them. - $skip = array_reduce( + $directivesByName = Utils::groupBy( $directives, - static function ($hasSkip, $directive) { - return (bool) $hasSkip || $directive->name === 'skip'; + static function (Directive $directive) : string { + return $directive->name; } ); - if (! $skip) { + if (! isset($directivesByName['skip'])) { $directives[] = Directive::skipDirective(); } - - $include = array_reduce( - $directives, - static function ($hasInclude, $directive) { - return (bool) $hasInclude || $directive->name === 'include'; - } - ); - if (! $include) { + if (! isset($directivesByName['include'])) { $directives[] = Directive::includeDirective(); } - - $deprecated = array_reduce( - $directives, - static function ($hasDeprecated, $directive) { - return (bool) $hasDeprecated || $directive->name === 'deprecated'; - } - ); - if (! $deprecated) { + if (! isset($directivesByName['deprecated'])) { $directives[] = Directive::deprecatedDirective(); } @@ -196,13 +189,14 @@ class BuildSchema 'subscription' => isset($operationTypes['subscription']) ? $DefinitionBuilder->buildType($operationTypes['subscription']) : null, - 'typeLoader' => static function ($name) use ($DefinitionBuilder) { + 'typeLoader' => static function ($name) use ($DefinitionBuilder) : Type { return $DefinitionBuilder->buildType($name); }, 'directives' => $directives, 'astNode' => $schemaDef, - 'types' => function () use ($DefinitionBuilder) { + 'types' => function () use ($DefinitionBuilder) : array { $types = []; + /** @var ScalarTypeDefinitionNode|ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode|UnionTypeDefinitionNode|EnumTypeDefinitionNode|InputObjectTypeDefinitionNode $def */ foreach ($this->nodeMap as $name => $def) { $types[] = $DefinitionBuilder->buildType($def->name->value); } diff --git a/vendor/webonyx/graphql-php/src/Utils/InterfaceImplementations.php b/vendor/webonyx/graphql-php/src/Utils/InterfaceImplementations.php new file mode 100644 index 0000000..eca7fd2 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Utils/InterfaceImplementations.php @@ -0,0 +1,48 @@ + */ + private $objects; + + /** @var array */ + private $interfaces; + + /** + * @param array $objects + * @param array $interfaces + */ + public function __construct(array $objects, array $interfaces) + { + $this->objects = $objects; + $this->interfaces = $interfaces; + } + + /** + * @return array + */ + public function objects() : array + { + return $this->objects; + } + + /** + * @return array + */ + public function interfaces() : array + { + return $this->interfaces; + } +} diff --git a/vendor/webonyx/graphql-php/src/Utils/MixedStore.php b/vendor/webonyx/graphql-php/src/Utils/MixedStore.php index 469abaa..8513fd5 100644 --- a/vendor/webonyx/graphql-php/src/Utils/MixedStore.php +++ b/vendor/webonyx/graphql-php/src/Utils/MixedStore.php @@ -21,7 +21,7 @@ use function is_string; * Similar to PHP array, but allows any type of data to act as key (including arrays, objects, scalars) * * Note: unfortunately when storing array as key - access and modification is O(N) - * (yet this should be really rare case and should be avoided when possible) + * (yet this should rarely be the case and should be avoided when possible) */ class MixedStore implements ArrayAccess { diff --git a/vendor/webonyx/graphql-php/src/Utils/SchemaExtender.php b/vendor/webonyx/graphql-php/src/Utils/SchemaExtender.php index 07a1447..ca605cc 100644 --- a/vendor/webonyx/graphql-php/src/Utils/SchemaExtender.php +++ b/vendor/webonyx/graphql-php/src/Utils/SchemaExtender.php @@ -7,24 +7,29 @@ namespace GraphQL\Utils; use GraphQL\Error\Error; use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DocumentNode; +use GraphQL\Language\AST\EnumTypeExtensionNode; +use GraphQL\Language\AST\InputObjectTypeExtensionNode; +use GraphQL\Language\AST\InterfaceTypeExtensionNode; use GraphQL\Language\AST\Node; -use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\ObjectTypeExtensionNode; use GraphQL\Language\AST\SchemaDefinitionNode; use GraphQL\Language\AST\SchemaTypeExtensionNode; use GraphQL\Language\AST\TypeDefinitionNode; use GraphQL\Language\AST\TypeExtensionNode; +use GraphQL\Language\AST\UnionTypeExtensionNode; use GraphQL\Type\Definition\CustomScalarType; use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\EnumValueDefinition; use GraphQL\Type\Definition\FieldArgument; +use GraphQL\Type\Definition\ImplementingType; use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InterfaceType; use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NamedType; use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; +use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Introspection; @@ -75,8 +80,8 @@ class SchemaExtender */ protected static function checkExtensionNode(Type $type, Node $node) : void { - switch ($node->kind) { - case NodeKind::OBJECT_TYPE_EXTENSION: + switch (true) { + case $node instanceof ObjectTypeExtensionNode: if (! ($type instanceof ObjectType)) { throw new Error( 'Cannot extend non-object type "' . $type->name . '".', @@ -84,7 +89,7 @@ class SchemaExtender ); } break; - case NodeKind::INTERFACE_TYPE_EXTENSION: + case $node instanceof InterfaceTypeExtensionNode: if (! ($type instanceof InterfaceType)) { throw new Error( 'Cannot extend non-interface type "' . $type->name . '".', @@ -92,7 +97,7 @@ class SchemaExtender ); } break; - case NodeKind::ENUM_TYPE_EXTENSION: + case $node instanceof EnumTypeExtensionNode: if (! ($type instanceof EnumType)) { throw new Error( 'Cannot extend non-enum type "' . $type->name . '".', @@ -100,7 +105,7 @@ class SchemaExtender ); } break; - case NodeKind::UNION_TYPE_EXTENSION: + case $node instanceof UnionTypeExtensionNode: if (! ($type instanceof UnionType)) { throw new Error( 'Cannot extend non-union type "' . $type->name . '".', @@ -108,7 +113,7 @@ class SchemaExtender ); } break; - case NodeKind::INPUT_OBJECT_TYPE_EXTENSION: + case $node instanceof InputObjectTypeExtensionNode: if (! ($type instanceof InputObjectType)) { throw new Error( 'Cannot extend non-input object type "' . $type->name . '".', @@ -119,7 +124,7 @@ class SchemaExtender } } - protected static function extendCustomScalarType(CustomScalarType $type) : CustomScalarType + protected static function extendScalarType(ScalarType $type) : CustomScalarType { return new CustomScalarType([ 'name' => $type->name, @@ -137,7 +142,7 @@ class SchemaExtender return new UnionType([ 'name' => $type->name, 'description' => $type->description, - 'types' => static function () use ($type) { + 'types' => static function () use ($type) : array { return static::extendPossibleTypes($type); }, 'astNode' => $type->astNode, @@ -162,7 +167,7 @@ class SchemaExtender return new InputObjectType([ 'name' => $type->name, 'description' => $type->description, - 'fields' => static function () use ($type) { + 'fields' => static function () use ($type) : array { return static::extendInputFieldMap($type); }, 'astNode' => $type->astNode, @@ -180,7 +185,7 @@ class SchemaExtender foreach ($oldFieldMap as $fieldName => $field) { $newFieldMap[$fieldName] = [ 'description' => $field->description, - 'type' => static::extendType($field->type), + 'type' => static::extendType($field->getType()), 'astNode' => $field->astNode, ]; @@ -268,9 +273,11 @@ class SchemaExtender } /** - * @return InterfaceType[] + * @param ObjectType|InterfaceType $type + * + * @return array */ - protected static function extendImplementedInterfaces(ObjectType $type) : array + protected static function extendImplementedInterfaces(ImplementingType $type) : array { $interfaces = array_map(static function (InterfaceType $interfaceType) { return static::extendNamedType($interfaceType); @@ -278,7 +285,7 @@ class SchemaExtender $extensions = static::$typeExtensionsMap[$type->name] ?? null; if ($extensions !== null) { - /** @var ObjectTypeExtensionNode $extension */ + /** @var ObjectTypeExtensionNode|InterfaceTypeExtensionNode $extension */ foreach ($extensions as $extension) { foreach ($extension->interfaces as $namedType) { $interfaces[] = static::$astBuilder->buildType($namedType); @@ -292,7 +299,7 @@ class SchemaExtender protected static function extendType($typeDef) { if ($typeDef instanceof ListOfType) { - return Type::listOf(static::extendType($typeDef->ofType)); + return Type::listOf(static::extendType($typeDef->getOfType())); } if ($typeDef instanceof NonNull) { @@ -311,10 +318,10 @@ class SchemaExtender { return Utils::keyValMap( $args, - static function (FieldArgument $arg) { + static function (FieldArgument $arg) : string { return $arg->name; }, - static function (FieldArgument $arg) { + static function (FieldArgument $arg) : array { $def = [ 'type' => static::extendType($arg->getType()), 'description' => $arg->description, @@ -378,15 +385,16 @@ class SchemaExtender return new ObjectType([ 'name' => $type->name, 'description' => $type->description, - 'interfaces' => static function () use ($type) { + 'interfaces' => static function () use ($type) : array { return static::extendImplementedInterfaces($type); }, - 'fields' => static function () use ($type) { + 'fields' => static function () use ($type) : array { return static::extendFieldMap($type); }, 'astNode' => $type->astNode, 'extensionASTNodes' => static::getExtensionASTNodes($type), 'isTypeOf' => $type->config['isTypeOf'] ?? null, + 'resolveField' => $type->resolveFieldFn ?? null, ]); } @@ -395,7 +403,10 @@ class SchemaExtender return new InterfaceType([ 'name' => $type->name, 'description' => $type->description, - 'fields' => static function () use ($type) { + 'interfaces' => static function () use ($type) : array { + return static::extendImplementedInterfaces($type); + }, + 'fields' => static function () use ($type) : array { return static::extendFieldMap($type); }, 'astNode' => $type->astNode, @@ -424,8 +435,8 @@ class SchemaExtender $name = $type->name; if (! isset(static::$extendTypeCache[$name])) { - if ($type instanceof CustomScalarType) { - static::$extendTypeCache[$name] = static::extendCustomScalarType($type); + if ($type instanceof ScalarType) { + static::$extendTypeCache[$name] = static::extendScalarType($type); } elseif ($type instanceof ObjectType) { static::$extendTypeCache[$name] = static::extendObjectType($type); } elseif ($type instanceof InterfaceType) { @@ -461,7 +472,7 @@ class SchemaExtender */ protected static function getMergedDirectives(Schema $schema, array $directiveDefinitions) : array { - $existingDirectives = array_map(static function (Directive $directive) { + $existingDirectives = array_map(static function (Directive $directive) : Directive { return static::extendDirective($directive); }, $schema->getDirectives()); @@ -469,7 +480,7 @@ class SchemaExtender return array_merge( $existingDirectives, - array_map(static function (DirectiveDefinitionNode $directive) { + array_map(static function (DirectiveDefinitionNode $directive) : Directive { return static::$astBuilder->buildDirective($directive); }, $directiveDefinitions) ); @@ -487,20 +498,25 @@ class SchemaExtender } /** - * @param mixed[]|null $options + * @param array $options */ - public static function extend(Schema $schema, DocumentNode $documentAST, ?array $options = null) : Schema - { - if ($options === null || ! (isset($options['assumeValid']) || isset($options['assumeValidSDL']))) { + public static function extend( + Schema $schema, + DocumentNode $documentAST, + array $options = [], + ?callable $typeConfigDecorator = null + ) : Schema { + if (! (isset($options['assumeValid']) || isset($options['assumeValidSDL']))) { DocumentValidator::assertValidSDLExtension($documentAST, $schema); } + /** @var array $typeDefinitionMap */ $typeDefinitionMap = []; static::$typeExtensionsMap = []; $directiveDefinitions = []; /** @var SchemaDefinitionNode|null $schemaDef */ $schemaDef = null; - /** @var SchemaTypeExtensionNode[] $schemaExtensions */ + /** @var array $schemaExtensions */ $schemaExtensions = []; $definitionsCount = count($documentAST->definitions); @@ -547,11 +563,11 @@ class SchemaExtender } } - if (count(static::$typeExtensionsMap) === 0 && - count($typeDefinitionMap) === 0 && - count($directiveDefinitions) === 0 && - count($schemaExtensions) === 0 && - $schemaDef === null + if (count(static::$typeExtensionsMap) === 0 + && count($typeDefinitionMap) === 0 + && count($directiveDefinitions) === 0 + && count($schemaExtensions) === 0 + && $schemaDef === null ) { return $schema; } @@ -560,14 +576,15 @@ class SchemaExtender $typeDefinitionMap, $options, static function (string $typeName) use ($schema) { - /** @var NamedType $existingType */ + /** @var ScalarType|ObjectType|InterfaceType|UnionType|EnumType|InputObjectType $existingType */ $existingType = $schema->getType($typeName); if ($existingType !== null) { return static::extendNamedType($existingType); } throw new Error('Unknown type: "' . $typeName . '". Ensure that this type exists either in the original schema, or is added in a type definition.', [$typeName]); - } + }, + $typeConfigDecorator ); static::$extendTypeCache = []; @@ -592,7 +609,7 @@ class SchemaExtender } foreach ($schemaExtensions as $schemaExtension) { - if (! $schemaExtension->operationTypes) { + if ($schemaExtension->operationTypes === null) { continue; } @@ -605,17 +622,18 @@ class SchemaExtender } } - $schemaExtensionASTNodes = count($schemaExtensions) > 0 - ? ($schema->extensionASTNodes ? array_merge($schema->extensionASTNodes, $schemaExtensions) : $schemaExtensions) - : $schema->extensionASTNodes; + $schemaExtensionASTNodes = array_merge($schema->extensionASTNodes, $schemaExtensions); $types = array_merge( - array_map(static function ($type) { - return static::extendType($type); - }, array_values($schema->getTypeMap())), - array_map(static function ($type) { + // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + array_map(static function (Type $type) : Type { + return static::extendNamedType($type); + }, $schema->getTypeMap()), + // Do the same with new types. + array_map(static function (TypeDefinitionNode $type) : Type { return static::$astBuilder->buildType($type); - }, array_values($typeDefinitionMap)) + }, $typeDefinitionMap) ); return new Schema([ diff --git a/vendor/webonyx/graphql-php/src/Utils/SchemaPrinter.php b/vendor/webonyx/graphql-php/src/Utils/SchemaPrinter.php index 9e9e1ca..c5f958c 100644 --- a/vendor/webonyx/graphql-php/src/Utils/SchemaPrinter.php +++ b/vendor/webonyx/graphql-php/src/Utils/SchemaPrinter.php @@ -38,23 +38,22 @@ use function substr; class SchemaPrinter { /** - * Accepts options as a second argument: - * + * @param array $options + * Available options: * - commentDescriptions: * Provide true to use preceding comments as the description. - * - * @param bool[] $options + * This option is provided to ease adoption and will be removed in v16. * * @api */ public static function doPrint(Schema $schema, array $options = []) : string { - return self::printFilteredSchema( + return static::printFilteredSchema( $schema, - static function ($type) { + static function ($type) : bool { return ! Directive::isSpecifiedDirective($type); }, - static function ($type) { + static function ($type) : bool { return ! Type::isBuiltInType($type); }, $options @@ -62,16 +61,11 @@ class SchemaPrinter } /** - * @param bool[] $options + * @param array $options */ - private static function printFilteredSchema(Schema $schema, $directiveFilter, $typeFilter, $options) : string + protected static function printFilteredSchema(Schema $schema, callable $directiveFilter, callable $typeFilter, array $options) : string { - $directives = array_filter( - $schema->getDirectives(), - static function ($directive) use ($directiveFilter) { - return $directiveFilter($directive); - } - ); + $directives = array_filter($schema->getDirectives(), $directiveFilter); $types = $schema->getTypeMap(); ksort($types); @@ -83,16 +77,16 @@ class SchemaPrinter "\n\n", array_filter( array_merge( - [self::printSchemaDefinition($schema)], + [static::printSchemaDefinition($schema)], array_map( - static function ($directive) use ($options) { - return self::printDirective($directive, $options); + static function (Directive $directive) use ($options) : string { + return static::printDirective($directive, $options); }, $directives ), array_map( - static function ($type) use ($options) { - return self::printType($type, $options); + static function ($type) use ($options) : string { + return static::printType($type, $options); }, $types ) @@ -102,26 +96,26 @@ class SchemaPrinter ); } - private static function printSchemaDefinition(Schema $schema) + protected static function printSchemaDefinition(Schema $schema) : string { - if (self::isSchemaOfCommonNames($schema)) { - return; + if (static::isSchemaOfCommonNames($schema)) { + return ''; } $operationTypes = []; $queryType = $schema->getQueryType(); - if ($queryType) { + if ($queryType !== null) { $operationTypes[] = sprintf(' query: %s', $queryType->name); } $mutationType = $schema->getMutationType(); - if ($mutationType) { + if ($mutationType !== null) { $operationTypes[] = sprintf(' mutation: %s', $mutationType->name); } $subscriptionType = $schema->getSubscriptionType(); - if ($subscriptionType) { + if ($subscriptionType !== null) { $operationTypes[] = sprintf(' subscription: %s', $subscriptionType->name); } @@ -140,38 +134,46 @@ class SchemaPrinter * * When using this naming convention, the schema description can be omitted. */ - private static function isSchemaOfCommonNames(Schema $schema) + protected static function isSchemaOfCommonNames(Schema $schema) : bool { $queryType = $schema->getQueryType(); - if ($queryType && $queryType->name !== 'Query') { + if ($queryType !== null && $queryType->name !== 'Query') { return false; } $mutationType = $schema->getMutationType(); - if ($mutationType && $mutationType->name !== 'Mutation') { + if ($mutationType !== null && $mutationType->name !== 'Mutation') { return false; } $subscriptionType = $schema->getSubscriptionType(); - return ! $subscriptionType || $subscriptionType->name === 'Subscription'; + return $subscriptionType === null || $subscriptionType->name === 'Subscription'; } - private static function printDirective($directive, $options) : string + /** + * @param array $options + */ + protected static function printDirective(Directive $directive, array $options) : string { - return self::printDescription($options, $directive) . - 'directive @' . $directive->name . self::printArgs($options, $directive->args) . - ' on ' . implode(' | ', $directive->locations); + return static::printDescription($options, $directive) + . 'directive @' . $directive->name + . static::printArgs($options, $directive->args) + . ($directive->isRepeatable ? ' repeatable' : '') + . ' on ' . implode(' | ', $directive->locations); } - private static function printDescription($options, $def, $indentation = '', $firstInBlock = true) : string + /** + * @param array $options + */ + protected static function printDescription(array $options, $def, $indentation = '', $firstInBlock = true) : string { if (! $def->description) { return ''; } - $lines = self::descriptionLines($def->description, 120 - strlen($indentation)); + $lines = static::descriptionLines($def->description, 120 - strlen($indentation)); if (isset($options['commentDescriptions'])) { - return self::printDescriptionWithComments($lines, $indentation, $firstInBlock); + return static::printDescriptionWithComments($lines, $indentation, $firstInBlock); } $description = $indentation && ! $firstInBlock @@ -183,7 +185,7 @@ class SchemaPrinter mb_strlen($lines[0]) < 70 && substr($lines[0], -1) !== '"' ) { - return $description . self::escapeQuote($lines[0]) . "\"\"\"\n"; + return $description . static::escapeQuote($lines[0]) . "\"\"\"\n"; } // Format a multi-line block quote to account for leading space. @@ -201,7 +203,7 @@ class SchemaPrinter if ($i !== 0 || ! $hasLeadingSpace) { $description .= $indentation; } - $description .= self::escapeQuote($lines[$i]) . "\n"; + $description .= static::escapeQuote($lines[$i]) . "\n"; } $description .= $indentation . "\"\"\"\n"; @@ -211,7 +213,7 @@ class SchemaPrinter /** * @return string[] */ - private static function descriptionLines(string $description, int $maxLen) : array + protected static function descriptionLines(string $description, int $maxLen) : array { $lines = []; $rawLines = explode("\n", $description); @@ -221,7 +223,7 @@ class SchemaPrinter } else { // For > 120 character long lines, cut at space boundaries into sublines // of ~80 chars. - $sublines = self::breakLine($line, $maxLen); + $sublines = static::breakLine($line, $maxLen); foreach ($sublines as $subline) { $lines[] = $subline; } @@ -234,7 +236,7 @@ class SchemaPrinter /** * @return string[] */ - private static function breakLine(string $line, int $maxLen) : array + protected static function breakLine(string $line, int $maxLen) : array { if (strlen($line) < $maxLen + 5) { return [$line]; @@ -245,7 +247,7 @@ class SchemaPrinter return array_map('trim', $parts); } - private static function printDescriptionWithComments($lines, $indentation, $firstInBlock) : string + protected static function printDescriptionWithComments($lines, $indentation, $firstInBlock) : string { $description = $indentation && ! $firstInBlock ? "\n" : ''; foreach ($lines as $line) { @@ -259,12 +261,15 @@ class SchemaPrinter return $description; } - private static function escapeQuote($line) : string + protected static function escapeQuote($line) : string { return str_replace('"""', '\\"""', $line); } - private static function printArgs($options, $args, $indentation = '') : string + /** + * @param array $options + */ + protected static function printArgs(array $options, $args, $indentation = '') : string { if (! $args) { return ''; @@ -273,11 +278,11 @@ class SchemaPrinter // If every arg does not have a description, print them on one line. if (Utils::every( $args, - static function ($arg) { - return empty($arg->description); + static function ($arg) : bool { + return strlen($arg->description ?? '') === 0; } )) { - return '(' . implode(', ', array_map('self::printInputValue', $args)) . ')'; + return '(' . implode(', ', array_map('static::printInputValue', $args)) . ')'; } return sprintf( @@ -285,9 +290,9 @@ class SchemaPrinter implode( "\n", array_map( - static function ($arg, $i) use ($indentation, $options) { - return self::printDescription($options, $arg, ' ' . $indentation, ! $i) . ' ' . $indentation . - self::printInputValue($arg); + static function ($arg, $i) use ($indentation, $options) : string { + return static::printDescription($options, $arg, ' ' . $indentation, ! $i) . ' ' . $indentation . + static::printInputValue($arg); }, $args, array_keys($args) @@ -297,7 +302,7 @@ class SchemaPrinter ); } - private static function printInputValue($arg) : string + protected static function printInputValue($arg) : string { $argDecl = $arg->name . ': ' . (string) $arg->getType(); if ($arg->defaultValueExists()) { @@ -308,80 +313,81 @@ class SchemaPrinter } /** - * @param bool[] $options + * @param array $options */ public static function printType(Type $type, array $options = []) : string { if ($type instanceof ScalarType) { - return self::printScalar($type, $options); + return static::printScalar($type, $options); } if ($type instanceof ObjectType) { - return self::printObject($type, $options); + return static::printObject($type, $options); } if ($type instanceof InterfaceType) { - return self::printInterface($type, $options); + return static::printInterface($type, $options); } if ($type instanceof UnionType) { - return self::printUnion($type, $options); + return static::printUnion($type, $options); } if ($type instanceof EnumType) { - return self::printEnum($type, $options); + return static::printEnum($type, $options); } if ($type instanceof InputObjectType) { - return self::printInputObject($type, $options); + return static::printInputObject($type, $options); } throw new Error(sprintf('Unknown type: %s.', Utils::printSafe($type))); } /** - * @param bool[] $options + * @param array $options */ - private static function printScalar(ScalarType $type, array $options) : string + protected static function printScalar(ScalarType $type, array $options) : string { - return sprintf('%sscalar %s', self::printDescription($options, $type), $type->name); + return sprintf('%sscalar %s', static::printDescription($options, $type), $type->name); } /** - * @param bool[] $options + * @param array $options */ - private static function printObject(ObjectType $type, array $options) : string + protected static function printObject(ObjectType $type, array $options) : string { $interfaces = $type->getInterfaces(); - $implementedInterfaces = ! empty($interfaces) ? - ' implements ' . implode( + $implementedInterfaces = count($interfaces) > 0 + ? ' implements ' . implode( ' & ', array_map( - static function ($i) { - return $i->name; + static function (InterfaceType $interface) : string { + return $interface->name; }, $interfaces ) - ) : ''; + ) + : ''; - return self::printDescription($options, $type) . - sprintf("type %s%s {\n%s\n}", $type->name, $implementedInterfaces, self::printFields($options, $type)); + return static::printDescription($options, $type) . + sprintf("type %s%s {\n%s\n}", $type->name, $implementedInterfaces, static::printFields($options, $type)); } /** - * @param bool[] $options + * @param array $options */ - private static function printFields($options, $type) : string + protected static function printFields(array $options, $type) : string { $fields = array_values($type->getFields()); return implode( "\n", array_map( - static function ($f, $i) use ($options) { - return self::printDescription($options, $f, ' ', ! $i) . ' ' . - $f->name . self::printArgs($options, $f->args, ' ') . ': ' . - (string) $f->getType() . self::printDeprecated($f); + static function ($f, $i) use ($options) : string { + return static::printDescription($options, $f, ' ', ! $i) . ' ' . + $f->name . static::printArgs($options, $f->args, ' ') . ': ' . + (string) $f->getType() . static::printDeprecated($f); }, $fields, array_keys($fields) @@ -389,10 +395,10 @@ class SchemaPrinter ); } - private static function printDeprecated($fieldOrEnumVal) : string + protected static function printDeprecated($fieldOrEnumVal) : string { $reason = $fieldOrEnumVal->deprecationReason; - if (empty($reason)) { + if ($reason === null) { return ''; } if ($reason === '' || $reason === Directive::DEFAULT_DEPRECATION_REASON) { @@ -404,43 +410,56 @@ class SchemaPrinter } /** - * @param bool[] $options + * @param array $options */ - private static function printInterface(InterfaceType $type, array $options) : string + protected static function printInterface(InterfaceType $type, array $options) : string { - return self::printDescription($options, $type) . - sprintf("interface %s {\n%s\n}", $type->name, self::printFields($options, $type)); + $interfaces = $type->getInterfaces(); + $implementedInterfaces = count($interfaces) > 0 + ? ' implements ' . implode( + ' & ', + array_map( + static function (InterfaceType $interface) : string { + return $interface->name; + }, + $interfaces + ) + ) + : ''; + + return static::printDescription($options, $type) . + sprintf("interface %s%s {\n%s\n}", $type->name, $implementedInterfaces, static::printFields($options, $type)); } /** - * @param bool[] $options + * @param array $options */ - private static function printUnion(UnionType $type, array $options) : string + protected static function printUnion(UnionType $type, array $options) : string { - return self::printDescription($options, $type) . + return static::printDescription($options, $type) . sprintf('union %s = %s', $type->name, implode(' | ', $type->getTypes())); } /** - * @param bool[] $options + * @param array $options */ - private static function printEnum(EnumType $type, array $options) : string + protected static function printEnum(EnumType $type, array $options) : string { - return self::printDescription($options, $type) . - sprintf("enum %s {\n%s\n}", $type->name, self::printEnumValues($type->getValues(), $options)); + return static::printDescription($options, $type) . + sprintf("enum %s {\n%s\n}", $type->name, static::printEnumValues($type->getValues(), $options)); } /** - * @param bool[] $options + * @param array $options */ - private static function printEnumValues($values, $options) : string + protected static function printEnumValues($values, array $options) : string { return implode( "\n", array_map( - static function ($value, $i) use ($options) { - return self::printDescription($options, $value, ' ', ! $i) . ' ' . - $value->name . self::printDeprecated($value); + static function ($value, $i) use ($options) : string { + return static::printDescription($options, $value, ' ', ! $i) . ' ' . + $value->name . static::printDeprecated($value); }, $values, array_keys($values) @@ -449,21 +468,21 @@ class SchemaPrinter } /** - * @param bool[] $options + * @param array $options */ - private static function printInputObject(InputObjectType $type, array $options) : string + protected static function printInputObject(InputObjectType $type, array $options) : string { $fields = array_values($type->getFields()); - return self::printDescription($options, $type) . + return static::printDescription($options, $type) . sprintf( "input %s {\n%s\n}", $type->name, implode( "\n", array_map( - static function ($f, $i) use ($options) { - return self::printDescription($options, $f, ' ', ! $i) . ' ' . self::printInputValue($f); + static function ($f, $i) use ($options) : string { + return static::printDescription($options, $f, ' ', ! $i) . ' ' . static::printInputValue($f); }, $fields, array_keys($fields) @@ -473,13 +492,13 @@ class SchemaPrinter } /** - * @param bool[] $options + * @param array $options * * @api */ public static function printIntrospectionSchema(Schema $schema, array $options = []) : string { - return self::printFilteredSchema( + return static::printFilteredSchema( $schema, [Directive::class, 'isSpecifiedDirective'], [Introspection::class, 'isIntrospectionType'], diff --git a/vendor/webonyx/graphql-php/src/Utils/TypeComparators.php b/vendor/webonyx/graphql-php/src/Utils/TypeComparators.php index 2beb942..7033eee 100644 --- a/vendor/webonyx/graphql-php/src/Utils/TypeComparators.php +++ b/vendor/webonyx/graphql-php/src/Utils/TypeComparators.php @@ -6,6 +6,7 @@ namespace GraphQL\Utils; use GraphQL\Type\Definition\AbstractType; use GraphQL\Type\Definition\CompositeType; +use GraphQL\Type\Definition\ImplementingType; use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; @@ -44,12 +45,9 @@ class TypeComparators * Provided a type and a super type, return true if the first type is either * equal or a subset of the second super type (covariant). * - * @param AbstractType $maybeSubType - * @param AbstractType $superType - * * @return bool */ - public static function isTypeSubTypeOf(Schema $schema, $maybeSubType, $superType) + public static function isTypeSubTypeOf(Schema $schema, Type $maybeSubType, Type $superType) { // Equivalent type is a valid subtype if ($maybeSubType === $superType) { @@ -85,10 +83,10 @@ class TypeComparators } // If superType type is an abstract type, maybeSubType type may be a currently - // possible object type. + // possible object or interface type. return Type::isAbstractType($superType) && - $maybeSubType instanceof ObjectType && - $schema->isPossibleType( + $maybeSubType instanceof ImplementingType && + $schema->isSubType( $superType, $maybeSubType ); @@ -117,7 +115,7 @@ class TypeComparators // If both types are abstract, then determine if there is any intersection // between possible concrete types of each. foreach ($schema->getPossibleTypes($typeA) as $type) { - if ($schema->isPossibleType($typeB, $type)) { + if ($schema->isSubType($typeB, $type)) { return true; } } @@ -126,12 +124,12 @@ class TypeComparators } // Determine if the latter type is a possible concrete type of the former. - return $schema->isPossibleType($typeA, $typeB); + return $schema->isSubType($typeA, $typeB); } if ($typeB instanceof AbstractType) { // Determine if the former type is a possible concrete type of the latter. - return $schema->isPossibleType($typeB, $typeA); + return $schema->isSubType($typeB, $typeA); } // Otherwise the types do not overlap. diff --git a/vendor/webonyx/graphql-php/src/Utils/TypeInfo.php b/vendor/webonyx/graphql-php/src/Utils/TypeInfo.php index 89d4ea1..58d17fb 100644 --- a/vendor/webonyx/graphql-php/src/Utils/TypeInfo.php +++ b/vendor/webonyx/graphql-php/src/Utils/TypeInfo.php @@ -5,18 +5,28 @@ declare(strict_types=1); namespace GraphQL\Utils; use GraphQL\Error\InvariantViolation; -use GraphQL\Error\Warning; +use GraphQL\Language\AST\ArgumentNode; +use GraphQL\Language\AST\DirectiveNode; +use GraphQL\Language\AST\EnumValueNode; use GraphQL\Language\AST\FieldNode; +use GraphQL\Language\AST\FragmentDefinitionNode; +use GraphQL\Language\AST\InlineFragmentNode; use GraphQL\Language\AST\ListTypeNode; +use GraphQL\Language\AST\ListValueNode; use GraphQL\Language\AST\NamedTypeNode; use GraphQL\Language\AST\Node; -use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\NonNullTypeNode; +use GraphQL\Language\AST\ObjectFieldNode; +use GraphQL\Language\AST\OperationDefinitionNode; +use GraphQL\Language\AST\SelectionSetNode; +use GraphQL\Language\AST\VariableDefinitionNode; use GraphQL\Type\Definition\CompositeType; use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\FieldArgument; use GraphQL\Type\Definition\FieldDefinition; +use GraphQL\Type\Definition\HasFieldsType; +use GraphQL\Type\Definition\ImplementingType; use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\InputType; use GraphQL\Type\Definition\InterfaceType; @@ -28,7 +38,6 @@ use GraphQL\Type\Definition\UnionType; use GraphQL\Type\Definition\WrappingType; use GraphQL\Type\Introspection; use GraphQL\Type\Schema; -use SplStack; use function array_map; use function array_merge; use function array_pop; @@ -41,22 +50,25 @@ class TypeInfo /** @var Schema */ private $schema; - /** @var SplStack */ + /** @var array<(OutputType&Type)|null> */ private $typeStack; - /** @var SplStack */ + /** @var array<(CompositeType&Type)|null> */ private $parentTypeStack; - /** @var SplStack */ + /** @var array<(InputType&Type)|null> */ private $inputTypeStack; - /** @var SplStack */ + /** @var array */ private $fieldDefStack; - /** @var Directive */ + /** @var array */ + private $defaultValueStack; + + /** @var Directive|null */ private $directive; - /** @var FieldArgument */ + /** @var FieldArgument|null */ private $argument; /** @var mixed */ @@ -67,12 +79,14 @@ class TypeInfo */ public function __construct(Schema $schema, $initialType = null) { - $this->schema = $schema; - $this->typeStack = []; - $this->parentTypeStack = []; - $this->inputTypeStack = []; - $this->fieldDefStack = []; - if (! $initialType) { + $this->schema = $schema; + $this->typeStack = []; + $this->parentTypeStack = []; + $this->inputTypeStack = []; + $this->fieldDefStack = []; + $this->defaultValueStack = []; + + if ($initialType === null) { return; } @@ -91,14 +105,18 @@ class TypeInfo /** * @deprecated moved to GraphQL\Utils\TypeComparators + * + * @codeCoverageIgnore */ - public static function isEqualType(Type $typeA, Type $typeB) + public static function isEqualType(Type $typeA, Type $typeB) : bool { return TypeComparators::isEqualType($typeA, $typeB); } /** * @deprecated moved to GraphQL\Utils\TypeComparators + * + * @codeCoverageIgnore */ public static function isTypeSubTypeOf(Schema $schema, Type $maybeSubType, Type $superType) { @@ -107,6 +125,8 @@ class TypeInfo /** * @deprecated moved to GraphQL\Utils\TypeComparators + * + * @codeCoverageIgnore */ public static function doTypesOverlap(Schema $schema, CompositeType $typeA, CompositeType $typeB) { @@ -141,6 +161,7 @@ class TypeInfo if ($type instanceof WrappingType) { return self::extractTypes($type->getWrappedType(true), $typeMap); } + if (! $type instanceof Type) { // Preserve these invalid types in map (at numeric index) to make them // detectable during $schema->validate() @@ -157,7 +178,7 @@ class TypeInfo return $typeMap; } - if (! empty($typeMap[$type->name])) { + if (isset($typeMap[$type->name])) { Utils::invariant( $typeMap[$type->name] === $type, sprintf('Schema must contain unique named types but contains multiple types named "%s" ', $type) . @@ -173,14 +194,15 @@ class TypeInfo if ($type instanceof UnionType) { $nestedTypes = $type->getTypes(); } - if ($type instanceof ObjectType) { + if ($type instanceof ImplementingType) { $nestedTypes = array_merge($nestedTypes, $type->getInterfaces()); } - if ($type instanceof ObjectType || $type instanceof InterfaceType) { - foreach ($type->getFields() as $fieldName => $field) { - if (! empty($field->args)) { + + if ($type instanceof HasFieldsType) { + foreach ($type->getFields() as $field) { + if (count($field->args) > 0) { $fieldArgTypes = array_map( - static function (FieldArgument $arg) { + static function (FieldArgument $arg) : Type { return $arg->getType(); }, $field->args @@ -192,7 +214,7 @@ class TypeInfo } } if ($type instanceof InputObjectType) { - foreach ($type->getFields() as $fieldName => $field) { + foreach ($type->getFields() as $field) { $nestedTypes[] = $field->getType(); } } @@ -220,20 +242,14 @@ class TypeInfo } /** - * @return InputType|null + * @return (Type&InputType)|null */ - public function getParentInputType() + public function getParentInputType() : ?InputType { - $inputTypeStackLength = count($this->inputTypeStack); - if ($inputTypeStackLength > 1) { - return $this->inputTypeStack[$inputTypeStackLength - 2]; - } + return $this->inputTypeStack[count($this->inputTypeStack) - 2] ?? null; } - /** - * @return FieldArgument|null - */ - public function getArgument() + public function getArgument() : ?FieldArgument { return $this->argument; } @@ -254,13 +270,13 @@ class TypeInfo // any assumptions of a valid schema to ensure runtime types are properly // checked before continuing since TypeInfo is used as part of validation // which occurs before guarantees of schema and document validity. - switch ($node->kind) { - case NodeKind::SELECTION_SET: + switch (true) { + case $node instanceof SelectionSetNode: $namedType = Type::getNamedType($this->getType()); $this->parentTypeStack[] = Type::isCompositeType($namedType) ? $namedType : null; break; - case NodeKind::FIELD: + case $node instanceof FieldNode: $parentType = $this->getParentType(); $fieldDef = null; if ($parentType) { @@ -274,11 +290,11 @@ class TypeInfo $this->typeStack[] = Type::isOutputType($fieldType) ? $fieldType : null; break; - case NodeKind::DIRECTIVE: + case $node instanceof DirectiveNode: $this->directive = $schema->getDirective($node->name->value); break; - case NodeKind::OPERATION_DEFINITION: + case $node instanceof OperationDefinitionNode: $type = null; if ($node->operation === 'query') { $type = $schema->getQueryType(); @@ -290,28 +306,31 @@ class TypeInfo $this->typeStack[] = Type::isOutputType($type) ? $type : null; break; - case NodeKind::INLINE_FRAGMENT: - case NodeKind::FRAGMENT_DEFINITION: + case $node instanceof InlineFragmentNode: + case $node instanceof FragmentDefinitionNode: $typeConditionNode = $node->typeCondition; - $outputType = $typeConditionNode ? self::typeFromAST( - $schema, - $typeConditionNode - ) : Type::getNamedType($this->getType()); + $outputType = $typeConditionNode + ? self::typeFromAST( + $schema, + $typeConditionNode + ) + : Type::getNamedType($this->getType()); $this->typeStack[] = Type::isOutputType($outputType) ? $outputType : null; break; - case NodeKind::VARIABLE_DEFINITION: + case $node instanceof VariableDefinitionNode: $inputType = self::typeFromAST($schema, $node->type); $this->inputTypeStack[] = Type::isInputType($inputType) ? $inputType : null; // push break; - case NodeKind::ARGUMENT: - $fieldOrDirective = $this->getDirective() ?: $this->getFieldDef(); + case $node instanceof ArgumentNode: + $fieldOrDirective = $this->getDirective() ?? $this->getFieldDef(); $argDef = $argType = null; if ($fieldOrDirective) { + /** @var FieldArgument $argDef */ $argDef = Utils::find( $fieldOrDirective->args, - static function ($arg) use ($node) { + static function ($arg) use ($node) : bool { return $arg->name === $node->name->value; } ); @@ -319,35 +338,41 @@ class TypeInfo $argType = $argDef->getType(); } } - $this->argument = $argDef; - $this->inputTypeStack[] = Type::isInputType($argType) ? $argType : null; + $this->argument = $argDef; + $this->defaultValueStack[] = $argDef && $argDef->defaultValueExists() ? $argDef->defaultValue : Utils::undefined(); + $this->inputTypeStack[] = Type::isInputType($argType) ? $argType : null; break; - case NodeKind::LST: - $listType = Type::getNullableType($this->getInputType()); - $itemType = $listType instanceof ListOfType + case $node instanceof ListValueNode: + $type = $this->getInputType(); + $listType = $type === null ? null : Type::getNullableType($type); + $itemType = $listType instanceof ListOfType ? $listType->getWrappedType() : $listType; - $this->inputTypeStack[] = Type::isInputType($itemType) ? $itemType : null; + // List positions never have a default value. + $this->defaultValueStack[] = Utils::undefined(); + $this->inputTypeStack[] = Type::isInputType($itemType) ? $itemType : null; break; - case NodeKind::OBJECT_FIELD: + case $node instanceof ObjectFieldNode: $objectType = Type::getNamedType($this->getInputType()); $fieldType = null; + $inputField = null; $inputFieldType = null; if ($objectType instanceof InputObjectType) { $tmp = $objectType->getFields(); $inputField = $tmp[$node->name->value] ?? null; $inputFieldType = $inputField ? $inputField->getType() : null; } - $this->inputTypeStack[] = Type::isInputType($inputFieldType) ? $inputFieldType : null; + $this->defaultValueStack[] = $inputField && $inputField->defaultValueExists() ? $inputField->defaultValue : Utils::undefined(); + $this->inputTypeStack[] = Type::isInputType($inputFieldType) ? $inputFieldType : null; break; - case NodeKind::ENUM: + case $node instanceof EnumValueNode: $enumType = Type::getNamedType($this->getInputType()); $enumValue = null; if ($enumType instanceof EnumType) { - $enumValue = $enumType->getValue($node->value); + $this->enumValue = $enumType->getValue($node->value); } $this->enumValue = $enumValue; break; @@ -355,37 +380,27 @@ class TypeInfo } /** - * @return Type + * @return (Type & OutputType) | null */ - public function getType() + public function getType() : ?OutputType { - if (! empty($this->typeStack)) { - return $this->typeStack[count($this->typeStack) - 1]; - } - - return null; + return $this->typeStack[count($this->typeStack) - 1] ?? null; } /** - * @return Type + * @return (CompositeType & Type) | null */ - public function getParentType() + public function getParentType() : ?CompositeType { - if (! empty($this->parentTypeStack)) { - return $this->parentTypeStack[count($this->parentTypeStack) - 1]; - } - - return null; + return $this->parentTypeStack[count($this->parentTypeStack) - 1] ?? null; } /** * Not exactly the same as the executor's definition of getFieldDef, in this * statically evaluated environment we do not always have an Object type, * and need to handle Interface and Union types. - * - * @return FieldDefinition */ - private static function getFieldDefinition(Schema $schema, Type $parentType, FieldNode $fieldNode) + private static function getFieldDefinition(Schema $schema, Type $parentType, FieldNode $fieldNode) : ?FieldDefinition { $name = $fieldNode->name->value; $schemaMeta = Introspection::schemaMetaFieldDef(); @@ -401,11 +416,11 @@ class TypeInfo if ($name === $typeNameMeta->name && $parentType instanceof CompositeType) { return $typeNameMeta; } - if ($parentType instanceof ObjectType || - $parentType instanceof InterfaceType) { - $fields = $parentType->getFields(); - return $fields[$name] ?? null; + if ($parentType instanceof ObjectType || + $parentType instanceof InterfaceType + ) { + return $parentType->findField($name); } return null; @@ -414,80 +429,74 @@ class TypeInfo /** * @param NamedTypeNode|ListTypeNode|NonNullTypeNode $inputTypeNode * - * @return Type|null - * * @throws InvariantViolation */ - public static function typeFromAST(Schema $schema, $inputTypeNode) + public static function typeFromAST(Schema $schema, $inputTypeNode) : ?Type { return AST::typeFromAST($schema, $inputTypeNode); } - /** - * @return Directive|null - */ - public function getDirective() + public function getDirective() : ?Directive { return $this->directive; } - /** - * @return FieldDefinition - */ - public function getFieldDef() + public function getFieldDef() : ?FieldDefinition { - if (! empty($this->fieldDefStack)) { - return $this->fieldDefStack[count($this->fieldDefStack) - 1]; - } - - return null; + return $this->fieldDefStack[count($this->fieldDefStack) - 1] ?? null; } /** - * @return InputType + * @return mixed|null */ - public function getInputType() + public function getDefaultValue() { - if (! empty($this->inputTypeStack)) { - return $this->inputTypeStack[count($this->inputTypeStack) - 1]; - } + return $this->defaultValueStack[count($this->defaultValueStack) - 1] ?? null; + } - return null; + /** + * @return (Type & InputType) | null + */ + public function getInputType() : ?InputType + { + return $this->inputTypeStack[count($this->inputTypeStack) - 1] ?? null; } public function leave(Node $node) { - switch ($node->kind) { - case NodeKind::SELECTION_SET: + switch (true) { + case $node instanceof SelectionSetNode: array_pop($this->parentTypeStack); break; - case NodeKind::FIELD: + case $node instanceof FieldNode: array_pop($this->fieldDefStack); array_pop($this->typeStack); break; - case NodeKind::DIRECTIVE: + case $node instanceof DirectiveNode: $this->directive = null; break; - case NodeKind::OPERATION_DEFINITION: - case NodeKind::INLINE_FRAGMENT: - case NodeKind::FRAGMENT_DEFINITION: + case $node instanceof OperationDefinitionNode: + case $node instanceof InlineFragmentNode: + case $node instanceof FragmentDefinitionNode: array_pop($this->typeStack); break; - case NodeKind::VARIABLE_DEFINITION: + case $node instanceof VariableDefinitionNode: array_pop($this->inputTypeStack); break; - case NodeKind::ARGUMENT: + case $node instanceof ArgumentNode: $this->argument = null; + array_pop($this->defaultValueStack); array_pop($this->inputTypeStack); break; - case NodeKind::LST: - case NodeKind::OBJECT_FIELD: + case $node instanceof ListValueNode: + case $node instanceof ObjectFieldNode: + array_pop($this->defaultValueStack); array_pop($this->inputTypeStack); break; - case NodeKind::ENUM: + case $node instanceof EnumValueNode: $this->enumValue = null; break; } diff --git a/vendor/webonyx/graphql-php/src/Utils/Utils.php b/vendor/webonyx/graphql-php/src/Utils/Utils.php index 8dddd65..5811ac0 100644 --- a/vendor/webonyx/graphql-php/src/Utils/Utils.php +++ b/vendor/webonyx/graphql-php/src/Utils/Utils.php @@ -23,7 +23,6 @@ use function array_shift; use function array_slice; use function array_values; use function asort; -use function chr; use function count; use function dechex; use function func_get_args; @@ -59,7 +58,7 @@ class Utils { static $undefined; - return $undefined ?: $undefined = new stdClass(); + return $undefined ?? $undefined = new stdClass(); } /** @@ -104,18 +103,18 @@ class Utils } /** - * @param mixed|Traversable $traversable + * @param iterable $iterable * * @return mixed|null */ - public static function find($traversable, callable $predicate) + public static function find($iterable, callable $predicate) { self::invariant( - is_array($traversable) || $traversable instanceof Traversable, + is_array($iterable) || $iterable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); - foreach ($traversable as $key => $value) { + foreach ($iterable as $key => $value) { if ($predicate($value, $key)) { return $value; } @@ -125,22 +124,22 @@ class Utils } /** - * @param mixed|Traversable $traversable + * @param iterable $iterable * - * @return mixed[] + * @return array * * @throws Exception */ - public static function filter($traversable, callable $predicate) + public static function filter($iterable, callable $predicate) : array { self::invariant( - is_array($traversable) || $traversable instanceof Traversable, + is_array($iterable) || $iterable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); $result = []; $assoc = false; - foreach ($traversable as $key => $value) { + foreach ($iterable as $key => $value) { if (! $assoc && ! is_int($key)) { $assoc = true; } @@ -155,21 +154,21 @@ class Utils } /** - * @param mixed|Traversable $traversable + * @param iterable $iterable * - * @return mixed[] + * @return array * * @throws Exception */ - public static function map($traversable, callable $fn) + public static function map($iterable, callable $fn) : array { self::invariant( - is_array($traversable) || $traversable instanceof Traversable, + is_array($iterable) || $iterable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); $map = []; - foreach ($traversable as $key => $value) { + foreach ($iterable as $key => $value) { $map[$key] = $fn($value, $key); } @@ -177,21 +176,21 @@ class Utils } /** - * @param mixed|Traversable $traversable + * @param iterable $iterable * - * @return mixed[] + * @return array * * @throws Exception */ - public static function mapKeyValue($traversable, callable $fn) + public static function mapKeyValue($iterable, callable $fn) : array { self::invariant( - is_array($traversable) || $traversable instanceof Traversable, + is_array($iterable) || $iterable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); $map = []; - foreach ($traversable as $key => $value) { + foreach ($iterable as $key => $value) { [$newKey, $newValue] = $fn($value, $key); $map[$newKey] = $newValue; } @@ -200,21 +199,21 @@ class Utils } /** - * @param mixed|Traversable $traversable + * @param iterable $iterable * - * @return mixed[] + * @return array * * @throws Exception */ - public static function keyMap($traversable, callable $keyFn) + public static function keyMap($iterable, callable $keyFn) : array { self::invariant( - is_array($traversable) || $traversable instanceof Traversable, + is_array($iterable) || $iterable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); $map = []; - foreach ($traversable as $key => $value) { + foreach ($iterable as $key => $value) { $newKey = $keyFn($value, $key); if (! is_scalar($newKey)) { continue; @@ -226,20 +225,23 @@ class Utils return $map; } - public static function each($traversable, callable $fn) + /** + * @param iterable $iterable + */ + public static function each($iterable, callable $fn) : void { self::invariant( - is_array($traversable) || $traversable instanceof Traversable, + is_array($iterable) || $iterable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); - foreach ($traversable as $key => $item) { + foreach ($iterable as $key => $item) { $fn($item, $key); } } /** - * Splits original traversable to several arrays with keys equal to $keyFn return + * Splits original iterable to several arrays with keys equal to $keyFn return * * E.g. Utils::groupBy([1, 2, 3, 4, 5], function($value) {return $value % 3}) will output: * [ @@ -250,19 +252,19 @@ class Utils * * $keyFn is also allowed to return array of keys. Then value will be added to all arrays with given keys * - * @param mixed[]|Traversable $traversable + * @param iterable $iterable * - * @return mixed[] + * @return array> */ - public static function groupBy($traversable, callable $keyFn) + public static function groupBy($iterable, callable $keyFn) : array { self::invariant( - is_array($traversable) || $traversable instanceof Traversable, + is_array($iterable) || $iterable instanceof Traversable, __METHOD__ . ' expects array or Traversable' ); $grouped = []; - foreach ($traversable as $key => $value) { + foreach ($iterable as $key => $value) { $newKeys = (array) $keyFn($value, $key); foreach ($newKeys as $newKey) { $grouped[$newKey][] = $value; @@ -273,14 +275,14 @@ class Utils } /** - * @param mixed[]|Traversable $traversable + * @param iterable $iterable * - * @return mixed[][] + * @return array */ - public static function keyValMap($traversable, callable $keyFn, callable $valFn) + public static function keyValMap($iterable, callable $keyFn, callable $valFn) : array { $map = []; - foreach ($traversable as $item) { + foreach ($iterable as $item) { $map[$keyFn($item)] = $valFn($item); } @@ -288,13 +290,11 @@ class Utils } /** - * @param mixed[] $traversable - * - * @return bool + * @param iterable $iterable */ - public static function every($traversable, callable $predicate) + public static function every($iterable, callable $predicate) : bool { - foreach ($traversable as $key => $value) { + foreach ($iterable as $key => $value) { if (! $predicate($value, $key)) { return false; } @@ -303,6 +303,20 @@ class Utils return true; } + /** + * @param iterable $iterable + */ + public static function some($iterable, callable $predicate) : bool + { + foreach ($iterable as $key => $value) { + if ($predicate($value, $key)) { + return true; + } + } + + return false; + } + /** * @param bool $test * @param string $message @@ -426,9 +440,6 @@ class Utils */ public static function chr($ord, $encoding = 'UTF-8') { - if ($ord <= 255) { - return chr($ord); - } if ($encoding === 'UCS-4BE') { return pack('N', $ord); } @@ -549,7 +560,7 @@ class Utils { return static function () use ($fn, &$errors) { // Catch custom errors (to report them in query results) - set_error_handler(static function ($severity, $message, $file, $line) use (&$errors) { + set_error_handler(static function ($severity, $message, $file, $line) use (&$errors) : void { $errors[] = new ErrorException($message, 0, $severity, $file, $line); }); @@ -569,7 +580,7 @@ class Utils public static function quotedOrList(array $items) { $items = array_map( - static function ($item) { + static function ($item) : string { return sprintf('"%s"', $item); }, $items @@ -598,7 +609,7 @@ class Utils return array_reduce( range(1, $selectedLength - 1), - static function ($list, $index) use ($selected, $selectedLength) { + static function ($list, $index) use ($selected, $selectedLength) : string { return $list . ($selectedLength > 2 ? ', ' : ' ') . ($index === $selectedLength - 1 ? 'or ' : '') . @@ -624,7 +635,7 @@ class Utils public static function suggestionList($input, array $options) { $optionsByDistance = []; - $inputThreshold = mb_strlen($input) / 2; + $threshold = mb_strlen($input) * 0.4 + 1; foreach ($options as $option) { if ($input === $option) { $distance = 0; @@ -633,7 +644,6 @@ class Utils ? 1 : levenshtein($input, $option)); } - $threshold = max($inputThreshold, mb_strlen($option) / 2, 1); if ($distance > $threshold) { continue; } diff --git a/vendor/webonyx/graphql-php/src/Utils/Value.php b/vendor/webonyx/graphql-php/src/Utils/Value.php index a3f8805..636abe2 100644 --- a/vendor/webonyx/graphql-php/src/Utils/Value.php +++ b/vendor/webonyx/graphql-php/src/Utils/Value.php @@ -36,7 +36,8 @@ class Value /** * Given a type and any value, return a runtime value coerced to match the type. * - * @param mixed[] $path + * @param ScalarType|EnumType|InputObjectType|ListOfType|NonNull $type + * @param mixed[] $path */ public static function coerceValue($value, InputType $type, $blameNode = null, ?array $path = null) { @@ -65,16 +66,6 @@ class Value // the original error. try { return self::ofValue($type->parseValue($value)); - } catch (Exception $error) { - return self::ofErrors([ - self::coercionError( - sprintf('Expected type %s', $type->name), - $blameNode, - $path, - $error->getMessage(), - $error - ), - ]); } catch (Throwable $error) { return self::ofErrors([ self::coercionError( @@ -99,7 +90,7 @@ class Value $suggestions = Utils::suggestionList( Utils::printSafe($value), array_map( - static function ($enumValue) { + static function ($enumValue) : string { return $enumValue->name; }, $type->getValues() @@ -190,7 +181,7 @@ class Value sprintf( 'Field %s of required type %s was not provided', $fieldPath, - $field->type->toString() + $field->getType()->toString() ), $blameNode ) @@ -258,7 +249,7 @@ class Value ($subMessage ? '; ' . $subMessage : '.'), $blameNode, null, - null, + [], null, $originalError ); diff --git a/vendor/webonyx/graphql-php/src/Validator/ASTValidationContext.php b/vendor/webonyx/graphql-php/src/Validator/ASTValidationContext.php new file mode 100644 index 0000000..0b1f1bc --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Validator/ASTValidationContext.php @@ -0,0 +1,54 @@ +ast = $ast; + $this->schema = $schema; + $this->errors = []; + } + + public function reportError(Error $error) + { + $this->errors[] = $error; + } + + /** + * @return Error[] + */ + public function getErrors() + { + return $this->errors; + } + + /** + * @return DocumentNode + */ + public function getDocument() + { + return $this->ast; + } + + public function getSchema() : ?Schema + { + return $this->schema; + } +} diff --git a/vendor/webonyx/graphql-php/src/Validator/DocumentValidator.php b/vendor/webonyx/graphql-php/src/Validator/DocumentValidator.php index 0364839..98a5871 100644 --- a/vendor/webonyx/graphql-php/src/Validator/DocumentValidator.php +++ b/vendor/webonyx/graphql-php/src/Validator/DocumentValidator.php @@ -28,12 +28,13 @@ use GraphQL\Validator\Rules\NoUnusedFragments; use GraphQL\Validator\Rules\NoUnusedVariables; use GraphQL\Validator\Rules\OverlappingFieldsCanBeMerged; use GraphQL\Validator\Rules\PossibleFragmentSpreads; -use GraphQL\Validator\Rules\ProvidedNonNullArguments; +use GraphQL\Validator\Rules\ProvidedRequiredArguments; use GraphQL\Validator\Rules\ProvidedRequiredArgumentsOnDirectives; use GraphQL\Validator\Rules\QueryComplexity; use GraphQL\Validator\Rules\QueryDepth; use GraphQL\Validator\Rules\QuerySecurityRule; use GraphQL\Validator\Rules\ScalarLeafs; +use GraphQL\Validator\Rules\SingleFieldSubscription; use GraphQL\Validator\Rules\UniqueArgumentNames; use GraphQL\Validator\Rules\UniqueDirectivesPerLocation; use GraphQL\Validator\Rules\UniqueFragmentNames; @@ -43,14 +44,11 @@ use GraphQL\Validator\Rules\UniqueVariableNames; use GraphQL\Validator\Rules\ValidationRule; use GraphQL\Validator\Rules\ValuesOfCorrectType; use GraphQL\Validator\Rules\VariablesAreInputTypes; -use GraphQL\Validator\Rules\VariablesDefaultValueAllowed; use GraphQL\Validator\Rules\VariablesInAllowedPosition; use Throwable; use function array_filter; -use function array_map; use function array_merge; use function count; -use function implode; use function is_array; use function sprintf; @@ -113,7 +111,7 @@ class DocumentValidator return []; } - $typeInfo = $typeInfo ?: new TypeInfo($schema); + $typeInfo = $typeInfo ?? new TypeInfo($schema); return static::visitUsingRules($schema, $typeInfo, $ast, $rules); } @@ -142,6 +140,7 @@ class DocumentValidator ExecutableDefinitions::class => new ExecutableDefinitions(), UniqueOperationNames::class => new UniqueOperationNames(), LoneAnonymousOperation::class => new LoneAnonymousOperation(), + SingleFieldSubscription::class => new SingleFieldSubscription(), KnownTypeNames::class => new KnownTypeNames(), FragmentsOnCompositeTypes::class => new FragmentsOnCompositeTypes(), VariablesAreInputTypes::class => new VariablesAreInputTypes(), @@ -160,8 +159,7 @@ class DocumentValidator KnownArgumentNames::class => new KnownArgumentNames(), UniqueArgumentNames::class => new UniqueArgumentNames(), ValuesOfCorrectType::class => new ValuesOfCorrectType(), - ProvidedNonNullArguments::class => new ProvidedNonNullArguments(), - VariablesDefaultValueAllowed::class => new VariablesDefaultValueAllowed(), + ProvidedRequiredArguments::class => new ProvidedRequiredArguments(), VariablesInAllowedPosition::class => new VariablesInAllowedPosition(), OverlappingFieldsCanBeMerged::class => new OverlappingFieldsCanBeMerged(), UniqueInputFieldNames::class => new UniqueInputFieldNames(), @@ -268,11 +266,11 @@ class DocumentValidator return is_array($value) ? count(array_filter( $value, - static function ($item) { - return $item instanceof Exception || $item instanceof Throwable; + static function ($item) : bool { + return $item instanceof Throwable; } )) === count($value) - : ($value instanceof Exception || $value instanceof Throwable); + : $value instanceof Throwable; } public static function append(&$arr, $items) @@ -309,18 +307,55 @@ class DocumentValidator return $context->getErrors(); } - public static function assertValidSDLExtension(DocumentNode $documentAST, Schema $schema) + /** + * @param ValidationRule[]|null $rules + * + * @return Error[] + * + * @throws Exception + */ + public static function validateSDL( + DocumentNode $documentAST, + ?Schema $schemaToExtend = null, + ?array $rules = null + ) { + $usedRules = $rules ?? self::sdlRules(); + $context = new SDLValidationContext($documentAST, $schemaToExtend); + $visitors = []; + foreach ($usedRules as $rule) { + $visitors[] = $rule->getSDLVisitor($context); + } + Visitor::visit($documentAST, Visitor::visitInParallel($visitors)); + + return $context->getErrors(); + } + + public static function assertValidSDL(DocumentNode $documentAST) { - $errors = self::visitUsingRules($schema, new TypeInfo($schema), $documentAST, self::sdlRules()); - if (count($errors) !== 0) { - throw new Error( - implode( - "\n\n", - array_map(static function (Error $error) : string { - return $error->message; - }, $errors) - ) - ); + $errors = self::validateSDL($documentAST); + if (count($errors) > 0) { + throw new Error(self::combineErrorMessages($errors)); } } + + public static function assertValidSDLExtension(DocumentNode $documentAST, Schema $schema) + { + $errors = self::validateSDL($documentAST, $schema); + if (count($errors) > 0) { + throw new Error(self::combineErrorMessages($errors)); + } + } + + /** + * @param Error[] $errors + */ + private static function combineErrorMessages(array $errors) : string + { + $str = ''; + foreach ($errors as $error) { + $str .= ($error->getMessage() . "\n\n"); + } + + return $str; + } } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/DisableIntrospection.php b/vendor/webonyx/graphql-php/src/Validator/Rules/DisableIntrospection.php index 6e0efab..01a9318 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/DisableIntrospection.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/DisableIntrospection.php @@ -31,7 +31,7 @@ class DisableIntrospection extends QuerySecurityRule return $this->invokeIfNeeded( $context, [ - NodeKind::FIELD => static function (FieldNode $node) use ($context) { + NodeKind::FIELD => static function (FieldNode $node) use ($context) : void { if ($node->name->value !== '__type' && $node->name->value !== '__schema') { return; } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/ExecutableDefinitions.php b/vendor/webonyx/graphql-php/src/Validator/Rules/ExecutableDefinitions.php index e626861..5966df7 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/ExecutableDefinitions.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/ExecutableDefinitions.php @@ -6,11 +6,11 @@ namespace GraphQL\Validator\Rules; use GraphQL\Error\Error; use GraphQL\Language\AST\DocumentNode; -use GraphQL\Language\AST\FragmentDefinitionNode; -use GraphQL\Language\AST\Node; +use GraphQL\Language\AST\ExecutableDefinitionNode; use GraphQL\Language\AST\NodeKind; -use GraphQL\Language\AST\OperationDefinitionNode; +use GraphQL\Language\AST\TypeSystemDefinitionNode; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Validator\ValidationContext; use function sprintf; @@ -25,12 +25,10 @@ class ExecutableDefinitions extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::DOCUMENT => static function (DocumentNode $node) use ($context) { - /** @var Node $definition */ + NodeKind::DOCUMENT => static function (DocumentNode $node) use ($context) : VisitorOperation { + /** @var ExecutableDefinitionNode|TypeSystemDefinitionNode $definition */ foreach ($node->definitions as $definition) { - if ($definition instanceof OperationDefinitionNode || - $definition instanceof FragmentDefinitionNode - ) { + if ($definition instanceof ExecutableDefinitionNode) { continue; } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/FieldsOnCorrectType.php b/vendor/webonyx/graphql-php/src/Validator/Rules/FieldsOnCorrectType.php index 1053255..3d7013c 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/FieldsOnCorrectType.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/FieldsOnCorrectType.php @@ -16,6 +16,7 @@ use GraphQL\Validator\ValidationContext; use function array_keys; use function array_merge; use function arsort; +use function count; use function sprintf; class FieldsOnCorrectType extends ValidationRule @@ -23,7 +24,7 @@ class FieldsOnCorrectType extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::FIELD => function (FieldNode $node) use ($context) { + NodeKind::FIELD => function (FieldNode $node) use ($context) : void { $type = $context->getParentType(); if (! $type) { return; @@ -84,15 +85,13 @@ class FieldsOnCorrectType extends ValidationRule $interfaceUsageCount = []; foreach ($schema->getPossibleTypes($type) as $possibleType) { - $fields = $possibleType->getFields(); - if (! isset($fields[$fieldName])) { + if (! $possibleType->hasField($fieldName)) { continue; } // This object type defines this field. $suggestedObjectTypes[] = $possibleType->name; foreach ($possibleType->getInterfaces() as $possibleInterface) { - $fields = $possibleInterface->getFields(); - if (! isset($fields[$fieldName])) { + if (! $possibleInterface->hasField($fieldName)) { continue; } // This interface type defines this field. @@ -127,7 +126,7 @@ class FieldsOnCorrectType extends ValidationRule private function getSuggestedFieldNames(Schema $schema, $type, $fieldName) { if ($type instanceof ObjectType || $type instanceof InterfaceType) { - $possibleFieldNames = array_keys($type->getFields()); + $possibleFieldNames = $type->getFieldNames(); return Utils::suggestionList($fieldName, $possibleFieldNames); } @@ -156,7 +155,7 @@ class FieldsOnCorrectType extends ValidationRule $suggestions = Utils::quotedOrList($suggestedTypeNames); $message .= sprintf(' Did you mean to use an inline fragment on %s?', $suggestions); - } elseif (! empty($suggestedFieldNames)) { + } elseif (count($suggestedFieldNames) > 0) { $suggestions = Utils::quotedOrList($suggestedFieldNames); $message .= sprintf(' Did you mean %s?', $suggestions); diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/FragmentsOnCompositeTypes.php b/vendor/webonyx/graphql-php/src/Validator/Rules/FragmentsOnCompositeTypes.php index c5ca807..db72a05 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/FragmentsOnCompositeTypes.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/FragmentsOnCompositeTypes.php @@ -19,7 +19,7 @@ class FragmentsOnCompositeTypes extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::INLINE_FRAGMENT => static function (InlineFragmentNode $node) use ($context) { + NodeKind::INLINE_FRAGMENT => static function (InlineFragmentNode $node) use ($context) : void { if (! $node->typeCondition) { return; } @@ -34,7 +34,7 @@ class FragmentsOnCompositeTypes extends ValidationRule [$node->typeCondition] )); }, - NodeKind::FRAGMENT_DEFINITION => static function (FragmentDefinitionNode $node) use ($context) { + NodeKind::FRAGMENT_DEFINITION => static function (FragmentDefinitionNode $node) use ($context) : void { $type = TypeInfo::typeFromAST($context->getSchema(), $node->typeCondition); if (! $type || Type::isCompositeType($type)) { diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNames.php index 96fd800..d301379 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNames.php @@ -6,9 +6,11 @@ namespace GraphQL\Validator\Rules; use GraphQL\Error\Error; use GraphQL\Language\AST\ArgumentNode; +use GraphQL\Language\AST\DirectiveNode; +use GraphQL\Language\AST\FieldNode; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeKind; -use GraphQL\Language\AST\NodeList; +use GraphQL\Type\Definition\Type; use GraphQL\Utils\Utils; use GraphQL\Validator\ValidationContext; use function array_map; @@ -25,58 +27,40 @@ class KnownArgumentNames extends ValidationRule { public function getVisitor(ValidationContext $context) { - return [ - NodeKind::ARGUMENT => static function (ArgumentNode $node, $key, $parent, $path, $ancestors) use ($context) { - /** @var NodeList|Node[] $ancestors */ + $knownArgumentNamesOnDirectives = new KnownArgumentNamesOnDirectives(); + + return $knownArgumentNamesOnDirectives->getVisitor($context) + [ + NodeKind::ARGUMENT => static function (ArgumentNode $node) use ($context) : void { $argDef = $context->getArgument(); if ($argDef !== null) { return; } - $argumentOf = $ancestors[count($ancestors) - 1]; - if ($argumentOf->kind === NodeKind::FIELD) { - $fieldDef = $context->getFieldDef(); - $parentType = $context->getParentType(); - if ($fieldDef && $parentType) { - $context->reportError(new Error( - self::unknownArgMessage( - $node->name->value, - $fieldDef->name, - $parentType->name, - Utils::suggestionList( - $node->name->value, - array_map( - static function ($arg) { - return $arg->name; - }, - $fieldDef->args - ) - ) - ), - [$node] - )); - } - } elseif ($argumentOf->kind === NodeKind::DIRECTIVE) { - $directive = $context->getDirective(); - if ($directive) { - $context->reportError(new Error( - self::unknownDirectiveArgMessage( - $node->name->value, - $directive->name, - Utils::suggestionList( - $node->name->value, - array_map( - static function ($arg) { - return $arg->name; - }, - $directive->args - ) - ) - ), - [$node] - )); - } + $fieldDef = $context->getFieldDef(); + $parentType = $context->getParentType(); + if ($fieldDef === null || ! ($parentType instanceof Type)) { + return; } + + $context->reportError(new Error( + self::unknownArgMessage( + $node->name->value, + $fieldDef->name, + $parentType->name, + Utils::suggestionList( + $node->name->value, + array_map( + static function ($arg) : string { + return $arg->name; + }, + $fieldDef->args + ) + ) + ), + [$node] + )); + + return; }, ]; } @@ -87,20 +71,7 @@ class KnownArgumentNames extends ValidationRule public static function unknownArgMessage($argName, $fieldName, $typeName, array $suggestedArgs) { $message = sprintf('Unknown argument "%s" on field "%s" of type "%s".', $argName, $fieldName, $typeName); - if (! empty($suggestedArgs)) { - $message .= sprintf(' Did you mean %s?', Utils::quotedOrList($suggestedArgs)); - } - - return $message; - } - - /** - * @param string[] $suggestedArgs - */ - public static function unknownDirectiveArgMessage($argName, $directiveName, array $suggestedArgs) - { - $message = sprintf('Unknown argument "%s" on directive "@%s".', $argName, $directiveName); - if (! empty($suggestedArgs)) { + if (isset($suggestedArgs[0])) { $message .= sprintf(' Did you mean %s?', Utils::quotedOrList($suggestedArgs)); } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNamesOnDirectives.php b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNamesOnDirectives.php index a013820..bdde5d3 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNamesOnDirectives.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownArgumentNamesOnDirectives.php @@ -9,13 +9,17 @@ use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DirectiveNode; use GraphQL\Language\AST\InputValueDefinitionNode; use GraphQL\Language\AST\NodeKind; -use GraphQL\Language\AST\NodeList; +use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\FieldArgument; +use GraphQL\Utils\Utils; +use GraphQL\Validator\ASTValidationContext; +use GraphQL\Validator\SDLValidationContext; use GraphQL\Validator\ValidationContext; use function array_map; use function in_array; -use function iterator_to_array; +use function sprintf; /** * Known argument names on directives @@ -25,12 +29,30 @@ use function iterator_to_array; */ class KnownArgumentNamesOnDirectives extends ValidationRule { - protected static function unknownDirectiveArgMessage(string $argName, string $directionName) + /** + * @param string[] $suggestedArgs + */ + public static function unknownDirectiveArgMessage($argName, $directiveName, array $suggestedArgs) { - return 'Unknown argument "' . $argName . '" on directive "@' . $directionName . '".'; + $message = sprintf('Unknown argument "%s" on directive "@%s".', $argName, $directiveName); + if (isset($suggestedArgs[0])) { + $message .= sprintf(' Did you mean %s?', Utils::quotedOrList($suggestedArgs)); + } + + return $message; + } + + public function getSDLVisitor(SDLValidationContext $context) + { + return $this->getASTVisitor($context); } public function getVisitor(ValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getASTVisitor(ASTValidationContext $context) { $directiveArgs = []; $schema = $context->getSchema(); @@ -53,27 +75,24 @@ class KnownArgumentNamesOnDirectives extends ValidationRule $name = $def->name->value; if ($def->arguments !== null) { - $arguments = $def->arguments; - - if ($arguments instanceof NodeList) { - $arguments = iterator_to_array($arguments->getIterator()); - } - - $directiveArgs[$name] = array_map(static function (InputValueDefinitionNode $arg) : string { - return $arg->name->value; - }, $arguments); + $directiveArgs[$name] = Utils::map( + $def->arguments ?? [], + static function (InputValueDefinitionNode $arg) : string { + return $arg->name->value; + } + ); } else { $directiveArgs[$name] = []; } } return [ - NodeKind::DIRECTIVE => static function (DirectiveNode $directiveNode) use ($directiveArgs, $context) { + NodeKind::DIRECTIVE => static function (DirectiveNode $directiveNode) use ($directiveArgs, $context) : VisitorOperation { $directiveName = $directiveNode->name->value; $knownArgs = $directiveArgs[$directiveName] ?? null; - if ($directiveNode->arguments === null || ! $knownArgs) { - return; + if ($directiveNode->arguments === null || $knownArgs === null) { + return Visitor::skipNode(); } foreach ($directiveNode->arguments as $argNode) { @@ -82,11 +101,14 @@ class KnownArgumentNamesOnDirectives extends ValidationRule continue; } + $suggestions = Utils::suggestionList($argName, $knownArgs); $context->reportError(new Error( - self::unknownDirectiveArgMessage($argName, $directiveName), + self::unknownDirectiveArgMessage($argName, $directiveName, $suggestions), [$argNode] )); } + + return Visitor::skipNode(); }, ]; } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownDirectives.php b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownDirectives.php index 927ce26..758e861 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownDirectives.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownDirectives.php @@ -4,27 +4,67 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; +use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DirectiveNode; +use GraphQL\Language\AST\EnumTypeDefinitionNode; +use GraphQL\Language\AST\EnumTypeExtensionNode; +use GraphQL\Language\AST\EnumValueDefinitionNode; +use GraphQL\Language\AST\FieldDefinitionNode; +use GraphQL\Language\AST\FieldNode; +use GraphQL\Language\AST\FragmentDefinitionNode; +use GraphQL\Language\AST\FragmentSpreadNode; +use GraphQL\Language\AST\InlineFragmentNode; use GraphQL\Language\AST\InputObjectTypeDefinitionNode; +use GraphQL\Language\AST\InputObjectTypeExtensionNode; +use GraphQL\Language\AST\InputValueDefinitionNode; +use GraphQL\Language\AST\InterfaceTypeDefinitionNode; +use GraphQL\Language\AST\InterfaceTypeExtensionNode; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\NodeList; +use GraphQL\Language\AST\ObjectTypeDefinitionNode; +use GraphQL\Language\AST\ObjectTypeExtensionNode; +use GraphQL\Language\AST\OperationDefinitionNode; +use GraphQL\Language\AST\ScalarTypeDefinitionNode; +use GraphQL\Language\AST\ScalarTypeExtensionNode; +use GraphQL\Language\AST\SchemaDefinitionNode; +use GraphQL\Language\AST\SchemaTypeExtensionNode; +use GraphQL\Language\AST\UnionTypeDefinitionNode; +use GraphQL\Language\AST\UnionTypeExtensionNode; +use GraphQL\Language\AST\VariableDefinitionNode; use GraphQL\Language\DirectiveLocation; +use GraphQL\Type\Definition\Directive; +use GraphQL\Utils\Utils; +use GraphQL\Validator\ASTValidationContext; +use GraphQL\Validator\SDLValidationContext; use GraphQL\Validator\ValidationContext; use function array_map; use function count; +use function get_class; use function in_array; use function sprintf; class KnownDirectives extends ValidationRule { public function getVisitor(ValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getSDLVisitor(SDLValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getASTVisitor(ASTValidationContext $context) { $locationsMap = []; $schema = $context->getSchema(); - $definedDirectives = $schema->getDirectives(); + $definedDirectives = $schema + ? $schema->getDirectives() + : Directive::getInternalDirectives(); foreach ($definedDirectives as $directive) { $locationsMap[$directive->name] = $directive->locations; @@ -37,11 +77,11 @@ class KnownDirectives extends ValidationRule continue; } - $locationsMap[$def->name->value] = array_map( - static function ($name) { + $locationsMap[$def->name->value] = Utils::map( + $def->locations, + static function ($name) : string { return $name->value; - }, - $def->locations + } ); } @@ -55,7 +95,7 @@ class KnownDirectives extends ValidationRule ) use ( $context, $locationsMap - ) { + ) : void { $name = $node->name->value; $locations = $locationsMap[$name] ?? null; @@ -96,8 +136,8 @@ class KnownDirectives extends ValidationRule private function getDirectiveLocationForASTPath(array $ancestors) { $appliedTo = $ancestors[count($ancestors) - 1]; - switch ($appliedTo->kind) { - case NodeKind::OPERATION_DEFINITION: + switch (true) { + case $appliedTo instanceof OperationDefinitionNode: switch ($appliedTo->operation) { case 'query': return DirectiveLocation::QUERY; @@ -107,46 +147,50 @@ class KnownDirectives extends ValidationRule return DirectiveLocation::SUBSCRIPTION; } break; - case NodeKind::FIELD: + case $appliedTo instanceof FieldNode: return DirectiveLocation::FIELD; - case NodeKind::FRAGMENT_SPREAD: + case $appliedTo instanceof FragmentSpreadNode: return DirectiveLocation::FRAGMENT_SPREAD; - case NodeKind::INLINE_FRAGMENT: + case $appliedTo instanceof InlineFragmentNode: return DirectiveLocation::INLINE_FRAGMENT; - case NodeKind::FRAGMENT_DEFINITION: + case $appliedTo instanceof FragmentDefinitionNode: return DirectiveLocation::FRAGMENT_DEFINITION; - case NodeKind::SCHEMA_DEFINITION: - case NodeKind::SCHEMA_EXTENSION: + case $appliedTo instanceof VariableDefinitionNode: + return DirectiveLocation::VARIABLE_DEFINITION; + case $appliedTo instanceof SchemaDefinitionNode: + case $appliedTo instanceof SchemaTypeExtensionNode: return DirectiveLocation::SCHEMA; - case NodeKind::SCALAR_TYPE_DEFINITION: - case NodeKind::SCALAR_TYPE_EXTENSION: + case $appliedTo instanceof ScalarTypeDefinitionNode: + case $appliedTo instanceof ScalarTypeExtensionNode: return DirectiveLocation::SCALAR; - case NodeKind::OBJECT_TYPE_DEFINITION: - case NodeKind::OBJECT_TYPE_EXTENSION: + case $appliedTo instanceof ObjectTypeDefinitionNode: + case $appliedTo instanceof ObjectTypeExtensionNode: return DirectiveLocation::OBJECT; - case NodeKind::FIELD_DEFINITION: + case $appliedTo instanceof FieldDefinitionNode: return DirectiveLocation::FIELD_DEFINITION; - case NodeKind::INTERFACE_TYPE_DEFINITION: - case NodeKind::INTERFACE_TYPE_EXTENSION: + case $appliedTo instanceof InterfaceTypeDefinitionNode: + case $appliedTo instanceof InterfaceTypeExtensionNode: return DirectiveLocation::IFACE; - case NodeKind::UNION_TYPE_DEFINITION: - case NodeKind::UNION_TYPE_EXTENSION: + case $appliedTo instanceof UnionTypeDefinitionNode: + case $appliedTo instanceof UnionTypeExtensionNode: return DirectiveLocation::UNION; - case NodeKind::ENUM_TYPE_DEFINITION: - case NodeKind::ENUM_TYPE_EXTENSION: + case $appliedTo instanceof EnumTypeDefinitionNode: + case $appliedTo instanceof EnumTypeExtensionNode: return DirectiveLocation::ENUM; - case NodeKind::ENUM_VALUE_DEFINITION: + case $appliedTo instanceof EnumValueDefinitionNode: return DirectiveLocation::ENUM_VALUE; - case NodeKind::INPUT_OBJECT_TYPE_DEFINITION: - case NodeKind::INPUT_OBJECT_TYPE_EXTENSION: + case $appliedTo instanceof InputObjectTypeDefinitionNode: + case $appliedTo instanceof InputObjectTypeExtensionNode: return DirectiveLocation::INPUT_OBJECT; - case NodeKind::INPUT_VALUE_DEFINITION: + case $appliedTo instanceof InputValueDefinitionNode: $parentNode = $ancestors[count($ancestors) - 3]; return $parentNode instanceof InputObjectTypeDefinitionNode ? DirectiveLocation::INPUT_FIELD_DEFINITION : DirectiveLocation::ARGUMENT_DEFINITION; } + + throw new Exception('Unknown directive location: ' . get_class($appliedTo)); } public static function misplacedDirectiveMessage($directiveName, $location) diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownFragmentNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownFragmentNames.php index e26e233..052686f 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownFragmentNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownFragmentNames.php @@ -15,7 +15,7 @@ class KnownFragmentNames extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::FRAGMENT_SPREAD => static function (FragmentSpreadNode $node) use ($context) { + NodeKind::FRAGMENT_SPREAD => static function (FragmentSpreadNode $node) use ($context) : void { $fragmentName = $node->name->value; $fragment = $context->getFragment($fragmentName); if ($fragment) { diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownTypeNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownTypeNames.php index 9abaf0a..b852f52 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/KnownTypeNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/KnownTypeNames.php @@ -8,9 +8,11 @@ use GraphQL\Error\Error; use GraphQL\Language\AST\NamedTypeNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Utils\Utils; use GraphQL\Validator\ValidationContext; use function array_keys; +use function count; use function sprintf; /** @@ -23,7 +25,7 @@ class KnownTypeNames extends ValidationRule { public function getVisitor(ValidationContext $context) { - $skip = static function () { + $skip = static function () : VisitorOperation { return Visitor::skipNode(); }; @@ -35,7 +37,7 @@ class KnownTypeNames extends ValidationRule NodeKind::INTERFACE_TYPE_DEFINITION => $skip, NodeKind::UNION_TYPE_DEFINITION => $skip, NodeKind::INPUT_OBJECT_TYPE_DEFINITION => $skip, - NodeKind::NAMED_TYPE => static function (NamedTypeNode $node) use ($context) { + NodeKind::NAMED_TYPE => static function (NamedTypeNode $node) use ($context) : void { $schema = $context->getSchema(); $typeName = $node->name->value; $type = $schema->getType($typeName); @@ -61,7 +63,7 @@ class KnownTypeNames extends ValidationRule public static function unknownTypeMessage($type, array $suggestedTypes) { $message = sprintf('Unknown type "%s".', $type); - if (! empty($suggestedTypes)) { + if (count($suggestedTypes) > 0) { $suggestions = Utils::quotedOrList($suggestedTypes); $message .= sprintf(' Did you mean %s?', $suggestions); diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/LoneAnonymousOperation.php b/vendor/webonyx/graphql-php/src/Validator/Rules/LoneAnonymousOperation.php index 40ff821..facc895 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/LoneAnonymousOperation.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/LoneAnonymousOperation.php @@ -26,11 +26,11 @@ class LoneAnonymousOperation extends ValidationRule $operationCount = 0; return [ - NodeKind::DOCUMENT => static function (DocumentNode $node) use (&$operationCount) { + NodeKind::DOCUMENT => static function (DocumentNode $node) use (&$operationCount) : void { $tmp = Utils::filter( $node->definitions, - static function (Node $definition) { - return $definition->kind === NodeKind::OPERATION_DEFINITION; + static function (Node $definition) : bool { + return $definition instanceof OperationDefinitionNode; } ); @@ -39,8 +39,8 @@ class LoneAnonymousOperation extends ValidationRule NodeKind::OPERATION_DEFINITION => static function (OperationDefinitionNode $node) use ( &$operationCount, $context - ) { - if ($node->name || $operationCount <= 1) { + ) : void { + if ($node->name !== null || $operationCount <= 1) { return; } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/LoneSchemaDefinition.php b/vendor/webonyx/graphql-php/src/Validator/Rules/LoneSchemaDefinition.php index 1a8da67..4ece976 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/LoneSchemaDefinition.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/LoneSchemaDefinition.php @@ -7,7 +7,7 @@ namespace GraphQL\Validator\Rules; use GraphQL\Error\Error; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\SchemaDefinitionNode; -use GraphQL\Validator\ValidationContext; +use GraphQL\Validator\SDLValidationContext; /** * Lone Schema definition @@ -16,28 +16,40 @@ use GraphQL\Validator\ValidationContext; */ class LoneSchemaDefinition extends ValidationRule { - public function getVisitor(ValidationContext $context) + public static function schemaDefinitionNotAloneMessage() + { + return 'Must provide only one schema definition.'; + } + + public static function canNotDefineSchemaWithinExtensionMessage() + { + return 'Cannot define a new schema within a schema extension.'; + } + + public function getSDLVisitor(SDLValidationContext $context) { $oldSchema = $context->getSchema(); - $alreadyDefined = $oldSchema !== null ? ( - $oldSchema->getAstNode() || - $oldSchema->getQueryType() || - $oldSchema->getMutationType() || - $oldSchema->getSubscriptionType() - ) : false; + $alreadyDefined = $oldSchema !== null + ? ( + $oldSchema->getAstNode() !== null || + $oldSchema->getQueryType() !== null || + $oldSchema->getMutationType() !== null || + $oldSchema->getSubscriptionType() !== null + ) + : false; $schemaDefinitionsCount = 0; return [ - NodeKind::SCHEMA_DEFINITION => static function (SchemaDefinitionNode $node) use ($alreadyDefined, $context, &$schemaDefinitionsCount) { + NodeKind::SCHEMA_DEFINITION => static function (SchemaDefinitionNode $node) use ($alreadyDefined, $context, &$schemaDefinitionsCount) : void { if ($alreadyDefined !== false) { - $context->reportError(new Error('Cannot define a new schema within a schema extension.', $node)); + $context->reportError(new Error(self::canNotDefineSchemaWithinExtensionMessage(), $node)); return; } if ($schemaDefinitionsCount > 0) { - $context->reportError(new Error('Must provide only one schema definition.', $node)); + $context->reportError(new Error(self::schemaDefinitionNotAloneMessage(), $node)); } ++$schemaDefinitionsCount; diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/NoFragmentCycles.php b/vendor/webonyx/graphql-php/src/Validator/Rules/NoFragmentCycles.php index 1180a4e..eec546d 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/NoFragmentCycles.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/NoFragmentCycles.php @@ -9,14 +9,13 @@ use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Utils\Utils; use GraphQL\Validator\ValidationContext; -use function array_merge; use function array_pop; use function array_slice; use function count; use function implode; -use function is_array; use function sprintf; class NoFragmentCycles extends ValidationRule @@ -43,13 +42,11 @@ class NoFragmentCycles extends ValidationRule $this->spreadPathIndexByName = []; return [ - NodeKind::OPERATION_DEFINITION => static function () { + NodeKind::OPERATION_DEFINITION => static function () : VisitorOperation { return Visitor::skipNode(); }, - NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) use ($context) { - if (! isset($this->visitedFrags[$node->name->value])) { - $this->detectCycleRecursive($node, $context); - } + NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) use ($context) : VisitorOperation { + $this->detectCycleRecursive($node, $context); return Visitor::skipNode(); }, @@ -58,12 +55,16 @@ class NoFragmentCycles extends ValidationRule private function detectCycleRecursive(FragmentDefinitionNode $fragment, ValidationContext $context) { + if (isset($this->visitedFrags[$fragment->name->value])) { + return; + } + $fragmentName = $fragment->name->value; $this->visitedFrags[$fragmentName] = true; $spreadNodes = $context->getFragmentSpreads($fragment); - if (empty($spreadNodes)) { + if (count($spreadNodes) === 0) { return; } @@ -74,38 +75,24 @@ class NoFragmentCycles extends ValidationRule $spreadName = $spreadNode->name->value; $cycleIndex = $this->spreadPathIndexByName[$spreadName] ?? null; + $this->spreadPath[] = $spreadNode; if ($cycleIndex === null) { - $this->spreadPath[] = $spreadNode; - if (empty($this->visitedFrags[$spreadName])) { - $spreadFragment = $context->getFragment($spreadName); - if ($spreadFragment) { - $this->detectCycleRecursive($spreadFragment, $context); - } + $spreadFragment = $context->getFragment($spreadName); + if ($spreadFragment) { + $this->detectCycleRecursive($spreadFragment, $context); } - array_pop($this->spreadPath); } else { - $cyclePath = array_slice($this->spreadPath, $cycleIndex); - $nodes = $cyclePath; - - if (is_array($spreadNode)) { - $nodes = array_merge($nodes, $spreadNode); - } else { - $nodes[] = $spreadNode; - } + $cyclePath = array_slice($this->spreadPath, $cycleIndex); + $fragmentNames = Utils::map(array_slice($cyclePath, 0, -1), static function ($s) { + return $s->name->value; + }); $context->reportError(new Error( - self::cycleErrorMessage( - $spreadName, - Utils::map( - $cyclePath, - static function ($s) { - return $s->name->value; - } - ) - ), - $nodes + self::cycleErrorMessage($spreadName, $fragmentNames), + $cyclePath )); } + array_pop($this->spreadPath); } $this->spreadPathIndexByName[$fragmentName] = null; @@ -119,7 +106,7 @@ class NoFragmentCycles extends ValidationRule return sprintf( 'Cannot spread fragment "%s" within itself%s.', $fragName, - ! empty($spreadNames) ? ' via ' . implode(', ', $spreadNames) : '' + count($spreadNames) > 0 ? ' via ' . implode(', ', $spreadNames) : '' ); } } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/NoUndefinedVariables.php b/vendor/webonyx/graphql-php/src/Validator/Rules/NoUndefinedVariables.php index c0cd22c..078990c 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/NoUndefinedVariables.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/NoUndefinedVariables.php @@ -23,31 +23,33 @@ class NoUndefinedVariables extends ValidationRule return [ NodeKind::OPERATION_DEFINITION => [ - 'enter' => static function () use (&$variableNameDefined) { + 'enter' => static function () use (&$variableNameDefined) : void { $variableNameDefined = []; }, - 'leave' => static function (OperationDefinitionNode $operation) use (&$variableNameDefined, $context) { + 'leave' => static function (OperationDefinitionNode $operation) use (&$variableNameDefined, $context) : void { $usages = $context->getRecursiveVariableUsages($operation); foreach ($usages as $usage) { $node = $usage['node']; $varName = $node->name->value; - if (! empty($variableNameDefined[$varName])) { + if ($variableNameDefined[$varName] ?? false) { continue; } $context->reportError(new Error( self::undefinedVarMessage( $varName, - $operation->name ? $operation->name->value : null + $operation->name !== null + ? $operation->name->value + : null ), [$node, $operation] )); } }, ], - NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $def) use (&$variableNameDefined) { + NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $def) use (&$variableNameDefined) : void { $variableNameDefined[$def->variable->name->value] = true; }, ]; diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedFragments.php b/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedFragments.php index d1cd366..4315c54 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedFragments.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedFragments.php @@ -9,6 +9,7 @@ use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\OperationDefinitionNode; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Validator\ValidationContext; use function sprintf; @@ -26,18 +27,18 @@ class NoUnusedFragments extends ValidationRule $this->fragmentDefs = []; return [ - NodeKind::OPERATION_DEFINITION => function ($node) { + NodeKind::OPERATION_DEFINITION => function ($node) : VisitorOperation { $this->operationDefs[] = $node; return Visitor::skipNode(); }, - NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $def) { + NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $def) : VisitorOperation { $this->fragmentDefs[] = $def; return Visitor::skipNode(); }, NodeKind::DOCUMENT => [ - 'leave' => function () use ($context) { + 'leave' => function () use ($context) : void { $fragmentNameUsed = []; foreach ($this->operationDefs as $operation) { @@ -48,7 +49,7 @@ class NoUnusedFragments extends ValidationRule foreach ($this->fragmentDefs as $fragmentDef) { $fragName = $fragmentDef->name->value; - if (! empty($fragmentNameUsed[$fragName])) { + if ($fragmentNameUsed[$fragName] ?? false) { continue; } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedVariables.php b/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedVariables.php index e8f7ff3..343a969 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedVariables.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/NoUnusedVariables.php @@ -22,13 +22,15 @@ class NoUnusedVariables extends ValidationRule return [ NodeKind::OPERATION_DEFINITION => [ - 'enter' => function () { + 'enter' => function () : void { $this->variableDefs = []; }, - 'leave' => function (OperationDefinitionNode $operation) use ($context) { + 'leave' => function (OperationDefinitionNode $operation) use ($context) : void { $variableNameUsed = []; $usages = $context->getRecursiveVariableUsages($operation); - $opName = $operation->name ? $operation->name->value : null; + $opName = $operation->name !== null + ? $operation->name->value + : null; foreach ($usages as $usage) { $node = $usage['node']; @@ -38,7 +40,7 @@ class NoUnusedVariables extends ValidationRule foreach ($this->variableDefs as $variableDef) { $variableName = $variableDef->variable->name->value; - if (! empty($variableNameUsed[$variableName])) { + if ($variableNameUsed[$variableName] ?? false) { continue; } @@ -49,7 +51,7 @@ class NoUnusedVariables extends ValidationRule } }, ], - NodeKind::VARIABLE_DEFINITION => function ($def) { + NodeKind::VARIABLE_DEFINITION => function ($def) : void { $this->variableDefs[] = $def; }, ]; diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/OverlappingFieldsCanBeMerged.php b/vendor/webonyx/graphql-php/src/Validator/Rules/OverlappingFieldsCanBeMerged.php index 8dfa7f1..6307313 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/OverlappingFieldsCanBeMerged.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/OverlappingFieldsCanBeMerged.php @@ -19,7 +19,6 @@ use GraphQL\Type\Definition\InterfaceType; use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NonNull; use GraphQL\Type\Definition\ObjectType; -use GraphQL\Type\Definition\OutputType; use GraphQL\Type\Definition\Type; use GraphQL\Utils\PairSet; use GraphQL\Utils\TypeInfo; @@ -60,7 +59,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule $this->cachedFieldsAndFragmentNames = new SplObjectStorage(); return [ - NodeKind::SELECTION_SET => function (SelectionSetNode $selectionSet) use ($context) { + NodeKind::SELECTION_SET => function (SelectionSetNode $selectionSet) use ($context) : void { $conflicts = $this->findConflictsWithinSelectionSet( $context, $context->getParentType(), @@ -251,10 +250,10 @@ class OverlappingFieldsCanBeMerged extends ValidationRule $fieldName = $selection->name->value; $fieldDef = null; if ($parentType instanceof ObjectType || - $parentType instanceof InterfaceType) { - $tmp = $parentType->getFields(); - if (isset($tmp[$fieldName])) { - $fieldDef = $tmp[$fieldName]; + $parentType instanceof InterfaceType + ) { + if ($parentType->hasField($fieldName)) { + $fieldDef = $parentType->getField($fieldName); } } $responseName = $selection->alias ? $selection->alias->value : $fieldName; @@ -381,7 +380,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule ]; } - if (! $this->sameArguments($ast1->arguments ?: [], $ast2->arguments ?: [])) { + if (! $this->sameArguments($ast1->arguments ?? [], $ast2->arguments ?? [])) { return [ [$responseName, 'they have differing arguments'], [$ast1], @@ -467,30 +466,28 @@ class OverlappingFieldsCanBeMerged extends ValidationRule * Two types conflict if both types could not apply to a value simultaneously. * Composite types are ignored as their individual field types will be compared * later recursively. However List and Non-Null types must match. - * - * @return bool */ - private function doTypesConflict(OutputType $type1, OutputType $type2) + private function doTypesConflict(Type $type1, Type $type2) : bool { if ($type1 instanceof ListOfType) { - return $type2 instanceof ListOfType ? - $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) : - true; + return $type2 instanceof ListOfType + ? $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) + : true; } if ($type2 instanceof ListOfType) { - return $type1 instanceof ListOfType ? - $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) : - true; + return $type1 instanceof ListOfType + ? $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) + : true; } if ($type1 instanceof NonNull) { - return $type2 instanceof NonNull ? - $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) : - true; + return $type2 instanceof NonNull + ? $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) + : true; } if ($type2 instanceof NonNull) { - return $type1 instanceof NonNull ? - $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) : - true; + return $type1 instanceof NonNull + ? $this->doTypesConflict($type1->getWrappedType(), $type2->getWrappedType()) + : true; } if (Type::isLeafType($type1) || Type::isLeafType($type2)) { return $type1 !== $type2; @@ -848,14 +845,14 @@ class OverlappingFieldsCanBeMerged extends ValidationRule ], array_reduce( $conflicts, - static function ($allFields, $conflict) { + static function ($allFields, $conflict) : array { return array_merge($allFields, $conflict[1]); }, [$ast1] ), array_reduce( $conflicts, - static function ($allFields, $conflict) { + static function ($allFields, $conflict) : array { return array_merge($allFields, $conflict[2]); }, [$ast2] @@ -882,7 +879,7 @@ class OverlappingFieldsCanBeMerged extends ValidationRule { if (is_array($reason)) { $tmp = array_map( - static function ($tmp) { + static function ($tmp) : string { [$responseName, $subReason] = $tmp; $reasonMessage = self::reasonMessage($subReason); diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/PossibleFragmentSpreads.php b/vendor/webonyx/graphql-php/src/Validator/Rules/PossibleFragmentSpreads.php index 26611e6..4251400 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/PossibleFragmentSpreads.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/PossibleFragmentSpreads.php @@ -23,7 +23,7 @@ class PossibleFragmentSpreads extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::INLINE_FRAGMENT => function (InlineFragmentNode $node) use ($context) { + NodeKind::INLINE_FRAGMENT => function (InlineFragmentNode $node) use ($context) : void { $fragType = $context->getType(); $parentType = $context->getParentType(); @@ -38,7 +38,7 @@ class PossibleFragmentSpreads extends ValidationRule [$node] )); }, - NodeKind::FRAGMENT_SPREAD => function (FragmentSpreadNode $node) use ($context) { + NodeKind::FRAGMENT_SPREAD => function (FragmentSpreadNode $node) use ($context) : void { $fragName = $node->name->value; $fragType = $this->getFragmentType($context, $fragName); $parentType = $context->getParentType(); @@ -68,12 +68,12 @@ class PossibleFragmentSpreads extends ValidationRule // Parent type is interface or union, fragment type is object type if ($parentType instanceof AbstractType && $fragType instanceof ObjectType) { - return $schema->isPossibleType($parentType, $fragType); + return $schema->isSubType($parentType, $fragType); } // Parent type is object type, fragment type is interface (or rather rare - union) if ($parentType instanceof ObjectType && $fragType instanceof AbstractType) { - return $schema->isPossibleType($fragType, $parentType); + return $schema->isSubType($fragType, $parentType); } // Both are object types: diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedNonNullArguments.php b/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedNonNullArguments.php deleted file mode 100644 index 976f38b..0000000 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedNonNullArguments.php +++ /dev/null @@ -1,98 +0,0 @@ - [ - 'leave' => static function (FieldNode $fieldNode) use ($context) { - $fieldDef = $context->getFieldDef(); - - if (! $fieldDef) { - return Visitor::skipNode(); - } - $argNodes = $fieldNode->arguments ?: []; - - $argNodeMap = []; - foreach ($argNodes as $argNode) { - $argNodeMap[$argNode->name->value] = $argNodes; - } - foreach ($fieldDef->args as $argDef) { - $argNode = $argNodeMap[$argDef->name] ?? null; - if ($argNode || ! ($argDef->getType() instanceof NonNull)) { - continue; - } - - $context->reportError(new Error( - self::missingFieldArgMessage($fieldNode->name->value, $argDef->name, $argDef->getType()), - [$fieldNode] - )); - } - }, - ], - NodeKind::DIRECTIVE => [ - 'leave' => static function (DirectiveNode $directiveNode) use ($context) { - $directiveDef = $context->getDirective(); - if (! $directiveDef) { - return Visitor::skipNode(); - } - $argNodes = $directiveNode->arguments ?: []; - $argNodeMap = []; - foreach ($argNodes as $argNode) { - $argNodeMap[$argNode->name->value] = $argNodes; - } - - foreach ($directiveDef->args as $argDef) { - $argNode = $argNodeMap[$argDef->name] ?? null; - if ($argNode || ! ($argDef->getType() instanceof NonNull)) { - continue; - } - - $context->reportError(new Error( - self::missingDirectiveArgMessage( - $directiveNode->name->value, - $argDef->name, - $argDef->getType() - ), - [$directiveNode] - )); - } - }, - ], - ]; - } - - public static function missingFieldArgMessage($fieldName, $argName, $type) - { - return sprintf( - 'Field "%s" argument "%s" of type "%s" is required but not provided.', - $fieldName, - $argName, - $type - ); - } - - public static function missingDirectiveArgMessage($directiveName, $argName, $type) - { - return sprintf( - 'Directive "@%s" argument "%s" of type "%s" is required but not provided.', - $directiveName, - $argName, - $type - ); - } -} diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArguments.php b/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArguments.php new file mode 100644 index 0000000..77a4aa5 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArguments.php @@ -0,0 +1,62 @@ +getVisitor($context) + [ + NodeKind::FIELD => [ + 'leave' => static function (FieldNode $fieldNode) use ($context) : ?VisitorOperation { + $fieldDef = $context->getFieldDef(); + + if (! $fieldDef) { + return Visitor::skipNode(); + } + $argNodes = $fieldNode->arguments ?? []; + + $argNodeMap = []; + foreach ($argNodes as $argNode) { + $argNodeMap[$argNode->name->value] = $argNode; + } + foreach ($fieldDef->args as $argDef) { + $argNode = $argNodeMap[$argDef->name] ?? null; + if ($argNode || ! $argDef->isRequired()) { + continue; + } + + $context->reportError(new Error( + self::missingFieldArgMessage($fieldNode->name->value, $argDef->name, $argDef->getType()), + [$fieldNode] + )); + } + + return null; + }, + ], + ]; + } + + public static function missingFieldArgMessage($fieldName, $argName, $type) + { + return sprintf( + 'Field "%s" argument "%s" of type "%s" is required but not provided.', + $fieldName, + $argName, + $type + ); + } +} diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArgumentsOnDirectives.php b/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArgumentsOnDirectives.php index 8750711..f8b34c7 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArgumentsOnDirectives.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedRequiredArgumentsOnDirectives.php @@ -8,18 +8,17 @@ use GraphQL\Error\Error; use GraphQL\Language\AST\ArgumentNode; use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DirectiveNode; -use GraphQL\Language\AST\NamedTypeNode; -use GraphQL\Language\AST\Node; +use GraphQL\Language\AST\InputValueDefinitionNode; use GraphQL\Language\AST\NodeKind; -use GraphQL\Language\AST\NodeList; use GraphQL\Language\AST\NonNullTypeNode; +use GraphQL\Language\Printer; +use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\FieldArgument; -use GraphQL\Type\Definition\NonNull; use GraphQL\Utils\Utils; +use GraphQL\Validator\ASTValidationContext; +use GraphQL\Validator\SDLValidationContext; use GraphQL\Validator\ValidationContext; use function array_filter; -use function is_array; -use function iterator_to_array; /** * Provided required arguments on directives @@ -29,21 +28,34 @@ use function iterator_to_array; */ class ProvidedRequiredArgumentsOnDirectives extends ValidationRule { - protected static function missingDirectiveArgMessage(string $directiveName, string $argName) + public static function missingDirectiveArgMessage(string $directiveName, string $argName, string $type) { - return 'Directive "' . $directiveName . '" argument "' . $argName . '" is required but ont provided.'; + return 'Directive "@' . $directiveName . '" argument "' . $argName + . '" of type "' . $type . '" is required but not provided.'; + } + + public function getSDLVisitor(SDLValidationContext $context) + { + return $this->getASTVisitor($context); } public function getVisitor(ValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getASTVisitor(ASTValidationContext $context) { $requiredArgsMap = []; $schema = $context->getSchema(); - $definedDirectives = $schema->getDirectives(); + $definedDirectives = $schema + ? $schema->getDirectives() + : Directive::getInternalDirectives(); foreach ($definedDirectives as $directive) { $requiredArgsMap[$directive->name] = Utils::keyMap( array_filter($directive->args, static function (FieldArgument $arg) : bool { - return $arg->getType() instanceof NonNull && ! isset($arg->defaultValue); + return $arg->isRequired(); }), static function (FieldArgument $arg) : string { return $arg->name; @@ -56,55 +68,61 @@ class ProvidedRequiredArgumentsOnDirectives extends ValidationRule if (! ($def instanceof DirectiveDefinitionNode)) { continue; } - - if (is_array($def->arguments)) { - $arguments = $def->arguments; - } elseif ($def->arguments instanceof NodeList) { - $arguments = iterator_to_array($def->arguments->getIterator()); - } else { - $arguments = null; - } + $arguments = $def->arguments ?? []; $requiredArgsMap[$def->name->value] = Utils::keyMap( - $arguments ? array_filter($arguments, static function (Node $argument) : bool { - return $argument instanceof NonNullTypeNode && + Utils::filter($arguments, static function (InputValueDefinitionNode $argument) : bool { + return $argument->type instanceof NonNullTypeNode && ( ! isset($argument->defaultValue) || $argument->defaultValue === null ); - }) : [], - static function (NamedTypeNode $argument) : string { + }), + static function (InputValueDefinitionNode $argument) : string { return $argument->name->value; } ); } return [ - NodeKind::DIRECTIVE => static function (DirectiveNode $directiveNode) use ($requiredArgsMap, $context) { - $directiveName = $directiveNode->name->value; - $requiredArgs = $requiredArgsMap[$directiveName] ?? null; - if (! $requiredArgs) { - return; - } - - $argNodes = $directiveNode->arguments ?: []; - $argNodeMap = Utils::keyMap( - $argNodes, - static function (ArgumentNode $arg) : string { - return $arg->name->value; - } - ); - - foreach ($requiredArgs as $argName => $arg) { - if (isset($argNodeMap[$argName])) { - continue; + NodeKind::DIRECTIVE => [ + // Validate on leave to allow for deeper errors to appear first. + 'leave' => static function (DirectiveNode $directiveNode) use ($requiredArgsMap, $context) : ?string { + $directiveName = $directiveNode->name->value; + $requiredArgs = $requiredArgsMap[$directiveName] ?? null; + if (! $requiredArgs) { + return null; } - $context->reportError( - new Error(static::missingDirectiveArgMessage($directiveName, $argName), [$directiveNode]) + $argNodes = $directiveNode->arguments ?? []; + $argNodeMap = Utils::keyMap( + $argNodes, + static function (ArgumentNode $arg) : string { + return $arg->name->value; + } ); - } - }, + + foreach ($requiredArgs as $argName => $arg) { + if (isset($argNodeMap[$argName])) { + continue; + } + + if ($arg instanceof FieldArgument) { + $argType = (string) $arg->getType(); + } elseif ($arg instanceof InputValueDefinitionNode) { + $argType = Printer::doPrint($arg->type); + } else { + $argType = ''; + } + + $context->reportError( + new Error(static::missingDirectiveArgMessage($directiveName, $argName, $argType), [$directiveNode]) + ); + } + + return null; + }, + ], ]; } } diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/QueryComplexity.php b/vendor/webonyx/graphql-php/src/Validator/Rules/QueryComplexity.php index b5c33f9..1a1eb4b 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/QueryComplexity.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/QueryComplexity.php @@ -15,11 +15,12 @@ use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\OperationDefinitionNode; use GraphQL\Language\AST\SelectionSetNode; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Type\Definition\Directive; use GraphQL\Type\Definition\FieldDefinition; use GraphQL\Validator\ValidationContext; use function array_map; -use function call_user_func_array; +use function count; use function implode; use function method_exists; use function sprintf; @@ -60,7 +61,7 @@ class QueryComplexity extends QuerySecurityRule return $this->invokeIfNeeded( $context, [ - NodeKind::SELECTION_SET => function (SelectionSetNode $selectionSet) use ($context) { + NodeKind::SELECTION_SET => function (SelectionSetNode $selectionSet) use ($context) : void { $this->fieldNodeAndDefs = $this->collectFieldASTsAndDefs( $context, $context->getParentType(), @@ -69,16 +70,16 @@ class QueryComplexity extends QuerySecurityRule $this->fieldNodeAndDefs ); }, - NodeKind::VARIABLE_DEFINITION => function ($def) { + NodeKind::VARIABLE_DEFINITION => function ($def) : VisitorOperation { $this->variableDefs[] = $def; return Visitor::skipNode(); }, NodeKind::OPERATION_DEFINITION => [ - 'leave' => function (OperationDefinitionNode $operationDefinition) use ($context, &$complexity) { + 'leave' => function (OperationDefinitionNode $operationDefinition) use ($context, &$complexity) : void { $errors = $context->getErrors(); - if (! empty($errors)) { + if (count($errors) > 0) { return; } @@ -113,9 +114,8 @@ class QueryComplexity extends QuerySecurityRule private function nodeComplexity(Node $node, $complexity = 0) { - switch ($node->kind) { - case NodeKind::FIELD: - /** @var FieldNode $node */ + switch (true) { + case $node instanceof FieldNode: // default values $args = []; $complexityFn = FieldDefinition::DEFAULT_COMPLEXITY_FN; @@ -143,19 +143,17 @@ class QueryComplexity extends QuerySecurityRule } } - $complexity += call_user_func_array($complexityFn, [$childrenComplexity, $args]); + $complexity += $complexityFn($childrenComplexity, $args); break; - case NodeKind::INLINE_FRAGMENT: - /** @var InlineFragmentNode $node */ + case $node instanceof InlineFragmentNode: // node has children? if (isset($node->selectionSet)) { $complexity = $this->fieldComplexity($node, $complexity); } break; - case NodeKind::FRAGMENT_SPREAD: - /** @var FragmentSpreadNode $node */ + case $node instanceof FragmentSpreadNode: $fragment = $this->getFragment($node); if ($fragment !== null) { @@ -194,7 +192,7 @@ class QueryComplexity extends QuerySecurityRule $this->variableDefs, $this->getRawVariableValues() ); - if (! empty($errors)) { + if (count($errors ?? []) > 0) { throw new Error(implode( "\n\n", array_map( @@ -212,11 +210,16 @@ class QueryComplexity extends QuerySecurityRule return ! $directiveArgsIf; } - $directive = Directive::skipDirective(); - $directiveArgsIf = Values::getArgumentValues($directive, $directiveNode, $variableValues); + if ($directiveNode->name->value === Directive::SKIP_NAME) { + $directive = Directive::skipDirective(); + /** @var bool $directiveArgsIf */ + $directiveArgsIf = Values::getArgumentValues($directive, $directiveNode, $variableValues)['if']; - return $directiveArgsIf['if']; + return $directiveArgsIf; + } } + + return false; } public function getRawVariableValues() @@ -229,7 +232,7 @@ class QueryComplexity extends QuerySecurityRule */ public function setRawVariableValues(?array $rawVariableValues = null) { - $this->rawVariableValues = $rawVariableValues ?: []; + $this->rawVariableValues = $rawVariableValues ?? []; } private function buildFieldArguments(FieldNode $node) @@ -247,7 +250,7 @@ class QueryComplexity extends QuerySecurityRule $rawVariableValues ); - if (! empty($errors)) { + if (count($errors ?? []) > 0) { throw new Error(implode( "\n\n", array_map( diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/QueryDepth.php b/vendor/webonyx/graphql-php/src/Validator/Rules/QueryDepth.php index e4b31a0..9b83d06 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/QueryDepth.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/QueryDepth.php @@ -5,6 +5,9 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; use GraphQL\Error\Error; +use GraphQL\Language\AST\FieldNode; +use GraphQL\Language\AST\FragmentSpreadNode; +use GraphQL\Language\AST\InlineFragmentNode; use GraphQL\Language\AST\Node; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\OperationDefinitionNode; @@ -28,7 +31,7 @@ class QueryDepth extends QuerySecurityRule $context, [ NodeKind::OPERATION_DEFINITION => [ - 'leave' => function (OperationDefinitionNode $operationDefinition) use ($context) { + 'leave' => function (OperationDefinitionNode $operationDefinition) use ($context) : void { $maxDepth = $this->fieldDepth($operationDefinition); if ($maxDepth <= $this->getMaxQueryDepth()) { @@ -57,9 +60,8 @@ class QueryDepth extends QuerySecurityRule private function nodeDepth(Node $node, $depth = 0, $maxDepth = 0) { - switch ($node->kind) { - case NodeKind::FIELD: - /** @var FieldNode $node */ + switch (true) { + case $node instanceof FieldNode: // node has children? if ($node->selectionSet !== null) { // update maxDepth if needed @@ -70,16 +72,14 @@ class QueryDepth extends QuerySecurityRule } break; - case NodeKind::INLINE_FRAGMENT: - /** @var InlineFragmentNode $node */ + case $node instanceof InlineFragmentNode: // node has children? if ($node->selectionSet !== null) { $maxDepth = $this->fieldDepth($node, $depth, $maxDepth); } break; - case NodeKind::FRAGMENT_SPREAD: - /** @var FragmentSpreadNode $node */ + case $node instanceof FragmentSpreadNode: $fragment = $this->getFragment($node); if ($fragment !== null) { diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/QuerySecurityRule.php b/vendor/webonyx/graphql-php/src/Validator/Rules/QuerySecurityRule.php index c5f0260..dcb76e9 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/QuerySecurityRule.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/QuerySecurityRule.php @@ -9,15 +9,15 @@ use GraphQL\Language\AST\FieldNode; use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\InlineFragmentNode; -use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\SelectionSetNode; +use GraphQL\Type\Definition\HasFieldsType; +use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Introspection; use GraphQL\Utils\TypeInfo; use GraphQL\Validator\ValidationContext; use InvalidArgumentException; use function class_alias; -use function method_exists; use function sprintf; abstract class QuerySecurityRule extends ValidationRule @@ -110,17 +110,15 @@ abstract class QuerySecurityRule extends ValidationRule ?ArrayObject $visitedFragmentNames = null, ?ArrayObject $astAndDefs = null ) { - $_visitedFragmentNames = $visitedFragmentNames ?: new ArrayObject(); - $_astAndDefs = $astAndDefs ?: new ArrayObject(); + $_visitedFragmentNames = $visitedFragmentNames ?? new ArrayObject(); + $_astAndDefs = $astAndDefs ?? new ArrayObject(); foreach ($selectionSet->selections as $selection) { - switch ($selection->kind) { - case NodeKind::FIELD: - /** @var FieldNode $selection */ + switch (true) { + case $selection instanceof FieldNode: $fieldName = $selection->name->value; $fieldDef = null; - if ($parentType && method_exists($parentType, 'getFields')) { - $tmp = $parentType->getFields(); + if ($parentType instanceof HasFieldsType || $parentType instanceof InputObjectType) { $schemaMetaFieldDef = Introspection::schemaMetaFieldDef(); $typeMetaFieldDef = Introspection::typeMetaFieldDef(); $typeNameMetaFieldDef = Introspection::typeNameMetaFieldDef(); @@ -131,8 +129,8 @@ abstract class QuerySecurityRule extends ValidationRule $fieldDef = $typeMetaFieldDef; } elseif ($fieldName === $typeNameMetaFieldDef->name) { $fieldDef = $typeNameMetaFieldDef; - } elseif (isset($tmp[$fieldName])) { - $fieldDef = $tmp[$fieldName]; + } elseif ($parentType->hasField($fieldName)) { + $fieldDef = $parentType->getField($fieldName); } } $responseName = $this->getFieldName($selection); @@ -142,8 +140,7 @@ abstract class QuerySecurityRule extends ValidationRule // create field context $_astAndDefs[$responseName][] = [$selection, $fieldDef]; break; - case NodeKind::INLINE_FRAGMENT: - /** @var InlineFragmentNode $selection */ + case $selection instanceof InlineFragmentNode: $_astAndDefs = $this->collectFieldASTsAndDefs( $context, TypeInfo::typeFromAST($context->getSchema(), $selection->typeCondition), @@ -152,11 +149,10 @@ abstract class QuerySecurityRule extends ValidationRule $_astAndDefs ); break; - case NodeKind::FRAGMENT_SPREAD: - /** @var FragmentSpreadNode $selection */ + case $selection instanceof FragmentSpreadNode: $fragName = $selection->name->value; - if (empty($_visitedFragmentNames[$fragName])) { + if (! ($_visitedFragmentNames[$fragName] ?? false)) { $_visitedFragmentNames[$fragName] = true; $fragment = $context->getFragment($fragName); diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/ScalarLeafs.php b/vendor/webonyx/graphql-php/src/Validator/Rules/ScalarLeafs.php index 1bd2515..f171423 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/ScalarLeafs.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/ScalarLeafs.php @@ -16,7 +16,7 @@ class ScalarLeafs extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::FIELD => static function (FieldNode $node) use ($context) { + NodeKind::FIELD => static function (FieldNode $node) use ($context) : void { $type = $context->getType(); if (! $type) { return; diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/SingleFieldSubscription.php b/vendor/webonyx/graphql-php/src/Validator/Rules/SingleFieldSubscription.php new file mode 100644 index 0000000..b98ee95 --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/SingleFieldSubscription.php @@ -0,0 +1,57 @@ + + */ + public function getVisitor(ValidationContext $context) : array + { + return [ + NodeKind::OPERATION_DEFINITION => static function (OperationDefinitionNode $node) use ($context) : VisitorOperation { + if ($node->operation === 'subscription') { + $selections = $node->selectionSet->selections; + + if (count($selections) !== 1) { + if ($selections instanceof NodeList) { + $offendingSelections = $selections->splice(1, count($selections)); + } else { + $offendingSelections = array_splice($selections, 1); + } + + $context->reportError(new Error( + self::multipleFieldsInOperation($node->name->value ?? null), + $offendingSelections + )); + } + } + + return Visitor::skipNode(); + }, + ]; + } + + public static function multipleFieldsInOperation(?string $operationName) : string + { + if ($operationName === null) { + return sprintf('Anonymous Subscription must select only one top level field.'); + } + + return sprintf('Subscription "%s" must select only one top level field.', $operationName); + } +} diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueArgumentNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueArgumentNames.php index 2e83d43..58daecf 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueArgumentNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueArgumentNames.php @@ -9,6 +9,9 @@ use GraphQL\Language\AST\ArgumentNode; use GraphQL\Language\AST\NameNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; +use GraphQL\Validator\ASTValidationContext; +use GraphQL\Validator\SDLValidationContext; use GraphQL\Validator\ValidationContext; use function sprintf; @@ -17,20 +20,30 @@ class UniqueArgumentNames extends ValidationRule /** @var NameNode[] */ public $knownArgNames; + public function getSDLVisitor(SDLValidationContext $context) + { + return $this->getASTVisitor($context); + } + public function getVisitor(ValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getASTVisitor(ASTValidationContext $context) { $this->knownArgNames = []; return [ - NodeKind::FIELD => function () { + NodeKind::FIELD => function () : void { $this->knownArgNames = []; }, - NodeKind::DIRECTIVE => function () { + NodeKind::DIRECTIVE => function () : void { $this->knownArgNames = []; }, - NodeKind::ARGUMENT => function (ArgumentNode $node) use ($context) { + NodeKind::ARGUMENT => function (ArgumentNode $node) use ($context) : VisitorOperation { $argName = $node->name->value; - if (! empty($this->knownArgNames[$argName])) { + if ($this->knownArgNames[$argName] ?? false) { $context->reportError(new Error( self::duplicateArgMessage($argName), [$this->knownArgNames[$argName], $node->name] diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueDirectivesPerLocation.php b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueDirectivesPerLocation.php index f0e8c45..02844af 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueDirectivesPerLocation.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueDirectivesPerLocation.php @@ -5,25 +5,70 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; use GraphQL\Error\Error; +use GraphQL\Language\AST\DirectiveDefinitionNode; use GraphQL\Language\AST\DirectiveNode; use GraphQL\Language\AST\Node; +use GraphQL\Type\Definition\Directive; +use GraphQL\Validator\ASTValidationContext; +use GraphQL\Validator\SDLValidationContext; use GraphQL\Validator\ValidationContext; use function sprintf; +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + */ class UniqueDirectivesPerLocation extends ValidationRule { public function getVisitor(ValidationContext $context) { + return $this->getASTVisitor($context); + } + + public function getSDLVisitor(SDLValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getASTVisitor(ASTValidationContext $context) + { + $uniqueDirectiveMap = []; + + $schema = $context->getSchema(); + $definedDirectives = $schema !== null + ? $schema->getDirectives() + : Directive::getInternalDirectives(); + foreach ($definedDirectives as $directive) { + $uniqueDirectiveMap[$directive->name] = ! $directive->isRepeatable; + } + + $astDefinitions = $context->getDocument()->definitions; + foreach ($astDefinitions as $definition) { + if (! ($definition instanceof DirectiveDefinitionNode)) { + continue; + } + + $uniqueDirectiveMap[$definition->name->value] = $definition->repeatable; + } + return [ - 'enter' => static function (Node $node) use ($context) { + 'enter' => static function (Node $node) use ($uniqueDirectiveMap, $context) : void { if (! isset($node->directives)) { return; } $knownDirectives = []; + + /** @var DirectiveNode $directive */ foreach ($node->directives as $directive) { - /** @var DirectiveNode $directive */ $directiveName = $directive->name->value; + + if (! isset($uniqueDirectiveMap[$directiveName])) { + continue; + } + if (isset($knownDirectives[$directiveName])) { $context->reportError(new Error( self::duplicateDirectiveMessage($directiveName), diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueFragmentNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueFragmentNames.php index 475e6b3..e9dba8a 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueFragmentNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueFragmentNames.php @@ -9,6 +9,7 @@ use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\NameNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Validator\ValidationContext; use function sprintf; @@ -22,12 +23,12 @@ class UniqueFragmentNames extends ValidationRule $this->knownFragmentNames = []; return [ - NodeKind::OPERATION_DEFINITION => static function () { + NodeKind::OPERATION_DEFINITION => static function () : VisitorOperation { return Visitor::skipNode(); }, - NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) use ($context) { + NodeKind::FRAGMENT_DEFINITION => function (FragmentDefinitionNode $node) use ($context) : VisitorOperation { $fragmentName = $node->name->value; - if (empty($this->knownFragmentNames[$fragmentName])) { + if (! isset($this->knownFragmentNames[$fragmentName])) { $this->knownFragmentNames[$fragmentName] = $node->name; } else { $context->reportError(new Error( diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueInputFieldNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueInputFieldNames.php index 6426b43..541a372 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueInputFieldNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueInputFieldNames.php @@ -5,40 +5,54 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; use GraphQL\Error\Error; +use GraphQL\Language\AST\NameNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\ObjectFieldNode; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; +use GraphQL\Validator\ASTValidationContext; +use GraphQL\Validator\SDLValidationContext; use GraphQL\Validator\ValidationContext; use function array_pop; use function sprintf; class UniqueInputFieldNames extends ValidationRule { - /** @var string[] */ + /** @var array */ public $knownNames; - /** @var string[][] */ + /** @var array> */ public $knownNameStack; public function getVisitor(ValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getSDLVisitor(SDLValidationContext $context) + { + return $this->getASTVisitor($context); + } + + public function getASTVisitor(ASTValidationContext $context) { $this->knownNames = []; $this->knownNameStack = []; return [ NodeKind::OBJECT => [ - 'enter' => function () { + 'enter' => function () : void { $this->knownNameStack[] = $this->knownNames; $this->knownNames = []; }, - 'leave' => function () { + 'leave' => function () : void { $this->knownNames = array_pop($this->knownNameStack); }, ], - NodeKind::OBJECT_FIELD => function (ObjectFieldNode $node) use ($context) { + NodeKind::OBJECT_FIELD => function (ObjectFieldNode $node) use ($context) : VisitorOperation { $fieldName = $node->name->value; - if (! empty($this->knownNames[$fieldName])) { + if (isset($this->knownNames[$fieldName])) { $context->reportError(new Error( self::duplicateInputFieldMessage($fieldName), [$this->knownNames[$fieldName], $node->name] diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueOperationNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueOperationNames.php index 969b90e..c4a0777 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueOperationNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueOperationNames.php @@ -9,6 +9,7 @@ use GraphQL\Language\AST\NameNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\OperationDefinitionNode; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Validator\ValidationContext; use function sprintf; @@ -22,11 +23,11 @@ class UniqueOperationNames extends ValidationRule $this->knownOperationNames = []; return [ - NodeKind::OPERATION_DEFINITION => function (OperationDefinitionNode $node) use ($context) { + NodeKind::OPERATION_DEFINITION => function (OperationDefinitionNode $node) use ($context) : VisitorOperation { $operationName = $node->name; - if ($operationName) { - if (empty($this->knownOperationNames[$operationName->value])) { + if ($operationName !== null) { + if (! isset($this->knownOperationNames[$operationName->value])) { $this->knownOperationNames[$operationName->value] = $operationName; } else { $context->reportError(new Error( @@ -38,7 +39,7 @@ class UniqueOperationNames extends ValidationRule return Visitor::skipNode(); }, - NodeKind::FRAGMENT_DEFINITION => static function () { + NodeKind::FRAGMENT_DEFINITION => static function () : VisitorOperation { return Visitor::skipNode(); }, ]; diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueVariableNames.php b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueVariableNames.php index f050a73..f6db14e 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueVariableNames.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/UniqueVariableNames.php @@ -21,12 +21,12 @@ class UniqueVariableNames extends ValidationRule $this->knownVariableNames = []; return [ - NodeKind::OPERATION_DEFINITION => function () { + NodeKind::OPERATION_DEFINITION => function () : void { $this->knownVariableNames = []; }, - NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $node) use ($context) { + NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $node) use ($context) : void { $variableName = $node->variable->name->value; - if (empty($this->knownVariableNames[$variableName])) { + if (! isset($this->knownVariableNames[$variableName])) { $this->knownVariableNames[$variableName] = $node->variable->name; } else { $context->reportError(new Error( diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/ValidationRule.php b/vendor/webonyx/graphql-php/src/Validator/Rules/ValidationRule.php index fe8504d..461aafe 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/ValidationRule.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/ValidationRule.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; +use GraphQL\Validator\SDLValidationContext; use GraphQL\Validator\ValidationContext; use function class_alias; @@ -14,7 +15,7 @@ abstract class ValidationRule public function getName() { - return $this->name ?: static::class; + return $this->name === '' || $this->name === null ? static::class : $this->name; } public function __invoke(ValidationContext $context) @@ -29,7 +30,22 @@ abstract class ValidationRule * * @return mixed[] */ - abstract public function getVisitor(ValidationContext $context); + public function getVisitor(ValidationContext $context) + { + return []; + } + + /** + * Returns structure suitable for GraphQL\Language\Visitor + * + * @see \GraphQL\Language\Visitor + * + * @return mixed[] + */ + public function getSDLVisitor(SDLValidationContext $context) + { + return []; + } } class_alias(ValidationRule::class, 'GraphQL\Validator\Rules\AbstractValidationRule'); diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/ValuesOfCorrectType.php b/vendor/webonyx/graphql-php/src/Validator/Rules/ValuesOfCorrectType.php index 4e8199b..a4c9667 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/ValuesOfCorrectType.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/ValuesOfCorrectType.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace GraphQL\Validator\Rules; -use Exception; use GraphQL\Error\Error; use GraphQL\Language\AST\BooleanValueNode; use GraphQL\Language\AST\EnumValueNode; @@ -18,11 +17,12 @@ use GraphQL\Language\AST\ObjectFieldNode; use GraphQL\Language\AST\ObjectValueNode; use GraphQL\Language\AST\StringValueNode; use GraphQL\Language\AST\ValueNode; +use GraphQL\Language\AST\VariableNode; use GraphQL\Language\Printer; use GraphQL\Language\Visitor; +use GraphQL\Language\VisitorOperation; use GraphQL\Type\Definition\EnumType; use GraphQL\Type\Definition\EnumValueDefinition; -use GraphQL\Type\Definition\FieldArgument; use GraphQL\Type\Definition\InputObjectType; use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NonNull; @@ -52,11 +52,11 @@ class ValuesOfCorrectType extends ValidationRule return [ NodeKind::FIELD => [ - 'enter' => static function (FieldNode $node) use (&$fieldName) { + 'enter' => static function (FieldNode $node) use (&$fieldName) : void { $fieldName = $node->name->value; }, ], - NodeKind::NULL => static function (NullValueNode $node) use ($context, &$fieldName) { + NodeKind::NULL => static function (NullValueNode $node) use ($context, &$fieldName) : void { $type = $context->getInputType(); if (! ($type instanceof NonNull)) { return; @@ -69,7 +69,7 @@ class ValuesOfCorrectType extends ValidationRule ) ); }, - NodeKind::LST => function (ListValueNode $node) use ($context, &$fieldName) { + NodeKind::LST => function (ListValueNode $node) use ($context, &$fieldName) : ?VisitorOperation { // Note: TypeInfo will traverse into a list's item type, so look to the // parent input type to check if it is a list. $type = Type::getNullableType($context->getParentInputType()); @@ -78,8 +78,10 @@ class ValuesOfCorrectType extends ValidationRule return Visitor::skipNode(); } + + return null; }, - NodeKind::OBJECT => function (ObjectValueNode $node) use ($context, &$fieldName) { + NodeKind::OBJECT => function (ObjectValueNode $node) use ($context, &$fieldName) : ?VisitorOperation { // Note: TypeInfo will traverse into a list's item type, so look to the // parent input type to check if it is a list. $type = Type::getNamedType($context->getInputType()); @@ -94,7 +96,7 @@ class ValuesOfCorrectType extends ValidationRule $nodeFields = iterator_to_array($node->fields); $fieldNodeMap = array_combine( array_map( - static function ($field) { + static function ($field) : string { return $field->name->value; }, $nodeFields @@ -103,7 +105,7 @@ class ValuesOfCorrectType extends ValidationRule ); foreach ($inputFields as $fieldName => $fieldDef) { $fieldType = $fieldDef->getType(); - if (isset($fieldNodeMap[$fieldName]) || ! ($fieldType instanceof NonNull)) { + if (isset($fieldNodeMap[$fieldName]) || ! $fieldDef->isRequired()) { continue; } @@ -114,10 +116,13 @@ class ValuesOfCorrectType extends ValidationRule ) ); } + + return null; }, - NodeKind::OBJECT_FIELD => static function (ObjectFieldNode $node) use ($context) { + NodeKind::OBJECT_FIELD => static function (ObjectFieldNode $node) use ($context) : void { $parentType = Type::getNamedType($context->getParentInputType()); - $fieldType = $context->getInputType(); + /** @var ScalarType|EnumType|InputObjectType|ListOfType|NonNull $fieldType */ + $fieldType = $context->getInputType(); if ($fieldType || ! ($parentType instanceof InputObjectType)) { return; } @@ -137,7 +142,7 @@ class ValuesOfCorrectType extends ValidationRule ) ); }, - NodeKind::ENUM => function (EnumValueNode $node) use ($context, &$fieldName) { + NodeKind::ENUM => function (EnumValueNode $node) use ($context, &$fieldName) : void { $type = Type::getNamedType($context->getInputType()); if (! $type instanceof EnumType) { $this->isValidScalar($context, $node, $fieldName); @@ -156,16 +161,16 @@ class ValuesOfCorrectType extends ValidationRule ); } }, - NodeKind::INT => function (IntValueNode $node) use ($context, &$fieldName) { + NodeKind::INT => function (IntValueNode $node) use ($context, &$fieldName) : void { $this->isValidScalar($context, $node, $fieldName); }, - NodeKind::FLOAT => function (FloatValueNode $node) use ($context, &$fieldName) { + NodeKind::FLOAT => function (FloatValueNode $node) use ($context, &$fieldName) : void { $this->isValidScalar($context, $node, $fieldName); }, - NodeKind::STRING => function (StringValueNode $node) use ($context, &$fieldName) { + NodeKind::STRING => function (StringValueNode $node) use ($context, &$fieldName) : void { $this->isValidScalar($context, $node, $fieldName); }, - NodeKind::BOOLEAN => function (BooleanValueNode $node) use ($context, &$fieldName) { + NodeKind::BOOLEAN => function (BooleanValueNode $node) use ($context, &$fieldName) : void { $this->isValidScalar($context, $node, $fieldName); }, ]; @@ -177,9 +182,13 @@ class ValuesOfCorrectType extends ValidationRule ($message ? "; ${message}" : '.'); } + /** + * @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode $node + */ private function isValidScalar(ValidationContext $context, ValueNode $node, $fieldName) { // Report any error at the full type expected by the location. + /** @var ScalarType|EnumType|InputObjectType|ListOfType|NonNull $locationType */ $locationType = $context->getInputType(); if (! $locationType) { @@ -209,20 +218,6 @@ class ValuesOfCorrectType extends ValidationRule // may throw to indicate failure. try { $type->parseLiteral($node); - } catch (Exception $error) { - // Ensure a reference to the original error is maintained. - $context->reportError( - new Error( - self::getBadValueMessage( - (string) $locationType, - Printer::doPrint($node), - $error->getMessage(), - $context, - $fieldName - ), - $node - ) - ); } catch (Throwable $error) { // Ensure a reference to the original error is maintained. $context->reportError( @@ -234,19 +229,26 @@ class ValuesOfCorrectType extends ValidationRule $context, $fieldName ), - $node + $node, + null, + [], + null, + $error ) ); } } + /** + * @param VariableNode|NullValueNode|IntValueNode|FloatValueNode|StringValueNode|BooleanValueNode|EnumValueNode|ListValueNode|ObjectValueNode $node + */ private function enumTypeSuggestion($type, ValueNode $node) { if ($type instanceof EnumType) { $suggestions = Utils::suggestionList( Printer::doPrint($node), array_map( - static function (EnumValueDefinition $value) { + static function (EnumValueDefinition $value) : string { return $value->name; }, $type->getValues() diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesAreInputTypes.php b/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesAreInputTypes.php index 5dc27b4..a1daaff 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesAreInputTypes.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesAreInputTypes.php @@ -18,7 +18,7 @@ class VariablesAreInputTypes extends ValidationRule public function getVisitor(ValidationContext $context) { return [ - NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $node) use ($context) { + NodeKind::VARIABLE_DEFINITION => static function (VariableDefinitionNode $node) use ($context) : void { $type = TypeInfo::typeFromAST($context->getSchema(), $node->type); // If the variable type is not an input type, return an error. diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesDefaultValueAllowed.php b/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesDefaultValueAllowed.php deleted file mode 100644 index a19c14d..0000000 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesDefaultValueAllowed.php +++ /dev/null @@ -1,65 +0,0 @@ - static function (VariableDefinitionNode $node) use ($context) { - $name = $node->variable->name->value; - $defaultValue = $node->defaultValue; - $type = $context->getInputType(); - if ($type instanceof NonNull && $defaultValue) { - $context->reportError( - new Error( - self::defaultForRequiredVarMessage( - $name, - $type, - $type->getWrappedType() - ), - [$defaultValue] - ) - ); - } - - return Visitor::skipNode(); - }, - NodeKind::SELECTION_SET => static function (SelectionSetNode $node) { - return Visitor::skipNode(); - }, - NodeKind::FRAGMENT_DEFINITION => static function (FragmentDefinitionNode $node) { - return Visitor::skipNode(); - }, - ]; - } - - public static function defaultForRequiredVarMessage($varName, $type, $guessType) - { - return sprintf( - 'Variable "$%s" of type "%s" is required and will not use the default value. Perhaps you meant to use type "%s".', - $varName, - $type, - $guessType - ); - } -} diff --git a/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesInAllowedPosition.php b/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesInAllowedPosition.php index 2deb0e9..717bd65 100644 --- a/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesInAllowedPosition.php +++ b/vendor/webonyx/graphql-php/src/Validator/Rules/VariablesInAllowedPosition.php @@ -6,35 +6,44 @@ namespace GraphQL\Validator\Rules; use GraphQL\Error\Error; use GraphQL\Language\AST\NodeKind; +use GraphQL\Language\AST\NullValueNode; use GraphQL\Language\AST\OperationDefinitionNode; +use GraphQL\Language\AST\ValueNode; use GraphQL\Language\AST\VariableDefinitionNode; -use GraphQL\Type\Definition\ListOfType; use GraphQL\Type\Definition\NonNull; +use GraphQL\Type\Definition\Type; +use GraphQL\Type\Schema; use GraphQL\Utils\TypeComparators; use GraphQL\Utils\TypeInfo; +use GraphQL\Utils\Utils; use GraphQL\Validator\ValidationContext; use function sprintf; class VariablesInAllowedPosition extends ValidationRule { - /** @var */ + /** + * A map from variable names to their definition nodes. + * + * @var VariableDefinitionNode[] + */ public $varDefMap; public function getVisitor(ValidationContext $context) { return [ NodeKind::OPERATION_DEFINITION => [ - 'enter' => function () { + 'enter' => function () : void { $this->varDefMap = []; }, - 'leave' => function (OperationDefinitionNode $operation) use ($context) { + 'leave' => function (OperationDefinitionNode $operation) use ($context) : void { $usages = $context->getRecursiveVariableUsages($operation); foreach ($usages as $usage) { - $node = $usage['node']; - $type = $usage['type']; - $varName = $node->name->value; - $varDef = $this->varDefMap[$varName] ?? null; + $node = $usage['node']; + $type = $usage['type']; + $defaultValue = $usage['defaultValue']; + $varName = $node->name->value; + $varDef = $this->varDefMap[$varName] ?? null; if ($varDef === null || $type === null) { continue; @@ -48,11 +57,7 @@ class VariablesInAllowedPosition extends ValidationRule $schema = $context->getSchema(); $varType = TypeInfo::typeFromAST($schema, $varDef->type); - if (! $varType || TypeComparators::isTypeSubTypeOf( - $schema, - $this->effectiveType($varType, $varDef), - $type - )) { + if (! $varType || $this->allowedVariableUsage($schema, $varType, $varDef->defaultValue, $type, $defaultValue)) { continue; } @@ -63,17 +68,12 @@ class VariablesInAllowedPosition extends ValidationRule } }, ], - NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $varDefNode) { + NodeKind::VARIABLE_DEFINITION => function (VariableDefinitionNode $varDefNode) : void { $this->varDefMap[$varDefNode->variable->name->value] = $varDefNode; }, ]; } - private function effectiveType($varType, $varDef) - { - return ! $varDef->defaultValue || $varType instanceof NonNull ? $varType : new NonNull($varType); - } - /** * A var type is allowed if it is the same or more strict than the expected * type. It can be more strict if the variable type is non-null when the @@ -90,23 +90,27 @@ class VariablesInAllowedPosition extends ValidationRule ); } - /** If a variable definition has a default value, it's effectively non-null. */ - private function varTypeAllowedForType($varType, $expectedType) + /** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + * + * @param ValueNode|null $varDefaultValue + * @param mixed $locationDefaultValue + */ + private function allowedVariableUsage(Schema $schema, Type $varType, $varDefaultValue, Type $locationType, $locationDefaultValue) : bool { - if ($expectedType instanceof NonNull) { - if ($varType instanceof NonNull) { - return $this->varTypeAllowedForType($varType->getWrappedType(), $expectedType->getWrappedType()); + if ($locationType instanceof NonNull && ! $varType instanceof NonNull) { + $hasNonNullVariableDefaultValue = $varDefaultValue && ! $varDefaultValue instanceof NullValueNode; + $hasLocationDefaultValue = ! Utils::isInvalid($locationDefaultValue); + if (! $hasNonNullVariableDefaultValue && ! $hasLocationDefaultValue) { + return false; } + $nullableLocationType = $locationType->getWrappedType(); - return false; - } - if ($varType instanceof NonNull) { - return $this->varTypeAllowedForType($varType->getWrappedType(), $expectedType); - } - if ($varType instanceof ListOfType && $expectedType instanceof ListOfType) { - return $this->varTypeAllowedForType($varType->getWrappedType(), $expectedType->getWrappedType()); + return TypeComparators::isTypeSubTypeOf($schema, $varType, $nullableLocationType); } - return $varType === $expectedType; + return TypeComparators::isTypeSubTypeOf($schema, $varType, $locationType); } } diff --git a/vendor/webonyx/graphql-php/src/Validator/SDLValidationContext.php b/vendor/webonyx/graphql-php/src/Validator/SDLValidationContext.php new file mode 100644 index 0000000..379515e --- /dev/null +++ b/vendor/webonyx/graphql-php/src/Validator/SDLValidationContext.php @@ -0,0 +1,9 @@ +schema = $schema; - $this->ast = $ast; + parent::__construct($ast, $schema); $this->typeInfo = $typeInfo; - $this->errors = []; $this->fragmentSpreads = new SplObjectStorage(); $this->recursivelyReferencedFragments = new SplObjectStorage(); $this->variableUsages = new SplObjectStorage(); $this->recursiveVariableUsages = new SplObjectStorage(); } - public function reportError(Error $error) - { - $this->errors[] = $error; - } - - /** - * @return Error[] - */ - public function getErrors() - { - return $this->errors; - } - - /** - * @return Schema - */ - public function getSchema() - { - return $this->schema; - } - /** * @return mixed[][] List of ['node' => VariableNode, 'type' => ?InputObjectType] */ @@ -102,11 +79,11 @@ class ValidationContext $usages = $this->getVariableUsages($operation); $fragments = $this->getRecursivelyReferencedFragments($operation); - $tmp = [$usages]; - foreach ($fragments as $i => $fragment) { - $tmp[] = $this->getVariableUsages($fragments[$i]); + $allUsages = [$usages]; + foreach ($fragments as $fragment) { + $allUsages[] = $this->getVariableUsages($fragment); } - $usages = call_user_func_array('array_merge', $tmp); + $usages = array_merge(...$allUsages); $this->recursiveVariableUsages[$operation] = $usages; } @@ -128,14 +105,18 @@ class ValidationContext Visitor::visitWithTypeInfo( $typeInfo, [ - NodeKind::VARIABLE_DEFINITION => static function () { + NodeKind::VARIABLE_DEFINITION => static function () : bool { return false; }, NodeKind::VARIABLE => static function (VariableNode $variable) use ( &$newUsages, $typeInfo - ) { - $newUsages[] = ['node' => $variable, 'type' => $typeInfo->getInputType()]; + ) : void { + $newUsages[] = [ + 'node' => $variable, + 'type' => $typeInfo->getInputType(), + 'defaultValue' => $typeInfo->getDefaultValue(), + ]; }, ] ) @@ -158,13 +139,13 @@ class ValidationContext $fragments = []; $collectedNames = []; $nodesToVisit = [$operation]; - while (! empty($nodesToVisit)) { + while (count($nodesToVisit) > 0) { $node = array_pop($nodesToVisit); $spreads = $this->getFragmentSpreads($node); foreach ($spreads as $spread) { $fragName = $spread->name->value; - if (! empty($collectedNames[$fragName])) { + if ($collectedNames[$fragName] ?? false) { continue; } @@ -185,24 +166,30 @@ class ValidationContext } /** + * @param OperationDefinitionNode|FragmentDefinitionNode $node + * * @return FragmentSpreadNode[] */ - public function getFragmentSpreads(HasSelectionSet $node) + public function getFragmentSpreads(HasSelectionSet $node) : array { $spreads = $this->fragmentSpreads[$node] ?? null; if ($spreads === null) { $spreads = []; /** @var SelectionSetNode[] $setsToVisit */ $setsToVisit = [$node->selectionSet]; - while (! empty($setsToVisit)) { + while (count($setsToVisit) > 0) { $set = array_pop($setsToVisit); for ($i = 0, $selectionCount = count($set->selections); $i < $selectionCount; $i++) { $selection = $set->selections[$i]; - if ($selection->kind === NodeKind::FRAGMENT_SPREAD) { + if ($selection instanceof FragmentSpreadNode) { $spreads[] = $selection; - } elseif ($selection->selectionSet) { - $setsToVisit[] = $selection->selectionSet; + } elseif ($selection instanceof FieldNode || $selection instanceof InlineFragmentNode) { + if ($selection->selectionSet) { + $setsToVisit[] = $selection->selectionSet; + } + } else { + throw InvariantViolation::shouldNotHappen(); } } } @@ -223,7 +210,7 @@ class ValidationContext if (! $fragments) { $fragments = []; foreach ($this->getDocument()->definitions as $statement) { - if ($statement->kind !== NodeKind::FRAGMENT_DEFINITION) { + if (! ($statement instanceof FragmentDefinitionNode)) { continue; } @@ -235,44 +222,31 @@ class ValidationContext return $fragments[$name] ?? null; } - /** - * @return DocumentNode - */ - public function getDocument() - { - return $this->ast; - } - - /** - * Returns OutputType - * - * @return Type - */ - public function getType() + public function getType() : ?OutputType { return $this->typeInfo->getType(); } /** - * @return Type + * @return (CompositeType & Type) | null */ - public function getParentType() + public function getParentType() : ?CompositeType { return $this->typeInfo->getParentType(); } /** - * @return InputType + * @return (Type & InputType) | null */ - public function getInputType() + public function getInputType() : ?InputType { return $this->typeInfo->getInputType(); } /** - * @return InputType + * @return (Type&InputType)|null */ - public function getParentInputType() + public function getParentInputType() : ?InputType { return $this->typeInfo->getParentInputType(); }