From db5f81c2941ed20299be29ac623ed124c34ef981 Mon Sep 17 00:00:00 2001 From: Kilian Hofmann Date: Mon, 26 Jul 2021 01:35:16 +0200 Subject: [PATCH] Lighthouse 5.16 --- assets/js/graphiql.js | 4 +- composer.json | 1 + vendor/composer/ClassLoader.php | 44 +- vendor/composer/autoload_classmap.php | 13 +- vendor/composer/autoload_files.php | 107 +- vendor/composer/autoload_psr4.php | 60 +- vendor/composer/autoload_real.php | 9 +- vendor/composer/autoload_static.php | 434 +- vendor/composer/installed.json | 5435 ++++++++++++++--- vendor/guzzlehttp/guzzle/CHANGELOG.md | 1338 ---- vendor/guzzlehttp/guzzle/Dockerfile | 18 - vendor/guzzlehttp/guzzle/LICENSE | 19 - vendor/guzzlehttp/guzzle/README.md | 90 - vendor/guzzlehttp/guzzle/UPGRADING.md | 1203 ---- vendor/guzzlehttp/guzzle/composer.json | 59 - vendor/guzzlehttp/guzzle/src/Client.php | 501 -- .../guzzlehttp/guzzle/src/ClientInterface.php | 87 - .../guzzle/src/Cookie/CookieJar.php | 316 - .../guzzle/src/Cookie/CookieJarInterface.php | 84 - .../guzzle/src/Cookie/FileCookieJar.php | 91 - .../guzzle/src/Cookie/SessionCookieJar.php | 72 - .../guzzle/src/Cookie/SetCookie.php | 403 -- .../src/Exception/BadResponseException.php | 27 - .../guzzle/src/Exception/ClientException.php | 9 - .../guzzle/src/Exception/ConnectException.php | 37 - .../guzzle/src/Exception/GuzzleException.php | 23 - .../Exception/InvalidArgumentException.php | 7 - .../guzzle/src/Exception/RequestException.php | 192 - .../guzzle/src/Exception/SeekException.php | 27 - .../guzzle/src/Exception/ServerException.php | 9 - .../Exception/TooManyRedirectsException.php | 6 - .../src/Exception/TransferException.php | 6 - .../guzzle/src/Handler/CurlFactory.php | 585 -- .../src/Handler/CurlFactoryInterface.php | 27 - .../guzzle/src/Handler/CurlHandler.php | 45 - .../guzzle/src/Handler/CurlMultiHandler.php | 219 - .../guzzle/src/Handler/EasyHandle.php | 92 - .../guzzle/src/Handler/MockHandler.php | 195 - .../guzzlehttp/guzzle/src/Handler/Proxy.php | 55 - .../guzzle/src/Handler/StreamHandler.php | 545 -- vendor/guzzlehttp/guzzle/src/HandlerStack.php | 277 - .../guzzle/src/MessageFormatter.php | 185 - vendor/guzzlehttp/guzzle/src/Middleware.php | 254 - vendor/guzzlehttp/guzzle/src/Pool.php | 134 - .../guzzle/src/PrepareBodyMiddleware.php | 111 - .../guzzle/src/RedirectMiddleware.php | 255 - .../guzzlehttp/guzzle/src/RequestOptions.php | 263 - .../guzzlehttp/guzzle/src/RetryMiddleware.php | 128 - .../guzzlehttp/guzzle/src/TransferStats.php | 126 - vendor/guzzlehttp/guzzle/src/UriTemplate.php | 237 - vendor/guzzlehttp/guzzle/src/Utils.php | 92 - vendor/guzzlehttp/guzzle/src/functions.php | 334 - .../guzzle/src/functions_include.php | 6 - vendor/guzzlehttp/promises/CHANGELOG.md | 65 - vendor/guzzlehttp/promises/LICENSE | 19 - vendor/guzzlehttp/promises/Makefile | 13 - vendor/guzzlehttp/promises/README.md | 504 -- vendor/guzzlehttp/promises/composer.json | 34 - .../promises/src/AggregateException.php | 16 - .../promises/src/CancellationException.php | 9 - vendor/guzzlehttp/promises/src/Coroutine.php | 151 - .../guzzlehttp/promises/src/EachPromise.php | 229 - .../promises/src/FulfilledPromise.php | 82 - vendor/guzzlehttp/promises/src/Promise.php | 280 - .../promises/src/PromiseInterface.php | 93 - .../promises/src/PromisorInterface.php | 15 - .../promises/src/RejectedPromise.php | 87 - .../promises/src/RejectionException.php | 47 - vendor/guzzlehttp/promises/src/TaskQueue.php | 66 - .../promises/src/TaskQueueInterface.php | 25 - vendor/guzzlehttp/promises/src/functions.php | 457 -- .../promises/src/functions_include.php | 6 - vendor/guzzlehttp/psr7/CHANGELOG.md | 246 - vendor/guzzlehttp/psr7/LICENSE | 19 - vendor/guzzlehttp/psr7/README.md | 745 --- vendor/guzzlehttp/psr7/composer.json | 49 - vendor/guzzlehttp/psr7/src/AppendStream.php | 241 - vendor/guzzlehttp/psr7/src/BufferStream.php | 137 - vendor/guzzlehttp/psr7/src/CachingStream.php | 138 - vendor/guzzlehttp/psr7/src/DroppingStream.php | 42 - vendor/guzzlehttp/psr7/src/FnStream.php | 158 - vendor/guzzlehttp/psr7/src/InflateStream.php | 52 - vendor/guzzlehttp/psr7/src/LazyOpenStream.php | 39 - vendor/guzzlehttp/psr7/src/LimitStream.php | 155 - vendor/guzzlehttp/psr7/src/MessageTrait.php | 213 - .../guzzlehttp/psr7/src/MultipartStream.php | 153 - vendor/guzzlehttp/psr7/src/NoSeekStream.php | 22 - vendor/guzzlehttp/psr7/src/PumpStream.php | 165 - vendor/guzzlehttp/psr7/src/Request.php | 151 - vendor/guzzlehttp/psr7/src/Response.php | 154 - vendor/guzzlehttp/psr7/src/Rfc7230.php | 18 - vendor/guzzlehttp/psr7/src/ServerRequest.php | 376 -- vendor/guzzlehttp/psr7/src/Stream.php | 267 - .../psr7/src/StreamDecoratorTrait.php | 149 - vendor/guzzlehttp/psr7/src/StreamWrapper.php | 161 - vendor/guzzlehttp/psr7/src/UploadedFile.php | 316 - vendor/guzzlehttp/psr7/src/Uri.php | 760 --- vendor/guzzlehttp/psr7/src/UriNormalizer.php | 216 - vendor/guzzlehttp/psr7/src/UriResolver.php | 219 - vendor/guzzlehttp/psr7/src/functions.php | 899 --- .../guzzlehttp/psr7/src/functions_include.php | 6 - 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/paragonie/random_compat/LICENSE | 22 - vendor/paragonie/random_compat/build-phar.sh | 5 - vendor/paragonie/random_compat/composer.json | 34 - .../dist/random_compat.phar.pubkey | 5 - .../dist/random_compat.phar.pubkey.asc | 11 - vendor/paragonie/random_compat/lib/random.php | 32 - .../random_compat/other/build_phar.php | 57 - .../random_compat/psalm-autoload.php | 9 - vendor/paragonie/random_compat/psalm.xml | 19 - vendor/psr/http-message/CHANGELOG.md | 36 - vendor/psr/http-message/LICENSE | 19 - vendor/psr/http-message/README.md | 13 - vendor/psr/http-message/composer.json | 26 - .../psr/http-message/src/MessageInterface.php | 187 - .../psr/http-message/src/RequestInterface.php | 129 - .../http-message/src/ResponseInterface.php | 68 - .../src/ServerRequestInterface.php | 261 - .../psr/http-message/src/StreamInterface.php | 158 - .../src/UploadedFileInterface.php | 123 - vendor/psr/http-message/src/UriInterface.php | 323 - vendor/ralouphie/getallheaders/LICENSE | 21 - vendor/ralouphie/getallheaders/README.md | 27 - vendor/ralouphie/getallheaders/composer.json | 26 - .../getallheaders/src/getallheaders.php | 46 - vendor/symfony/polyfill-intl-idn/Idn.php | 144 +- .../symfony/polyfill-intl-idn/bootstrap.php | 14 +- .../symfony/polyfill-intl-idn/composer.json | 5 +- .../polyfill-intl-normalizer/Normalizer.php | 42 +- .../Resources/stubs/Normalizer.php | 18 +- .../polyfill-intl-normalizer/bootstrap.php | 8 +- .../polyfill-intl-normalizer/composer.json | 4 +- vendor/symfony/polyfill-php70/LICENSE | 19 - vendor/symfony/polyfill-php70/Php70.php | 74 - vendor/symfony/polyfill-php70/README.md | 28 - .../Resources/stubs/ArithmeticError.php | 5 - .../Resources/stubs/AssertionError.php | 5 - .../Resources/stubs/DivisionByZeroError.php | 5 - .../polyfill-php70/Resources/stubs/Error.php | 5 - .../Resources/stubs/ParseError.php | 5 - ...SessionUpdateTimestampHandlerInterface.php | 23 - .../Resources/stubs/TypeError.php | 5 - vendor/symfony/polyfill-php70/bootstrap.php | 30 - vendor/symfony/polyfill-php70/composer.json | 37 - vendor/symfony/polyfill-php72/Php72.php | 22 +- vendor/symfony/polyfill-php72/bootstrap.php | 16 +- vendor/symfony/polyfill-php72/composer.json | 4 +- 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 - vendor/webonyx/graphql-php/phpstan.neon.dist | 46 +- vendor/webonyx/graphql-php/src/Deferred.php | 61 +- .../webonyx/graphql-php/src/Error/Debug.php | 16 - .../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/Executor/ExecutionContext.php | 16 +- .../src/Executor/ExecutionResult.php | 22 +- .../graphql-php/src/Executor/Executor.php | 61 +- .../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/IDType.php | 32 +- .../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/UnionType.php | 47 +- .../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 +- vendor/webonyx/graphql-php/src/Utils/AST.php | 89 +- .../src/Utils/ASTDefinitionBuilder.php | 334 +- .../src/Utils/BreakingChangesFinder.php | 97 +- .../graphql-php/src/Utils/BuildSchema.php | 102 +- .../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/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 - .../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 +- .../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/ValidationContext.php | 116 +- 736 files changed, 26648 insertions(+), 36472 deletions(-) delete mode 100644 vendor/guzzlehttp/guzzle/CHANGELOG.md delete mode 100644 vendor/guzzlehttp/guzzle/Dockerfile delete mode 100644 vendor/guzzlehttp/guzzle/LICENSE delete mode 100644 vendor/guzzlehttp/guzzle/README.md delete mode 100644 vendor/guzzlehttp/guzzle/UPGRADING.md delete mode 100644 vendor/guzzlehttp/guzzle/composer.json delete mode 100644 vendor/guzzlehttp/guzzle/src/Client.php delete mode 100644 vendor/guzzlehttp/guzzle/src/ClientInterface.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ClientException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ConnectException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/InvalidArgumentException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/RequestException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/SeekException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ServerException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/TooManyRedirectsException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Exception/TransferException.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/Proxy.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php delete mode 100644 vendor/guzzlehttp/guzzle/src/HandlerStack.php delete mode 100644 vendor/guzzlehttp/guzzle/src/MessageFormatter.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Middleware.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Pool.php delete mode 100644 vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php delete mode 100644 vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php delete mode 100644 vendor/guzzlehttp/guzzle/src/RequestOptions.php delete mode 100644 vendor/guzzlehttp/guzzle/src/RetryMiddleware.php delete mode 100644 vendor/guzzlehttp/guzzle/src/TransferStats.php delete mode 100644 vendor/guzzlehttp/guzzle/src/UriTemplate.php delete mode 100644 vendor/guzzlehttp/guzzle/src/Utils.php delete mode 100644 vendor/guzzlehttp/guzzle/src/functions.php delete mode 100644 vendor/guzzlehttp/guzzle/src/functions_include.php delete mode 100644 vendor/guzzlehttp/promises/CHANGELOG.md delete mode 100644 vendor/guzzlehttp/promises/LICENSE delete mode 100644 vendor/guzzlehttp/promises/Makefile delete mode 100644 vendor/guzzlehttp/promises/README.md delete mode 100644 vendor/guzzlehttp/promises/composer.json delete mode 100644 vendor/guzzlehttp/promises/src/AggregateException.php delete mode 100644 vendor/guzzlehttp/promises/src/CancellationException.php delete mode 100644 vendor/guzzlehttp/promises/src/Coroutine.php delete mode 100644 vendor/guzzlehttp/promises/src/EachPromise.php delete mode 100644 vendor/guzzlehttp/promises/src/FulfilledPromise.php delete mode 100644 vendor/guzzlehttp/promises/src/Promise.php delete mode 100644 vendor/guzzlehttp/promises/src/PromiseInterface.php delete mode 100644 vendor/guzzlehttp/promises/src/PromisorInterface.php delete mode 100644 vendor/guzzlehttp/promises/src/RejectedPromise.php delete mode 100644 vendor/guzzlehttp/promises/src/RejectionException.php delete mode 100644 vendor/guzzlehttp/promises/src/TaskQueue.php delete mode 100644 vendor/guzzlehttp/promises/src/TaskQueueInterface.php delete mode 100644 vendor/guzzlehttp/promises/src/functions.php delete mode 100644 vendor/guzzlehttp/promises/src/functions_include.php delete mode 100644 vendor/guzzlehttp/psr7/CHANGELOG.md delete mode 100644 vendor/guzzlehttp/psr7/LICENSE delete mode 100644 vendor/guzzlehttp/psr7/README.md delete mode 100644 vendor/guzzlehttp/psr7/composer.json delete mode 100644 vendor/guzzlehttp/psr7/src/AppendStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/BufferStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/CachingStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/DroppingStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/FnStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/InflateStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/LazyOpenStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/LimitStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/MessageTrait.php delete mode 100644 vendor/guzzlehttp/psr7/src/MultipartStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/NoSeekStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/PumpStream.php delete mode 100644 vendor/guzzlehttp/psr7/src/Request.php delete mode 100644 vendor/guzzlehttp/psr7/src/Response.php delete mode 100644 vendor/guzzlehttp/psr7/src/Rfc7230.php delete mode 100644 vendor/guzzlehttp/psr7/src/ServerRequest.php delete mode 100644 vendor/guzzlehttp/psr7/src/Stream.php delete mode 100644 vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php delete mode 100644 vendor/guzzlehttp/psr7/src/StreamWrapper.php delete mode 100644 vendor/guzzlehttp/psr7/src/UploadedFile.php delete mode 100644 vendor/guzzlehttp/psr7/src/Uri.php delete mode 100644 vendor/guzzlehttp/psr7/src/UriNormalizer.php delete mode 100644 vendor/guzzlehttp/psr7/src/UriResolver.php delete mode 100644 vendor/guzzlehttp/psr7/src/functions.php delete mode 100644 vendor/guzzlehttp/psr7/src/functions_include.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 delete mode 100644 vendor/paragonie/random_compat/LICENSE delete mode 100644 vendor/paragonie/random_compat/build-phar.sh delete mode 100644 vendor/paragonie/random_compat/composer.json delete mode 100644 vendor/paragonie/random_compat/dist/random_compat.phar.pubkey delete mode 100644 vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc delete mode 100644 vendor/paragonie/random_compat/lib/random.php delete mode 100644 vendor/paragonie/random_compat/other/build_phar.php delete mode 100644 vendor/paragonie/random_compat/psalm-autoload.php delete mode 100644 vendor/paragonie/random_compat/psalm.xml delete mode 100644 vendor/psr/http-message/CHANGELOG.md delete mode 100644 vendor/psr/http-message/LICENSE delete mode 100644 vendor/psr/http-message/README.md delete mode 100644 vendor/psr/http-message/composer.json delete mode 100644 vendor/psr/http-message/src/MessageInterface.php delete mode 100644 vendor/psr/http-message/src/RequestInterface.php delete mode 100644 vendor/psr/http-message/src/ResponseInterface.php delete mode 100644 vendor/psr/http-message/src/ServerRequestInterface.php delete mode 100644 vendor/psr/http-message/src/StreamInterface.php delete mode 100644 vendor/psr/http-message/src/UploadedFileInterface.php delete mode 100644 vendor/psr/http-message/src/UriInterface.php delete mode 100644 vendor/ralouphie/getallheaders/LICENSE delete mode 100644 vendor/ralouphie/getallheaders/README.md delete mode 100644 vendor/ralouphie/getallheaders/composer.json delete mode 100644 vendor/ralouphie/getallheaders/src/getallheaders.php delete mode 100644 vendor/symfony/polyfill-php70/LICENSE delete mode 100644 vendor/symfony/polyfill-php70/Php70.php delete mode 100644 vendor/symfony/polyfill-php70/README.md delete mode 100644 vendor/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php delete mode 100644 vendor/symfony/polyfill-php70/Resources/stubs/AssertionError.php delete mode 100644 vendor/symfony/polyfill-php70/Resources/stubs/DivisionByZeroError.php delete mode 100644 vendor/symfony/polyfill-php70/Resources/stubs/Error.php delete mode 100644 vendor/symfony/polyfill-php70/Resources/stubs/ParseError.php delete mode 100644 vendor/symfony/polyfill-php70/Resources/stubs/SessionUpdateTimestampHandlerInterface.php delete mode 100644 vendor/symfony/polyfill-php70/Resources/stubs/TypeError.php delete mode 100644 vendor/symfony/polyfill-php70/bootstrap.php delete mode 100644 vendor/symfony/polyfill-php70/composer.json 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 delete mode 100644 vendor/webonyx/graphql-php/src/Error/Debug.php delete mode 100644 vendor/webonyx/graphql-php/src/Schema.php delete mode 100644 vendor/webonyx/graphql-php/src/Validator/Rules/ProvidedNonNullArguments.php delete mode 100644 vendor/webonyx/graphql-php/src/Validator/Rules/VariablesDefaultValueAllowed.php diff --git a/assets/js/graphiql.js b/assets/js/graphiql.js index ab37092..072dfde 100644 --- a/assets/js/graphiql.js +++ b/assets/js/graphiql.js @@ -32920,7 +32920,7 @@ var _validUrl = __webpack_require__(429); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var options = { method: 'post', headers: { 'Content-Type': 'application/json' } }; -var endpoint = 'https://ga-development.hofmannnet.myhome-server.de/graphql/'; // Initial +var endpoint = 'http://localhost/graphql/'; // Initial var defaultQuery = '\n# Welcome to GraphiQL\n#\n# GraphiQL is an in-browser tool for writing, validating, and\n# testing GraphQL queries.\n#\n# Type queries into this side of the screen, and you will see intelligent\n# typeaheads aware of the current GraphQL type schema and live syntax and\n# validation errors highlighted within the text.\n#\n# GraphQL queries typically start with a "{" character. Lines that starts\n# with a # are ignored.\n#\n# An example GraphQL query might look like:\n#\n# {\n# field(arg: "value") {\n# subField\n# }\n# }\n#\n# Keyboard shortcuts:\n#\n# Run Query: Ctrl-Enter (or press the play button above)\n#\n# Auto Complete: Ctrl-Space (or just start typing)\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# Default endpoint is an instance of https://www.graph.cool/\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\nquery {\n countries {\n name\n }\n}\n'; @@ -61202,4 +61202,4 @@ module.exports = __webpack_require__(185); /***/ }) -/******/ ]); \ No newline at end of file +/******/ ]); diff --git a/composer.json b/composer.json index f0359c3..62e65a9 100644 --- a/composer.json +++ b/composer.json @@ -3,6 +3,7 @@ "type": "october-plugin", "description": "None", "require": { +"nuwave/lighthouse": "^5.0", "composer/installers": "~1.0" } } diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php index fce8549..6d0c3f2 100644 --- a/vendor/composer/ClassLoader.php +++ b/vendor/composer/ClassLoader.php @@ -37,11 +37,13 @@ namespace Composer\Autoload; * * @author Fabien Potencier * @author Jordi Boggiano - * @see http://www.php-fig.org/psr/psr-0/ - * @see http://www.php-fig.org/psr/psr-4/ + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ */ class ClassLoader { + private $vendorDir; + // PSR-4 private $prefixLengthsPsr4 = array(); private $prefixDirsPsr4 = array(); @@ -57,10 +59,17 @@ class ClassLoader private $missingClasses = array(); private $apcuPrefix; + private static $registeredLoaders = array(); + + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + } + public function getPrefixes() { if (!empty($this->prefixesPsr0)) { - return call_user_func_array('array_merge', $this->prefixesPsr0); + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); @@ -300,6 +309,17 @@ class ClassLoader public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } } /** @@ -308,13 +328,17 @@ class ClassLoader public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } } /** * Loads the given class or interface. * * @param string $class The name of the class - * @return bool|null True if loaded, null otherwise + * @return true|null True if loaded, null otherwise */ public function loadClass($class) { @@ -323,6 +347,8 @@ class ClassLoader return true; } + + return null; } /** @@ -367,6 +393,16 @@ class ClassLoader return $file; } + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + private function findFileWithExtension($class, $ext) { // PSR-4 lookup diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php index 6e0d84a..83006fa 100644 --- a/vendor/composer/autoload_classmap.php +++ b/vendor/composer/autoload_classmap.php @@ -6,12 +6,11 @@ $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( - 'ArithmeticError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php', - 'AssertionError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/AssertionError.php', - 'DivisionByZeroError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/DivisionByZeroError.php', - 'Error' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/Error.php', + 'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'JsonException' => $vendorDir . '/symfony/polyfill-php73/Resources/stubs/JsonException.php', 'Normalizer' => $vendorDir . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', - 'ParseError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/ParseError.php', - 'SessionUpdateTimestampHandlerInterface' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/SessionUpdateTimestampHandlerInterface.php', - 'TypeError' => $vendorDir . '/symfony/polyfill-php70/Resources/stubs/TypeError.php', + 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', ); diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php index 851b997..6c4b263 100644 --- a/vendor/composer/autoload_files.php +++ b/vendor/composer/autoload_files.php @@ -6,12 +6,109 @@ $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( - '7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', 'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php', - '023d27dca8066ef29e6739335ea73bad' => $vendorDir . '/symfony/polyfill-php70/bootstrap.php', '25072dd6e2470089de65ae7bf11d3109' => $vendorDir . '/symfony/polyfill-php72/bootstrap.php', - 'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php', - 'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php', 'f598d06aa772fa33d905e87be6398fb1' => $vendorDir . '/symfony/polyfill-intl-idn/bootstrap.php', - '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', + '0d59ee240a4cd96ddbb4ff164fccea4d' => $vendorDir . '/symfony/polyfill-php73/bootstrap.php', + '60799491728b879e74601d83e38b2cad' => $vendorDir . '/illuminate/collections/helpers.php', + 'a1105708a18b76903365ca1c4aa61b02' => $vendorDir . '/symfony/translation/Resources/functions.php', + '72579e7bd17821bb1321b87411366eae' => $vendorDir . '/illuminate/support/helpers.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', + '667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php', + '538ca81a9a966a6716601ecf48f4eaef' => $vendorDir . '/opis/closure/functions.php', + 'e39a8b23c42d4e1452234d762b03835a' => $vendorDir . '/ramsey/uuid/src/functions.php', + '51fcf4e06c07cc00c920b44bcd900e7a' => $vendorDir . '/thecodingmachine/safe/deprecated/apc.php', + '47f619d9197b36cf5ab70738d7743fe2' => $vendorDir . '/thecodingmachine/safe/deprecated/libevent.php', + 'ea6bb8a12ef9b68f6ada99058e530760' => $vendorDir . '/thecodingmachine/safe/deprecated/mssql.php', + '9a29089eb3ce41a446744c68a00f118c' => $vendorDir . '/thecodingmachine/safe/deprecated/stats.php', + '72243e5536b63e298acb6476f01f1aff' => $vendorDir . '/thecodingmachine/safe/lib/special_cases.php', + '3f648889e687f31c52f949ba8a9d0873' => $vendorDir . '/thecodingmachine/safe/generated/apache.php', + 'eeb4581d958421a4244aaa4167c6a575' => $vendorDir . '/thecodingmachine/safe/generated/apcu.php', + '04cb0b3c1dac5b5ddb23c14e3d66dbe9' => $vendorDir . '/thecodingmachine/safe/generated/array.php', + '450b332a74a9a21e043c5e953485a791' => $vendorDir . '/thecodingmachine/safe/generated/bzip2.php', + '6e9b7954ecfd7cbb9ca239319d1acdb6' => $vendorDir . '/thecodingmachine/safe/generated/calendar.php', + '2c6d7e8bd2de9a272a9d4d43b0a4304a' => $vendorDir . '/thecodingmachine/safe/generated/classobj.php', + '0b8231c1ad0865447c988a4c16b4001f' => $vendorDir . '/thecodingmachine/safe/generated/com.php', + '7643a71fe1c3256058c8fee234cb86e5' => $vendorDir . '/thecodingmachine/safe/generated/cubrid.php', + '68e1365710575942efc1d55000032cee' => $vendorDir . '/thecodingmachine/safe/generated/curl.php', + '02fd26bca803106c5b942a7197c3ad8b' => $vendorDir . '/thecodingmachine/safe/generated/datetime.php', + 'f4817dcbd956cd221b1c31f6fbd5749c' => $vendorDir . '/thecodingmachine/safe/generated/dir.php', + '51c3f2d10ca61a70dbcea0e38d8e902d' => $vendorDir . '/thecodingmachine/safe/generated/eio.php', + '1d34f34327ca3e81535963016e3be2c3' => $vendorDir . '/thecodingmachine/safe/generated/errorfunc.php', + '4fd0ba2d3717b0424d474bebfdafa2b4' => $vendorDir . '/thecodingmachine/safe/generated/exec.php', + '98f4dae054bc7fb19c13be14935cbdd3' => $vendorDir . '/thecodingmachine/safe/generated/fileinfo.php', + '5530ae063ba88323eaf0a07904efdf85' => $vendorDir . '/thecodingmachine/safe/generated/filesystem.php', + '633f4f134975d70e97bddad83348e91a' => $vendorDir . '/thecodingmachine/safe/generated/filter.php', + 'fbd163fc68c5faf73d5ed4002ffd836d' => $vendorDir . '/thecodingmachine/safe/generated/fpm.php', + '21b511999d61411fab0692ff8795bbed' => $vendorDir . '/thecodingmachine/safe/generated/ftp.php', + '85fbd73fc92365cd90526b0ea03cae3a' => $vendorDir . '/thecodingmachine/safe/generated/funchand.php', + '51df9c146e0b7dcbdf358d8abd24dbdc' => $vendorDir . '/thecodingmachine/safe/generated/gmp.php', + '93bb7fe678d7dcfb1322f8e3475a48b0' => $vendorDir . '/thecodingmachine/safe/generated/gnupg.php', + 'c171ba99cf316379ff66468392bf4950' => $vendorDir . '/thecodingmachine/safe/generated/hash.php', + '5ab4aad4c28e468209fbfcceb2e5e6a5' => $vendorDir . '/thecodingmachine/safe/generated/ibase.php', + '4d57409c5e8e576b0c64c08d9d731cfb' => $vendorDir . '/thecodingmachine/safe/generated/ibmDb2.php', + 'eeb246d5403972a9d62106e4a4883496' => $vendorDir . '/thecodingmachine/safe/generated/iconv.php', + 'c28a05f498c01b810a714f7214b7a8da' => $vendorDir . '/thecodingmachine/safe/generated/image.php', + '8063cd92acdf00fd978b5599eb7cc142' => $vendorDir . '/thecodingmachine/safe/generated/imap.php', + '8bd26dbe768e9c9599edad7b198e5446' => $vendorDir . '/thecodingmachine/safe/generated/info.php', + '0c577fe603b029d4b65c84376b15dbd5' => $vendorDir . '/thecodingmachine/safe/generated/ingres-ii.php', + 'd4362910bde43c0f956b52527effd7d4' => $vendorDir . '/thecodingmachine/safe/generated/inotify.php', + '696ba49197d9b55f0428a12bb5a818e1' => $vendorDir . '/thecodingmachine/safe/generated/json.php', + '9818aaa99c8647c63f8ef62b7a368160' => $vendorDir . '/thecodingmachine/safe/generated/ldap.php', + 'bcf523ff2a195eb08e0fbb668ed784d0' => $vendorDir . '/thecodingmachine/safe/generated/libxml.php', + '68be68a9a8b95bb56cab6109ff03bc88' => $vendorDir . '/thecodingmachine/safe/generated/lzf.php', + 'bdca804bb0904ea9f53f328dfc0bb8a5' => $vendorDir . '/thecodingmachine/safe/generated/mailparse.php', + 'b0a3fcac3eaf55445796d6af26b89366' => $vendorDir . '/thecodingmachine/safe/generated/mbstring.php', + '98de16b8db03eb0cb4d318b4402215a6' => $vendorDir . '/thecodingmachine/safe/generated/misc.php', + 'c112440003b56e243b192c11fa9d836e' => $vendorDir . '/thecodingmachine/safe/generated/msql.php', + '7cefd81607cd21b8b3a15656eb6465f5' => $vendorDir . '/thecodingmachine/safe/generated/mysql.php', + 'aaf438b080089c6d0686679cd34aa72e' => $vendorDir . '/thecodingmachine/safe/generated/mysqli.php', + 'df0ef890e9afbf95f3924feb1c7a89f3' => $vendorDir . '/thecodingmachine/safe/generated/mysqlndMs.php', + 'db595fee5972867e45c5327010d78735' => $vendorDir . '/thecodingmachine/safe/generated/mysqlndQc.php', + 'cbac956836b72483dcff1ac39d5c0a0f' => $vendorDir . '/thecodingmachine/safe/generated/network.php', + '6c8f89dfbdc117d7871f572269363f25' => $vendorDir . '/thecodingmachine/safe/generated/oci8.php', + '169a669966a45c06bf55ed029122729b' => $vendorDir . '/thecodingmachine/safe/generated/opcache.php', + 'def61bf4fecd4d4bca7354919cd69302' => $vendorDir . '/thecodingmachine/safe/generated/openssl.php', + '26bb010649a6d32d4120181458aa6ef2' => $vendorDir . '/thecodingmachine/safe/generated/outcontrol.php', + '1212c201fe43c7492a085b2c71505e0f' => $vendorDir . '/thecodingmachine/safe/generated/password.php', + '002ebcb842e2c0d5b7f67fe64cc93158' => $vendorDir . '/thecodingmachine/safe/generated/pcntl.php', + '86df38612982dade72c7085ce7eca81f' => $vendorDir . '/thecodingmachine/safe/generated/pcre.php', + '1cacc3e65f82a473fbd5507c7ce4385d' => $vendorDir . '/thecodingmachine/safe/generated/pdf.php', + '1fc22f445c69ea8706e82fce301c0831' => $vendorDir . '/thecodingmachine/safe/generated/pgsql.php', + 'c70b42561584f7144bff38cd63c4eef3' => $vendorDir . '/thecodingmachine/safe/generated/posix.php', + '9923214639c32ca5173db03a177d3b63' => $vendorDir . '/thecodingmachine/safe/generated/ps.php', + '7e9c3f8eae2b5bf42205c4f1295cb7a7' => $vendorDir . '/thecodingmachine/safe/generated/pspell.php', + '91aa91f6245c349c2e2e88bd0025f199' => $vendorDir . '/thecodingmachine/safe/generated/readline.php', + 'd43773cacb9e5e8e897aa255e32007d1' => $vendorDir . '/thecodingmachine/safe/generated/rpminfo.php', + 'f053a3849e9e8383762b34b91db0320b' => $vendorDir . '/thecodingmachine/safe/generated/rrd.php', + '775b964f72f827a1bf87c65ab5b10800' => $vendorDir . '/thecodingmachine/safe/generated/sem.php', + '816428bd69c29ab5e1ed622af5dca0cd' => $vendorDir . '/thecodingmachine/safe/generated/session.php', + '5093e233bedbefaef0df262bfbab0a5c' => $vendorDir . '/thecodingmachine/safe/generated/shmop.php', + '01352920b0151f17e671266e44b52536' => $vendorDir . '/thecodingmachine/safe/generated/simplexml.php', + 'b080617b1d949683c2e37f8f01dc0e15' => $vendorDir . '/thecodingmachine/safe/generated/sockets.php', + '2708aa182ddcfe6ce27c96acaaa40f69' => $vendorDir . '/thecodingmachine/safe/generated/sodium.php', + 'f1b96cb260a5baeea9a7285cda82a1ec' => $vendorDir . '/thecodingmachine/safe/generated/solr.php', + '3fd8853757d0fe3557c179efb807afeb' => $vendorDir . '/thecodingmachine/safe/generated/spl.php', + '9312ce96a51c846913fcda5f186d58dd' => $vendorDir . '/thecodingmachine/safe/generated/sqlsrv.php', + 'd3eb383ad0b8b962b29dc4afd29d6715' => $vendorDir . '/thecodingmachine/safe/generated/ssdeep.php', + '42a09bc448f441a0b9f9367ea975c0bf' => $vendorDir . '/thecodingmachine/safe/generated/ssh2.php', + 'ef711077d356d1b33ca0b10b67b0be8f' => $vendorDir . '/thecodingmachine/safe/generated/stream.php', + '764b09f6df081cbb2807b97c6ace3866' => $vendorDir . '/thecodingmachine/safe/generated/strings.php', + 'ef241678769fee4a44aaa288f3b78aa1' => $vendorDir . '/thecodingmachine/safe/generated/swoole.php', + '0efc8f6778cba932b9e2a89e28de2452' => $vendorDir . '/thecodingmachine/safe/generated/uodbc.php', + 'd383d32907b98af53ee9208c62204fd0' => $vendorDir . '/thecodingmachine/safe/generated/uopz.php', + '2fd2e4060f7fe772660f002ce38f0b71' => $vendorDir . '/thecodingmachine/safe/generated/url.php', + '782249e03deebeaf57b9991ff5493aa0' => $vendorDir . '/thecodingmachine/safe/generated/var.php', + '344440cd1cd7200fdb4f12af0d3c587f' => $vendorDir . '/thecodingmachine/safe/generated/xdiff.php', + '3599f369219c658a5fb6c4fe66832f62' => $vendorDir . '/thecodingmachine/safe/generated/xml.php', + '7fcd313da9fae337051b091b3492c21b' => $vendorDir . '/thecodingmachine/safe/generated/xmlrpc.php', + 'd668c74cfa92d893b582356733d9a80e' => $vendorDir . '/thecodingmachine/safe/generated/yaml.php', + '4af1dca6db8c527c6eed27bff85ff0e5' => $vendorDir . '/thecodingmachine/safe/generated/yaz.php', + 'fe43ca06499ac37bc2dedd823af71eb5' => $vendorDir . '/thecodingmachine/safe/generated/zip.php', + '356736db98a6834f0a886b8d509b0ecd' => $vendorDir . '/thecodingmachine/safe/generated/zlib.php', + '8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php', ); diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index 99b563b..3b233c4 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -6,14 +6,64 @@ $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( + 'voku\\' => array($vendorDir . '/voku/portable-ascii/src/voku'), + 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), + 'Symfony\\Polyfill\\Php73\\' => array($vendorDir . '/symfony/polyfill-php73'), 'Symfony\\Polyfill\\Php72\\' => array($vendorDir . '/symfony/polyfill-php72'), - 'Symfony\\Polyfill\\Php70\\' => array($vendorDir . '/symfony/polyfill-php70'), + 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), 'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'), 'Symfony\\Polyfill\\Intl\\Idn\\' => array($vendorDir . '/symfony/polyfill-intl-idn'), - 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => array($vendorDir . '/symfony/polyfill-intl-grapheme'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), + 'Symfony\\Contracts\\Translation\\' => array($vendorDir . '/symfony/translation-contracts'), + 'Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'), + 'Symfony\\Contracts\\HttpClient\\' => array($vendorDir . '/symfony/http-client-contracts'), + 'Symfony\\Contracts\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher-contracts'), + 'Symfony\\Component\\VarDumper\\' => array($vendorDir . '/symfony/var-dumper'), + 'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'), + 'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'), + 'Symfony\\Component\\Routing\\' => array($vendorDir . '/symfony/routing'), + 'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'), + 'Symfony\\Component\\Mime\\' => array($vendorDir . '/symfony/mime'), + 'Symfony\\Component\\HttpKernel\\' => array($vendorDir . '/symfony/http-kernel'), + 'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'), + 'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'), + 'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'), + 'Symfony\\Component\\ErrorHandler\\' => array($vendorDir . '/symfony/error-handler'), + 'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'), + 'Safe\\' => array($vendorDir . '/thecodingmachine/safe/lib', $vendorDir . '/thecodingmachine/safe/deprecated', $vendorDir . '/thecodingmachine/safe/generated'), + 'Ramsey\\Uuid\\' => array($vendorDir . '/ramsey/uuid/src'), + 'Ramsey\\Collection\\' => array($vendorDir . '/ramsey/collection/src'), + 'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), + 'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'Opis\\Closure\\' => array($vendorDir . '/opis/closure/src'), 'Nuwave\\Lighthouse\\' => array($vendorDir . '/nuwave/lighthouse/src'), - 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), - 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), - 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), + 'Laragraph\\Utils\\' => array($vendorDir . '/laragraph/utils/src'), + 'Illuminate\\Validation\\' => array($vendorDir . '/illuminate/validation'), + 'Illuminate\\Translation\\' => array($vendorDir . '/illuminate/translation'), + 'Illuminate\\Support\\' => array($vendorDir . '/illuminate/macroable', $vendorDir . '/illuminate/collections', $vendorDir . '/illuminate/support'), + 'Illuminate\\Session\\' => array($vendorDir . '/illuminate/session'), + 'Illuminate\\Routing\\' => array($vendorDir . '/illuminate/routing'), + 'Illuminate\\Queue\\' => array($vendorDir . '/illuminate/queue'), + 'Illuminate\\Pipeline\\' => array($vendorDir . '/illuminate/pipeline'), + 'Illuminate\\Pagination\\' => array($vendorDir . '/illuminate/pagination'), + 'Illuminate\\Http\\' => array($vendorDir . '/illuminate/http'), + 'Illuminate\\Filesystem\\' => array($vendorDir . '/illuminate/filesystem'), + 'Illuminate\\Database\\' => array($vendorDir . '/illuminate/database'), + 'Illuminate\\Contracts\\' => array($vendorDir . '/illuminate/contracts'), + 'Illuminate\\Container\\' => array($vendorDir . '/illuminate/container'), + 'Illuminate\\Console\\' => array($vendorDir . '/illuminate/console'), + 'Illuminate\\Bus\\' => array($vendorDir . '/illuminate/bus'), + 'Illuminate\\Auth\\' => array($vendorDir . '/illuminate/auth'), + 'HaydenPierce\\ClassFinder\\UnitTest\\' => array($vendorDir . '/haydenpierce/class-finder/test/unit'), + 'HaydenPierce\\ClassFinder\\' => array($vendorDir . '/haydenpierce/class-finder/src'), 'GraphQL\\' => array($vendorDir . '/webonyx/graphql-php/src'), + 'Egulias\\EmailValidator\\' => array($vendorDir . '/egulias/email-validator/src'), + 'Doctrine\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib/Doctrine/Inflector'), + 'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib/Doctrine/Common/Lexer'), + 'Composer\\Installers\\' => array($vendorDir . '/composer/installers/src/Composer/Installers'), + 'Carbon\\' => array($vendorDir . '/nesbot/carbon/src/Carbon'), + 'Brick\\Math\\' => array($vendorDir . '/brick/math/src'), ); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index cc9299a..4e4a7b9 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -13,19 +13,24 @@ class ComposerAutoloaderInit02b791b67b928853969b061eb6816088 } } + /** + * @return \Composer\Autoload\ClassLoader + */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } + require __DIR__ . '/platform_check.php'; + spl_autoload_register(array('ComposerAutoloaderInit02b791b67b928853969b061eb6816088', 'loadClassLoader'), true, true); - self::$loader = $loader = new \Composer\Autoload\ClassLoader(); + self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__))); spl_autoload_unregister(array('ComposerAutoloaderInit02b791b67b928853969b061eb6816088', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); if ($useStaticLoader) { - require_once __DIR__ . '/autoload_static.php'; + require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit02b791b67b928853969b061eb6816088::getInitializer($loader)); } else { diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index 8de5d37..8e4e9a7 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -7,49 +7,238 @@ namespace Composer\Autoload; class ComposerStaticInit02b791b67b928853969b061eb6816088 { public static $files = array ( - '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', 'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php', - '023d27dca8066ef29e6739335ea73bad' => __DIR__ . '/..' . '/symfony/polyfill-php70/bootstrap.php', '25072dd6e2470089de65ae7bf11d3109' => __DIR__ . '/..' . '/symfony/polyfill-php72/bootstrap.php', - 'c964ee0ededf28c96ebd9db5099ef910' => __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php', - 'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php', 'f598d06aa772fa33d905e87be6398fb1' => __DIR__ . '/..' . '/symfony/polyfill-intl-idn/bootstrap.php', - '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', + '0d59ee240a4cd96ddbb4ff164fccea4d' => __DIR__ . '/..' . '/symfony/polyfill-php73/bootstrap.php', + '60799491728b879e74601d83e38b2cad' => __DIR__ . '/..' . '/illuminate/collections/helpers.php', + 'a1105708a18b76903365ca1c4aa61b02' => __DIR__ . '/..' . '/symfony/translation/Resources/functions.php', + '72579e7bd17821bb1321b87411366eae' => __DIR__ . '/..' . '/illuminate/support/helpers.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + '667aeda72477189d0494fecd327c3641' => __DIR__ . '/..' . '/symfony/var-dumper/Resources/functions/dump.php', + '538ca81a9a966a6716601ecf48f4eaef' => __DIR__ . '/..' . '/opis/closure/functions.php', + 'e39a8b23c42d4e1452234d762b03835a' => __DIR__ . '/..' . '/ramsey/uuid/src/functions.php', + '51fcf4e06c07cc00c920b44bcd900e7a' => __DIR__ . '/..' . '/thecodingmachine/safe/deprecated/apc.php', + '47f619d9197b36cf5ab70738d7743fe2' => __DIR__ . '/..' . '/thecodingmachine/safe/deprecated/libevent.php', + 'ea6bb8a12ef9b68f6ada99058e530760' => __DIR__ . '/..' . '/thecodingmachine/safe/deprecated/mssql.php', + '9a29089eb3ce41a446744c68a00f118c' => __DIR__ . '/..' . '/thecodingmachine/safe/deprecated/stats.php', + '72243e5536b63e298acb6476f01f1aff' => __DIR__ . '/..' . '/thecodingmachine/safe/lib/special_cases.php', + '3f648889e687f31c52f949ba8a9d0873' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/apache.php', + 'eeb4581d958421a4244aaa4167c6a575' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/apcu.php', + '04cb0b3c1dac5b5ddb23c14e3d66dbe9' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/array.php', + '450b332a74a9a21e043c5e953485a791' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/bzip2.php', + '6e9b7954ecfd7cbb9ca239319d1acdb6' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/calendar.php', + '2c6d7e8bd2de9a272a9d4d43b0a4304a' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/classobj.php', + '0b8231c1ad0865447c988a4c16b4001f' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/com.php', + '7643a71fe1c3256058c8fee234cb86e5' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/cubrid.php', + '68e1365710575942efc1d55000032cee' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/curl.php', + '02fd26bca803106c5b942a7197c3ad8b' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/datetime.php', + 'f4817dcbd956cd221b1c31f6fbd5749c' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/dir.php', + '51c3f2d10ca61a70dbcea0e38d8e902d' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/eio.php', + '1d34f34327ca3e81535963016e3be2c3' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/errorfunc.php', + '4fd0ba2d3717b0424d474bebfdafa2b4' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/exec.php', + '98f4dae054bc7fb19c13be14935cbdd3' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/fileinfo.php', + '5530ae063ba88323eaf0a07904efdf85' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/filesystem.php', + '633f4f134975d70e97bddad83348e91a' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/filter.php', + 'fbd163fc68c5faf73d5ed4002ffd836d' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/fpm.php', + '21b511999d61411fab0692ff8795bbed' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ftp.php', + '85fbd73fc92365cd90526b0ea03cae3a' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/funchand.php', + '51df9c146e0b7dcbdf358d8abd24dbdc' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/gmp.php', + '93bb7fe678d7dcfb1322f8e3475a48b0' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/gnupg.php', + 'c171ba99cf316379ff66468392bf4950' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/hash.php', + '5ab4aad4c28e468209fbfcceb2e5e6a5' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ibase.php', + '4d57409c5e8e576b0c64c08d9d731cfb' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ibmDb2.php', + 'eeb246d5403972a9d62106e4a4883496' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/iconv.php', + 'c28a05f498c01b810a714f7214b7a8da' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/image.php', + '8063cd92acdf00fd978b5599eb7cc142' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/imap.php', + '8bd26dbe768e9c9599edad7b198e5446' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/info.php', + '0c577fe603b029d4b65c84376b15dbd5' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ingres-ii.php', + 'd4362910bde43c0f956b52527effd7d4' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/inotify.php', + '696ba49197d9b55f0428a12bb5a818e1' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/json.php', + '9818aaa99c8647c63f8ef62b7a368160' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ldap.php', + 'bcf523ff2a195eb08e0fbb668ed784d0' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/libxml.php', + '68be68a9a8b95bb56cab6109ff03bc88' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/lzf.php', + 'bdca804bb0904ea9f53f328dfc0bb8a5' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/mailparse.php', + 'b0a3fcac3eaf55445796d6af26b89366' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/mbstring.php', + '98de16b8db03eb0cb4d318b4402215a6' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/misc.php', + 'c112440003b56e243b192c11fa9d836e' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/msql.php', + '7cefd81607cd21b8b3a15656eb6465f5' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/mysql.php', + 'aaf438b080089c6d0686679cd34aa72e' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/mysqli.php', + 'df0ef890e9afbf95f3924feb1c7a89f3' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/mysqlndMs.php', + 'db595fee5972867e45c5327010d78735' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/mysqlndQc.php', + 'cbac956836b72483dcff1ac39d5c0a0f' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/network.php', + '6c8f89dfbdc117d7871f572269363f25' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/oci8.php', + '169a669966a45c06bf55ed029122729b' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/opcache.php', + 'def61bf4fecd4d4bca7354919cd69302' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/openssl.php', + '26bb010649a6d32d4120181458aa6ef2' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/outcontrol.php', + '1212c201fe43c7492a085b2c71505e0f' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/password.php', + '002ebcb842e2c0d5b7f67fe64cc93158' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/pcntl.php', + '86df38612982dade72c7085ce7eca81f' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/pcre.php', + '1cacc3e65f82a473fbd5507c7ce4385d' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/pdf.php', + '1fc22f445c69ea8706e82fce301c0831' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/pgsql.php', + 'c70b42561584f7144bff38cd63c4eef3' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/posix.php', + '9923214639c32ca5173db03a177d3b63' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ps.php', + '7e9c3f8eae2b5bf42205c4f1295cb7a7' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/pspell.php', + '91aa91f6245c349c2e2e88bd0025f199' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/readline.php', + 'd43773cacb9e5e8e897aa255e32007d1' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/rpminfo.php', + 'f053a3849e9e8383762b34b91db0320b' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/rrd.php', + '775b964f72f827a1bf87c65ab5b10800' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/sem.php', + '816428bd69c29ab5e1ed622af5dca0cd' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/session.php', + '5093e233bedbefaef0df262bfbab0a5c' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/shmop.php', + '01352920b0151f17e671266e44b52536' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/simplexml.php', + 'b080617b1d949683c2e37f8f01dc0e15' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/sockets.php', + '2708aa182ddcfe6ce27c96acaaa40f69' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/sodium.php', + 'f1b96cb260a5baeea9a7285cda82a1ec' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/solr.php', + '3fd8853757d0fe3557c179efb807afeb' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/spl.php', + '9312ce96a51c846913fcda5f186d58dd' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/sqlsrv.php', + 'd3eb383ad0b8b962b29dc4afd29d6715' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ssdeep.php', + '42a09bc448f441a0b9f9367ea975c0bf' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/ssh2.php', + 'ef711077d356d1b33ca0b10b67b0be8f' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/stream.php', + '764b09f6df081cbb2807b97c6ace3866' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/strings.php', + 'ef241678769fee4a44aaa288f3b78aa1' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/swoole.php', + '0efc8f6778cba932b9e2a89e28de2452' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/uodbc.php', + 'd383d32907b98af53ee9208c62204fd0' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/uopz.php', + '2fd2e4060f7fe772660f002ce38f0b71' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/url.php', + '782249e03deebeaf57b9991ff5493aa0' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/var.php', + '344440cd1cd7200fdb4f12af0d3c587f' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/xdiff.php', + '3599f369219c658a5fb6c4fe66832f62' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/xml.php', + '7fcd313da9fae337051b091b3492c21b' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/xmlrpc.php', + 'd668c74cfa92d893b582356733d9a80e' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/yaml.php', + '4af1dca6db8c527c6eed27bff85ff0e5' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/yaz.php', + 'fe43ca06499ac37bc2dedd823af71eb5' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/zip.php', + '356736db98a6834f0a886b8d509b0ecd' => __DIR__ . '/..' . '/thecodingmachine/safe/generated/zlib.php', + '8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php', ); public static $prefixLengthsPsr4 = array ( + 'v' => + array ( + 'voku\\' => 5, + ), 'S' => array ( + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Symfony\\Polyfill\\Php73\\' => 23, 'Symfony\\Polyfill\\Php72\\' => 23, - 'Symfony\\Polyfill\\Php70\\' => 23, + 'Symfony\\Polyfill\\Mbstring\\' => 26, 'Symfony\\Polyfill\\Intl\\Normalizer\\' => 33, 'Symfony\\Polyfill\\Intl\\Idn\\' => 26, + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => 31, + 'Symfony\\Polyfill\\Ctype\\' => 23, + 'Symfony\\Contracts\\Translation\\' => 30, + 'Symfony\\Contracts\\Service\\' => 26, + 'Symfony\\Contracts\\HttpClient\\' => 29, + 'Symfony\\Contracts\\EventDispatcher\\' => 34, + 'Symfony\\Component\\VarDumper\\' => 28, + 'Symfony\\Component\\Translation\\' => 30, + 'Symfony\\Component\\String\\' => 25, + 'Symfony\\Component\\Routing\\' => 26, + 'Symfony\\Component\\Process\\' => 26, + 'Symfony\\Component\\Mime\\' => 23, + 'Symfony\\Component\\HttpKernel\\' => 29, + 'Symfony\\Component\\HttpFoundation\\' => 33, + 'Symfony\\Component\\Finder\\' => 25, + 'Symfony\\Component\\EventDispatcher\\' => 34, + 'Symfony\\Component\\ErrorHandler\\' => 31, + 'Symfony\\Component\\Console\\' => 26, + 'Safe\\' => 5, + ), + 'R' => + array ( + 'Ramsey\\Uuid\\' => 12, + 'Ramsey\\Collection\\' => 18, ), 'P' => array ( - 'Psr\\Http\\Message\\' => 17, + 'Psr\\SimpleCache\\' => 16, + 'Psr\\Log\\' => 8, + 'Psr\\EventDispatcher\\' => 20, + 'Psr\\Container\\' => 14, + ), + 'O' => + array ( + 'Opis\\Closure\\' => 13, ), 'N' => array ( 'Nuwave\\Lighthouse\\' => 18, ), + 'L' => + array ( + 'Laragraph\\Utils\\' => 16, + ), + 'I' => + array ( + 'Illuminate\\Validation\\' => 22, + 'Illuminate\\Translation\\' => 23, + 'Illuminate\\Support\\' => 19, + 'Illuminate\\Session\\' => 19, + 'Illuminate\\Routing\\' => 19, + 'Illuminate\\Queue\\' => 17, + 'Illuminate\\Pipeline\\' => 20, + 'Illuminate\\Pagination\\' => 22, + 'Illuminate\\Http\\' => 16, + 'Illuminate\\Filesystem\\' => 22, + 'Illuminate\\Database\\' => 20, + 'Illuminate\\Contracts\\' => 21, + 'Illuminate\\Container\\' => 21, + 'Illuminate\\Console\\' => 19, + 'Illuminate\\Bus\\' => 15, + 'Illuminate\\Auth\\' => 16, + ), + 'H' => + array ( + 'HaydenPierce\\ClassFinder\\UnitTest\\' => 34, + 'HaydenPierce\\ClassFinder\\' => 25, + ), 'G' => array ( - 'GuzzleHttp\\Psr7\\' => 16, - 'GuzzleHttp\\Promise\\' => 19, - 'GuzzleHttp\\' => 11, 'GraphQL\\' => 8, ), + 'E' => + array ( + 'Egulias\\EmailValidator\\' => 23, + ), + 'D' => + array ( + 'Doctrine\\Inflector\\' => 19, + 'Doctrine\\Common\\Lexer\\' => 22, + ), + 'C' => + array ( + 'Composer\\Installers\\' => 20, + 'Carbon\\' => 7, + ), + 'B' => + array ( + 'Brick\\Math\\' => 11, + ), ); public static $prefixDirsPsr4 = array ( + 'voku\\' => + array ( + 0 => __DIR__ . '/..' . '/voku/portable-ascii/src/voku', + ), + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Symfony\\Polyfill\\Php73\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php73', + ), 'Symfony\\Polyfill\\Php72\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-php72', ), - 'Symfony\\Polyfill\\Php70\\' => + 'Symfony\\Polyfill\\Mbstring\\' => array ( - 0 => __DIR__ . '/..' . '/symfony/polyfill-php70', + 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', ), 'Symfony\\Polyfill\\Intl\\Normalizer\\' => array ( @@ -59,41 +248,232 @@ class ComposerStaticInit02b791b67b928853969b061eb6816088 array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-idn', ), - 'Psr\\Http\\Message\\' => + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => array ( - 0 => __DIR__ . '/..' . '/psr/http-message/src', + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), + 'Symfony\\Contracts\\Translation\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/translation-contracts', + ), + 'Symfony\\Contracts\\Service\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/service-contracts', + ), + 'Symfony\\Contracts\\HttpClient\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/http-client-contracts', + ), + 'Symfony\\Contracts\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher-contracts', + ), + 'Symfony\\Component\\VarDumper\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/var-dumper', + ), + 'Symfony\\Component\\Translation\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/translation', + ), + 'Symfony\\Component\\String\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/string', + ), + 'Symfony\\Component\\Routing\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/routing', + ), + 'Symfony\\Component\\Process\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/process', + ), + 'Symfony\\Component\\Mime\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/mime', + ), + 'Symfony\\Component\\HttpKernel\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/http-kernel', + ), + 'Symfony\\Component\\HttpFoundation\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/http-foundation', + ), + 'Symfony\\Component\\Finder\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/finder', + ), + 'Symfony\\Component\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher', + ), + 'Symfony\\Component\\ErrorHandler\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/error-handler', + ), + 'Symfony\\Component\\Console\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/console', + ), + 'Safe\\' => + array ( + 0 => __DIR__ . '/..' . '/thecodingmachine/safe/lib', + 1 => __DIR__ . '/..' . '/thecodingmachine/safe/deprecated', + 2 => __DIR__ . '/..' . '/thecodingmachine/safe/generated', + ), + 'Ramsey\\Uuid\\' => + array ( + 0 => __DIR__ . '/..' . '/ramsey/uuid/src', + ), + 'Ramsey\\Collection\\' => + array ( + 0 => __DIR__ . '/..' . '/ramsey/collection/src', + ), + 'Psr\\SimpleCache\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/simple-cache/src', + ), + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/Psr/Log', + ), + 'Psr\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/event-dispatcher/src', + ), + 'Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'Opis\\Closure\\' => + array ( + 0 => __DIR__ . '/..' . '/opis/closure/src', ), 'Nuwave\\Lighthouse\\' => array ( 0 => __DIR__ . '/..' . '/nuwave/lighthouse/src', ), - 'GuzzleHttp\\Psr7\\' => + 'Laragraph\\Utils\\' => array ( - 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + 0 => __DIR__ . '/..' . '/laragraph/utils/src', ), - 'GuzzleHttp\\Promise\\' => + 'Illuminate\\Validation\\' => array ( - 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + 0 => __DIR__ . '/..' . '/illuminate/validation', ), - 'GuzzleHttp\\' => + 'Illuminate\\Translation\\' => array ( - 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + 0 => __DIR__ . '/..' . '/illuminate/translation', + ), + 'Illuminate\\Support\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/macroable', + 1 => __DIR__ . '/..' . '/illuminate/collections', + 2 => __DIR__ . '/..' . '/illuminate/support', + ), + 'Illuminate\\Session\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/session', + ), + 'Illuminate\\Routing\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/routing', + ), + 'Illuminate\\Queue\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/queue', + ), + 'Illuminate\\Pipeline\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/pipeline', + ), + 'Illuminate\\Pagination\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/pagination', + ), + 'Illuminate\\Http\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/http', + ), + 'Illuminate\\Filesystem\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/filesystem', + ), + 'Illuminate\\Database\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/database', + ), + 'Illuminate\\Contracts\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/contracts', + ), + 'Illuminate\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/container', + ), + 'Illuminate\\Console\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/console', + ), + 'Illuminate\\Bus\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/bus', + ), + 'Illuminate\\Auth\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/auth', + ), + 'HaydenPierce\\ClassFinder\\UnitTest\\' => + array ( + 0 => __DIR__ . '/..' . '/haydenpierce/class-finder/test/unit', + ), + 'HaydenPierce\\ClassFinder\\' => + array ( + 0 => __DIR__ . '/..' . '/haydenpierce/class-finder/src', ), 'GraphQL\\' => array ( 0 => __DIR__ . '/..' . '/webonyx/graphql-php/src', ), + 'Egulias\\EmailValidator\\' => + array ( + 0 => __DIR__ . '/..' . '/egulias/email-validator/src', + ), + 'Doctrine\\Inflector\\' => + array ( + 0 => __DIR__ . '/..' . '/doctrine/inflector/lib/Doctrine/Inflector', + ), + 'Doctrine\\Common\\Lexer\\' => + array ( + 0 => __DIR__ . '/..' . '/doctrine/lexer/lib/Doctrine/Common/Lexer', + ), + 'Composer\\Installers\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/installers/src/Composer/Installers', + ), + 'Carbon\\' => + array ( + 0 => __DIR__ . '/..' . '/nesbot/carbon/src/Carbon', + ), + 'Brick\\Math\\' => + array ( + 0 => __DIR__ . '/..' . '/brick/math/src', + ), ); public static $classMap = array ( - 'ArithmeticError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php', - 'AssertionError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/AssertionError.php', - 'DivisionByZeroError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/DivisionByZeroError.php', - 'Error' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/Error.php', + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'JsonException' => __DIR__ . '/..' . '/symfony/polyfill-php73/Resources/stubs/JsonException.php', 'Normalizer' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', - 'ParseError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/ParseError.php', - 'SessionUpdateTimestampHandlerInterface' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/SessionUpdateTimestampHandlerInterface.php', - 'TypeError' => __DIR__ . '/..' . '/symfony/polyfill-php70/Resources/stubs/TypeError.php', + 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', ); public static function getInitializer(ClassLoader $loader) diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index 06e2c76..73e99d6 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -1,748 +1,4725 @@ -[ - { - "name": "guzzlehttp/guzzle", - "version": "6.5.5", - "version_normalized": "6.5.5.0", - "source": { - "type": "git", - "url": "https://github.com/guzzle/guzzle.git", - "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle/zipball/9d4290de1cfd701f38099ef7e183b64b4b7b0c5e", - "reference": "9d4290de1cfd701f38099ef7e183b64b4b7b0c5e", - "shasum": "" - }, - "require": { - "ext-json": "*", - "guzzlehttp/promises": "^1.0", - "guzzlehttp/psr7": "^1.6.1", - "php": ">=5.5", - "symfony/polyfill-intl-idn": "^1.17.0" - }, - "require-dev": { - "ext-curl": "*", - "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0", - "psr/log": "^1.1" - }, - "suggest": { - "psr/log": "Required for using the Log middleware" - }, - "time": "2020-06-16T21:01:06+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "6.5-dev" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "GuzzleHttp\\": "src/" +{ + "packages": [ + { + "name": "brick/math", + "version": "0.9.2", + "version_normalized": "0.9.2.0", + "source": { + "type": "git", + "url": "https://github.com/brick/math.git", + "reference": "dff976c2f3487d42c1db75a3b180e2b9f0e72ce0" }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "description": "Guzzle is a PHP HTTP client library", - "homepage": "http://guzzlephp.org/", - "keywords": [ - "client", - "curl", - "framework", - "http", - "http client", - "rest", - "web service" - ] - }, - { - "name": "guzzlehttp/promises", - "version": "v1.3.1", - "version_normalized": "1.3.1.0", - "source": { - "type": "git", - "url": "https://github.com/guzzle/promises.git", - "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", - "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", - "shasum": "" - }, - "require": { - "php": ">=5.5.0" - }, - "require-dev": { - "phpunit/phpunit": "^4.0" - }, - "time": "2016-12-20T10:07:11+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.4-dev" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "GuzzleHttp\\Promise\\": "src/" + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/brick/math/zipball/dff976c2f3487d42c1db75a3b180e2b9f0e72ce0", + "reference": "dff976c2f3487d42c1db75a3b180e2b9f0e72ce0", + "shasum": "" }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "description": "Guzzle promises library", - "keywords": [ - "promise" - ] - }, - { - "name": "guzzlehttp/psr7", - "version": "1.6.1", - "version_normalized": "1.6.1.0", - "source": { - "type": "git", - "url": "https://github.com/guzzle/psr7.git", - "reference": "239400de7a173fe9901b9ac7c06497751f00727a" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/239400de7a173fe9901b9ac7c06497751f00727a", - "reference": "239400de7a173fe9901b9ac7c06497751f00727a", - "shasum": "" - }, - "require": { - "php": ">=5.4.0", - "psr/http-message": "~1.0", - "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" - }, - "provide": { - "psr/http-message-implementation": "1.0" - }, - "require-dev": { - "ext-zlib": "*", - "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" - }, - "suggest": { - "zendframework/zend-httphandlerrunner": "Emit PSR-7 responses" - }, - "time": "2019-07-01T23:21:34+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.6-dev" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "GuzzleHttp\\Psr7\\": "src/" + "require": { + "ext-json": "*", + "php": "^7.1 || ^8.0" }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" + "require-dev": { + "php-coveralls/php-coveralls": "^2.2", + "phpunit/phpunit": "^7.5.15 || ^8.5 || ^9.0", + "vimeo/psalm": "4.3.2" }, - { - "name": "Tobias Schultze", - "homepage": "https://github.com/Tobion" - } - ], - "description": "PSR-7 message implementation that also provides common utility methods", - "keywords": [ - "http", - "message", - "psr-7", - "request", - "response", - "stream", - "uri", - "url" - ] - }, - { - "name": "nuwave/lighthouse", - "version": "v4.3.0", - "version_normalized": "4.3.0.0", - "source": { - "type": "git", - "url": "https://github.com/nuwave/lighthouse.git", - "reference": "7016151ff3b0ff7b00e0400f20437692448bda6c" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/nuwave/lighthouse/zipball/7016151ff3b0ff7b00e0400f20437692448bda6c", - "reference": "7016151ff3b0ff7b00e0400f20437692448bda6c", - "shasum": "" - }, - "require": { - "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", - "php": ">= 7.1", - "webonyx/graphql-php": "^0.13.2" - }, - "require-dev": { - "bensampo/laravel-enum": "^1.22", - "haydenpierce/class-finder": "^0.3.3", - "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" - }, - "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/laravel-graphql-playground": "GraphQL IDE for better development workflow - integrated with Laravel" - }, - "time": "2019-09-04T12:54:31+00:00", - "type": "library", - "extra": { - "laravel": { - "providers": [ - "Nuwave\\Lighthouse\\LighthouseServiceProvider", - "Nuwave\\Lighthouse\\SoftDeletes\\SoftDeletesServiceProvider" - ], - "aliases": { - "graphql": "Nuwave\\Lighthouse\\GraphQL" + "time": "2021-01-20T22:51:39+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Brick\\Math\\": "src/" } - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "Nuwave\\Lighthouse\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Christopher Moore", - "email": "chris@nuwavecommerce.com", - "homepage": "https://www.nuwavecommerce.com" }, - { - "name": "Benedikt Franke", - "email": "benedikt@franke.tech", - "homepage": "https://franke.tech" - } - ], - "description": "Lighthouse is a schema first GraphQL package for Laravel applications.", - "homepage": "https://lighthouse-php.com", - "keywords": [ - "api", - "graphql", - "laravel", - "laravel-graphql" - ] - }, - { - "name": "paragonie/random_compat", - "version": "v9.99.99", - "version_normalized": "9.99.99.0", - "source": { - "type": "git", - "url": "https://github.com/paragonie/random_compat.git", - "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/paragonie/random_compat/zipball/84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", - "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", - "shasum": "" - }, - "require": { - "php": "^7" - }, - "require-dev": { - "phpunit/phpunit": "4.*|5.*", - "vimeo/psalm": "^1" - }, - "suggest": { - "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." - }, - "time": "2018-07-02T15:55:56+00:00", - "type": "library", - "installation-source": "dist", - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Paragon Initiative Enterprises", - "email": "security@paragonie.com", - "homepage": "https://paragonie.com" - } - ], - "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", - "keywords": [ - "csprng", - "polyfill", - "pseudorandom", - "random" - ] - }, - { - "name": "psr/http-message", - "version": "1.0.1", - "version_normalized": "1.0.1.0", - "source": { - "type": "git", - "url": "https://github.com/php-fig/http-message.git", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", - "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "time": "2016-08-06T14:39:51+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "Psr\\Http\\Message\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for HTTP messages", - "homepage": "https://github.com/php-fig/http-message", - "keywords": [ - "http", - "http-message", - "psr", - "psr-7", - "request", - "response" - ] - }, - { - "name": "ralouphie/getallheaders", - "version": "3.0.3", - "version_normalized": "3.0.3.0", - "source": { - "type": "git", - "url": "https://github.com/ralouphie/getallheaders.git", - "reference": "120b605dfeb996808c31b6477290a714d356e822" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", - "reference": "120b605dfeb996808c31b6477290a714d356e822", - "shasum": "" - }, - "require": { - "php": ">=5.6" - }, - "require-dev": { - "php-coveralls/php-coveralls": "^2.1", - "phpunit/phpunit": "^5 || ^6.5" - }, - "time": "2019-03-08T08:55:37+00:00", - "type": "library", - "installation-source": "dist", - "autoload": { - "files": [ - "src/getallheaders.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Ralph Khattar", - "email": "ralph.khattar@gmail.com" - } - ], - "description": "A polyfill for getallheaders." - }, - { - "name": "symfony/polyfill-intl-idn", - "version": "v1.18.0", - "version_normalized": "1.18.0.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-intl-idn.git", - "reference": "bc6549d068d0160e0f10f7a5a23c7d1406b95ebe" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/bc6549d068d0160e0f10f7a5a23c7d1406b95ebe", - "reference": "bc6549d068d0160e0f10f7a5a23c7d1406b95ebe", - "shasum": "" - }, - "require": { - "php": ">=5.3.3", - "symfony/polyfill-intl-normalizer": "^1.10", - "symfony/polyfill-php70": "^1.10", - "symfony/polyfill-php72": "^1.10" - }, - "suggest": { - "ext-intl": "For best performance" - }, - "time": "2020-07-14T12:35:20+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.18-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Intl\\Idn\\": "" - }, - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Laurent Bassin", - "email": "laurent@bassin.info" - }, - { - "name": "Trevor Rowbotham", - "email": "trevor.rowbotham@pm.me" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "idn", - "intl", - "polyfill", - "portable", - "shim" - ] - }, - { - "name": "symfony/polyfill-intl-normalizer", - "version": "v1.18.0", - "version_normalized": "1.18.0.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-intl-normalizer.git", - "reference": "37078a8dd4a2a1e9ab0231af7c6cb671b2ed5a7e" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/37078a8dd4a2a1e9ab0231af7c6cb671b2ed5a7e", - "reference": "37078a8dd4a2a1e9ab0231af7c6cb671b2ed5a7e", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "suggest": { - "ext-intl": "For best performance" - }, - "time": "2020-07-14T12:35:20+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.18-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Intl\\Normalizer\\": "" - }, - "files": [ - "bootstrap.php" + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" ], - "classmap": [ - "Resources/stubs" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for intl's Normalizer class and related functions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "intl", - "normalizer", - "polyfill", - "portable", - "shim" - ] - }, - { - "name": "symfony/polyfill-php70", - "version": "v1.18.0", - "version_normalized": "1.18.0.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php70.git", - "reference": "0dd93f2c578bdc9c72697eaa5f1dd25644e618d3" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/0dd93f2c578bdc9c72697eaa5f1dd25644e618d3", - "reference": "0dd93f2c578bdc9c72697eaa5f1dd25644e618d3", - "shasum": "" - }, - "require": { - "paragonie/random_compat": "~1.0|~2.0|~9.99", - "php": ">=5.3.3" - }, - "time": "2020-07-14T12:35:20+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.18-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Php70\\": "" - }, - "files": [ - "bootstrap.php" + "description": "Arbitrary-precision arithmetic library", + "keywords": [ + "Arbitrary-precision", + "BigInteger", + "BigRational", + "arithmetic", + "bigdecimal", + "bignum", + "brick", + "math" ], - "classmap": [ - "Resources/stubs" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" + "support": { + "issues": "https://github.com/brick/math/issues", + "source": "https://github.com/brick/math/tree/0.9.2" }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ] - }, - { - "name": "symfony/polyfill-php72", - "version": "v1.18.0", - "version_normalized": "1.18.0.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php72.git", - "reference": "639447d008615574653fb3bc60d1986d7172eaae" + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/brick/math", + "type": "tidelift" + } + ], + "install-path": "../brick/math" }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/639447d008615574653fb3bc60d1986d7172eaae", - "reference": "639447d008615574653fb3bc60d1986d7172eaae", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "time": "2020-07-14T12:35:20+00:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.18-dev" + { + "name": "composer/installers", + "version": "v1.11.0", + "version_normalized": "1.11.0.0", + "source": { + "type": "git", + "url": "https://github.com/composer/installers.git", + "reference": "ae03311f45dfe194412081526be2e003960df74b" }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Php72\\": "" + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/installers/zipball/ae03311f45dfe194412081526be2e003960df74b", + "reference": "ae03311f45dfe194412081526be2e003960df74b", + "shasum": "" }, - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" + "require": { + "composer-plugin-api": "^1.0 || ^2.0" }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ] - }, - { - "name": "webonyx/graphql-php", - "version": "v0.13.9", - "version_normalized": "0.13.9.0", - "source": { - "type": "git", - "url": "https://github.com/webonyx/graphql-php.git", - "reference": "d9a94fddcad0a35d4bced212b8a44ad1bc59bdf3" + "replace": { + "roundcube/plugin-installer": "*", + "shama/baton": "*" + }, + "require-dev": { + "composer/composer": "1.6.* || ^2.0", + "composer/semver": "^1 || ^3", + "phpstan/phpstan": "^0.12.55", + "phpstan/phpstan-phpunit": "^0.12.16", + "symfony/phpunit-bridge": "^4.2 || ^5", + "symfony/process": "^2.3" + }, + "time": "2021-04-28T06:42:17+00:00", + "type": "composer-plugin", + "extra": { + "class": "Composer\\Installers\\Plugin", + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Composer\\Installers\\": "src/Composer/Installers" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Kyle Robinson Young", + "email": "kyle@dontkry.com", + "homepage": "https://github.com/shama" + } + ], + "description": "A multi-framework Composer library installer", + "homepage": "https://composer.github.io/installers/", + "keywords": [ + "Craft", + "Dolibarr", + "Eliasis", + "Hurad", + "ImageCMS", + "Kanboard", + "Lan Management System", + "MODX Evo", + "MantisBT", + "Mautic", + "Maya", + "OXID", + "Plentymarkets", + "Porto", + "RadPHP", + "SMF", + "Starbug", + "Thelia", + "Whmcs", + "WolfCMS", + "agl", + "aimeos", + "annotatecms", + "attogram", + "bitrix", + "cakephp", + "chef", + "cockpit", + "codeigniter", + "concrete5", + "croogo", + "dokuwiki", + "drupal", + "eZ Platform", + "elgg", + "expressionengine", + "fuelphp", + "grav", + "installer", + "itop", + "joomla", + "known", + "kohana", + "laravel", + "lavalite", + "lithium", + "magento", + "majima", + "mako", + "mediawiki", + "miaoxing", + "modulework", + "modx", + "moodle", + "osclass", + "phpbb", + "piwik", + "ppi", + "processwire", + "puppet", + "pxcms", + "reindex", + "roundcube", + "shopware", + "silverstripe", + "sydes", + "sylius", + "symfony", + "tastyigniter", + "typo3", + "wordpress", + "yawik", + "zend", + "zikula" + ], + "support": { + "issues": "https://github.com/composer/installers/issues", + "source": "https://github.com/composer/installers/tree/v1.11.0" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "install-path": "./installers" }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/webonyx/graphql-php/zipball/d9a94fddcad0a35d4bced212b8a44ad1bc59bdf3", - "reference": "d9a94fddcad0a35d4bced212b8a44ad1bc59bdf3", - "shasum": "" + { + "name": "doctrine/inflector", + "version": "2.0.3", + "version_normalized": "2.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/inflector.git", + "reference": "9cf661f4eb38f7c881cac67c75ea9b00bf97b210" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/inflector/zipball/9cf661f4eb38f7c881cac67c75ea9b00bf97b210", + "reference": "9cf661f4eb38f7c881cac67c75ea9b00bf97b210", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^7.0", + "phpstan/phpstan": "^0.11", + "phpstan/phpstan-phpunit": "^0.11", + "phpstan/phpstan-strict-rules": "^0.11", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + }, + "time": "2020-05-29T15:13:26+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Doctrine\\Inflector\\": "lib/Doctrine/Inflector" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.", + "homepage": "https://www.doctrine-project.org/projects/inflector.html", + "keywords": [ + "inflection", + "inflector", + "lowercase", + "manipulation", + "php", + "plural", + "singular", + "strings", + "uppercase", + "words" + ], + "support": { + "issues": "https://github.com/doctrine/inflector/issues", + "source": "https://github.com/doctrine/inflector/tree/2.0.x" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finflector", + "type": "tidelift" + } + ], + "install-path": "../doctrine/inflector" }, - "require": { - "ext-json": "*", - "ext-mbstring": "*", - "php": "^7.1||^8.0" + { + "name": "doctrine/lexer", + "version": "1.2.1", + "version_normalized": "1.2.1.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "e864bbf5904cb8f5bb334f99209b48018522f042" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/e864bbf5904cb8f5bb334f99209b48018522f042", + "reference": "e864bbf5904cb8f5bb334f99209b48018522f042", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^6.0", + "phpstan/phpstan": "^0.11.8", + "phpunit/phpunit": "^8.2" + }, + "time": "2020-05-25T17:44:05+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Doctrine\\Common\\Lexer\\": "lib/Doctrine/Common/Lexer" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "https://www.doctrine-project.org/projects/lexer.html", + "keywords": [ + "annotations", + "docblock", + "lexer", + "parser", + "php" + ], + "support": { + "issues": "https://github.com/doctrine/lexer/issues", + "source": "https://github.com/doctrine/lexer/tree/1.2.1" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Flexer", + "type": "tidelift" + } + ], + "install-path": "../doctrine/lexer" }, - "require-dev": { - "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", - "psr/http-message": "^1.0", - "react/promise": "2.*" + { + "name": "egulias/email-validator", + "version": "2.1.25", + "version_normalized": "2.1.25.0", + "source": { + "type": "git", + "url": "https://github.com/egulias/EmailValidator.git", + "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/0dbf5d78455d4d6a41d186da50adc1122ec066f4", + "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4", + "shasum": "" + }, + "require": { + "doctrine/lexer": "^1.0.1", + "php": ">=5.5", + "symfony/polyfill-intl-idn": "^1.10" + }, + "require-dev": { + "dominicsayers/isemail": "^3.0.7", + "phpunit/phpunit": "^4.8.36|^7.5.15", + "satooshi/php-coveralls": "^1.0.1" + }, + "suggest": { + "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" + }, + "time": "2020-12-29T14:50:06+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Egulias\\EmailValidator\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eduardo Gulias Davis" + } + ], + "description": "A library for validating emails against several RFCs", + "homepage": "https://github.com/egulias/EmailValidator", + "keywords": [ + "email", + "emailvalidation", + "emailvalidator", + "validation", + "validator" + ], + "support": { + "issues": "https://github.com/egulias/EmailValidator/issues", + "source": "https://github.com/egulias/EmailValidator/tree/2.1.25" + }, + "funding": [ + { + "url": "https://github.com/egulias", + "type": "github" + } + ], + "install-path": "../egulias/email-validator" }, - "suggest": { - "psr/http-message": "To use standard GraphQL server", - "react/promise": "To leverage async resolving on React PHP platform" + { + "name": "haydenpierce/class-finder", + "version": "0.4.3", + "version_normalized": "0.4.3.0", + "source": { + "type": "git", + "url": "https://gitlab.com/hpierce1102/ClassFinder.git", + "reference": "d6c68f386c764674c59ee336d1dfca35aada5f90" + }, + "dist": { + "type": "zip", + "url": "https://gitlab.com/api/v4/projects/hpierce1102%2FClassFinder/repository/archive.zip?sha=d6c68f386c764674c59ee336d1dfca35aada5f90", + "reference": "d6c68f386c764674c59ee336d1dfca35aada5f90", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": ">=5.3" + }, + "require-dev": { + "mikey179/vfsstream": "^1.6", + "phpunit/phpunit": "~9.0" + }, + "time": "2021-01-05T20:50:49+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "HaydenPierce\\ClassFinder\\": "src/", + "HaydenPierce\\ClassFinder\\UnitTest\\": "test/unit" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Hayden Pierce", + "email": "hayden@haydenpierce.com" + } + ], + "description": "A library that can provide of a list of classes in a given namespace", + "support": { + "issues": "https://gitlab.com/api/v4/projects/7670051/issues" + }, + "install-path": "../haydenpierce/class-finder" }, - "time": "2020-07-02T05:49:25+00:00", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-4": { - "GraphQL\\": "src/" - } + { + "name": "illuminate/auth", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/auth.git", + "reference": "8c7847c73359f56b8610e3e4420184b7555738b0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/auth/zipball/8c7847c73359f56b8610e3e4420184b7555738b0", + "reference": "8c7847c73359f56b8610e3e4420184b7555738b0", + "shasum": "" + }, + "require": { + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/http": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/queue": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0" + }, + "suggest": { + "illuminate/console": "Required to use the auth:clear-resets command (^8.0).", + "illuminate/queue": "Required to fire login / logout events (^8.0).", + "illuminate/session": "Required to use the session based guard (^8.0)." + }, + "time": "2021-07-05T15:30:07+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Auth\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Auth package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/auth" }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "description": "A PHP port of GraphQL reference implementation", - "homepage": "https://github.com/webonyx/graphql-php", - "keywords": [ - "api", - "graphql" - ] - } -] + { + "name": "illuminate/bus", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/bus.git", + "reference": "0b9722013b908a67e9b815a3bad4f49e25828f7b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/bus/zipball/0b9722013b908a67e9b815a3bad4f49e25828f7b", + "reference": "0b9722013b908a67e9b815a3bad4f49e25828f7b", + "shasum": "" + }, + "require": { + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/pipeline": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0" + }, + "suggest": { + "illuminate/queue": "Required to use closures when chaining jobs (^7.0)." + }, + "time": "2021-07-16T12:35:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Bus\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Bus package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/bus" + }, + { + "name": "illuminate/collections", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/collections.git", + "reference": "7942bc71aca503d2f2721469c650fce38b1058e3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/collections/zipball/7942bc71aca503d2f2721469c650fce38b1058e3", + "reference": "7942bc71aca503d2f2721469c650fce38b1058e3", + "shasum": "" + }, + "require": { + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "php": "^7.3|^8.0" + }, + "suggest": { + "symfony/var-dumper": "Required to use the dump method (^5.1.4)." + }, + "time": "2021-07-15T14:07:19+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Support\\": "" + }, + "files": [ + "helpers.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Collections package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/collections" + }, + { + "name": "illuminate/console", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/console.git", + "reference": "1f1ff88a2efbfc85f87ea7d8283acbefc5b56191" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/console/zipball/1f1ff88a2efbfc85f87ea7d8283acbefc5b56191", + "reference": "1f1ff88a2efbfc85f87ea7d8283acbefc5b56191", + "shasum": "" + }, + "require": { + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0", + "symfony/console": "^5.1.4", + "symfony/process": "^5.1.4" + }, + "suggest": { + "dragonmantank/cron-expression": "Required to use scheduler (^3.0.2).", + "guzzlehttp/guzzle": "Required to use the ping methods on schedules (^6.5.5|^7.0.1).", + "illuminate/bus": "Required to use the scheduled job dispatcher (^8.0).", + "illuminate/container": "Required to use the scheduler (^8.0).", + "illuminate/filesystem": "Required to use the generator command (^8.0).", + "illuminate/queue": "Required to use closures for scheduled jobs (^8.0)." + }, + "time": "2021-06-04T13:29:57+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Console\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Console package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/console" + }, + { + "name": "illuminate/container", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/container.git", + "reference": "382959676d85583f0e8fdd248bceb4b8762dc1ed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/container/zipball/382959676d85583f0e8fdd248bceb4b8762dc1ed", + "reference": "382959676d85583f0e8fdd248bceb4b8762dc1ed", + "shasum": "" + }, + "require": { + "illuminate/contracts": "^8.0", + "php": "^7.3|^8.0", + "psr/container": "^1.0" + }, + "provide": { + "psr/container-implementation": "1.0" + }, + "time": "2021-06-08T14:08:11+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Container\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Container package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/container" + }, + { + "name": "illuminate/contracts", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/contracts.git", + "reference": "199fcedc161ba4a0b83feaddc4629f395dbf1641" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/contracts/zipball/199fcedc161ba4a0b83feaddc4629f395dbf1641", + "reference": "199fcedc161ba4a0b83feaddc4629f395dbf1641", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0", + "psr/container": "^1.0", + "psr/simple-cache": "^1.0" + }, + "time": "2021-06-01T14:53:38+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Contracts\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Contracts package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/contracts" + }, + { + "name": "illuminate/database", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/database.git", + "reference": "29b68195c967ad7233237387deffaf16570423c8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/database/zipball/29b68195c967ad7233237387deffaf16570423c8", + "reference": "29b68195c967ad7233237387deffaf16570423c8", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0", + "symfony/console": "^5.1.4" + }, + "suggest": { + "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.6|^3.0).", + "fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).", + "illuminate/console": "Required to use the database commands (^8.0).", + "illuminate/events": "Required to use the observers with Eloquent (^8.0).", + "illuminate/filesystem": "Required to use the migrations (^8.0).", + "illuminate/pagination": "Required to paginate the result set (^8.0).", + "symfony/finder": "Required to use Eloquent model factories (^5.1.4)." + }, + "time": "2021-07-19T12:57:48+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Database\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Database package.", + "homepage": "https://laravel.com", + "keywords": [ + "database", + "laravel", + "orm", + "sql" + ], + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/database" + }, + { + "name": "illuminate/filesystem", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/filesystem.git", + "reference": "f33219e5550f8f280169e933b91a95250920de06" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/filesystem/zipball/f33219e5550f8f280169e933b91a95250920de06", + "reference": "f33219e5550f8f280169e933b91a95250920de06", + "shasum": "" + }, + "require": { + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0", + "symfony/finder": "^5.1.4" + }, + "suggest": { + "ext-ftp": "Required to use the Flysystem FTP driver.", + "illuminate/http": "Required for handling uploaded files (^7.0).", + "league/flysystem": "Required to use the Flysystem local and FTP drivers (^1.1).", + "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).", + "league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).", + "league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).", + "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).", + "symfony/filesystem": "Required to enable support for relative symbolic links (^5.1.4).", + "symfony/mime": "Required to enable support for guessing extensions (^5.1.4)." + }, + "time": "2021-07-20T13:46:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Filesystem\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Filesystem package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/filesystem" + }, + { + "name": "illuminate/http", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/http.git", + "reference": "42d6cf08120492cac9ba84913f05a3f4f3516c0a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/http/zipball/42d6cf08120492cac9ba84913f05a3f4f3516c0a", + "reference": "42d6cf08120492cac9ba84913f05a3f4f3516c0a", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/session": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0", + "symfony/http-foundation": "^5.1.4", + "symfony/http-kernel": "^5.1.4", + "symfony/mime": "^5.1.4" + }, + "suggest": { + "ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().", + "guzzlehttp/guzzle": "Required to use the HTTP Client (^6.5.5|^7.0.1)." + }, + "time": "2021-07-19T18:24:28+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Http\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Http package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/http" + }, + { + "name": "illuminate/macroable", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/macroable.git", + "reference": "300aa13c086f25116b5f3cde3ca54ff5c822fb05" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/macroable/zipball/300aa13c086f25116b5f3cde3ca54ff5c822fb05", + "reference": "300aa13c086f25116b5f3cde3ca54ff5c822fb05", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0" + }, + "time": "2020-10-27T15:20:30+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Support\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Macroable package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/macroable" + }, + { + "name": "illuminate/pagination", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/pagination.git", + "reference": "27eee63808e3c22f6df443c36e51af00ca09ee66" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/pagination/zipball/27eee63808e3c22f6df443c36e51af00ca09ee66", + "reference": "27eee63808e3c22f6df443c36e51af00ca09ee66", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0" + }, + "time": "2021-07-15T18:57:54+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Pagination\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Pagination package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/pagination" + }, + { + "name": "illuminate/pipeline", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/pipeline.git", + "reference": "23aeff5b26ae4aee3f370835c76bd0f4e93f71d2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/pipeline/zipball/23aeff5b26ae4aee3f370835c76bd0f4e93f71d2", + "reference": "23aeff5b26ae4aee3f370835c76bd0f4e93f71d2", + "shasum": "" + }, + "require": { + "illuminate/contracts": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0" + }, + "time": "2021-03-26T18:39:16+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Pipeline\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Pipeline package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/pipeline" + }, + { + "name": "illuminate/queue", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/queue.git", + "reference": "cb8bda6bdf881b21203bac5f5a24da7bc630425f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/queue/zipball/cb8bda6bdf881b21203bac5f5a24da7bc630425f", + "reference": "cb8bda6bdf881b21203bac5f5a24da7bc630425f", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/console": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/database": "^8.0", + "illuminate/filesystem": "^8.0", + "illuminate/pipeline": "^8.0", + "illuminate/support": "^8.0", + "opis/closure": "^3.6", + "php": "^7.3|^8.0", + "ramsey/uuid": "^4.0", + "symfony/process": "^5.1.4" + }, + "suggest": { + "aws/aws-sdk-php": "Required to use the SQS queue driver and DynamoDb failed job storage (^3.155).", + "ext-pcntl": "Required to use all features of the queue worker.", + "ext-posix": "Required to use all features of the queue worker.", + "illuminate/redis": "Required to use the Redis queue driver (^8.0).", + "pda/pheanstalk": "Required to use the Beanstalk queue driver (^4.0)." + }, + "time": "2021-06-30T15:39:25+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Queue\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Queue package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/queue" + }, + { + "name": "illuminate/routing", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/routing.git", + "reference": "e12acd2f0ffc07321a45def5876e41d164a075bc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/routing/zipball/e12acd2f0ffc07321a45def5876e41d164a075bc", + "reference": "e12acd2f0ffc07321a45def5876e41d164a075bc", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/http": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/pipeline": "^8.0", + "illuminate/session": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0", + "symfony/http-foundation": "^5.1.4", + "symfony/http-kernel": "^5.1.4", + "symfony/routing": "^5.1.4" + }, + "suggest": { + "illuminate/console": "Required to use the make commands (^8.0).", + "nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).", + "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0)." + }, + "time": "2021-07-16T12:37:32+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Routing\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Routing package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/routing" + }, + { + "name": "illuminate/session", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/session.git", + "reference": "7d42957ce6c42002db6f21a79aab4573dd3cc00f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/session/zipball/7d42957ce6c42002db6f21a79aab4573dd3cc00f", + "reference": "7d42957ce6c42002db6f21a79aab4573dd3cc00f", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/filesystem": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0", + "symfony/finder": "^5.1.4", + "symfony/http-foundation": "^5.1.4" + }, + "suggest": { + "illuminate/console": "Required to use the session:table command (^8.0)." + }, + "time": "2021-06-28T13:56:26+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Session\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Session package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/session" + }, + { + "name": "illuminate/support", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/support.git", + "reference": "ee397b851a411ad490363a47df7476a24f93ca2e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/support/zipball/ee397b851a411ad490363a47df7476a24f93ca2e", + "reference": "ee397b851a411ad490363a47df7476a24f93ca2e", + "shasum": "" + }, + "require": { + "doctrine/inflector": "^1.4|^2.0", + "ext-json": "*", + "ext-mbstring": "*", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "nesbot/carbon": "^2.31", + "php": "^7.3|^8.0", + "voku/portable-ascii": "^1.4.8" + }, + "conflict": { + "tightenco/collect": "<5.5.33" + }, + "suggest": { + "illuminate/filesystem": "Required to use the composer class (^8.0).", + "league/commonmark": "Required to use Str::markdown() and Stringable::markdown() (^1.3|^2.0).", + "ramsey/uuid": "Required to use Str::uuid() (^4.0).", + "symfony/process": "Required to use the composer class (^5.1.4).", + "symfony/var-dumper": "Required to use the dd function (^5.1.4).", + "vlucas/phpdotenv": "Required to use the Env class and env helper (^5.2)." + }, + "time": "2021-07-16T12:34:54+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Support\\": "" + }, + "files": [ + "helpers.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Support package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/support" + }, + { + "name": "illuminate/translation", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/translation.git", + "reference": "2af0b8af56468284d7ce4fb61e0fc7b3c0194fc8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/translation/zipball/2af0b8af56468284d7ce4fb61e0fc7b3c0194fc8", + "reference": "2af0b8af56468284d7ce4fb61e0fc7b3c0194fc8", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/filesystem": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "php": "^7.3|^8.0" + }, + "time": "2021-05-18T12:49:19+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Translation\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Translation package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/translation" + }, + { + "name": "illuminate/validation", + "version": "v8.51.0", + "version_normalized": "8.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/illuminate/validation.git", + "reference": "8b57c1ce8c1b4b23cb6f7c4ac2e34a0c716491b6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/illuminate/validation/zipball/8b57c1ce8c1b4b23cb6f7c4ac2e34a0c716491b6", + "reference": "8b57c1ce8c1b4b23cb6f7c4ac2e34a0c716491b6", + "shasum": "" + }, + "require": { + "egulias/email-validator": "^2.1.10", + "ext-json": "*", + "illuminate/collections": "^8.0", + "illuminate/container": "^8.0", + "illuminate/contracts": "^8.0", + "illuminate/macroable": "^8.0", + "illuminate/support": "^8.0", + "illuminate/translation": "^8.0", + "php": "^7.3|^8.0", + "symfony/http-foundation": "^5.1.4", + "symfony/mime": "^5.1.4" + }, + "suggest": { + "illuminate/database": "Required to use the database presence verifier (^8.0)." + }, + "time": "2021-07-20T13:44:22+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "8.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Illuminate\\Validation\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Validation package.", + "homepage": "https://laravel.com", + "support": { + "issues": "https://github.com/laravel/framework/issues", + "source": "https://github.com/laravel/framework" + }, + "install-path": "../illuminate/validation" + }, + { + "name": "laragraph/utils", + "version": "v1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/laragraph/utils.git", + "reference": "36b489f37b0688a0c806c839dd0e27cbb0cb4dca" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laragraph/utils/zipball/36b489f37b0688a0c806c839dd0e27cbb0cb4dca", + "reference": "36b489f37b0688a0c806c839dd0e27cbb0cb4dca", + "shasum": "" + }, + "require": { + "illuminate/contracts": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "illuminate/http": "5.6.* || 5.7.* || 5.8.* || ^6 || ^7 || ^8", + "php": "^7.2 || ^8.0", + "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" + }, + "time": "2020-12-30T13:17:17+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Laragraph\\Utils\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Benedikt Franke", + "email": "benedikt@franke.tech" + } + ], + "description": "Utilities for using GraphQL with Laravel", + "homepage": "https://github.com/laragraph/utils", + "support": { + "issues": "https://github.com/laragraph/utils/issues", + "source": "https://github.com/laragraph/utils" + }, + "install-path": "../laragraph/utils" + }, + { + "name": "nesbot/carbon", + "version": "2.50.0", + "version_normalized": "2.50.0.0", + "source": { + "type": "git", + "url": "https://github.com/briannesbitt/Carbon.git", + "reference": "f47f17d17602b2243414a44ad53d9f8b9ada5fdb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/f47f17d17602b2243414a44ad53d9f8b9ada5fdb", + "reference": "f47f17d17602b2243414a44ad53d9f8b9ada5fdb", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": "^7.1.8 || ^8.0", + "symfony/polyfill-mbstring": "^1.0", + "symfony/translation": "^3.4 || ^4.0 || ^5.0" + }, + "require-dev": { + "doctrine/orm": "^2.7", + "friendsofphp/php-cs-fixer": "^2.14 || ^3.0", + "kylekatarnls/multi-tester": "^2.0", + "phpmd/phpmd": "^2.9", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12.54", + "phpunit/phpunit": "^7.5.20 || ^8.5.14", + "squizlabs/php_codesniffer": "^3.4" + }, + "time": "2021-06-28T22:38:45+00:00", + "bin": [ + "bin/carbon" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev", + "dev-3.x": "3.x-dev" + }, + "laravel": { + "providers": [ + "Carbon\\Laravel\\ServiceProvider" + ] + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Carbon\\": "src/Carbon/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brian Nesbitt", + "email": "brian@nesbot.com", + "homepage": "https://markido.com" + }, + { + "name": "kylekatarnls", + "homepage": "https://github.com/kylekatarnls" + } + ], + "description": "An API extension for DateTime that supports 281 different languages.", + "homepage": "https://carbon.nesbot.com", + "keywords": [ + "date", + "datetime", + "time" + ], + "support": { + "issues": "https://github.com/briannesbitt/Carbon/issues", + "source": "https://github.com/briannesbitt/Carbon" + }, + "funding": [ + { + "url": "https://opencollective.com/Carbon", + "type": "open_collective" + }, + { + "url": "https://tidelift.com/funding/github/packagist/nesbot/carbon", + "type": "tidelift" + } + ], + "install-path": "../nesbot/carbon" + }, + { + "name": "nuwave/lighthouse", + "version": "v5.16.1", + "version_normalized": "5.16.1.0", + "source": { + "type": "git", + "url": "https://github.com/nuwave/lighthouse.git", + "reference": "507a15259e2d10cc601faff3d2c06d8cb5a9b6ab" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nuwave/lighthouse/zipball/507a15259e2d10cc601faff3d2c06d8cb5a9b6ab", + "reference": "507a15259e2d10cc601faff3d2c06d8cb5a9b6ab", + "shasum": "" + }, + "require": { + "ext-json": "*", + "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", + "php": ">= 7.2", + "thecodingmachine/safe": "^1", + "webonyx/graphql-php": "^14.7" + }, + "require-dev": { + "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 @whereConditions", + "mll-lab/laravel-graphql-playground": "GraphQL IDE for better development workflow - integrated with Laravel", + "pusher/pusher-php-server": "Required when using the Pusher Subscriptions driver" + }, + "time": "2021-07-22T11:31:47+00:00", + "type": "library", + "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" + ] + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Nuwave\\Lighthouse\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christopher Moore", + "email": "chris@nuwavecommerce.com", + "homepage": "https://www.nuwavecommerce.com" + }, + { + "name": "Benedikt Franke", + "email": "benedikt@franke.tech", + "homepage": "https://franke.tech" + } + ], + "description": "A framework for serving GraphQL from Laravel", + "homepage": "https://lighthouse-php.com", + "keywords": [ + "graphql", + "laravel", + "laravel-graphql" + ], + "support": { + "issues": "https://github.com/nuwave/lighthouse/issues", + "source": "https://github.com/nuwave/lighthouse" + }, + "funding": [ + { + "url": "https://github.com/spawnia", + "type": "github" + }, + { + "url": "https://issuehunt.io/r/nuwave/lighthouse", + "type": "issuehunt" + }, + { + "url": "https://www.patreon.com/lighthouse_php", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/nuwave/lighthouse", + "type": "tidelift" + } + ], + "install-path": "../nuwave/lighthouse" + }, + { + "name": "opis/closure", + "version": "3.6.2", + "version_normalized": "3.6.2.0", + "source": { + "type": "git", + "url": "https://github.com/opis/closure.git", + "reference": "06e2ebd25f2869e54a306dda991f7db58066f7f6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opis/closure/zipball/06e2ebd25f2869e54a306dda991f7db58066f7f6", + "reference": "06e2ebd25f2869e54a306dda991f7db58066f7f6", + "shasum": "" + }, + "require": { + "php": "^5.4 || ^7.0 || ^8.0" + }, + "require-dev": { + "jeremeamia/superclosure": "^2.0", + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0" + }, + "time": "2021-04-09T13:42:10+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.6.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Opis\\Closure\\": "src/" + }, + "files": [ + "functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marius Sarca", + "email": "marius.sarca@gmail.com" + }, + { + "name": "Sorin Sarca", + "email": "sarca_sorin@hotmail.com" + } + ], + "description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.", + "homepage": "https://opis.io/closure", + "keywords": [ + "anonymous functions", + "closure", + "function", + "serializable", + "serialization", + "serialize" + ], + "support": { + "issues": "https://github.com/opis/closure/issues", + "source": "https://github.com/opis/closure/tree/3.6.2" + }, + "install-path": "../opis/closure" + }, + { + "name": "psr/container", + "version": "1.1.1", + "version_normalized": "1.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "8622567409010282b7aeebe4bb841fe98b58dcaf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/8622567409010282b7aeebe4bb841fe98b58dcaf", + "reference": "8622567409010282b7aeebe4bb841fe98b58dcaf", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "time": "2021-03-05T17:36:06+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/1.1.1" + }, + "install-path": "../psr/container" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "time": "2019-01-08T18:20:26+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "install-path": "../psr/event-dispatcher" + }, + { + "name": "psr/log", + "version": "1.1.4", + "version_normalized": "1.1.4.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "d49695b909c3b7628b6289db5479a1c204601f11" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", + "reference": "d49695b909c3b7628b6289db5479a1c204601f11", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2021-05-03T11:20:27+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/1.1.4" + }, + "install-path": "../psr/log" + }, + { + "name": "psr/simple-cache", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/simple-cache.git", + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2017-10-23T01:57:42+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\SimpleCache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interfaces for simple caching", + "keywords": [ + "cache", + "caching", + "psr", + "psr-16", + "simple-cache" + ], + "support": { + "source": "https://github.com/php-fig/simple-cache/tree/master" + }, + "install-path": "../psr/simple-cache" + }, + { + "name": "ramsey/collection", + "version": "1.1.3", + "version_normalized": "1.1.3.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/collection.git", + "reference": "28a5c4ab2f5111db6a60b2b4ec84057e0f43b9c1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/collection/zipball/28a5c4ab2f5111db6a60b2b4ec84057e0f43b9c1", + "reference": "28a5c4ab2f5111db6a60b2b4ec84057e0f43b9c1", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8" + }, + "require-dev": { + "captainhook/captainhook": "^5.3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "ergebnis/composer-normalize": "^2.6", + "fakerphp/faker": "^1.5", + "hamcrest/hamcrest-php": "^2", + "jangregor/phpstan-prophecy": "^0.8", + "mockery/mockery": "^1.3", + "phpstan/extension-installer": "^1", + "phpstan/phpstan": "^0.12.32", + "phpstan/phpstan-mockery": "^0.12.5", + "phpstan/phpstan-phpunit": "^0.12.11", + "phpunit/phpunit": "^8.5 || ^9", + "psy/psysh": "^0.10.4", + "slevomat/coding-standard": "^6.3", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.4" + }, + "time": "2021-01-21T17:40:04+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Ramsey\\Collection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ben Ramsey", + "email": "ben@benramsey.com", + "homepage": "https://benramsey.com" + } + ], + "description": "A PHP 7.2+ library for representing and manipulating collections.", + "keywords": [ + "array", + "collection", + "hash", + "map", + "queue", + "set" + ], + "support": { + "issues": "https://github.com/ramsey/collection/issues", + "source": "https://github.com/ramsey/collection/tree/1.1.3" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/collection", + "type": "tidelift" + } + ], + "install-path": "../ramsey/collection" + }, + { + "name": "ramsey/uuid", + "version": "4.1.1", + "version_normalized": "4.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/uuid.git", + "reference": "cd4032040a750077205918c86049aa0f43d22947" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/cd4032040a750077205918c86049aa0f43d22947", + "reference": "cd4032040a750077205918c86049aa0f43d22947", + "shasum": "" + }, + "require": { + "brick/math": "^0.8 || ^0.9", + "ext-json": "*", + "php": "^7.2 || ^8", + "ramsey/collection": "^1.0", + "symfony/polyfill-ctype": "^1.8" + }, + "replace": { + "rhumsaa/uuid": "self.version" + }, + "require-dev": { + "codeception/aspect-mock": "^3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.6.2 || ^0.7.0", + "doctrine/annotations": "^1.8", + "goaop/framework": "^2", + "mockery/mockery": "^1.3", + "moontoast/math": "^1.1", + "paragonie/random-lib": "^2", + "php-mock/php-mock-mockery": "^1.3", + "php-mock/php-mock-phpunit": "^2.5", + "php-parallel-lint/php-parallel-lint": "^1.1", + "phpbench/phpbench": "^0.17.1", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-mockery": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "phpunit/phpunit": "^8.5", + "psy/psysh": "^0.10.0", + "slevomat/coding-standard": "^6.0", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "3.9.4" + }, + "suggest": { + "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-ctype": "Enables faster processing of character classification using ctype functions.", + "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", + "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", + "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." + }, + "time": "2020-08-18T17:17:46+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Ramsey\\Uuid\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", + "homepage": "https://github.com/ramsey/uuid", + "keywords": [ + "guid", + "identifier", + "uuid" + ], + "support": { + "issues": "https://github.com/ramsey/uuid/issues", + "rss": "https://github.com/ramsey/uuid/releases.atom", + "source": "https://github.com/ramsey/uuid" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + } + ], + "install-path": "../ramsey/uuid" + }, + { + "name": "symfony/console", + "version": "v5.3.2", + "version_normalized": "5.3.2.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "649730483885ff2ca99ca0560ef0e5f6b03f2ac1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/649730483885ff2ca99ca0560ef0e5f6b03f2ac1", + "reference": "649730483885ff2ca99ca0560ef0e5f6b03f2ac1", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php73": "^1.8", + "symfony/polyfill-php80": "^1.15", + "symfony/service-contracts": "^1.1|^2", + "symfony/string": "^5.1" + }, + "conflict": { + "symfony/dependency-injection": "<4.4", + "symfony/dotenv": "<5.1", + "symfony/event-dispatcher": "<4.4", + "symfony/lock": "<4.4", + "symfony/process": "<4.4" + }, + "provide": { + "psr/log-implementation": "1.0" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "^4.4|^5.0", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/event-dispatcher": "^4.4|^5.0", + "symfony/lock": "^4.4|^5.0", + "symfony/process": "^4.4|^5.0", + "symfony/var-dumper": "^4.4|^5.0" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/lock": "", + "symfony/process": "" + }, + "time": "2021-06-12T09:42:48+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v5.3.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/console" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v2.4.0", + "version_normalized": "2.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "5f38c8804a9e97d23e0c8d63341088cd8a22d627" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/5f38c8804a9e97d23e0c8d63341088cd8a22d627", + "reference": "5f38c8804a9e97d23e0c8d63341088cd8a22d627", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2021-03-23T23:28:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v2.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/deprecation-contracts" + }, + { + "name": "symfony/error-handler", + "version": "v5.3.3", + "version_normalized": "5.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/error-handler.git", + "reference": "43323e79c80719e8a4674e33484bca98270d223f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/error-handler/zipball/43323e79c80719e8a4674e33484bca98270d223f", + "reference": "43323e79c80719e8a4674e33484bca98270d223f", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/log": "^1.0", + "symfony/polyfill-php80": "^1.15", + "symfony/var-dumper": "^4.4|^5.0" + }, + "require-dev": { + "symfony/deprecation-contracts": "^2.1", + "symfony/http-kernel": "^4.4|^5.0", + "symfony/serializer": "^4.4|^5.0" + }, + "time": "2021-06-24T08:13:00+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\ErrorHandler\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools to manage errors and ease debugging PHP code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/error-handler/tree/v5.3.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/error-handler" + }, + { + "name": "symfony/event-dispatcher", + "version": "v5.3.0", + "version_normalized": "5.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "67a5f354afa8e2f231081b3fa11a5912f933c3ce" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/67a5f354afa8e2f231081b3fa11a5912f933c3ce", + "reference": "67a5f354afa8e2f231081b3fa11a5912f933c3ce", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", + "symfony/event-dispatcher-contracts": "^2", + "symfony/polyfill-php80": "^1.15" + }, + "conflict": { + "symfony/dependency-injection": "<4.4" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "^4.4|^5.0", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/error-handler": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/http-foundation": "^4.4|^5.0", + "symfony/service-contracts": "^1.1|^2", + "symfony/stopwatch": "^4.4|^5.0" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "time": "2021-05-26T17:43:10+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v5.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v2.4.0", + "version_normalized": "2.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "69fee1ad2332a7cbab3aca13591953da9cdb7a11" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/69fee1ad2332a7cbab3aca13591953da9cdb7a11", + "reference": "69fee1ad2332a7cbab3aca13591953da9cdb7a11", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/event-dispatcher": "^1" + }, + "suggest": { + "symfony/event-dispatcher-implementation": "" + }, + "time": "2021-03-23T23:28:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v2.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher-contracts" + }, + { + "name": "symfony/finder", + "version": "v5.3.0", + "version_normalized": "5.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "0ae3f047bed4edff6fd35b26a9a6bfdc92c953c6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/0ae3f047bed4edff6fd35b26a9a6bfdc92c953c6", + "reference": "0ae3f047bed4edff6fd35b26a9a6bfdc92c953c6", + "shasum": "" + }, + "require": { + "php": ">=7.2.5" + }, + "time": "2021-05-26T12:52:38+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v5.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/finder" + }, + { + "name": "symfony/http-client-contracts", + "version": "v2.4.0", + "version_normalized": "2.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client-contracts.git", + "reference": "7e82f6084d7cae521a75ef2cb5c9457bbda785f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/7e82f6084d7cae521a75ef2cb5c9457bbda785f4", + "reference": "7e82f6084d7cae521a75ef2cb5c9457bbda785f4", + "shasum": "" + }, + "require": { + "php": ">=7.2.5" + }, + "suggest": { + "symfony/http-client-implementation": "" + }, + "time": "2021-04-11T23:07:08+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\HttpClient\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to HTTP clients", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/http-client-contracts/tree/v2.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/http-client-contracts" + }, + { + "name": "symfony/http-foundation", + "version": "v5.3.3", + "version_normalized": "5.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-foundation.git", + "reference": "0e45ab1574caa0460d9190871a8ce47539e40ccf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/0e45ab1574caa0460d9190871a8ce47539e40ccf", + "reference": "0e45ab1574caa0460d9190871a8ce47539e40ccf", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", + "symfony/polyfill-mbstring": "~1.1", + "symfony/polyfill-php80": "^1.15" + }, + "require-dev": { + "predis/predis": "~1.0", + "symfony/cache": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/mime": "^4.4|^5.0" + }, + "suggest": { + "symfony/mime": "To use the file extension guesser" + }, + "time": "2021-06-27T09:19:40+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpFoundation\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Defines an object-oriented layer for the HTTP specification", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-foundation/tree/v5.3.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/http-foundation" + }, + { + "name": "symfony/http-kernel", + "version": "v5.3.3", + "version_normalized": "5.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-kernel.git", + "reference": "90ad9f4b21ddcb8ebe9faadfcca54929ad23f9f8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/90ad9f4b21ddcb8ebe9faadfcca54929ad23f9f8", + "reference": "90ad9f4b21ddcb8ebe9faadfcca54929ad23f9f8", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/log": "~1.0", + "symfony/deprecation-contracts": "^2.1", + "symfony/error-handler": "^4.4|^5.0", + "symfony/event-dispatcher": "^5.0", + "symfony/http-client-contracts": "^1.1|^2", + "symfony/http-foundation": "^5.3", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-php73": "^1.9", + "symfony/polyfill-php80": "^1.15" + }, + "conflict": { + "symfony/browser-kit": "<4.4", + "symfony/cache": "<5.0", + "symfony/config": "<5.0", + "symfony/console": "<4.4", + "symfony/dependency-injection": "<5.3", + "symfony/doctrine-bridge": "<5.0", + "symfony/form": "<5.0", + "symfony/http-client": "<5.0", + "symfony/mailer": "<5.0", + "symfony/messenger": "<5.0", + "symfony/translation": "<5.0", + "symfony/twig-bridge": "<5.0", + "symfony/validator": "<5.0", + "twig/twig": "<2.13" + }, + "provide": { + "psr/log-implementation": "1.0" + }, + "require-dev": { + "psr/cache": "^1.0|^2.0|^3.0", + "symfony/browser-kit": "^4.4|^5.0", + "symfony/config": "^5.0", + "symfony/console": "^4.4|^5.0", + "symfony/css-selector": "^4.4|^5.0", + "symfony/dependency-injection": "^5.3", + "symfony/dom-crawler": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/finder": "^4.4|^5.0", + "symfony/process": "^4.4|^5.0", + "symfony/routing": "^4.4|^5.0", + "symfony/stopwatch": "^4.4|^5.0", + "symfony/translation": "^4.4|^5.0", + "symfony/translation-contracts": "^1.1|^2", + "twig/twig": "^2.13|^3.0.4" + }, + "suggest": { + "symfony/browser-kit": "", + "symfony/config": "", + "symfony/console": "", + "symfony/dependency-injection": "" + }, + "time": "2021-06-30T08:27:49+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpKernel\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides a structured process for converting a Request into a Response", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-kernel/tree/v5.3.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/http-kernel" + }, + { + "name": "symfony/mime", + "version": "v5.3.2", + "version_normalized": "5.3.2.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/mime.git", + "reference": "47dd7912152b82d0d4c8d9040dbc93d6232d472a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mime/zipball/47dd7912152b82d0d4c8d9040dbc93d6232d472a", + "reference": "47dd7912152b82d0d4c8d9040dbc93d6232d472a", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", + "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php80": "^1.15" + }, + "conflict": { + "egulias/email-validator": "~3.0.0", + "phpdocumentor/reflection-docblock": "<3.2.2", + "phpdocumentor/type-resolver": "<1.4.0", + "symfony/mailer": "<4.4" + }, + "require-dev": { + "egulias/email-validator": "^2.1.10|^3.1", + "phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/property-access": "^4.4|^5.1", + "symfony/property-info": "^4.4|^5.1", + "symfony/serializer": "^5.2" + }, + "time": "2021-06-09T10:58:01+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mime\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Allows manipulating MIME messages", + "homepage": "https://symfony.com", + "keywords": [ + "mime", + "mime-type" + ], + "support": { + "source": "https://github.com/symfony/mime/tree/v5.3.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/mime" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/46cd95797e9df938fdd2b03693b5fca5e64b01ce", + "reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2021-02-19T12:13:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-ctype" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "24b72c6baa32c746a4d0840147c9715e42bb68ab" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/24b72c6baa32c746a4d0840147c9715e42bb68ab", + "reference": "24b72c6baa32c746a4d0840147c9715e42bb68ab", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2021-05-27T09:17:38+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-grapheme" + }, + { + "name": "symfony/polyfill-intl-idn", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-idn.git", + "reference": "65bd267525e82759e7d8c4e8ceea44f398838e65" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/65bd267525e82759e7d8c4e8ceea44f398838e65", + "reference": "65bd267525e82759e7d8c4e8ceea44f398838e65", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "symfony/polyfill-intl-normalizer": "^1.10", + "symfony/polyfill-php72": "^1.10" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2021-05-27T09:27:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Intl\\Idn\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Laurent Bassin", + "email": "laurent@bassin.info" + }, + { + "name": "Trevor Rowbotham", + "email": "trevor.rowbotham@pm.me" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "idn", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-idn" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "8590a5f561694770bdcd3f9b5c69dde6945028e8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/8590a5f561694770bdcd3f9b5c69dde6945028e8", + "reference": "8590a5f561694770bdcd3f9b5c69dde6945028e8", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2021-02-19T12:13:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-normalizer" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "2df51500adbaebdc4c38dea4c89a2e131c45c8a1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/2df51500adbaebdc4c38dea4c89a2e131c45c8a1", + "reference": "2df51500adbaebdc4c38dea4c89a2e131c45c8a1", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "time": "2021-05-27T09:27:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-mbstring" + }, + { + "name": "symfony/polyfill-php72", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php72.git", + "reference": "9a142215a36a3888e30d0a9eeea9766764e96976" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/9a142215a36a3888e30d0a9eeea9766764e96976", + "reference": "9a142215a36a3888e30d0a9eeea9766764e96976", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2021-05-27T09:17:38+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php72\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php72/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php72" + }, + { + "name": "symfony/polyfill-php73", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php73.git", + "reference": "fba8933c384d6476ab14fb7b8526e5287ca7e010" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/fba8933c384d6476ab14fb7b8526e5287ca7e010", + "reference": "fba8933c384d6476ab14fb7b8526e5287ca7e010", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2021-02-19T12:13:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php73\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php73/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php73" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.23.0", + "version_normalized": "1.23.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "eca0bf41ed421bed1b57c4958bab16aa86b757d0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/eca0bf41ed421bed1b57c4958bab16aa86b757d0", + "reference": "eca0bf41ed421bed1b57c4958bab16aa86b757d0", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2021-02-19T12:13:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.23-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.23.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php80" + }, + { + "name": "symfony/process", + "version": "v5.3.2", + "version_normalized": "5.3.2.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "714b47f9196de61a196d86c4bad5f09201b307df" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/714b47f9196de61a196d86c4bad5f09201b307df", + "reference": "714b47f9196de61a196d86c4bad5f09201b307df", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/polyfill-php80": "^1.15" + }, + "time": "2021-06-12T10:15:01+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Executes commands in sub-processes", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v5.3.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/process" + }, + { + "name": "symfony/routing", + "version": "v5.3.0", + "version_normalized": "5.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/routing.git", + "reference": "368e81376a8e049c37cb80ae87dbfbf411279199" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/routing/zipball/368e81376a8e049c37cb80ae87dbfbf411279199", + "reference": "368e81376a8e049c37cb80ae87dbfbf411279199", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", + "symfony/polyfill-php80": "^1.15" + }, + "conflict": { + "doctrine/annotations": "<1.12", + "symfony/config": "<5.3", + "symfony/dependency-injection": "<4.4", + "symfony/yaml": "<4.4" + }, + "require-dev": { + "doctrine/annotations": "^1.12", + "psr/log": "~1.0", + "symfony/config": "^5.3", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/http-foundation": "^4.4|^5.0", + "symfony/yaml": "^4.4|^5.0" + }, + "suggest": { + "symfony/config": "For using the all-in-one router or any loader", + "symfony/expression-language": "For using expression matching", + "symfony/http-foundation": "For using a Symfony Request object", + "symfony/yaml": "For using the YAML loader" + }, + "time": "2021-05-26T17:43:10+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Routing\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Maps an HTTP request to a set of configuration variables", + "homepage": "https://symfony.com", + "keywords": [ + "router", + "routing", + "uri", + "url" + ], + "support": { + "source": "https://github.com/symfony/routing/tree/v5.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/routing" + }, + { + "name": "symfony/service-contracts", + "version": "v2.4.0", + "version_normalized": "2.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "f040a30e04b57fbcc9c6cbcf4dbaa96bd318b9bb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/f040a30e04b57fbcc9c6cbcf4dbaa96bd318b9bb", + "reference": "f040a30e04b57fbcc9c6cbcf4dbaa96bd318b9bb", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/container": "^1.1" + }, + "suggest": { + "symfony/service-implementation": "" + }, + "time": "2021-04-01T10:43:52+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v2.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/service-contracts" + }, + { + "name": "symfony/string", + "version": "v5.3.3", + "version_normalized": "5.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "bd53358e3eccec6a670b5f33ab680d8dbe1d4ae1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/bd53358e3eccec6a670b5f33ab680d8dbe1d4ae1", + "reference": "bd53358e3eccec6a670b5f33ab680d8dbe1d4ae1", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", + "symfony/polyfill-intl-normalizer": "~1.0", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php80": "~1.15" + }, + "require-dev": { + "symfony/error-handler": "^4.4|^5.0", + "symfony/http-client": "^4.4|^5.0", + "symfony/translation-contracts": "^1.1|^2", + "symfony/var-exporter": "^4.4|^5.0" + }, + "time": "2021-06-27T11:44:38+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "files": [ + "Resources/functions.php" + ], + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v5.3.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/string" + }, + { + "name": "symfony/translation", + "version": "v5.3.3", + "version_normalized": "5.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation.git", + "reference": "380b8c9e944d0e364b25f28e8e555241eb49c01c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/translation/zipball/380b8c9e944d0e364b25f28e8e555241eb49c01c", + "reference": "380b8c9e944d0e364b25f28e8e555241eb49c01c", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php80": "^1.15", + "symfony/translation-contracts": "^2.3" + }, + "conflict": { + "symfony/config": "<4.4", + "symfony/dependency-injection": "<5.0", + "symfony/http-kernel": "<5.0", + "symfony/twig-bundle": "<5.0", + "symfony/yaml": "<4.4" + }, + "provide": { + "symfony/translation-implementation": "2.3" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "^4.4|^5.0", + "symfony/console": "^4.4|^5.0", + "symfony/dependency-injection": "^5.0", + "symfony/finder": "^4.4|^5.0", + "symfony/http-kernel": "^5.0", + "symfony/intl": "^4.4|^5.0", + "symfony/polyfill-intl-icu": "^1.21", + "symfony/service-contracts": "^1.1.2|^2", + "symfony/yaml": "^4.4|^5.0" + }, + "suggest": { + "psr/log-implementation": "To use logging capability in translator", + "symfony/config": "", + "symfony/yaml": "" + }, + "time": "2021-06-27T12:22:47+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\Translation\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools to internationalize your application", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/translation/tree/v5.3.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/translation" + }, + { + "name": "symfony/translation-contracts", + "version": "v2.4.0", + "version_normalized": "2.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/translation-contracts.git", + "reference": "95c812666f3e91db75385749fe219c5e494c7f95" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/95c812666f3e91db75385749fe219c5e494c7f95", + "reference": "95c812666f3e91db75385749fe219c5e494c7f95", + "shasum": "" + }, + "require": { + "php": ">=7.2.5" + }, + "suggest": { + "symfony/translation-implementation": "" + }, + "time": "2021-03-23T23:28:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Translation\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to translation", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/translation-contracts/tree/v2.4.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/translation-contracts" + }, + { + "name": "symfony/var-dumper", + "version": "v5.3.3", + "version_normalized": "5.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/var-dumper.git", + "reference": "46aa709affb9ad3355bd7a810f9662d71025c384" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/46aa709affb9ad3355bd7a810f9662d71025c384", + "reference": "46aa709affb9ad3355bd7a810f9662d71025c384", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/polyfill-mbstring": "~1.0", + "symfony/polyfill-php80": "^1.15" + }, + "conflict": { + "phpunit/phpunit": "<5.4.3", + "symfony/console": "<4.4" + }, + "require-dev": { + "ext-iconv": "*", + "symfony/console": "^4.4|^5.0", + "symfony/process": "^4.4|^5.0", + "twig/twig": "^2.13|^3.0.4" + }, + "suggest": { + "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).", + "ext-intl": "To show region name in time zone dump", + "symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script" + }, + "time": "2021-06-24T08:13:00+00:00", + "bin": [ + "Resources/bin/var-dump-server" + ], + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "Resources/functions/dump.php" + ], + "psr-4": { + "Symfony\\Component\\VarDumper\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides mechanisms for walking through any arbitrary PHP variable", + "homepage": "https://symfony.com", + "keywords": [ + "debug", + "dump" + ], + "support": { + "source": "https://github.com/symfony/var-dumper/tree/v5.3.3" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/var-dumper" + }, + { + "name": "thecodingmachine/safe", + "version": "v1.3.3", + "version_normalized": "1.3.3.0", + "source": { + "type": "git", + "url": "https://github.com/thecodingmachine/safe.git", + "reference": "a8ab0876305a4cdaef31b2350fcb9811b5608dbc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thecodingmachine/safe/zipball/a8ab0876305a4cdaef31b2350fcb9811b5608dbc", + "reference": "a8ab0876305a4cdaef31b2350fcb9811b5608dbc", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "require-dev": { + "phpstan/phpstan": "^0.12", + "squizlabs/php_codesniffer": "^3.2", + "thecodingmachine/phpstan-strict-rules": "^0.12" + }, + "time": "2020-10-28T17:51:34+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.1-dev" + } + }, + "installation-source": "dist", + "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" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHP core functions that throw exceptions instead of returning FALSE on error", + "support": { + "issues": "https://github.com/thecodingmachine/safe/issues", + "source": "https://github.com/thecodingmachine/safe/tree/v1.3.3" + }, + "install-path": "../thecodingmachine/safe" + }, + { + "name": "voku/portable-ascii", + "version": "1.5.6", + "version_normalized": "1.5.6.0", + "source": { + "type": "git", + "url": "https://github.com/voku/portable-ascii.git", + "reference": "80953678b19901e5165c56752d087fc11526017c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/voku/portable-ascii/zipball/80953678b19901e5165c56752d087fc11526017c", + "reference": "80953678b19901e5165c56752d087fc11526017c", + "shasum": "" + }, + "require": { + "php": ">=7.0.0" + }, + "require-dev": { + "phpunit/phpunit": "~6.0 || ~7.0 || ~9.0" + }, + "suggest": { + "ext-intl": "Use Intl for transliterator_transliterate() support" + }, + "time": "2020-11-12T00:07:28+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "voku\\": "src/voku/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Lars Moelleken", + "homepage": "http://www.moelleken.org/" + } + ], + "description": "Portable ASCII library - performance optimized (ascii) string functions for php.", + "homepage": "https://github.com/voku/portable-ascii", + "keywords": [ + "ascii", + "clean", + "php" + ], + "support": { + "issues": "https://github.com/voku/portable-ascii/issues", + "source": "https://github.com/voku/portable-ascii/tree/1.5.6" + }, + "funding": [ + { + "url": "https://www.paypal.me/moelleken", + "type": "custom" + }, + { + "url": "https://github.com/voku", + "type": "github" + }, + { + "url": "https://opencollective.com/portable-ascii", + "type": "open_collective" + }, + { + "url": "https://www.patreon.com/voku", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/voku/portable-ascii", + "type": "tidelift" + } + ], + "install-path": "../voku/portable-ascii" + }, + { + "name": "webonyx/graphql-php", + "version": "v14.9.0", + "version_normalized": "14.9.0.0", + "source": { + "type": "git", + "url": "https://github.com/webonyx/graphql-php.git", + "reference": "36b83621deb5eae354347a2e86dc7aec81b32a82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webonyx/graphql-php/zipball/36b83621deb5eae354347a2e86dc7aec81b32a82", + "reference": "36b83621deb5eae354347a2e86dc7aec81b32a82", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-mbstring": "*", + "php": "^7.1||^8.0" + }, + "require-dev": { + "amphp/amp": "^2.3", + "doctrine/coding-standard": "^6.0", + "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.*", + "simpod/php-coveralls-mirror": "^3.0", + "squizlabs/php_codesniffer": "3.5.4" + }, + "suggest": { + "psr/http-message": "To use standard GraphQL server", + "react/promise": "To leverage async resolving on React PHP platform" + }, + "time": "2021-06-15T16:14:17+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "GraphQL\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A PHP port of GraphQL reference implementation", + "homepage": "https://github.com/webonyx/graphql-php", + "keywords": [ + "api", + "graphql" + ], + "support": { + "issues": "https://github.com/webonyx/graphql-php/issues", + "source": "https://github.com/webonyx/graphql-php/tree/v14.9.0" + }, + "funding": [ + { + "url": "https://opencollective.com/webonyx-graphql-php", + "type": "open_collective" + } + ], + "install-path": "../webonyx/graphql-php" + } + ], + "dev": true, + "dev-package-names": [] +} diff --git a/vendor/guzzlehttp/guzzle/CHANGELOG.md b/vendor/guzzlehttp/guzzle/CHANGELOG.md deleted file mode 100644 index 464cf1c..0000000 --- a/vendor/guzzlehttp/guzzle/CHANGELOG.md +++ /dev/null @@ -1,1338 +0,0 @@ -# Change Log - -## 6.5.5 - 2020-06-16 - -* Unpin version constraint for `symfony/polyfill-intl-idn` [#2678](https://github.com/guzzle/guzzle/pull/2678) - -## 6.5.4 - 2020-05-25 - -* Fix various intl icu issues [#2626](https://github.com/guzzle/guzzle/pull/2626) - -## 6.5.3 - 2020-04-18 - -* Use Symfony intl-idn polyfill [#2550](https://github.com/guzzle/guzzle/pull/2550) -* Remove use of internal functions [#2548](https://github.com/guzzle/guzzle/pull/2548) - -## 6.5.2 - 2019-12-23 - -* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489) - -## 6.5.1 - 2019-12-21 - -* Better defaults for PHP installations with old ICU lib [#2454](https://github.com/guzzle/guzzle/pull/2454) -* IDN support for redirects [#2424](https://github.com/guzzle/guzzle/pull/2424) - -## 6.5.0 - 2019-12-07 - -* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143) -* Improvement: Added support to pass arbitrary options to `curl_multi_init`. [#2287](https://github.com/guzzle/guzzle/pull/2287) -* Fix: Gracefully handle passing `null` to the `header` option. [#2132](https://github.com/guzzle/guzzle/pull/2132) -* Fix: `RetryMiddleware` did not do exponential delay between retries due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132) - Previously, `RetryMiddleware` would sleep for 1 millisecond, then 2 milliseconds, then 4 milliseconds. - **After this change, `RetryMiddleware` will sleep for 1 second, then 2 seconds, then 4 seconds.** - `Middleware::retry()` accepts a second callback parameter to override the default timeouts if needed. -* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348) -* Deprecated `ClientInterface::VERSION` - -## 6.4.1 - 2019-10-23 - -* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that -* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar` - -## 6.4.0 - 2019-10-23 - -* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108) -* Fix: Test if response is readable before returning a summary in `RequestException::getResponseBodySummary()` [#2081](https://github.com/guzzle/guzzle/pull/2081) -* Fix: Add support for GUZZLE_CURL_SELECT_TIMEOUT environment variable [#2161](https://github.com/guzzle/guzzle/pull/2161) -* Improvement: Added `GuzzleHttp\Exception\InvalidArgumentException` [#2163](https://github.com/guzzle/guzzle/pull/2163) -* Improvement: Added `GuzzleHttp\_current_time()` to use `hrtime()` if that function exists. [#2242](https://github.com/guzzle/guzzle/pull/2242) -* Improvement: Added curl's `appconnect_time` in `TransferStats` [#2284](https://github.com/guzzle/guzzle/pull/2284) -* Improvement: Make GuzzleException extend Throwable wherever it's available [#2273](https://github.com/guzzle/guzzle/pull/2273) -* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335) -* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362) - -## 6.3.3 - 2018-04-22 - -* Fix: Default headers when decode_content is specified - - -## 6.3.2 - 2018-03-26 - -* Fix: Release process - - -## 6.3.1 - 2018-03-26 - -* Bug fix: Parsing 0 epoch expiry times in cookies [#2014](https://github.com/guzzle/guzzle/pull/2014) -* Improvement: Better ConnectException detection [#2012](https://github.com/guzzle/guzzle/pull/2012) -* Bug fix: Malformed domain that contains a "/" [#1999](https://github.com/guzzle/guzzle/pull/1999) -* Bug fix: Undefined offset when a cookie has no first key-value pair [#1998](https://github.com/guzzle/guzzle/pull/1998) -* Improvement: Support PHPUnit 6 [#1953](https://github.com/guzzle/guzzle/pull/1953) -* Bug fix: Support empty headers [#1915](https://github.com/guzzle/guzzle/pull/1915) -* Bug fix: Ignore case during header modifications [#1916](https://github.com/guzzle/guzzle/pull/1916) - -+ Minor code cleanups, documentation fixes and clarifications. - - -## 6.3.0 - 2017-06-22 - -* Feature: force IP resolution (ipv4 or ipv6) [#1608](https://github.com/guzzle/guzzle/pull/1608), [#1659](https://github.com/guzzle/guzzle/pull/1659) -* Improvement: Don't include summary in exception message when body is empty [#1621](https://github.com/guzzle/guzzle/pull/1621) -* Improvement: Handle `on_headers` option in MockHandler [#1580](https://github.com/guzzle/guzzle/pull/1580) -* Improvement: Added SUSE Linux CA path [#1609](https://github.com/guzzle/guzzle/issues/1609) -* Improvement: Use class reference for getting the name of the class instead of using hardcoded strings [#1641](https://github.com/guzzle/guzzle/pull/1641) -* Feature: Added `read_timeout` option [#1611](https://github.com/guzzle/guzzle/pull/1611) -* Bug fix: PHP 7.x fixes [#1685](https://github.com/guzzle/guzzle/pull/1685), [#1686](https://github.com/guzzle/guzzle/pull/1686), [#1811](https://github.com/guzzle/guzzle/pull/1811) -* Deprecation: BadResponseException instantiation without a response [#1642](https://github.com/guzzle/guzzle/pull/1642) -* Feature: Added NTLM auth [#1569](https://github.com/guzzle/guzzle/pull/1569) -* Feature: Track redirect HTTP status codes [#1711](https://github.com/guzzle/guzzle/pull/1711) -* Improvement: Check handler type during construction [#1745](https://github.com/guzzle/guzzle/pull/1745) -* Improvement: Always include the Content-Length if there's a body [#1721](https://github.com/guzzle/guzzle/pull/1721) -* Feature: Added convenience method to access a cookie by name [#1318](https://github.com/guzzle/guzzle/pull/1318) -* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684) -* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827) - - -+ Minor code cleanups, documentation fixes and clarifications. - -## 6.2.3 - 2017-02-28 - -* Fix deprecations with guzzle/psr7 version 1.4 - -## 6.2.2 - 2016-10-08 - -* Allow to pass nullable Response to delay callable -* Only add scheme when host is present -* Fix drain case where content-length is the literal string zero -* Obfuscate in-URL credentials in exceptions - -## 6.2.1 - 2016-07-18 - -* Address HTTP_PROXY security vulnerability, CVE-2016-5385: - https://httpoxy.org/ -* Fixing timeout bug with StreamHandler: - https://github.com/guzzle/guzzle/pull/1488 -* Only read up to `Content-Length` in PHP StreamHandler to avoid timeouts when - a server does not honor `Connection: close`. -* Ignore URI fragment when sending requests. - -## 6.2.0 - 2016-03-21 - -* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`. - https://github.com/guzzle/guzzle/pull/1389 -* Bug fix: Fix sleep calculation when waiting for delayed requests. - https://github.com/guzzle/guzzle/pull/1324 -* Feature: More flexible history containers. - https://github.com/guzzle/guzzle/pull/1373 -* Bug fix: defer sink stream opening in StreamHandler. - https://github.com/guzzle/guzzle/pull/1377 -* Bug fix: do not attempt to escape cookie values. - https://github.com/guzzle/guzzle/pull/1406 -* Feature: report original content encoding and length on decoded responses. - https://github.com/guzzle/guzzle/pull/1409 -* Bug fix: rewind seekable request bodies before dispatching to cURL. - https://github.com/guzzle/guzzle/pull/1422 -* Bug fix: provide an empty string to `http_build_query` for HHVM workaround. - https://github.com/guzzle/guzzle/pull/1367 - -## 6.1.1 - 2015-11-22 - -* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler - https://github.com/guzzle/guzzle/commit/911bcbc8b434adce64e223a6d1d14e9a8f63e4e4 -* Feature: HandlerStack is now more generic. - https://github.com/guzzle/guzzle/commit/f2102941331cda544745eedd97fc8fd46e1ee33e -* Bug fix: setting verify to false in the StreamHandler now disables peer - verification. https://github.com/guzzle/guzzle/issues/1256 -* Feature: Middleware now uses an exception factory, including more error - context. https://github.com/guzzle/guzzle/pull/1282 -* Feature: better support for disabled functions. - https://github.com/guzzle/guzzle/pull/1287 -* Bug fix: fixed regression where MockHandler was not using `sink`. - https://github.com/guzzle/guzzle/pull/1292 - -## 6.1.0 - 2015-09-08 - -* Feature: Added the `on_stats` request option to provide access to transfer - statistics for requests. https://github.com/guzzle/guzzle/pull/1202 -* Feature: Added the ability to persist session cookies in CookieJars. - https://github.com/guzzle/guzzle/pull/1195 -* Feature: Some compatibility updates for Google APP Engine - https://github.com/guzzle/guzzle/pull/1216 -* Feature: Added support for NO_PROXY to prevent the use of a proxy based on - a simple set of rules. https://github.com/guzzle/guzzle/pull/1197 -* Feature: Cookies can now contain square brackets. - https://github.com/guzzle/guzzle/pull/1237 -* Bug fix: Now correctly parsing `=` inside of quotes in Cookies. - https://github.com/guzzle/guzzle/pull/1232 -* Bug fix: Cusotm cURL options now correctly override curl options of the - same name. https://github.com/guzzle/guzzle/pull/1221 -* Bug fix: Content-Type header is now added when using an explicitly provided - multipart body. https://github.com/guzzle/guzzle/pull/1218 -* Bug fix: Now ignoring Set-Cookie headers that have no name. -* Bug fix: Reason phrase is no longer cast to an int in some cases in the - cURL handler. https://github.com/guzzle/guzzle/pull/1187 -* Bug fix: Remove the Authorization header when redirecting if the Host - header changes. https://github.com/guzzle/guzzle/pull/1207 -* Bug fix: Cookie path matching fixes - https://github.com/guzzle/guzzle/issues/1129 -* Bug fix: Fixing the cURL `body_as_string` setting - https://github.com/guzzle/guzzle/pull/1201 -* Bug fix: quotes are no longer stripped when parsing cookies. - https://github.com/guzzle/guzzle/issues/1172 -* Bug fix: `form_params` and `query` now always uses the `&` separator. - https://github.com/guzzle/guzzle/pull/1163 -* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set. - https://github.com/guzzle/guzzle/pull/1189 - -## 6.0.2 - 2015-07-04 - -* Fixed a memory leak in the curl handlers in which references to callbacks - were not being removed by `curl_reset`. -* Cookies are now extracted properly before redirects. -* Cookies now allow more character ranges. -* Decoded Content-Encoding responses are now modified to correctly reflect - their state if the encoding was automatically removed by a handler. This - means that the `Content-Encoding` header may be removed an the - `Content-Length` modified to reflect the message size after removing the - encoding. -* Added a more explicit error message when trying to use `form_params` and - `multipart` in the same request. -* Several fixes for HHVM support. -* Functions are now conditionally required using an additional level of - indirection to help with global Composer installations. - -## 6.0.1 - 2015-05-27 - -* Fixed a bug with serializing the `query` request option where the `&` - separator was missing. -* Added a better error message for when `body` is provided as an array. Please - use `form_params` or `multipart` instead. -* Various doc fixes. - -## 6.0.0 - 2015-05-26 - -* See the UPGRADING.md document for more information. -* Added `multipart` and `form_params` request options. -* Added `synchronous` request option. -* Added the `on_headers` request option. -* Fixed `expect` handling. -* No longer adding default middlewares in the client ctor. These need to be - present on the provided handler in order to work. -* Requests are no longer initiated when sending async requests with the - CurlMultiHandler. This prevents unexpected recursion from requests completing - while ticking the cURL loop. -* Removed the semantics of setting `default` to `true`. This is no longer - required now that the cURL loop is not ticked for async requests. -* Added request and response logging middleware. -* No longer allowing self signed certificates when using the StreamHandler. -* Ensuring that `sink` is valid if saving to a file. -* Request exceptions now include a "handler context" which provides handler - specific contextual information. -* Added `GuzzleHttp\RequestOptions` to allow request options to be applied - using constants. -* `$maxHandles` has been removed from CurlMultiHandler. -* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package. - -## 5.3.0 - 2015-05-19 - -* Mock now supports `save_to` -* Marked `AbstractRequestEvent::getTransaction()` as public. -* Fixed a bug in which multiple headers using different casing would overwrite - previous headers in the associative array. -* Added `Utils::getDefaultHandler()` -* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated. -* URL scheme is now always lowercased. - -## 6.0.0-beta.1 - -* Requires PHP >= 5.5 -* Updated to use PSR-7 - * Requires immutable messages, which basically means an event based system - owned by a request instance is no longer possible. - * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). - * Removed the dependency on `guzzlehttp/streams`. These stream abstractions - are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` - namespace. -* Added middleware and handler system - * Replaced the Guzzle event and subscriber system with a middleware system. - * No longer depends on RingPHP, but rather places the HTTP handlers directly - in Guzzle, operating on PSR-7 messages. - * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which - means the `guzzlehttp/retry-subscriber` is now obsolete. - * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. -* Asynchronous responses - * No longer supports the `future` request option to send an async request. - Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, - `getAsync`, etc.). - * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid - recursion required by chaining and forwarding react promises. See - https://github.com/guzzle/promises - * Added `requestAsync` and `sendAsync` to send request asynchronously. - * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests - asynchronously. -* Request options - * POST and form updates - * Added the `form_fields` and `form_files` request options. - * Removed the `GuzzleHttp\Post` namespace. - * The `body` request option no longer accepts an array for POST requests. - * The `exceptions` request option has been deprecated in favor of the - `http_errors` request options. - * The `save_to` request option has been deprecated in favor of `sink` request - option. -* Clients no longer accept an array of URI template string and variables for - URI variables. You will need to expand URI templates before passing them - into a client constructor or request method. -* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are - now magic methods that will send synchronous requests. -* Replaced `Utils.php` with plain functions in `functions.php`. -* Removed `GuzzleHttp\Collection`. -* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as - an array. -* Removed `GuzzleHttp\Query`. Query string handling is now handled using an - associative array passed into the `query` request option. The query string - is serialized using PHP's `http_build_query`. If you need more control, you - can pass the query string in as a string. -* `GuzzleHttp\QueryParser` has been replaced with the - `GuzzleHttp\Psr7\parse_query`. - -## 5.2.0 - 2015-01-27 - -* Added `AppliesHeadersInterface` to make applying headers to a request based - on the body more generic and not specific to `PostBodyInterface`. -* Reduced the number of stack frames needed to send requests. -* Nested futures are now resolved in the client rather than the RequestFsm -* Finishing state transitions is now handled in the RequestFsm rather than the - RingBridge. -* Added a guard in the Pool class to not use recursion for request retries. - -## 5.1.0 - 2014-12-19 - -* Pool class no longer uses recursion when a request is intercepted. -* The size of a Pool can now be dynamically adjusted using a callback. - See https://github.com/guzzle/guzzle/pull/943. -* Setting a request option to `null` when creating a request with a client will - ensure that the option is not set. This allows you to overwrite default - request options on a per-request basis. - See https://github.com/guzzle/guzzle/pull/937. -* Added the ability to limit which protocols are allowed for redirects by - specifying a `protocols` array in the `allow_redirects` request option. -* Nested futures due to retries are now resolved when waiting for synchronous - responses. See https://github.com/guzzle/guzzle/pull/947. -* `"0"` is now an allowed URI path. See - https://github.com/guzzle/guzzle/pull/935. -* `Query` no longer typehints on the `$query` argument in the constructor, - allowing for strings and arrays. -* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle - specific exceptions if necessary. - -## 5.0.3 - 2014-11-03 - -This change updates query strings so that they are treated as un-encoded values -by default where the value represents an un-encoded value to send over the -wire. A Query object then encodes the value before sending over the wire. This -means that even value query string values (e.g., ":") are url encoded. This -makes the Query class match PHP's http_build_query function. However, if you -want to send requests over the wire using valid query string characters that do -not need to be encoded, then you can provide a string to Url::setQuery() and -pass true as the second argument to specify that the query string is a raw -string that should not be parsed or encoded (unless a call to getQuery() is -subsequently made, forcing the query-string to be converted into a Query -object). - -## 5.0.2 - 2014-10-30 - -* Added a trailing `\r\n` to multipart/form-data payloads. See - https://github.com/guzzle/guzzle/pull/871 -* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. -* Status codes are now returned as integers. See - https://github.com/guzzle/guzzle/issues/881 -* No longer overwriting an existing `application/x-www-form-urlencoded` header - when sending POST requests, allowing for customized headers. See - https://github.com/guzzle/guzzle/issues/877 -* Improved path URL serialization. - - * No longer double percent-encoding characters in the path or query string if - they are already encoded. - * Now properly encoding the supplied path to a URL object, instead of only - encoding ' ' and '?'. - * Note: This has been changed in 5.0.3 to now encode query string values by - default unless the `rawString` argument is provided when setting the query - string on a URL: Now allowing many more characters to be present in the - query string without being percent encoded. See http://tools.ietf.org/html/rfc3986#appendix-A - -## 5.0.1 - 2014-10-16 - -Bugfix release. - -* Fixed an issue where connection errors still returned response object in - error and end events event though the response is unusable. This has been - corrected so that a response is not returned in the `getResponse` method of - these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 -* Fixed an issue where transfer statistics were not being populated in the - RingBridge. https://github.com/guzzle/guzzle/issues/866 - -## 5.0.0 - 2014-10-12 - -Adding support for non-blocking responses and some minor API cleanup. - -### New Features - -* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. -* Added a public API for creating a default HTTP adapter. -* Updated the redirect plugin to be non-blocking so that redirects are sent - concurrently. Other plugins like this can now be updated to be non-blocking. -* Added a "progress" event so that you can get upload and download progress - events. -* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers - requests concurrently using a capped pool size as efficiently as possible. -* Added `hasListeners()` to EmitterInterface. -* Removed `GuzzleHttp\ClientInterface::sendAll` and marked - `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the - recommended way). - -### Breaking changes - -The breaking changes in this release are relatively minor. The biggest thing to -look out for is that request and response objects no longer implement fluent -interfaces. - -* Removed the fluent interfaces (i.e., `return $this`) from requests, - responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, - `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and - `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of - why I did this: http://ocramius.github.io/blog/fluent-interfaces-are-evil/. - This also makes the Guzzle message interfaces compatible with the current - PSR-7 message proposal. -* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except - for the HTTP request functions from function.php, these functions are now - implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` - moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to - `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to - `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be - `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php - caused problems for many users: they aren't PSR-4 compliant, require an - explicit include, and needed an if-guard to ensure that the functions are not - declared multiple times. -* Rewrote adapter layer. - * Removing all classes from `GuzzleHttp\Adapter`, these are now - implemented as callables that are stored in `GuzzleHttp\Ring\Client`. - * Removed the concept of "parallel adapters". Sending requests serially or - concurrently is now handled using a single adapter. - * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The - Transaction object now exposes the request, response, and client as public - properties. The getters and setters have been removed. -* Removed the "headers" event. This event was only useful for changing the - body a response once the headers of the response were known. You can implement - a similar behavior in a number of ways. One example might be to use a - FnStream that has access to the transaction being sent. For example, when the - first byte is written, you could check if the response headers match your - expectations, and if so, change the actual stream body that is being - written to. -* Removed the `asArray` parameter from - `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header - value as an array, then use the newly added `getHeaderAsArray()` method of - `MessageInterface`. This change makes the Guzzle interfaces compatible with - the PSR-7 interfaces. -* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add - custom request options using double-dispatch (this was an implementation - detail). Instead, you should now provide an associative array to the - constructor which is a mapping of the request option name mapping to a - function that applies the option value to a request. -* Removed the concept of "throwImmediately" from exceptions and error events. - This control mechanism was used to stop a transfer of concurrent requests - from completing. This can now be handled by throwing the exception or by - cancelling a pool of requests or each outstanding future request individually. -* Updated to "GuzzleHttp\Streams" 3.0. - * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a - `maxLen` parameter. This update makes the Guzzle streams project - compatible with the current PSR-7 proposal. - * `GuzzleHttp\Stream\Stream::__construct`, - `GuzzleHttp\Stream\Stream::factory`, and - `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second - argument. They now accept an associative array of options, including the - "size" key and "metadata" key which can be used to provide custom metadata. - -## 4.2.2 - 2014-09-08 - -* Fixed a memory leak in the CurlAdapter when reusing cURL handles. -* No longer using `request_fulluri` in stream adapter proxies. -* Relative redirects are now based on the last response, not the first response. - -## 4.2.1 - 2014-08-19 - -* Ensuring that the StreamAdapter does not always add a Content-Type header -* Adding automated github releases with a phar and zip - -## 4.2.0 - 2014-08-17 - -* Now merging in default options using a case-insensitive comparison. - Closes https://github.com/guzzle/guzzle/issues/767 -* Added the ability to automatically decode `Content-Encoding` response bodies - using the `decode_content` request option. This is set to `true` by default - to decode the response body if it comes over the wire with a - `Content-Encoding`. Set this value to `false` to disable decoding the - response content, and pass a string to provide a request `Accept-Encoding` - header and turn on automatic response decoding. This feature now allows you - to pass an `Accept-Encoding` header in the headers of a request but still - disable automatic response decoding. - Closes https://github.com/guzzle/guzzle/issues/764 -* Added the ability to throw an exception immediately when transferring - requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 -* Updating guzzlehttp/streams dependency to ~2.1 -* No longer utilizing the now deprecated namespaced methods from the stream - package. - -## 4.1.8 - 2014-08-14 - -* Fixed an issue in the CurlFactory that caused setting the `stream=false` - request option to throw an exception. - See: https://github.com/guzzle/guzzle/issues/769 -* TransactionIterator now calls rewind on the inner iterator. - See: https://github.com/guzzle/guzzle/pull/765 -* You can now set the `Content-Type` header to `multipart/form-data` - when creating POST requests to force multipart bodies. - See https://github.com/guzzle/guzzle/issues/768 - -## 4.1.7 - 2014-08-07 - -* Fixed an error in the HistoryPlugin that caused the same request and response - to be logged multiple times when an HTTP protocol error occurs. -* Ensuring that cURL does not add a default Content-Type when no Content-Type - has been supplied by the user. This prevents the adapter layer from modifying - the request that is sent over the wire after any listeners may have already - put the request in a desired state (e.g., signed the request). -* Throwing an exception when you attempt to send requests that have the - "stream" set to true in parallel using the MultiAdapter. -* Only calling curl_multi_select when there are active cURL handles. This was - previously changed and caused performance problems on some systems due to PHP - always selecting until the maximum select timeout. -* Fixed a bug where multipart/form-data POST fields were not correctly - aggregated (e.g., values with "&"). - -## 4.1.6 - 2014-08-03 - -* Added helper methods to make it easier to represent messages as strings, - including getting the start line and getting headers as a string. - -## 4.1.5 - 2014-08-02 - -* Automatically retrying cURL "Connection died, retrying a fresh connect" - errors when possible. -* cURL implementation cleanup -* Allowing multiple event subscriber listeners to be registered per event by - passing an array of arrays of listener configuration. - -## 4.1.4 - 2014-07-22 - -* Fixed a bug that caused multi-part POST requests with more than one field to - serialize incorrectly. -* Paths can now be set to "0" -* `ResponseInterface::xml` now accepts a `libxml_options` option and added a - missing default argument that was required when parsing XML response bodies. -* A `save_to` stream is now created lazily, which means that files are not - created on disk unless a request succeeds. - -## 4.1.3 - 2014-07-15 - -* Various fixes to multipart/form-data POST uploads -* Wrapping function.php in an if-statement to ensure Guzzle can be used - globally and in a Composer install -* Fixed an issue with generating and merging in events to an event array -* POST headers are only applied before sending a request to allow you to change - the query aggregator used before uploading -* Added much more robust query string parsing -* Fixed various parsing and normalization issues with URLs -* Fixing an issue where multi-valued headers were not being utilized correctly - in the StreamAdapter - -## 4.1.2 - 2014-06-18 - -* Added support for sending payloads with GET requests - -## 4.1.1 - 2014-06-08 - -* Fixed an issue related to using custom message factory options in subclasses -* Fixed an issue with nested form fields in a multi-part POST -* Fixed an issue with using the `json` request option for POST requests -* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` - -## 4.1.0 - 2014-05-27 - -* Added a `json` request option to easily serialize JSON payloads. -* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. -* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. -* Added the ability to provide an emitter to a client in the client constructor. -* Added the ability to persist a cookie session using $_SESSION. -* Added a trait that can be used to add event listeners to an iterator. -* Removed request method constants from RequestInterface. -* Fixed warning when invalid request start-lines are received. -* Updated MessageFactory to work with custom request option methods. -* Updated cacert bundle to latest build. - -4.0.2 (2014-04-16) ------------------- - -* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) -* Added the ability to set scalars as POST fields (#628) - -## 4.0.1 - 2014-04-04 - -* The HTTP status code of a response is now set as the exception code of - RequestException objects. -* 303 redirects will now correctly switch from POST to GET requests. -* The default parallel adapter of a client now correctly uses the MultiAdapter. -* HasDataTrait now initializes the internal data array as an empty array so - that the toArray() method always returns an array. - -## 4.0.0 - 2014-03-29 - -* For more information on the 4.0 transition, see: - http://mtdowling.com/blog/2014/03/15/guzzle-4-rc/ -* For information on changes and upgrading, see: - https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 -* Added `GuzzleHttp\batch()` as a convenience function for sending requests in - parallel without needing to write asynchronous code. -* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. - You can now pass a callable or an array of associative arrays where each - associative array contains the "fn", "priority", and "once" keys. - -## 4.0.0.rc-2 - 2014-03-25 - -* Removed `getConfig()` and `setConfig()` from clients to avoid confusion - around whether things like base_url, message_factory, etc. should be able to - be retrieved or modified. -* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface -* functions.php functions were renamed using snake_case to match PHP idioms -* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and - `GUZZLE_CURL_SELECT_TIMEOUT` environment variables -* Added the ability to specify custom `sendAll()` event priorities -* Added the ability to specify custom stream context options to the stream - adapter. -* Added a functions.php function for `get_path()` and `set_path()` -* CurlAdapter and MultiAdapter now use a callable to generate curl resources -* MockAdapter now properly reads a body and emits a `headers` event -* Updated Url class to check if a scheme and host are set before adding ":" - and "//". This allows empty Url (e.g., "") to be serialized as "". -* Parsing invalid XML no longer emits warnings -* Curl classes now properly throw AdapterExceptions -* Various performance optimizations -* Streams are created with the faster `Stream\create()` function -* Marked deprecation_proxy() as internal -* Test server is now a collection of static methods on a class - -## 4.0.0-rc.1 - 2014-03-15 - -* See https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 - -## 3.8.1 - 2014-01-28 - -* Bug: Always using GET requests when redirecting from a 303 response -* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in - `Guzzle\Http\ClientInterface::setSslVerification()` -* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL -* Bug: The body of a request can now be set to `"0"` -* Sending PHP stream requests no longer forces `HTTP/1.0` -* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of - each sub-exception -* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than - clobbering everything). -* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) -* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. - For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. -* Now properly escaping the regular expression delimiter when matching Cookie domains. -* Network access is now disabled when loading XML documents - -## 3.8.0 - 2013-12-05 - -* Added the ability to define a POST name for a file -* JSON response parsing now properly walks additionalProperties -* cURL error code 18 is now retried automatically in the BackoffPlugin -* Fixed a cURL error when URLs contain fragments -* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were - CurlExceptions -* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) -* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` -* Fixed a bug that was encountered when parsing empty header parameters -* UriTemplate now has a `setRegex()` method to match the docs -* The `debug` request parameter now checks if it is truthy rather than if it exists -* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin -* Added the ability to combine URLs using strict RFC 3986 compliance -* Command objects can now return the validation errors encountered by the command -* Various fixes to cache revalidation (#437 and 29797e5) -* Various fixes to the AsyncPlugin -* Cleaned up build scripts - -## 3.7.4 - 2013-10-02 - -* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) -* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp - (see https://github.com/aws/aws-sdk-php/issues/147) -* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots -* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) -* Updated the bundled cacert.pem (#419) -* OauthPlugin now supports adding authentication to headers or query string (#425) - -## 3.7.3 - 2013-09-08 - -* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and - `CommandTransferException`. -* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description -* Schemas are only injected into response models when explicitly configured. -* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of - an EntityBody. -* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. -* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. -* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() -* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin -* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests -* Bug fix: Properly parsing headers that contain commas contained in quotes -* Bug fix: mimetype guessing based on a filename is now case-insensitive - -## 3.7.2 - 2013-08-02 - -* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander - See https://github.com/guzzle/guzzle/issues/371 -* Bug fix: Cookie domains are now matched correctly according to RFC 6265 - See https://github.com/guzzle/guzzle/issues/377 -* Bug fix: GET parameters are now used when calculating an OAuth signature -* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted -* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched -* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. - See https://github.com/guzzle/guzzle/issues/379 -* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See - https://github.com/guzzle/guzzle/pull/380 -* cURL multi cleanup and optimizations - -## 3.7.1 - 2013-07-05 - -* Bug fix: Setting default options on a client now works -* Bug fix: Setting options on HEAD requests now works. See #352 -* Bug fix: Moving stream factory before send event to before building the stream. See #353 -* Bug fix: Cookies no longer match on IP addresses per RFC 6265 -* Bug fix: Correctly parsing header parameters that are in `<>` and quotes -* Added `cert` and `ssl_key` as request options -* `Host` header can now diverge from the host part of a URL if the header is set manually -* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter -* OAuth parameters are only added via the plugin if they aren't already set -* Exceptions are now thrown when a URL cannot be parsed -* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails -* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin - -## 3.7.0 - 2013-06-10 - -* See UPGRADING.md for more information on how to upgrade. -* Requests now support the ability to specify an array of $options when creating a request to more easily modify a - request. You can pass a 'request.options' configuration setting to a client to apply default request options to - every request created by a client (e.g. default query string variables, headers, curl options, etc.). -* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. - See `Guzzle\Http\StaticClient::mount`. -* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests - created by a command (e.g. custom headers, query string variables, timeout settings, etc.). -* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the - headers of a response -* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key - (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) -* ServiceBuilders now support storing and retrieving arbitrary data -* CachePlugin can now purge all resources for a given URI -* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource -* CachePlugin now uses the Vary header to determine if a resource is a cache hit -* `Guzzle\Http\Message\Response` now implements `\Serializable` -* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters -* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable -* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` -* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size -* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message -* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older - Symfony users can still use the old version of Monolog. -* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. - Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. -* Several performance improvements to `Guzzle\Common\Collection` -* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: - createRequest, head, delete, put, patch, post, options, prepareRequest -* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` -* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` -* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to - `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a - resource, string, or EntityBody into the $options parameter to specify the download location of the response. -* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a - default `array()` -* Added `Guzzle\Stream\StreamInterface::isRepeatable` -* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use - $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or - $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. -* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. -* Removed `Guzzle\Http\ClientInterface::expandTemplate()` -* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` -* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` -* Removed `Guzzle\Http\Message\RequestInterface::canCache` -* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` -* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` -* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. -* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting - `Guzzle\Common\Version::$emitWarnings` to true. -* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use - `$request->getResponseBody()->isRepeatable()` instead. -* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use - `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. -* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use - `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. -* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. -* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. -* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated -* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. - These will work through Guzzle 4.0 -* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. -* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. -* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. -* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. -* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. -* Marked `Guzzle\Common\Collection::inject()` as deprecated. -* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` -* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a - CacheStorageInterface. These two objects and interface will be removed in a future version. -* Always setting X-cache headers on cached responses -* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin -* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface - $request, Response $response);` -* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` -* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` -* Added `CacheStorageInterface::purge($url)` -* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin - $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, - CanCacheStrategyInterface $canCache = null)` -* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` - -## 3.6.0 - 2013-05-29 - -* ServiceDescription now implements ToArrayInterface -* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters -* Guzzle can now correctly parse incomplete URLs -* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. -* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution -* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). -* Specific header implementations can be created for complex headers. When a message creates a header, it uses a - HeaderFactory which can map specific headers to specific header classes. There is now a Link header and - CacheControl header implementation. -* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate -* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() -* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in - Guzzle\Http\Curl\RequestMediator -* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. -* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface -* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() -* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() -* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). -* All response header helper functions return a string rather than mixing Header objects and strings inconsistently -* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle - directly via interfaces -* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist - but are a no-op until removed. -* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a - `Guzzle\Service\Command\ArrayCommandInterface`. -* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response - on a request while the request is still being transferred -* The ability to case-insensitively search for header values -* Guzzle\Http\Message\Header::hasExactHeader -* Guzzle\Http\Message\Header::raw. Use getAll() -* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object - instead. -* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess -* Added the ability to cast Model objects to a string to view debug information. - -## 3.5.0 - 2013-05-13 - -* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times -* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove - itself from the EventDispatcher) -* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values -* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too -* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a - non-existent key -* Bug: All __call() method arguments are now required (helps with mocking frameworks) -* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference - to help with refcount based garbage collection of resources created by sending a request -* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. -* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the - HistoryPlugin for a history. -* Added a `responseBody` alias for the `response_body` location -* Refactored internals to no longer rely on Response::getRequest() -* HistoryPlugin can now be cast to a string -* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests - and responses that are sent over the wire -* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects - -## 3.4.3 - 2013-04-30 - -* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response -* Added a check to re-extract the temp cacert bundle from the phar before sending each request - -## 3.4.2 - 2013-04-29 - -* Bug fix: Stream objects now work correctly with "a" and "a+" modes -* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present -* Bug fix: AsyncPlugin no longer forces HEAD requests -* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter -* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails -* Setting a response on a request will write to the custom request body from the response body if one is specified -* LogPlugin now writes to php://output when STDERR is undefined -* Added the ability to set multiple POST files for the same key in a single call -* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default -* Added the ability to queue CurlExceptions to the MockPlugin -* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) -* Configuration loading now allows remote files - -## 3.4.1 - 2013-04-16 - -* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti - handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. -* Exceptions are now properly grouped when sending requests in parallel -* Redirects are now properly aggregated when a multi transaction fails -* Redirects now set the response on the original object even in the event of a failure -* Bug fix: Model names are now properly set even when using $refs -* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax -* Added support for oauth_callback in OAuth signatures -* Added support for oauth_verifier in OAuth signatures -* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection - -## 3.4.0 - 2013-04-11 - -* Bug fix: URLs are now resolved correctly based on http://tools.ietf.org/html/rfc3986#section-5.2. #289 -* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 -* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 -* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. -* Bug fix: Added `number` type to service descriptions. -* Bug fix: empty parameters are removed from an OAuth signature -* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header -* Bug fix: Fixed "array to string" error when validating a union of types in a service description -* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream -* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. -* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. -* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. -* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if - the Content-Type can be determined based on the entity body or the path of the request. -* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. -* Added support for a PSR-3 LogAdapter. -* Added a `command.after_prepare` event -* Added `oauth_callback` parameter to the OauthPlugin -* Added the ability to create a custom stream class when using a stream factory -* Added a CachingEntityBody decorator -* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. -* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. -* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies -* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This - means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use - POST fields or files (the latter is only used when emulating a form POST in the browser). -* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest - -## 3.3.1 - 2013-03-10 - -* Added the ability to create PHP streaming responses from HTTP requests -* Bug fix: Running any filters when parsing response headers with service descriptions -* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing -* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across - response location visitors. -* Bug fix: Removed the possibility of creating configuration files with circular dependencies -* RequestFactory::create() now uses the key of a POST file when setting the POST file name -* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set - -## 3.3.0 - 2013-03-03 - -* A large number of performance optimizations have been made -* Bug fix: Added 'wb' as a valid write mode for streams -* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned -* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` -* BC: Removed `Guzzle\Http\Utils` class -* BC: Setting a service description on a client will no longer modify the client's command factories. -* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using - the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' -* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to - lowercase -* Operation parameter objects are now lazy loaded internally -* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses -* Added support for instantiating responseType=class responseClass classes. Classes must implement - `Guzzle\Service\Command\ResponseClassInterface` -* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These - additional properties also support locations and can be used to parse JSON responses where the outermost part of the - JSON is an array -* Added support for nested renaming of JSON models (rename sentAs to name) -* CachePlugin - * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error - * Debug headers can now added to cached response in the CachePlugin - -## 3.2.0 - 2013-02-14 - -* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. -* URLs with no path no longer contain a "/" by default -* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. -* BadResponseException no longer includes the full request and response message -* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface -* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface -* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription -* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list -* xmlEncoding can now be customized for the XML declaration of a XML service description operation -* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value - aggregation and no longer uses callbacks -* The URL encoding implementation of Guzzle\Http\QueryString can now be customized -* Bug fix: Filters were not always invoked for array service description parameters -* Bug fix: Redirects now use a target response body rather than a temporary response body -* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded -* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives - -## 3.1.2 - 2013-01-27 - -* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the - response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. -* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent -* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) -* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() -* Setting default headers on a client after setting the user-agent will not erase the user-agent setting - -## 3.1.1 - 2013-01-20 - -* Adding wildcard support to Guzzle\Common\Collection::getPath() -* Adding alias support to ServiceBuilder configs -* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface - -## 3.1.0 - 2013-01-12 - -* BC: CurlException now extends from RequestException rather than BadResponseException -* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() -* Added getData to ServiceDescriptionInterface -* Added context array to RequestInterface::setState() -* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http -* Bug: Adding required content-type when JSON request visitor adds JSON to a command -* Bug: Fixing the serialization of a service description with custom data -* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing - an array of successful and failed responses -* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection -* Added Guzzle\Http\IoEmittingEntityBody -* Moved command filtration from validators to location visitors -* Added `extends` attributes to service description parameters -* Added getModels to ServiceDescriptionInterface - -## 3.0.7 - 2012-12-19 - -* Fixing phar detection when forcing a cacert to system if null or true -* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` -* Cleaning up `Guzzle\Common\Collection::inject` method -* Adding a response_body location to service descriptions - -## 3.0.6 - 2012-12-09 - -* CurlMulti performance improvements -* Adding setErrorResponses() to Operation -* composer.json tweaks - -## 3.0.5 - 2012-11-18 - -* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin -* Bug: Response body can now be a string containing "0" -* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert -* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs -* Added support for XML attributes in service description responses -* DefaultRequestSerializer now supports array URI parameter values for URI template expansion -* Added better mimetype guessing to requests and post files - -## 3.0.4 - 2012-11-11 - -* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value -* Bug: Cookies can now be added that have a name, domain, or value set to "0" -* Bug: Using the system cacert bundle when using the Phar -* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures -* Enhanced cookie jar de-duplication -* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added -* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies -* Added the ability to create any sort of hash for a stream rather than just an MD5 hash - -## 3.0.3 - 2012-11-04 - -* Implementing redirects in PHP rather than cURL -* Added PECL URI template extension and using as default parser if available -* Bug: Fixed Content-Length parsing of Response factory -* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. -* Adding ToArrayInterface throughout library -* Fixing OauthPlugin to create unique nonce values per request - -## 3.0.2 - 2012-10-25 - -* Magic methods are enabled by default on clients -* Magic methods return the result of a command -* Service clients no longer require a base_url option in the factory -* Bug: Fixed an issue with URI templates where null template variables were being expanded - -## 3.0.1 - 2012-10-22 - -* Models can now be used like regular collection objects by calling filter, map, etc. -* Models no longer require a Parameter structure or initial data in the constructor -* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` - -## 3.0.0 - 2012-10-15 - -* Rewrote service description format to be based on Swagger - * Now based on JSON schema - * Added nested input structures and nested response models - * Support for JSON and XML input and output models - * Renamed `commands` to `operations` - * Removed dot class notation - * Removed custom types -* Broke the project into smaller top-level namespaces to be more component friendly -* Removed support for XML configs and descriptions. Use arrays or JSON files. -* Removed the Validation component and Inspector -* Moved all cookie code to Guzzle\Plugin\Cookie -* Magic methods on a Guzzle\Service\Client now return the command un-executed. -* Calling getResult() or getResponse() on a command will lazily execute the command if needed. -* Now shipping with cURL's CA certs and using it by default -* Added previousResponse() method to response objects -* No longer sending Accept and Accept-Encoding headers on every request -* Only sending an Expect header by default when a payload is greater than 1MB -* Added/moved client options: - * curl.blacklist to curl.option.blacklist - * Added ssl.certificate_authority -* Added a Guzzle\Iterator component -* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin -* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) -* Added a more robust caching plugin -* Added setBody to response objects -* Updating LogPlugin to use a more flexible MessageFormatter -* Added a completely revamped build process -* Cleaning up Collection class and removing default values from the get method -* Fixed ZF2 cache adapters - -## 2.8.8 - 2012-10-15 - -* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did - -## 2.8.7 - 2012-09-30 - -* Bug: Fixed config file aliases for JSON includes -* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests -* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload -* Bug: Hardening request and response parsing to account for missing parts -* Bug: Fixed PEAR packaging -* Bug: Fixed Request::getInfo -* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail -* Adding the ability for the namespace Iterator factory to look in multiple directories -* Added more getters/setters/removers from service descriptions -* Added the ability to remove POST fields from OAuth signatures -* OAuth plugin now supports 2-legged OAuth - -## 2.8.6 - 2012-09-05 - -* Added the ability to modify and build service descriptions -* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command -* Added a `json` parameter location -* Now allowing dot notation for classes in the CacheAdapterFactory -* Using the union of two arrays rather than an array_merge when extending service builder services and service params -* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references - in service builder config files. -* Services defined in two different config files that include one another will by default replace the previously - defined service, but you can now create services that extend themselves and merge their settings over the previous -* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like - '_default' with a default JSON configuration file. - -## 2.8.5 - 2012-08-29 - -* Bug: Suppressed empty arrays from URI templates -* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching -* Added support for HTTP responses that do not contain a reason phrase in the start-line -* AbstractCommand commands are now invokable -* Added a way to get the data used when signing an Oauth request before a request is sent - -## 2.8.4 - 2012-08-15 - -* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin -* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. -* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream -* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream -* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) -* Added additional response status codes -* Removed SSL information from the default User-Agent header -* DELETE requests can now send an entity body -* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries -* Added the ability of the MockPlugin to consume mocked request bodies -* LogPlugin now exposes request and response objects in the extras array - -## 2.8.3 - 2012-07-30 - -* Bug: Fixed a case where empty POST requests were sent as GET requests -* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body -* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new -* Added multiple inheritance to service description commands -* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` -* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything -* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles - -## 2.8.2 - 2012-07-24 - -* Bug: Query string values set to 0 are no longer dropped from the query string -* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` -* Bug: `+` is now treated as an encoded space when parsing query strings -* QueryString and Collection performance improvements -* Allowing dot notation for class paths in filters attribute of a service descriptions - -## 2.8.1 - 2012-07-16 - -* Loosening Event Dispatcher dependency -* POST redirects can now be customized using CURLOPT_POSTREDIR - -## 2.8.0 - 2012-07-15 - -* BC: Guzzle\Http\Query - * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) - * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() - * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) - * Changed the aggregation functions of QueryString to be static methods - * Can now use fromString() with querystrings that have a leading ? -* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters -* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body -* Cookies are no longer URL decoded by default -* Bug: URI template variables set to null are no longer expanded - -## 2.7.2 - 2012-07-02 - -* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. -* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() -* CachePlugin now allows for a custom request parameter function to check if a request can be cached -* Bug fix: CachePlugin now only caches GET and HEAD requests by default -* Bug fix: Using header glue when transferring headers over the wire -* Allowing deeply nested arrays for composite variables in URI templates -* Batch divisors can now return iterators or arrays - -## 2.7.1 - 2012-06-26 - -* Minor patch to update version number in UA string -* Updating build process - -## 2.7.0 - 2012-06-25 - -* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. -* BC: Removed magic setX methods from commands -* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method -* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. -* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) -* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace -* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin -* Added the ability to set POST fields and files in a service description -* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method -* Adding a command.before_prepare event to clients -* Added BatchClosureTransfer and BatchClosureDivisor -* BatchTransferException now includes references to the batch divisor and transfer strategies -* Fixed some tests so that they pass more reliably -* Added Guzzle\Common\Log\ArrayLogAdapter - -## 2.6.6 - 2012-06-10 - -* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin -* BC: Removing Guzzle\Service\Command\CommandSet -* Adding generic batching system (replaces the batch queue plugin and command set) -* Updating ZF cache and log adapters and now using ZF's composer repository -* Bug: Setting the name of each ApiParam when creating through an ApiCommand -* Adding result_type, result_doc, deprecated, and doc_url to service descriptions -* Bug: Changed the default cookie header casing back to 'Cookie' - -## 2.6.5 - 2012-06-03 - -* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() -* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from -* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data -* BC: Renaming methods in the CookieJarInterface -* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations -* Making the default glue for HTTP headers ';' instead of ',' -* Adding a removeValue to Guzzle\Http\Message\Header -* Adding getCookies() to request interface. -* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() - -## 2.6.4 - 2012-05-30 - -* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. -* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand -* Bug: Fixing magic method command calls on clients -* Bug: Email constraint only validates strings -* Bug: Aggregate POST fields when POST files are present in curl handle -* Bug: Fixing default User-Agent header -* Bug: Only appending or prepending parameters in commands if they are specified -* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes -* Allowing the use of dot notation for class namespaces when using instance_of constraint -* Added any_match validation constraint -* Added an AsyncPlugin -* Passing request object to the calculateWait method of the ExponentialBackoffPlugin -* Allowing the result of a command object to be changed -* Parsing location and type sub values when instantiating a service description rather than over and over at runtime - -## 2.6.3 - 2012-05-23 - -* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. -* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. -* You can now use an array of data when creating PUT request bodies in the request factory. -* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. -* [Http] Adding support for Content-Type in multipart POST uploads per upload -* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) -* Adding more POST data operations for easier manipulation of POST data. -* You can now set empty POST fields. -* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. -* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. -* CS updates - -## 2.6.2 - 2012-05-19 - -* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. - -## 2.6.1 - 2012-05-19 - -* [BC] Removing 'path' support in service descriptions. Use 'uri'. -* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. -* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. -* [BC] Removing Guzzle\Common\XmlElement. -* All commands, both dynamic and concrete, have ApiCommand objects. -* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. -* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. -* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. - -## 2.6.0 - 2012-05-15 - -* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder -* [BC] Executing a Command returns the result of the command rather than the command -* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. -* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. -* [BC] Moving ResourceIterator* to Guzzle\Service\Resource -* [BC] Completely refactored ResourceIterators to iterate over a cloned command object -* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate -* [BC] Guzzle\Guzzle is now deprecated -* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject -* Adding Guzzle\Version class to give version information about Guzzle -* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() -* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data -* ServiceDescription and ServiceBuilder are now cacheable using similar configs -* Changing the format of XML and JSON service builder configs. Backwards compatible. -* Cleaned up Cookie parsing -* Trimming the default Guzzle User-Agent header -* Adding a setOnComplete() method to Commands that is called when a command completes -* Keeping track of requests that were mocked in the MockPlugin -* Fixed a caching bug in the CacheAdapterFactory -* Inspector objects can be injected into a Command object -* Refactoring a lot of code and tests to be case insensitive when dealing with headers -* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL -* Adding the ability to set global option overrides to service builder configs -* Adding the ability to include other service builder config files from within XML and JSON files -* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. - -## 2.5.0 - 2012-05-08 - -* Major performance improvements -* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. -* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. -* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" -* Added the ability to passed parameters to all requests created by a client -* Added callback functionality to the ExponentialBackoffPlugin -* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. -* Rewinding request stream bodies when retrying requests -* Exception is thrown when JSON response body cannot be decoded -* Added configurable magic method calls to clients and commands. This is off by default. -* Fixed a defect that added a hash to every parsed URL part -* Fixed duplicate none generation for OauthPlugin. -* Emitting an event each time a client is generated by a ServiceBuilder -* Using an ApiParams object instead of a Collection for parameters of an ApiCommand -* cache.* request parameters should be renamed to params.cache.* -* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. -* Added the ability to disable type validation of service descriptions -* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/vendor/guzzlehttp/guzzle/Dockerfile b/vendor/guzzlehttp/guzzle/Dockerfile deleted file mode 100644 index f6a0952..0000000 --- a/vendor/guzzlehttp/guzzle/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM composer:latest as setup - -RUN mkdir /guzzle - -WORKDIR /guzzle - -RUN set -xe \ - && composer init --name=guzzlehttp/test --description="Simple project for testing Guzzle scripts" --author="Márk Sági-Kazár " --no-interaction \ - && composer require guzzlehttp/guzzle - - -FROM php:7.3 - -RUN mkdir /guzzle - -WORKDIR /guzzle - -COPY --from=setup /guzzle /guzzle diff --git a/vendor/guzzlehttp/guzzle/LICENSE b/vendor/guzzlehttp/guzzle/LICENSE deleted file mode 100644 index 50a177b..0000000 --- a/vendor/guzzlehttp/guzzle/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011-2018 Michael Dowling, https://github.com/mtdowling - -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/guzzlehttp/guzzle/README.md b/vendor/guzzlehttp/guzzle/README.md deleted file mode 100644 index 5fdb6c5..0000000 --- a/vendor/guzzlehttp/guzzle/README.md +++ /dev/null @@ -1,90 +0,0 @@ -Guzzle, PHP HTTP client -======================= - -[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases) -[![Build Status](https://img.shields.io/travis/guzzle/guzzle.svg?style=flat-square)](https://travis-ci.org/guzzle/guzzle) -[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle) - -Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and -trivial to integrate with web services. - -- Simple interface for building query strings, POST requests, streaming large - uploads, streaming large downloads, using HTTP cookies, uploading JSON data, - etc... -- Can send both synchronous and asynchronous requests using the same interface. -- Uses PSR-7 interfaces for requests, responses, and streams. This allows you - to utilize other PSR-7 compatible libraries with Guzzle. -- Abstracts away the underlying HTTP transport, allowing you to write - environment and transport agnostic code; i.e., no hard dependency on cURL, - PHP streams, sockets, or non-blocking event loops. -- Middleware system allows you to augment and compose client behavior. - -```php -$client = new \GuzzleHttp\Client(); -$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); - -echo $response->getStatusCode(); # 200 -echo $response->getHeaderLine('content-type'); # 'application/json; charset=utf8' -echo $response->getBody(); # '{"id": 1420053, "name": "guzzle", ...}' - -# Send an asynchronous request. -$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); -$promise = $client->sendAsync($request)->then(function ($response) { - echo 'I completed! ' . $response->getBody(); -}); - -$promise->wait(); -``` - -## Help and docs - -- [Documentation](http://guzzlephp.org/) -- [Stack Overflow](http://stackoverflow.com/questions/tagged/guzzle) -- [Gitter](https://gitter.im/guzzle/guzzle) - - -## Installing Guzzle - -The recommended way to install Guzzle is through -[Composer](http://getcomposer.org). - -```bash -# Install Composer -curl -sS https://getcomposer.org/installer | php -``` - -Next, run the Composer command to install the latest stable version of Guzzle: - -```bash -composer require guzzlehttp/guzzle -``` - -After installing, you need to require Composer's autoloader: - -```php -require 'vendor/autoload.php'; -``` - -You can then later update Guzzle using composer: - - ```bash -composer update - ``` - - -## Version Guidance - -| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version | -|---------|------------|---------------------|--------------|---------------------|---------------------|-------|-------------| -| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >= 5.3.3 | -| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >= 5.4 | -| 5.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >= 5.4 | -| 6.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >= 5.5 | - -[guzzle-3-repo]: https://github.com/guzzle/guzzle3 -[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x -[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3 -[guzzle-6-repo]: https://github.com/guzzle/guzzle -[guzzle-3-docs]: http://guzzle3.readthedocs.org -[guzzle-5-docs]: http://guzzle.readthedocs.org/en/5.3/ -[guzzle-6-docs]: http://guzzle.readthedocs.org/en/latest/ diff --git a/vendor/guzzlehttp/guzzle/UPGRADING.md b/vendor/guzzlehttp/guzzle/UPGRADING.md deleted file mode 100644 index 91d1dcc..0000000 --- a/vendor/guzzlehttp/guzzle/UPGRADING.md +++ /dev/null @@ -1,1203 +0,0 @@ -Guzzle Upgrade Guide -==================== - -5.0 to 6.0 ----------- - -Guzzle now uses [PSR-7](http://www.php-fig.org/psr/psr-7/) for HTTP messages. -Due to the fact that these messages are immutable, this prompted a refactoring -of Guzzle to use a middleware based system rather than an event system. Any -HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be -updated to work with the new immutable PSR-7 request and response objects. Any -event listeners or subscribers need to be updated to become middleware -functions that wrap handlers (or are injected into a -`GuzzleHttp\HandlerStack`). - -- Removed `GuzzleHttp\BatchResults` -- Removed `GuzzleHttp\Collection` -- Removed `GuzzleHttp\HasDataTrait` -- Removed `GuzzleHttp\ToArrayInterface` -- The `guzzlehttp/streams` dependency has been removed. Stream functionality - is now present in the `GuzzleHttp\Psr7` namespace provided by the - `guzzlehttp/psr7` package. -- Guzzle no longer uses ReactPHP promises and now uses the - `guzzlehttp/promises` library. We use a custom promise library for three - significant reasons: - 1. React promises (at the time of writing this) are recursive. Promise - chaining and promise resolution will eventually blow the stack. Guzzle - promises are not recursive as they use a sort of trampolining technique. - Note: there has been movement in the React project to modify promises to - no longer utilize recursion. - 2. Guzzle needs to have the ability to synchronously block on a promise to - wait for a result. Guzzle promises allows this functionality (and does - not require the use of recursion). - 3. Because we need to be able to wait on a result, doing so using React - promises requires wrapping react promises with RingPHP futures. This - overhead is no longer needed, reducing stack sizes, reducing complexity, - and improving performance. -- `GuzzleHttp\Mimetypes` has been moved to a function in - `GuzzleHttp\Psr7\mimetype_from_extension` and - `GuzzleHttp\Psr7\mimetype_from_filename`. -- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query - strings must now be passed into request objects as strings, or provided to - the `query` request option when creating requests with clients. The `query` - option uses PHP's `http_build_query` to convert an array to a string. If you - need a different serialization technique, you will need to pass the query - string in as a string. There are a couple helper functions that will make - working with query strings easier: `GuzzleHttp\Psr7\parse_query` and - `GuzzleHttp\Psr7\build_query`. -- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware - system based on PSR-7, using RingPHP and it's middleware system as well adds - more complexity than the benefits it provides. All HTTP handlers that were - present in RingPHP have been modified to work directly with PSR-7 messages - and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces - complexity in Guzzle, removes a dependency, and improves performance. RingPHP - will be maintained for Guzzle 5 support, but will no longer be a part of - Guzzle 6. -- As Guzzle now uses a middleware based systems the event system and RingPHP - integration has been removed. Note: while the event system has been removed, - it is possible to add your own type of event system that is powered by the - middleware system. - - Removed the `Event` namespace. - - Removed the `Subscriber` namespace. - - Removed `Transaction` class - - Removed `RequestFsm` - - Removed `RingBridge` - - `GuzzleHttp\Subscriber\Cookie` is now provided by - `GuzzleHttp\Middleware::cookies` - - `GuzzleHttp\Subscriber\HttpError` is now provided by - `GuzzleHttp\Middleware::httpError` - - `GuzzleHttp\Subscriber\History` is now provided by - `GuzzleHttp\Middleware::history` - - `GuzzleHttp\Subscriber\Mock` is now provided by - `GuzzleHttp\Handler\MockHandler` - - `GuzzleHttp\Subscriber\Prepare` is now provided by - `GuzzleHttp\PrepareBodyMiddleware` - - `GuzzleHttp\Subscriber\Redirect` is now provided by - `GuzzleHttp\RedirectMiddleware` -- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in - `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. -- Static functions in `GuzzleHttp\Utils` have been moved to namespaced - functions under the `GuzzleHttp` namespace. This requires either a Composer - based autoloader or you to include functions.php. -- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to - `GuzzleHttp\ClientInterface::getConfig`. -- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. -- The `json` and `xml` methods of response objects has been removed. With the - migration to strictly adhering to PSR-7 as the interface for Guzzle messages, - adding methods to message interfaces would actually require Guzzle messages - to extend from PSR-7 messages rather then work with them directly. - -## Migrating to middleware - -The change to PSR-7 unfortunately required significant refactoring to Guzzle -due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event -system from plugins. The event system relied on mutability of HTTP messages and -side effects in order to work. With immutable messages, you have to change your -workflow to become more about either returning a value (e.g., functional -middlewares) or setting a value on an object. Guzzle v6 has chosen the -functional middleware approach. - -Instead of using the event system to listen for things like the `before` event, -you now create a stack based middleware function that intercepts a request on -the way in and the promise of the response on the way out. This is a much -simpler and more predictable approach than the event system and works nicely -with PSR-7 middleware. Due to the use of promises, the middleware system is -also asynchronous. - -v5: - -```php -use GuzzleHttp\Event\BeforeEvent; -$client = new GuzzleHttp\Client(); -// Get the emitter and listen to the before event. -$client->getEmitter()->on('before', function (BeforeEvent $e) { - // Guzzle v5 events relied on mutation - $e->getRequest()->setHeader('X-Foo', 'Bar'); -}); -``` - -v6: - -In v6, you can modify the request before it is sent using the `mapRequest` -middleware. The idiomatic way in v6 to modify the request/response lifecycle is -to setup a handler middleware stack up front and inject the handler into a -client. - -```php -use GuzzleHttp\Middleware; -// Create a handler stack that has all of the default middlewares attached -$handler = GuzzleHttp\HandlerStack::create(); -// Push the handler onto the handler stack -$handler->push(Middleware::mapRequest(function (RequestInterface $request) { - // Notice that we have to return a request object - return $request->withHeader('X-Foo', 'Bar'); -})); -// Inject the handler into the client -$client = new GuzzleHttp\Client(['handler' => $handler]); -``` - -## POST Requests - -This version added the [`form_params`](http://guzzle.readthedocs.org/en/latest/request-options.html#form_params) -and `multipart` request options. `form_params` is an associative array of -strings or array of strings and is used to serialize an -`application/x-www-form-urlencoded` POST request. The -[`multipart`](http://guzzle.readthedocs.org/en/latest/request-options.html#multipart) -option is now used to send a multipart/form-data POST request. - -`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add -POST files to a multipart/form-data request. - -The `body` option no longer accepts an array to send POST requests. Please use -`multipart` or `form_params` instead. - -The `base_url` option has been renamed to `base_uri`. - -4.x to 5.0 ----------- - -## Rewritten Adapter Layer - -Guzzle now uses [RingPHP](http://ringphp.readthedocs.org/en/latest) to send -HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor -is still supported, but it has now been renamed to `handler`. Instead of -passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP -`callable` that follows the RingPHP specification. - -## Removed Fluent Interfaces - -[Fluent interfaces were removed](http://ocramius.github.io/blog/fluent-interfaces-are-evil) -from the following classes: - -- `GuzzleHttp\Collection` -- `GuzzleHttp\Url` -- `GuzzleHttp\Query` -- `GuzzleHttp\Post\PostBody` -- `GuzzleHttp\Cookie\SetCookie` - -## Removed functions.php - -Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following -functions can be used as replacements. - -- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode` -- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` -- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` -- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, - deprecated in favor of using `GuzzleHttp\Pool::batch()`. - -The "procedural" global client has been removed with no replacement (e.g., -`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` -object as a replacement. - -## `throwImmediately` has been removed - -The concept of "throwImmediately" has been removed from exceptions and error -events. This control mechanism was used to stop a transfer of concurrent -requests from completing. This can now be handled by throwing the exception or -by cancelling a pool of requests or each outstanding future request -individually. - -## headers event has been removed - -Removed the "headers" event. This event was only useful for changing the -body a response once the headers of the response were known. You can implement -a similar behavior in a number of ways. One example might be to use a -FnStream that has access to the transaction being sent. For example, when the -first byte is written, you could check if the response headers match your -expectations, and if so, change the actual stream body that is being -written to. - -## Updates to HTTP Messages - -Removed the `asArray` parameter from -`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header -value as an array, then use the newly added `getHeaderAsArray()` method of -`MessageInterface`. This change makes the Guzzle interfaces compatible with -the PSR-7 interfaces. - -3.x to 4.0 ----------- - -## Overarching changes: - -- Now requires PHP 5.4 or greater. -- No longer requires cURL to send requests. -- Guzzle no longer wraps every exception it throws. Only exceptions that are - recoverable are now wrapped by Guzzle. -- Various namespaces have been removed or renamed. -- No longer requiring the Symfony EventDispatcher. A custom event dispatcher - based on the Symfony EventDispatcher is - now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant - speed and functionality improvements). - -Changes per Guzzle 3.x namespace are described below. - -## Batch - -The `Guzzle\Batch` namespace has been removed. This is best left to -third-parties to implement on top of Guzzle's core HTTP library. - -## Cache - -The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement -has been implemented yet, but hoping to utilize a PSR cache interface). - -## Common - -- Removed all of the wrapped exceptions. It's better to use the standard PHP - library for unrecoverable exceptions. -- `FromConfigInterface` has been removed. -- `Guzzle\Common\Version` has been removed. The VERSION constant can be found - at `GuzzleHttp\ClientInterface::VERSION`. - -### Collection - -- `getAll` has been removed. Use `toArray` to convert a collection to an array. -- `inject` has been removed. -- `keySearch` has been removed. -- `getPath` no longer supports wildcard expressions. Use something better like - JMESPath for this. -- `setPath` now supports appending to an existing array via the `[]` notation. - -### Events - -Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses -`GuzzleHttp\Event\Emitter`. - -- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by - `GuzzleHttp\Event\EmitterInterface`. -- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by - `GuzzleHttp\Event\Emitter`. -- `Symfony\Component\EventDispatcher\Event` is replaced by - `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in - `GuzzleHttp\Event\EventInterface`. -- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and - `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the - event emitter of a request, client, etc. now uses the `getEmitter` method - rather than the `getDispatcher` method. - -#### Emitter - -- Use the `once()` method to add a listener that automatically removes itself - the first time it is invoked. -- Use the `listeners()` method to retrieve a list of event listeners rather than - the `getListeners()` method. -- Use `emit()` instead of `dispatch()` to emit an event from an emitter. -- Use `attach()` instead of `addSubscriber()` and `detach()` instead of - `removeSubscriber()`. - -```php -$mock = new Mock(); -// 3.x -$request->getEventDispatcher()->addSubscriber($mock); -$request->getEventDispatcher()->removeSubscriber($mock); -// 4.x -$request->getEmitter()->attach($mock); -$request->getEmitter()->detach($mock); -``` - -Use the `on()` method to add a listener rather than the `addListener()` method. - -```php -// 3.x -$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); -// 4.x -$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); -``` - -## Http - -### General changes - -- The cacert.pem certificate has been moved to `src/cacert.pem`. -- Added the concept of adapters that are used to transfer requests over the - wire. -- Simplified the event system. -- Sending requests in parallel is still possible, but batching is no longer a - concept of the HTTP layer. Instead, you must use the `complete` and `error` - events to asynchronously manage parallel request transfers. -- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. -- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. -- QueryAggregators have been rewritten so that they are simply callable - functions. -- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in - `functions.php` for an easy to use static client instance. -- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from - `GuzzleHttp\Exception\TransferException`. - -### Client - -Calling methods like `get()`, `post()`, `head()`, etc. no longer create and -return a request, but rather creates a request, sends the request, and returns -the response. - -```php -// 3.0 -$request = $client->get('/'); -$response = $request->send(); - -// 4.0 -$response = $client->get('/'); - -// or, to mirror the previous behavior -$request = $client->createRequest('GET', '/'); -$response = $client->send($request); -``` - -`GuzzleHttp\ClientInterface` has changed. - -- The `send` method no longer accepts more than one request. Use `sendAll` to - send multiple requests in parallel. -- `setUserAgent()` has been removed. Use a default request option instead. You - could, for example, do something like: - `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. -- `setSslVerification()` has been removed. Use default request options instead, - like `$client->setConfig('defaults/verify', true)`. - -`GuzzleHttp\Client` has changed. - -- The constructor now accepts only an associative array. You can include a - `base_url` string or array to use a URI template as the base URL of a client. - You can also specify a `defaults` key that is an associative array of default - request options. You can pass an `adapter` to use a custom adapter, - `batch_adapter` to use a custom adapter for sending requests in parallel, or - a `message_factory` to change the factory used to create HTTP requests and - responses. -- The client no longer emits a `client.create_request` event. -- Creating requests with a client no longer automatically utilize a URI - template. You must pass an array into a creational method (e.g., - `createRequest`, `get`, `put`, etc.) in order to expand a URI template. - -### Messages - -Messages no longer have references to their counterparts (i.e., a request no -longer has a reference to it's response, and a response no loger has a -reference to its request). This association is now managed through a -`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to -these transaction objects using request events that are emitted over the -lifecycle of a request. - -#### Requests with a body - -- `GuzzleHttp\Message\EntityEnclosingRequest` and - `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The - separation between requests that contain a body and requests that do not - contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` - handles both use cases. -- Any method that previously accepts a `GuzzleHttp\Response` object now accept a - `GuzzleHttp\Message\ResponseInterface`. -- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to - `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create - both requests and responses and is implemented in - `GuzzleHttp\Message\MessageFactory`. -- POST field and file methods have been removed from the request object. You - must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` - to control the format of a POST body. Requests that are created using a - standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use - a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if - the method is POST and no body is provided. - -```php -$request = $client->createRequest('POST', '/'); -$request->getBody()->setField('foo', 'bar'); -$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); -``` - -#### Headers - -- `GuzzleHttp\Message\Header` has been removed. Header values are now simply - represented by an array of values or as a string. Header values are returned - as a string by default when retrieving a header value from a message. You can - pass an optional argument of `true` to retrieve a header value as an array - of strings instead of a single concatenated string. -- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to - `GuzzleHttp\Post`. This interface has been simplified and now allows the - addition of arbitrary headers. -- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most - of the custom headers are now handled separately in specific - subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has - been updated to properly handle headers that contain parameters (like the - `Link` header). - -#### Responses - -- `GuzzleHttp\Message\Response::getInfo()` and - `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event - system to retrieve this type of information. -- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. -- `GuzzleHttp\Message\Response::getMessage()` has been removed. -- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific - methods have moved to the CacheSubscriber. -- Header specific helper functions like `getContentMd5()` have been removed. - Just use `getHeader('Content-MD5')` instead. -- `GuzzleHttp\Message\Response::setRequest()` and - `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event - system to work with request and response objects as a transaction. -- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the - Redirect subscriber instead. -- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have - been removed. Use `getStatusCode()` instead. - -#### Streaming responses - -Streaming requests can now be created by a client directly, returning a -`GuzzleHttp\Message\ResponseInterface` object that contains a body stream -referencing an open PHP HTTP stream. - -```php -// 3.0 -use Guzzle\Stream\PhpStreamRequestFactory; -$request = $client->get('/'); -$factory = new PhpStreamRequestFactory(); -$stream = $factory->fromRequest($request); -$data = $stream->read(1024); - -// 4.0 -$response = $client->get('/', ['stream' => true]); -// Read some data off of the stream in the response body -$data = $response->getBody()->read(1024); -``` - -#### Redirects - -The `configureRedirects()` method has been removed in favor of a -`allow_redirects` request option. - -```php -// Standard redirects with a default of a max of 5 redirects -$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); - -// Strict redirects with a custom number of redirects -$request = $client->createRequest('GET', '/', [ - 'allow_redirects' => ['max' => 5, 'strict' => true] -]); -``` - -#### EntityBody - -EntityBody interfaces and classes have been removed or moved to -`GuzzleHttp\Stream`. All classes and interfaces that once required -`GuzzleHttp\EntityBodyInterface` now require -`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no -longer uses `GuzzleHttp\EntityBody::factory` but now uses -`GuzzleHttp\Stream\Stream::factory` or even better: -`GuzzleHttp\Stream\create()`. - -- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` -- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` -- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` -- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` -- `Guzzle\Http\IoEmittyinEntityBody` has been removed. - -#### Request lifecycle events - -Requests previously submitted a large number of requests. The number of events -emitted over the lifecycle of a request has been significantly reduced to make -it easier to understand how to extend the behavior of a request. All events -emitted during the lifecycle of a request now emit a custom -`GuzzleHttp\Event\EventInterface` object that contains context providing -methods and a way in which to modify the transaction at that specific point in -time (e.g., intercept the request and set a response on the transaction). - -- `request.before_send` has been renamed to `before` and now emits a - `GuzzleHttp\Event\BeforeEvent` -- `request.complete` has been renamed to `complete` and now emits a - `GuzzleHttp\Event\CompleteEvent`. -- `request.sent` has been removed. Use `complete`. -- `request.success` has been removed. Use `complete`. -- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. -- `request.exception` has been removed. Use `error`. -- `request.receive.status_line` has been removed. -- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to - maintain a status update. -- `curl.callback.write` has been removed. Use a custom `StreamInterface` to - intercept writes. -- `curl.callback.read` has been removed. Use a custom `StreamInterface` to - intercept reads. - -`headers` is a new event that is emitted after the response headers of a -request have been received before the body of the response is downloaded. This -event emits a `GuzzleHttp\Event\HeadersEvent`. - -You can intercept a request and inject a response using the `intercept()` event -of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and -`GuzzleHttp\Event\ErrorEvent` event. - -See: http://docs.guzzlephp.org/en/latest/events.html - -## Inflection - -The `Guzzle\Inflection` namespace has been removed. This is not a core concern -of Guzzle. - -## Iterator - -The `Guzzle\Iterator` namespace has been removed. - -- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and - `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of - Guzzle itself. -- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent - class is shipped with PHP 5.4. -- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because - it's easier to just wrap an iterator in a generator that maps values. - -For a replacement of these iterators, see https://github.com/nikic/iter - -## Log - -The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The -`Guzzle\Log` namespace has been removed. Guzzle now relies on -`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been -moved to `GuzzleHttp\Subscriber\Log\Formatter`. - -## Parser - -The `Guzzle\Parser` namespace has been removed. This was previously used to -make it possible to plug in custom parsers for cookies, messages, URI -templates, and URLs; however, this level of complexity is not needed in Guzzle -so it has been removed. - -- Cookie: Cookie parsing logic has been moved to - `GuzzleHttp\Cookie\SetCookie::fromString`. -- Message: Message parsing logic for both requests and responses has been moved - to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only - used in debugging or deserializing messages, so it doesn't make sense for - Guzzle as a library to add this level of complexity to parsing messages. -- UriTemplate: URI template parsing has been moved to - `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL - URI template library if it is installed. -- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously - it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, - then developers are free to subclass `GuzzleHttp\Url`. - -## Plugin - -The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. -Several plugins are shipping with the core Guzzle library under this namespace. - -- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar - code has moved to `GuzzleHttp\Cookie`. -- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. -- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is - received. -- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. -- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before - sending. This subscriber is attached to all requests by default. -- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. - -The following plugins have been removed (third-parties are free to re-implement -these if needed): - -- `GuzzleHttp\Plugin\Async` has been removed. -- `GuzzleHttp\Plugin\CurlAuth` has been removed. -- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This - functionality should instead be implemented with event listeners that occur - after normal response parsing occurs in the guzzle/command package. - -The following plugins are not part of the core Guzzle package, but are provided -in separate repositories: - -- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler - to build custom retry policies using simple functions rather than various - chained classes. See: https://github.com/guzzle/retry-subscriber -- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to - https://github.com/guzzle/cache-subscriber -- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to - https://github.com/guzzle/log-subscriber -- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to - https://github.com/guzzle/message-integrity-subscriber -- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to - `GuzzleHttp\Subscriber\MockSubscriber`. -- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to - https://github.com/guzzle/oauth-subscriber - -## Service - -The service description layer of Guzzle has moved into two separate packages: - -- http://github.com/guzzle/command Provides a high level abstraction over web - services by representing web service operations using commands. -- http://github.com/guzzle/guzzle-services Provides an implementation of - guzzle/command that provides request serialization and response parsing using - Guzzle service descriptions. - -## Stream - -Stream have moved to a separate package available at -https://github.com/guzzle/streams. - -`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take -on the responsibilities of `Guzzle\Http\EntityBody` and -`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number -of methods implemented by the `StreamInterface` has been drastically reduced to -allow developers to more easily extend and decorate stream behavior. - -## Removed methods from StreamInterface - -- `getStream` and `setStream` have been removed to better encapsulate streams. -- `getMetadata` and `setMetadata` have been removed in favor of - `GuzzleHttp\Stream\MetadataStreamInterface`. -- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been - removed. This data is accessible when - using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. -- `rewind` has been removed. Use `seek(0)` for a similar behavior. - -## Renamed methods - -- `detachStream` has been renamed to `detach`. -- `feof` has been renamed to `eof`. -- `ftell` has been renamed to `tell`. -- `readLine` has moved from an instance method to a static class method of - `GuzzleHttp\Stream\Stream`. - -## Metadata streams - -`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams -that contain additional metadata accessible via `getMetadata()`. -`GuzzleHttp\Stream\StreamInterface::getMetadata` and -`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. - -## StreamRequestFactory - -The entire concept of the StreamRequestFactory has been removed. The way this -was used in Guzzle 3 broke the actual interface of sending streaming requests -(instead of getting back a Response, you got a StreamInterface). Streaming -PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. - -3.6 to 3.7 ----------- - -### Deprecations - -- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: - -```php -\Guzzle\Common\Version::$emitWarnings = true; -``` - -The following APIs and options have been marked as deprecated: - -- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. -- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. -- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. -- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. -- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. -- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated -- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. -- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. -- Marked `Guzzle\Common\Collection::inject()` as deprecated. -- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use - `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or - `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` - -3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational -request methods. When paired with a client's configuration settings, these options allow you to specify default settings -for various aspects of a request. Because these options make other previous configuration options redundant, several -configuration options and methods of a client and AbstractCommand have been deprecated. - -- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. -- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. -- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` -- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 - - $command = $client->getCommand('foo', array( - 'command.headers' => array('Test' => '123'), - 'command.response_body' => '/path/to/file' - )); - - // Should be changed to: - - $command = $client->getCommand('foo', array( - 'command.request_options' => array( - 'headers' => array('Test' => '123'), - 'save_as' => '/path/to/file' - ) - )); - -### Interface changes - -Additions and changes (you will need to update any implementations or subclasses you may have created): - -- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: - createRequest, head, delete, put, patch, post, options, prepareRequest -- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` -- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` -- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to - `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a - resource, string, or EntityBody into the $options parameter to specify the download location of the response. -- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a - default `array()` -- Added `Guzzle\Stream\StreamInterface::isRepeatable` -- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. - -The following methods were removed from interfaces. All of these methods are still available in the concrete classes -that implement them, but you should update your code to use alternative methods: - -- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use - `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or - `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or - `$client->setDefaultOption('headers/{header_name}', 'value')`. or - `$client->setDefaultOption('headers', array('header_name' => 'value'))`. -- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. -- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. -- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. -- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. -- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. -- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. -- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. - -### Cache plugin breaking changes - -- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a - CacheStorageInterface. These two objects and interface will be removed in a future version. -- Always setting X-cache headers on cached responses -- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin -- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface - $request, Response $response);` -- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` -- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` -- Added `CacheStorageInterface::purge($url)` -- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin - $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, - CanCacheStrategyInterface $canCache = null)` -- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` - -3.5 to 3.6 ----------- - -* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. -* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution -* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). - For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). - Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. -* Specific header implementations can be created for complex headers. When a message creates a header, it uses a - HeaderFactory which can map specific headers to specific header classes. There is now a Link header and - CacheControl header implementation. -* Moved getLinks() from Response to just be used on a Link header object. - -If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the -HeaderInterface (e.g. toArray(), getAll(), etc.). - -### Interface changes - -* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate -* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() -* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in - Guzzle\Http\Curl\RequestMediator -* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. -* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface -* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() - -### Removed deprecated functions - -* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() -* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). - -### Deprecations - -* The ability to case-insensitively search for header values -* Guzzle\Http\Message\Header::hasExactHeader -* Guzzle\Http\Message\Header::raw. Use getAll() -* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object - instead. - -### Other changes - -* All response header helper functions return a string rather than mixing Header objects and strings inconsistently -* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle - directly via interfaces -* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist - but are a no-op until removed. -* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a - `Guzzle\Service\Command\ArrayCommandInterface`. -* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response - on a request while the request is still being transferred -* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess - -3.3 to 3.4 ----------- - -Base URLs of a client now follow the rules of http://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs. - -3.2 to 3.3 ----------- - -### Response::getEtag() quote stripping removed - -`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header - -### Removed `Guzzle\Http\Utils` - -The `Guzzle\Http\Utils` class was removed. This class was only used for testing. - -### Stream wrapper and type - -`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. - -### curl.emit_io became emit_io - -Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the -'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' - -3.1 to 3.2 ----------- - -### CurlMulti is no longer reused globally - -Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added -to a single client can pollute requests dispatched from other clients. - -If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the -ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is -created. - -```php -$multi = new Guzzle\Http\Curl\CurlMulti(); -$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); -$builder->addListener('service_builder.create_client', function ($event) use ($multi) { - $event['client']->setCurlMulti($multi); -} -}); -``` - -### No default path - -URLs no longer have a default path value of '/' if no path was specified. - -Before: - -```php -$request = $client->get('http://www.foo.com'); -echo $request->getUrl(); -// >> http://www.foo.com/ -``` - -After: - -```php -$request = $client->get('http://www.foo.com'); -echo $request->getUrl(); -// >> http://www.foo.com -``` - -### Less verbose BadResponseException - -The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and -response information. You can, however, get access to the request and response object by calling `getRequest()` or -`getResponse()` on the exception object. - -### Query parameter aggregation - -Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a -setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is -responsible for handling the aggregation of multi-valued query string variables into a flattened hash. - -2.8 to 3.x ----------- - -### Guzzle\Service\Inspector - -Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` - -**Before** - -```php -use Guzzle\Service\Inspector; - -class YourClient extends \Guzzle\Service\Client -{ - public static function factory($config = array()) - { - $default = array(); - $required = array('base_url', 'username', 'api_key'); - $config = Inspector::fromConfig($config, $default, $required); - - $client = new self( - $config->get('base_url'), - $config->get('username'), - $config->get('api_key') - ); - $client->setConfig($config); - - $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); - - return $client; - } -``` - -**After** - -```php -use Guzzle\Common\Collection; - -class YourClient extends \Guzzle\Service\Client -{ - public static function factory($config = array()) - { - $default = array(); - $required = array('base_url', 'username', 'api_key'); - $config = Collection::fromConfig($config, $default, $required); - - $client = new self( - $config->get('base_url'), - $config->get('username'), - $config->get('api_key') - ); - $client->setConfig($config); - - $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); - - return $client; - } -``` - -### Convert XML Service Descriptions to JSON - -**Before** - -```xml - - - - - - Get a list of groups - - - Uses a search query to get a list of groups - - - - Create a group - - - - - Delete a group by ID - - - - - - - Update a group - - - - - - -``` - -**After** - -```json -{ - "name": "Zendesk REST API v2", - "apiVersion": "2012-12-31", - "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", - "operations": { - "list_groups": { - "httpMethod":"GET", - "uri": "groups.json", - "summary": "Get a list of groups" - }, - "search_groups":{ - "httpMethod":"GET", - "uri": "search.json?query=\"{query} type:group\"", - "summary": "Uses a search query to get a list of groups", - "parameters":{ - "query":{ - "location": "uri", - "description":"Zendesk Search Query", - "type": "string", - "required": true - } - } - }, - "create_group": { - "httpMethod":"POST", - "uri": "groups.json", - "summary": "Create a group", - "parameters":{ - "data": { - "type": "array", - "location": "body", - "description":"Group JSON", - "filters": "json_encode", - "required": true - }, - "Content-Type":{ - "type": "string", - "location":"header", - "static": "application/json" - } - } - }, - "delete_group": { - "httpMethod":"DELETE", - "uri": "groups/{id}.json", - "summary": "Delete a group", - "parameters":{ - "id":{ - "location": "uri", - "description":"Group to delete by ID", - "type": "integer", - "required": true - } - } - }, - "get_group": { - "httpMethod":"GET", - "uri": "groups/{id}.json", - "summary": "Get a ticket", - "parameters":{ - "id":{ - "location": "uri", - "description":"Group to get by ID", - "type": "integer", - "required": true - } - } - }, - "update_group": { - "httpMethod":"PUT", - "uri": "groups/{id}.json", - "summary": "Update a group", - "parameters":{ - "id": { - "location": "uri", - "description":"Group to update by ID", - "type": "integer", - "required": true - }, - "data": { - "type": "array", - "location": "body", - "description":"Group JSON", - "filters": "json_encode", - "required": true - }, - "Content-Type":{ - "type": "string", - "location":"header", - "static": "application/json" - } - } - } -} -``` - -### Guzzle\Service\Description\ServiceDescription - -Commands are now called Operations - -**Before** - -```php -use Guzzle\Service\Description\ServiceDescription; - -$sd = new ServiceDescription(); -$sd->getCommands(); // @returns ApiCommandInterface[] -$sd->hasCommand($name); -$sd->getCommand($name); // @returns ApiCommandInterface|null -$sd->addCommand($command); // @param ApiCommandInterface $command -``` - -**After** - -```php -use Guzzle\Service\Description\ServiceDescription; - -$sd = new ServiceDescription(); -$sd->getOperations(); // @returns OperationInterface[] -$sd->hasOperation($name); -$sd->getOperation($name); // @returns OperationInterface|null -$sd->addOperation($operation); // @param OperationInterface $operation -``` - -### Guzzle\Common\Inflection\Inflector - -Namespace is now `Guzzle\Inflection\Inflector` - -### Guzzle\Http\Plugin - -Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. - -### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log - -Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. - -**Before** - -```php -use Guzzle\Common\Log\ClosureLogAdapter; -use Guzzle\Http\Plugin\LogPlugin; - -/** @var \Guzzle\Http\Client */ -$client; - -// $verbosity is an integer indicating desired message verbosity level -$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); -``` - -**After** - -```php -use Guzzle\Log\ClosureLogAdapter; -use Guzzle\Log\MessageFormatter; -use Guzzle\Plugin\Log\LogPlugin; - -/** @var \Guzzle\Http\Client */ -$client; - -// $format is a string indicating desired message format -- @see MessageFormatter -$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); -``` - -### Guzzle\Http\Plugin\CurlAuthPlugin - -Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. - -### Guzzle\Http\Plugin\ExponentialBackoffPlugin - -Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. - -**Before** - -```php -use Guzzle\Http\Plugin\ExponentialBackoffPlugin; - -$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( - ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) - )); - -$client->addSubscriber($backoffPlugin); -``` - -**After** - -```php -use Guzzle\Plugin\Backoff\BackoffPlugin; -use Guzzle\Plugin\Backoff\HttpBackoffStrategy; - -// Use convenient factory method instead -- see implementation for ideas of what -// you can do with chaining backoff strategies -$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( - HttpBackoffStrategy::getDefaultFailureCodes(), array(429) - )); -$client->addSubscriber($backoffPlugin); -``` - -### Known Issues - -#### [BUG] Accept-Encoding header behavior changed unintentionally. - -(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) - -In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to -properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. -See issue #217 for a workaround, or use a version containing the fix. diff --git a/vendor/guzzlehttp/guzzle/composer.json b/vendor/guzzlehttp/guzzle/composer.json deleted file mode 100644 index c01864f..0000000 --- a/vendor/guzzlehttp/guzzle/composer.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "guzzlehttp/guzzle", - "type": "library", - "description": "Guzzle is a PHP HTTP client library", - "keywords": [ - "framework", - "http", - "rest", - "web service", - "curl", - "client", - "HTTP client" - ], - "homepage": "http://guzzlephp.org/", - "license": "MIT", - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "require": { - "php": ">=5.5", - "ext-json": "*", - "symfony/polyfill-intl-idn": "^1.17.0", - "guzzlehttp/promises": "^1.0", - "guzzlehttp/psr7": "^1.6.1" - }, - "require-dev": { - "ext-curl": "*", - "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0", - "psr/log": "^1.1" - }, - "suggest": { - "psr/log": "Required for using the Log middleware" - }, - "config": { - "sort-packages": true - }, - "extra": { - "branch-alias": { - "dev-master": "6.5-dev" - } - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\": "src/" - }, - "files": [ - "src/functions_include.php" - ] - }, - "autoload-dev": { - "psr-4": { - "GuzzleHttp\\Tests\\": "tests/" - } - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Client.php b/vendor/guzzlehttp/guzzle/src/Client.php deleted file mode 100644 index 315a022..0000000 --- a/vendor/guzzlehttp/guzzle/src/Client.php +++ /dev/null @@ -1,501 +0,0 @@ - 'http://www.foo.com/1.0/', - * 'timeout' => 0, - * 'allow_redirects' => false, - * 'proxy' => '192.168.16.1:10' - * ]); - * - * Client configuration settings include the following options: - * - * - handler: (callable) Function that transfers HTTP requests over the - * wire. The function is called with a Psr7\Http\Message\RequestInterface - * and array of transfer options, and must return a - * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a - * Psr7\Http\Message\ResponseInterface on success. - * If no handler is provided, a default handler will be created - * that enables all of the request options below by attaching all of the - * default middleware to the handler. - * - base_uri: (string|UriInterface) Base URI of the client that is merged - * into relative URIs. Can be a string or instance of UriInterface. - * - **: any request option - * - * @param array $config Client configuration settings. - * - * @see \GuzzleHttp\RequestOptions for a list of available request options. - */ - public function __construct(array $config = []) - { - if (!isset($config['handler'])) { - $config['handler'] = HandlerStack::create(); - } elseif (!is_callable($config['handler'])) { - throw new \InvalidArgumentException('handler must be a callable'); - } - - // Convert the base_uri to a UriInterface - if (isset($config['base_uri'])) { - $config['base_uri'] = Psr7\uri_for($config['base_uri']); - } - - $this->configureDefaults($config); - } - - /** - * @param string $method - * @param array $args - * - * @return Promise\PromiseInterface - */ - public function __call($method, $args) - { - if (count($args) < 1) { - throw new \InvalidArgumentException('Magic request methods require a URI and optional options array'); - } - - $uri = $args[0]; - $opts = isset($args[1]) ? $args[1] : []; - - return substr($method, -5) === 'Async' - ? $this->requestAsync(substr($method, 0, -5), $uri, $opts) - : $this->request($method, $uri, $opts); - } - - /** - * Asynchronously send an HTTP request. - * - * @param array $options Request options to apply to the given - * request and to the transfer. See \GuzzleHttp\RequestOptions. - * - * @return Promise\PromiseInterface - */ - public function sendAsync(RequestInterface $request, array $options = []) - { - // Merge the base URI into the request URI if needed. - $options = $this->prepareDefaults($options); - - return $this->transfer( - $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), - $options - ); - } - - /** - * Send an HTTP request. - * - * @param array $options Request options to apply to the given - * request and to the transfer. See \GuzzleHttp\RequestOptions. - * - * @return ResponseInterface - * @throws GuzzleException - */ - public function send(RequestInterface $request, array $options = []) - { - $options[RequestOptions::SYNCHRONOUS] = true; - return $this->sendAsync($request, $options)->wait(); - } - - /** - * Create and send an asynchronous HTTP request. - * - * Use an absolute path to override the base path of the client, or a - * relative path to append to the base path of the client. The URL can - * contain the query string as well. Use an array to provide a URL - * template and additional variables to use in the URL template expansion. - * - * @param string $method HTTP method - * @param string|UriInterface $uri URI object or string. - * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. - * - * @return Promise\PromiseInterface - */ - public function requestAsync($method, $uri = '', array $options = []) - { - $options = $this->prepareDefaults($options); - // Remove request modifying parameter because it can be done up-front. - $headers = isset($options['headers']) ? $options['headers'] : []; - $body = isset($options['body']) ? $options['body'] : null; - $version = isset($options['version']) ? $options['version'] : '1.1'; - // Merge the URI into the base URI. - $uri = $this->buildUri($uri, $options); - if (is_array($body)) { - $this->invalidBody(); - } - $request = new Psr7\Request($method, $uri, $headers, $body, $version); - // Remove the option so that they are not doubly-applied. - unset($options['headers'], $options['body'], $options['version']); - - return $this->transfer($request, $options); - } - - /** - * Create and send an HTTP request. - * - * Use an absolute path to override the base path of the client, or a - * relative path to append to the base path of the client. The URL can - * contain the query string as well. - * - * @param string $method HTTP method. - * @param string|UriInterface $uri URI object or string. - * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. - * - * @return ResponseInterface - * @throws GuzzleException - */ - public function request($method, $uri = '', array $options = []) - { - $options[RequestOptions::SYNCHRONOUS] = true; - return $this->requestAsync($method, $uri, $options)->wait(); - } - - /** - * Get a client configuration option. - * - * These options include default request options of the client, a "handler" - * (if utilized by the concrete client), and a "base_uri" if utilized by - * the concrete client. - * - * @param string|null $option The config option to retrieve. - * - * @return mixed - */ - public function getConfig($option = null) - { - return $option === null - ? $this->config - : (isset($this->config[$option]) ? $this->config[$option] : null); - } - - /** - * @param string|null $uri - * - * @return UriInterface - */ - private function buildUri($uri, array $config) - { - // for BC we accept null which would otherwise fail in uri_for - $uri = Psr7\uri_for($uri === null ? '' : $uri); - - if (isset($config['base_uri'])) { - $uri = Psr7\UriResolver::resolve(Psr7\uri_for($config['base_uri']), $uri); - } - - if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) { - $idnOptions = ($config['idn_conversion'] === true) ? IDNA_DEFAULT : $config['idn_conversion']; - $uri = Utils::idnUriConvert($uri, $idnOptions); - } - - return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; - } - - /** - * Configures the default options for a client. - * - * @param array $config - * @return void - */ - private function configureDefaults(array $config) - { - $defaults = [ - 'allow_redirects' => RedirectMiddleware::$defaultSettings, - 'http_errors' => true, - 'decode_content' => true, - 'verify' => true, - 'cookies' => false, - 'idn_conversion' => true, - ]; - - // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. - - // We can only trust the HTTP_PROXY environment variable in a CLI - // process due to the fact that PHP has no reliable mechanism to - // get environment variables that start with "HTTP_". - if (php_sapi_name() === 'cli' && getenv('HTTP_PROXY')) { - $defaults['proxy']['http'] = getenv('HTTP_PROXY'); - } - - if ($proxy = getenv('HTTPS_PROXY')) { - $defaults['proxy']['https'] = $proxy; - } - - if ($noProxy = getenv('NO_PROXY')) { - $cleanedNoProxy = str_replace(' ', '', $noProxy); - $defaults['proxy']['no'] = explode(',', $cleanedNoProxy); - } - - $this->config = $config + $defaults; - - if (!empty($config['cookies']) && $config['cookies'] === true) { - $this->config['cookies'] = new CookieJar(); - } - - // Add the default user-agent header. - if (!isset($this->config['headers'])) { - $this->config['headers'] = ['User-Agent' => default_user_agent()]; - } else { - // Add the User-Agent header if one was not already set. - foreach (array_keys($this->config['headers']) as $name) { - if (strtolower($name) === 'user-agent') { - return; - } - } - $this->config['headers']['User-Agent'] = default_user_agent(); - } - } - - /** - * Merges default options into the array. - * - * @param array $options Options to modify by reference - * - * @return array - */ - private function prepareDefaults(array $options) - { - $defaults = $this->config; - - if (!empty($defaults['headers'])) { - // Default headers are only added if they are not present. - $defaults['_conditional'] = $defaults['headers']; - unset($defaults['headers']); - } - - // Special handling for headers is required as they are added as - // conditional headers and as headers passed to a request ctor. - if (array_key_exists('headers', $options)) { - // Allows default headers to be unset. - if ($options['headers'] === null) { - $defaults['_conditional'] = []; - unset($options['headers']); - } elseif (!is_array($options['headers'])) { - throw new \InvalidArgumentException('headers must be an array'); - } - } - - // Shallow merge defaults underneath options. - $result = $options + $defaults; - - // Remove null values. - foreach ($result as $k => $v) { - if ($v === null) { - unset($result[$k]); - } - } - - return $result; - } - - /** - * Transfers the given request and applies request options. - * - * The URI of the request is not modified and the request options are used - * as-is without merging in default options. - * - * @param array $options See \GuzzleHttp\RequestOptions. - * - * @return Promise\PromiseInterface - */ - private function transfer(RequestInterface $request, array $options) - { - // save_to -> sink - if (isset($options['save_to'])) { - $options['sink'] = $options['save_to']; - unset($options['save_to']); - } - - // exceptions -> http_errors - if (isset($options['exceptions'])) { - $options['http_errors'] = $options['exceptions']; - unset($options['exceptions']); - } - - $request = $this->applyOptions($request, $options); - /** @var HandlerStack $handler */ - $handler = $options['handler']; - - try { - return Promise\promise_for($handler($request, $options)); - } catch (\Exception $e) { - return Promise\rejection_for($e); - } - } - - /** - * Applies the array of request options to a request. - * - * @param RequestInterface $request - * @param array $options - * - * @return RequestInterface - */ - private function applyOptions(RequestInterface $request, array &$options) - { - $modify = [ - 'set_headers' => [], - ]; - - if (isset($options['headers'])) { - $modify['set_headers'] = $options['headers']; - unset($options['headers']); - } - - if (isset($options['form_params'])) { - if (isset($options['multipart'])) { - throw new \InvalidArgumentException('You cannot use ' - . 'form_params and multipart at the same time. Use the ' - . 'form_params option if you want to send application/' - . 'x-www-form-urlencoded requests, and the multipart ' - . 'option to send multipart/form-data requests.'); - } - $options['body'] = http_build_query($options['form_params'], '', '&'); - unset($options['form_params']); - // Ensure that we don't have the header in different case and set the new value. - $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']); - $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; - } - - if (isset($options['multipart'])) { - $options['body'] = new Psr7\MultipartStream($options['multipart']); - unset($options['multipart']); - } - - if (isset($options['json'])) { - $options['body'] = \GuzzleHttp\json_encode($options['json']); - unset($options['json']); - // Ensure that we don't have the header in different case and set the new value. - $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']); - $options['_conditional']['Content-Type'] = 'application/json'; - } - - if (!empty($options['decode_content']) - && $options['decode_content'] !== true - ) { - // Ensure that we don't have the header in different case and set the new value. - $options['_conditional'] = Psr7\_caseless_remove(['Accept-Encoding'], $options['_conditional']); - $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; - } - - if (isset($options['body'])) { - if (is_array($options['body'])) { - $this->invalidBody(); - } - $modify['body'] = Psr7\stream_for($options['body']); - unset($options['body']); - } - - if (!empty($options['auth']) && is_array($options['auth'])) { - $value = $options['auth']; - $type = isset($value[2]) ? strtolower($value[2]) : 'basic'; - switch ($type) { - case 'basic': - // Ensure that we don't have the header in different case and set the new value. - $modify['set_headers'] = Psr7\_caseless_remove(['Authorization'], $modify['set_headers']); - $modify['set_headers']['Authorization'] = 'Basic ' - . base64_encode("$value[0]:$value[1]"); - break; - case 'digest': - // @todo: Do not rely on curl - $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; - $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]"; - break; - case 'ntlm': - $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_NTLM; - $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]"; - break; - } - } - - if (isset($options['query'])) { - $value = $options['query']; - if (is_array($value)) { - $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986); - } - if (!is_string($value)) { - throw new \InvalidArgumentException('query must be a string or array'); - } - $modify['query'] = $value; - unset($options['query']); - } - - // Ensure that sink is not an invalid value. - if (isset($options['sink'])) { - // TODO: Add more sink validation? - if (is_bool($options['sink'])) { - throw new \InvalidArgumentException('sink must not be a boolean'); - } - } - - $request = Psr7\modify_request($request, $modify); - if ($request->getBody() instanceof Psr7\MultipartStream) { - // Use a multipart/form-data POST if a Content-Type is not set. - // Ensure that we don't have the header in different case and set the new value. - $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']); - $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' - . $request->getBody()->getBoundary(); - } - - // Merge in conditional headers if they are not present. - if (isset($options['_conditional'])) { - // Build up the changes so it's in a single clone of the message. - $modify = []; - foreach ($options['_conditional'] as $k => $v) { - if (!$request->hasHeader($k)) { - $modify['set_headers'][$k] = $v; - } - } - $request = Psr7\modify_request($request, $modify); - // Don't pass this internal value along to middleware/handlers. - unset($options['_conditional']); - } - - return $request; - } - - /** - * Throw Exception with pre-set message. - * @return void - * @throws \InvalidArgumentException Invalid body. - */ - private function invalidBody() - { - throw new \InvalidArgumentException('Passing in the "body" request ' - . 'option as an array to send a POST request has been deprecated. ' - . 'Please use the "form_params" request option to send a ' - . 'application/x-www-form-urlencoded request, or the "multipart" ' - . 'request option to send a multipart/form-data request.'); - } -} diff --git a/vendor/guzzlehttp/guzzle/src/ClientInterface.php b/vendor/guzzlehttp/guzzle/src/ClientInterface.php deleted file mode 100644 index 638b75d..0000000 --- a/vendor/guzzlehttp/guzzle/src/ClientInterface.php +++ /dev/null @@ -1,87 +0,0 @@ -strictMode = $strictMode; - - foreach ($cookieArray as $cookie) { - if (!($cookie instanceof SetCookie)) { - $cookie = new SetCookie($cookie); - } - $this->setCookie($cookie); - } - } - - /** - * Create a new Cookie jar from an associative array and domain. - * - * @param array $cookies Cookies to create the jar from - * @param string $domain Domain to set the cookies to - * - * @return self - */ - public static function fromArray(array $cookies, $domain) - { - $cookieJar = new self(); - foreach ($cookies as $name => $value) { - $cookieJar->setCookie(new SetCookie([ - 'Domain' => $domain, - 'Name' => $name, - 'Value' => $value, - 'Discard' => true - ])); - } - - return $cookieJar; - } - - /** - * @deprecated - */ - public static function getCookieValue($value) - { - return $value; - } - - /** - * Evaluate if this cookie should be persisted to storage - * that survives between requests. - * - * @param SetCookie $cookie Being evaluated. - * @param bool $allowSessionCookies If we should persist session cookies - * @return bool - */ - public static function shouldPersist( - SetCookie $cookie, - $allowSessionCookies = false - ) { - if ($cookie->getExpires() || $allowSessionCookies) { - if (!$cookie->getDiscard()) { - return true; - } - } - - return false; - } - - /** - * Finds and returns the cookie based on the name - * - * @param string $name cookie name to search for - * @return SetCookie|null cookie that was found or null if not found - */ - public function getCookieByName($name) - { - // don't allow a non string name - if ($name === null || !is_scalar($name)) { - return null; - } - foreach ($this->cookies as $cookie) { - if ($cookie->getName() !== null && strcasecmp($cookie->getName(), $name) === 0) { - return $cookie; - } - } - - return null; - } - - public function toArray() - { - return array_map(function (SetCookie $cookie) { - return $cookie->toArray(); - }, $this->getIterator()->getArrayCopy()); - } - - public function clear($domain = null, $path = null, $name = null) - { - if (!$domain) { - $this->cookies = []; - return; - } elseif (!$path) { - $this->cookies = array_filter( - $this->cookies, - function (SetCookie $cookie) use ($domain) { - return !$cookie->matchesDomain($domain); - } - ); - } elseif (!$name) { - $this->cookies = array_filter( - $this->cookies, - function (SetCookie $cookie) use ($path, $domain) { - return !($cookie->matchesPath($path) && - $cookie->matchesDomain($domain)); - } - ); - } else { - $this->cookies = array_filter( - $this->cookies, - function (SetCookie $cookie) use ($path, $domain, $name) { - return !($cookie->getName() == $name && - $cookie->matchesPath($path) && - $cookie->matchesDomain($domain)); - } - ); - } - } - - public function clearSessionCookies() - { - $this->cookies = array_filter( - $this->cookies, - function (SetCookie $cookie) { - return !$cookie->getDiscard() && $cookie->getExpires(); - } - ); - } - - public function setCookie(SetCookie $cookie) - { - // If the name string is empty (but not 0), ignore the set-cookie - // string entirely. - $name = $cookie->getName(); - if (!$name && $name !== '0') { - return false; - } - - // Only allow cookies with set and valid domain, name, value - $result = $cookie->validate(); - if ($result !== true) { - if ($this->strictMode) { - throw new \RuntimeException('Invalid cookie: ' . $result); - } else { - $this->removeCookieIfEmpty($cookie); - return false; - } - } - - // Resolve conflicts with previously set cookies - foreach ($this->cookies as $i => $c) { - - // Two cookies are identical, when their path, and domain are - // identical. - if ($c->getPath() != $cookie->getPath() || - $c->getDomain() != $cookie->getDomain() || - $c->getName() != $cookie->getName() - ) { - continue; - } - - // The previously set cookie is a discard cookie and this one is - // not so allow the new cookie to be set - if (!$cookie->getDiscard() && $c->getDiscard()) { - unset($this->cookies[$i]); - continue; - } - - // If the new cookie's expiration is further into the future, then - // replace the old cookie - if ($cookie->getExpires() > $c->getExpires()) { - unset($this->cookies[$i]); - continue; - } - - // If the value has changed, we better change it - if ($cookie->getValue() !== $c->getValue()) { - unset($this->cookies[$i]); - continue; - } - - // The cookie exists, so no need to continue - return false; - } - - $this->cookies[] = $cookie; - - return true; - } - - public function count() - { - return count($this->cookies); - } - - public function getIterator() - { - return new \ArrayIterator(array_values($this->cookies)); - } - - public function extractCookies( - RequestInterface $request, - ResponseInterface $response - ) { - if ($cookieHeader = $response->getHeader('Set-Cookie')) { - foreach ($cookieHeader as $cookie) { - $sc = SetCookie::fromString($cookie); - if (!$sc->getDomain()) { - $sc->setDomain($request->getUri()->getHost()); - } - if (0 !== strpos($sc->getPath(), '/')) { - $sc->setPath($this->getCookiePathFromRequest($request)); - } - $this->setCookie($sc); - } - } - } - - /** - * Computes cookie path following RFC 6265 section 5.1.4 - * - * @link https://tools.ietf.org/html/rfc6265#section-5.1.4 - * - * @param RequestInterface $request - * @return string - */ - private function getCookiePathFromRequest(RequestInterface $request) - { - $uriPath = $request->getUri()->getPath(); - if ('' === $uriPath) { - return '/'; - } - if (0 !== strpos($uriPath, '/')) { - return '/'; - } - if ('/' === $uriPath) { - return '/'; - } - if (0 === $lastSlashPos = strrpos($uriPath, '/')) { - return '/'; - } - - return substr($uriPath, 0, $lastSlashPos); - } - - public function withCookieHeader(RequestInterface $request) - { - $values = []; - $uri = $request->getUri(); - $scheme = $uri->getScheme(); - $host = $uri->getHost(); - $path = $uri->getPath() ?: '/'; - - foreach ($this->cookies as $cookie) { - if ($cookie->matchesPath($path) && - $cookie->matchesDomain($host) && - !$cookie->isExpired() && - (!$cookie->getSecure() || $scheme === 'https') - ) { - $values[] = $cookie->getName() . '=' - . $cookie->getValue(); - } - } - - return $values - ? $request->withHeader('Cookie', implode('; ', $values)) - : $request; - } - - /** - * If a cookie already exists and the server asks to set it again with a - * null value, the cookie must be deleted. - * - * @param SetCookie $cookie - */ - private function removeCookieIfEmpty(SetCookie $cookie) - { - $cookieValue = $cookie->getValue(); - if ($cookieValue === null || $cookieValue === '') { - $this->clear( - $cookie->getDomain(), - $cookie->getPath(), - $cookie->getName() - ); - } - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php deleted file mode 100644 index 6ee1188..0000000 --- a/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php +++ /dev/null @@ -1,84 +0,0 @@ -filename = $cookieFile; - $this->storeSessionCookies = $storeSessionCookies; - - if (file_exists($cookieFile)) { - $this->load($cookieFile); - } - } - - /** - * Saves the file when shutting down - */ - public function __destruct() - { - $this->save($this->filename); - } - - /** - * Saves the cookies to a file. - * - * @param string $filename File to save - * @throws \RuntimeException if the file cannot be found or created - */ - public function save($filename) - { - $json = []; - foreach ($this as $cookie) { - /** @var SetCookie $cookie */ - if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { - $json[] = $cookie->toArray(); - } - } - - $jsonStr = \GuzzleHttp\json_encode($json); - if (false === file_put_contents($filename, $jsonStr, LOCK_EX)) { - throw new \RuntimeException("Unable to save file {$filename}"); - } - } - - /** - * Load cookies from a JSON formatted file. - * - * Old cookies are kept unless overwritten by newly loaded ones. - * - * @param string $filename Cookie file to load. - * @throws \RuntimeException if the file cannot be loaded. - */ - public function load($filename) - { - $json = file_get_contents($filename); - if (false === $json) { - throw new \RuntimeException("Unable to load file {$filename}"); - } elseif ($json === '') { - return; - } - - $data = \GuzzleHttp\json_decode($json, true); - if (is_array($data)) { - foreach (json_decode($json, true) as $cookie) { - $this->setCookie(new SetCookie($cookie)); - } - } elseif (strlen($data)) { - throw new \RuntimeException("Invalid cookie file: {$filename}"); - } - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php deleted file mode 100644 index 0224a24..0000000 --- a/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php +++ /dev/null @@ -1,72 +0,0 @@ -sessionKey = $sessionKey; - $this->storeSessionCookies = $storeSessionCookies; - $this->load(); - } - - /** - * Saves cookies to session when shutting down - */ - public function __destruct() - { - $this->save(); - } - - /** - * Save cookies to the client session - */ - public function save() - { - $json = []; - foreach ($this as $cookie) { - /** @var SetCookie $cookie */ - if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { - $json[] = $cookie->toArray(); - } - } - - $_SESSION[$this->sessionKey] = json_encode($json); - } - - /** - * Load the contents of the client session into the data array - */ - protected function load() - { - if (!isset($_SESSION[$this->sessionKey])) { - return; - } - $data = json_decode($_SESSION[$this->sessionKey], true); - if (is_array($data)) { - foreach ($data as $cookie) { - $this->setCookie(new SetCookie($cookie)); - } - } elseif (strlen($data)) { - throw new \RuntimeException("Invalid cookie data"); - } - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php deleted file mode 100644 index 3d776a7..0000000 --- a/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php +++ /dev/null @@ -1,403 +0,0 @@ - null, - 'Value' => null, - 'Domain' => null, - 'Path' => '/', - 'Max-Age' => null, - 'Expires' => null, - 'Secure' => false, - 'Discard' => false, - 'HttpOnly' => false - ]; - - /** @var array Cookie data */ - private $data; - - /** - * Create a new SetCookie object from a string - * - * @param string $cookie Set-Cookie header string - * - * @return self - */ - public static function fromString($cookie) - { - // Create the default return array - $data = self::$defaults; - // Explode the cookie string using a series of semicolons - $pieces = array_filter(array_map('trim', explode(';', $cookie))); - // The name of the cookie (first kvp) must exist and include an equal sign. - if (empty($pieces[0]) || !strpos($pieces[0], '=')) { - return new self($data); - } - - // Add the cookie pieces into the parsed data array - foreach ($pieces as $part) { - $cookieParts = explode('=', $part, 2); - $key = trim($cookieParts[0]); - $value = isset($cookieParts[1]) - ? trim($cookieParts[1], " \n\r\t\0\x0B") - : true; - - // Only check for non-cookies when cookies have been found - if (empty($data['Name'])) { - $data['Name'] = $key; - $data['Value'] = $value; - } else { - foreach (array_keys(self::$defaults) as $search) { - if (!strcasecmp($search, $key)) { - $data[$search] = $value; - continue 2; - } - } - $data[$key] = $value; - } - } - - return new self($data); - } - - /** - * @param array $data Array of cookie data provided by a Cookie parser - */ - public function __construct(array $data = []) - { - $this->data = array_replace(self::$defaults, $data); - // Extract the Expires value and turn it into a UNIX timestamp if needed - if (!$this->getExpires() && $this->getMaxAge()) { - // Calculate the Expires date - $this->setExpires(time() + $this->getMaxAge()); - } elseif ($this->getExpires() && !is_numeric($this->getExpires())) { - $this->setExpires($this->getExpires()); - } - } - - public function __toString() - { - $str = $this->data['Name'] . '=' . $this->data['Value'] . '; '; - foreach ($this->data as $k => $v) { - if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { - if ($k === 'Expires') { - $str .= 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $v) . '; '; - } else { - $str .= ($v === true ? $k : "{$k}={$v}") . '; '; - } - } - } - - return rtrim($str, '; '); - } - - public function toArray() - { - return $this->data; - } - - /** - * Get the cookie name - * - * @return string - */ - public function getName() - { - return $this->data['Name']; - } - - /** - * Set the cookie name - * - * @param string $name Cookie name - */ - public function setName($name) - { - $this->data['Name'] = $name; - } - - /** - * Get the cookie value - * - * @return string - */ - public function getValue() - { - return $this->data['Value']; - } - - /** - * Set the cookie value - * - * @param string $value Cookie value - */ - public function setValue($value) - { - $this->data['Value'] = $value; - } - - /** - * Get the domain - * - * @return string|null - */ - public function getDomain() - { - return $this->data['Domain']; - } - - /** - * Set the domain of the cookie - * - * @param string $domain - */ - public function setDomain($domain) - { - $this->data['Domain'] = $domain; - } - - /** - * Get the path - * - * @return string - */ - public function getPath() - { - return $this->data['Path']; - } - - /** - * Set the path of the cookie - * - * @param string $path Path of the cookie - */ - public function setPath($path) - { - $this->data['Path'] = $path; - } - - /** - * Maximum lifetime of the cookie in seconds - * - * @return int|null - */ - public function getMaxAge() - { - return $this->data['Max-Age']; - } - - /** - * Set the max-age of the cookie - * - * @param int $maxAge Max age of the cookie in seconds - */ - public function setMaxAge($maxAge) - { - $this->data['Max-Age'] = $maxAge; - } - - /** - * The UNIX timestamp when the cookie Expires - * - * @return mixed - */ - public function getExpires() - { - return $this->data['Expires']; - } - - /** - * Set the unix timestamp for which the cookie will expire - * - * @param int $timestamp Unix timestamp - */ - public function setExpires($timestamp) - { - $this->data['Expires'] = is_numeric($timestamp) - ? (int) $timestamp - : strtotime($timestamp); - } - - /** - * Get whether or not this is a secure cookie - * - * @return bool|null - */ - public function getSecure() - { - return $this->data['Secure']; - } - - /** - * Set whether or not the cookie is secure - * - * @param bool $secure Set to true or false if secure - */ - public function setSecure($secure) - { - $this->data['Secure'] = $secure; - } - - /** - * Get whether or not this is a session cookie - * - * @return bool|null - */ - public function getDiscard() - { - return $this->data['Discard']; - } - - /** - * Set whether or not this is a session cookie - * - * @param bool $discard Set to true or false if this is a session cookie - */ - public function setDiscard($discard) - { - $this->data['Discard'] = $discard; - } - - /** - * Get whether or not this is an HTTP only cookie - * - * @return bool - */ - public function getHttpOnly() - { - return $this->data['HttpOnly']; - } - - /** - * Set whether or not this is an HTTP only cookie - * - * @param bool $httpOnly Set to true or false if this is HTTP only - */ - public function setHttpOnly($httpOnly) - { - $this->data['HttpOnly'] = $httpOnly; - } - - /** - * Check if the cookie matches a path value. - * - * A request-path path-matches a given cookie-path if at least one of - * the following conditions holds: - * - * - The cookie-path and the request-path are identical. - * - The cookie-path is a prefix of the request-path, and the last - * character of the cookie-path is %x2F ("/"). - * - The cookie-path is a prefix of the request-path, and the first - * character of the request-path that is not included in the cookie- - * path is a %x2F ("/") character. - * - * @param string $requestPath Path to check against - * - * @return bool - */ - public function matchesPath($requestPath) - { - $cookiePath = $this->getPath(); - - // Match on exact matches or when path is the default empty "/" - if ($cookiePath === '/' || $cookiePath == $requestPath) { - return true; - } - - // Ensure that the cookie-path is a prefix of the request path. - if (0 !== strpos($requestPath, $cookiePath)) { - return false; - } - - // Match if the last character of the cookie-path is "/" - if (substr($cookiePath, -1, 1) === '/') { - return true; - } - - // Match if the first character not included in cookie path is "/" - return substr($requestPath, strlen($cookiePath), 1) === '/'; - } - - /** - * Check if the cookie matches a domain value - * - * @param string $domain Domain to check against - * - * @return bool - */ - public function matchesDomain($domain) - { - // Remove the leading '.' as per spec in RFC 6265. - // http://tools.ietf.org/html/rfc6265#section-5.2.3 - $cookieDomain = ltrim($this->getDomain(), '.'); - - // Domain not set or exact match. - if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) { - return true; - } - - // Matching the subdomain according to RFC 6265. - // http://tools.ietf.org/html/rfc6265#section-5.1.3 - if (filter_var($domain, FILTER_VALIDATE_IP)) { - return false; - } - - return (bool) preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/', $domain); - } - - /** - * Check if the cookie is expired - * - * @return bool - */ - public function isExpired() - { - return $this->getExpires() !== null && time() > $this->getExpires(); - } - - /** - * Check if the cookie is valid according to RFC 6265 - * - * @return bool|string Returns true if valid or an error message if invalid - */ - public function validate() - { - // Names must not be empty, but can be 0 - $name = $this->getName(); - if (empty($name) && !is_numeric($name)) { - return 'The cookie name must not be empty'; - } - - // Check if any of the invalid characters are present in the cookie name - if (preg_match( - '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', - $name - )) { - return 'Cookie name must not contain invalid characters: ASCII ' - . 'Control characters (0-31;127), space, tab and the ' - . 'following characters: ()<>@,;:\"/?={}'; - } - - // Value must not be empty, but can be 0 - $value = $this->getValue(); - if (empty($value) && !is_numeric($value)) { - return 'The cookie value must not be empty'; - } - - // Domains must not be empty, but can be 0 - // A "0" is not a valid internet domain, but may be used as server name - // in a private network. - $domain = $this->getDomain(); - if (empty($domain) && !is_numeric($domain)) { - return 'The cookie domain must not be empty'; - } - - return true; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php b/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php deleted file mode 100644 index 427d896..0000000 --- a/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php +++ /dev/null @@ -1,27 +0,0 @@ -getStatusCode() - : 0; - parent::__construct($message, $code, $previous); - $this->request = $request; - $this->response = $response; - $this->handlerContext = $handlerContext; - } - - /** - * Wrap non-RequestExceptions with a RequestException - * - * @param RequestInterface $request - * @param \Exception $e - * - * @return RequestException - */ - public static function wrapException(RequestInterface $request, \Exception $e) - { - return $e instanceof RequestException - ? $e - : new RequestException($e->getMessage(), $request, null, $e); - } - - /** - * Factory method to create a new exception with a normalized error message - * - * @param RequestInterface $request Request - * @param ResponseInterface $response Response received - * @param \Exception $previous Previous exception - * @param array $ctx Optional handler context. - * - * @return self - */ - public static function create( - RequestInterface $request, - ResponseInterface $response = null, - \Exception $previous = null, - array $ctx = [] - ) { - if (!$response) { - return new self( - 'Error completing request', - $request, - null, - $previous, - $ctx - ); - } - - $level = (int) floor($response->getStatusCode() / 100); - if ($level === 4) { - $label = 'Client error'; - $className = ClientException::class; - } elseif ($level === 5) { - $label = 'Server error'; - $className = ServerException::class; - } else { - $label = 'Unsuccessful request'; - $className = __CLASS__; - } - - $uri = $request->getUri(); - $uri = static::obfuscateUri($uri); - - // Client Error: `GET /` resulted in a `404 Not Found` response: - // ... (truncated) - $message = sprintf( - '%s: `%s %s` resulted in a `%s %s` response', - $label, - $request->getMethod(), - $uri, - $response->getStatusCode(), - $response->getReasonPhrase() - ); - - $summary = static::getResponseBodySummary($response); - - if ($summary !== null) { - $message .= ":\n{$summary}\n"; - } - - return new $className($message, $request, $response, $previous, $ctx); - } - - /** - * Get a short summary of the response - * - * Will return `null` if the response is not printable. - * - * @param ResponseInterface $response - * - * @return string|null - */ - public static function getResponseBodySummary(ResponseInterface $response) - { - return \GuzzleHttp\Psr7\get_message_body_summary($response); - } - - /** - * Obfuscates URI if there is a username and a password present - * - * @param UriInterface $uri - * - * @return UriInterface - */ - private static function obfuscateUri(UriInterface $uri) - { - $userInfo = $uri->getUserInfo(); - - if (false !== ($pos = strpos($userInfo, ':'))) { - return $uri->withUserInfo(substr($userInfo, 0, $pos), '***'); - } - - return $uri; - } - - /** - * Get the request that caused the exception - * - * @return RequestInterface - */ - public function getRequest() - { - return $this->request; - } - - /** - * Get the associated response - * - * @return ResponseInterface|null - */ - public function getResponse() - { - return $this->response; - } - - /** - * Check if a response was received - * - * @return bool - */ - public function hasResponse() - { - return $this->response !== null; - } - - /** - * Get contextual information about the error from the underlying handler. - * - * The contents of this array will vary depending on which handler you are - * using. It may also be just an empty array. Relying on this data will - * couple you to a specific handler, but can give more debug information - * when needed. - * - * @return array - */ - public function getHandlerContext() - { - return $this->handlerContext; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/SeekException.php b/vendor/guzzlehttp/guzzle/src/Exception/SeekException.php deleted file mode 100644 index a77c289..0000000 --- a/vendor/guzzlehttp/guzzle/src/Exception/SeekException.php +++ /dev/null @@ -1,27 +0,0 @@ -stream = $stream; - $msg = $msg ?: 'Could not seek the stream to position ' . $pos; - parent::__construct($msg); - } - - /** - * @return StreamInterface - */ - public function getStream() - { - return $this->stream; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php b/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php deleted file mode 100644 index 127094c..0000000 --- a/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php +++ /dev/null @@ -1,9 +0,0 @@ -maxHandles = $maxHandles; - } - - public function create(RequestInterface $request, array $options) - { - if (isset($options['curl']['body_as_string'])) { - $options['_body_as_string'] = $options['curl']['body_as_string']; - unset($options['curl']['body_as_string']); - } - - $easy = new EasyHandle; - $easy->request = $request; - $easy->options = $options; - $conf = $this->getDefaultConf($easy); - $this->applyMethod($easy, $conf); - $this->applyHandlerOptions($easy, $conf); - $this->applyHeaders($easy, $conf); - unset($conf['_headers']); - - // Add handler options from the request configuration options - if (isset($options['curl'])) { - $conf = array_replace($conf, $options['curl']); - } - - $conf[CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); - $easy->handle = $this->handles - ? array_pop($this->handles) - : curl_init(); - curl_setopt_array($easy->handle, $conf); - - return $easy; - } - - public function release(EasyHandle $easy) - { - $resource = $easy->handle; - unset($easy->handle); - - if (count($this->handles) >= $this->maxHandles) { - curl_close($resource); - } else { - // Remove all callback functions as they can hold onto references - // and are not cleaned up by curl_reset. Using curl_setopt_array - // does not work for some reason, so removing each one - // individually. - curl_setopt($resource, CURLOPT_HEADERFUNCTION, null); - curl_setopt($resource, CURLOPT_READFUNCTION, null); - curl_setopt($resource, CURLOPT_WRITEFUNCTION, null); - curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null); - curl_reset($resource); - $this->handles[] = $resource; - } - } - - /** - * Completes a cURL transaction, either returning a response promise or a - * rejected promise. - * - * @param callable $handler - * @param EasyHandle $easy - * @param CurlFactoryInterface $factory Dictates how the handle is released - * - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public static function finish( - callable $handler, - EasyHandle $easy, - CurlFactoryInterface $factory - ) { - if (isset($easy->options['on_stats'])) { - self::invokeStats($easy); - } - - if (!$easy->response || $easy->errno) { - return self::finishError($handler, $easy, $factory); - } - - // Return the response if it is present and there is no error. - $factory->release($easy); - - // Rewind the body of the response if possible. - $body = $easy->response->getBody(); - if ($body->isSeekable()) { - $body->rewind(); - } - - return new FulfilledPromise($easy->response); - } - - private static function invokeStats(EasyHandle $easy) - { - $curlStats = curl_getinfo($easy->handle); - $curlStats['appconnect_time'] = curl_getinfo($easy->handle, CURLINFO_APPCONNECT_TIME); - $stats = new TransferStats( - $easy->request, - $easy->response, - $curlStats['total_time'], - $easy->errno, - $curlStats - ); - call_user_func($easy->options['on_stats'], $stats); - } - - private static function finishError( - callable $handler, - EasyHandle $easy, - CurlFactoryInterface $factory - ) { - // Get error information and release the handle to the factory. - $ctx = [ - 'errno' => $easy->errno, - 'error' => curl_error($easy->handle), - 'appconnect_time' => curl_getinfo($easy->handle, CURLINFO_APPCONNECT_TIME), - ] + curl_getinfo($easy->handle); - $ctx[self::CURL_VERSION_STR] = curl_version()['version']; - $factory->release($easy); - - // Retry when nothing is present or when curl failed to rewind. - if (empty($easy->options['_err_message']) - && (!$easy->errno || $easy->errno == 65) - ) { - return self::retryFailedRewind($handler, $easy, $ctx); - } - - return self::createRejection($easy, $ctx); - } - - private static function createRejection(EasyHandle $easy, array $ctx) - { - static $connectionErrors = [ - CURLE_OPERATION_TIMEOUTED => true, - CURLE_COULDNT_RESOLVE_HOST => true, - CURLE_COULDNT_CONNECT => true, - CURLE_SSL_CONNECT_ERROR => true, - CURLE_GOT_NOTHING => true, - ]; - - // If an exception was encountered during the onHeaders event, then - // return a rejected promise that wraps that exception. - if ($easy->onHeadersException) { - return \GuzzleHttp\Promise\rejection_for( - new RequestException( - 'An error was encountered during the on_headers event', - $easy->request, - $easy->response, - $easy->onHeadersException, - $ctx - ) - ); - } - if (version_compare($ctx[self::CURL_VERSION_STR], self::LOW_CURL_VERSION_NUMBER)) { - $message = sprintf( - 'cURL error %s: %s (%s)', - $ctx['errno'], - $ctx['error'], - 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html' - ); - } else { - $message = sprintf( - 'cURL error %s: %s (%s) for %s', - $ctx['errno'], - $ctx['error'], - 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html', - $easy->request->getUri() - ); - } - - // Create a connection exception if it was a specific error code. - $error = isset($connectionErrors[$easy->errno]) - ? new ConnectException($message, $easy->request, null, $ctx) - : new RequestException($message, $easy->request, $easy->response, null, $ctx); - - return \GuzzleHttp\Promise\rejection_for($error); - } - - private function getDefaultConf(EasyHandle $easy) - { - $conf = [ - '_headers' => $easy->request->getHeaders(), - CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), - CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), - CURLOPT_RETURNTRANSFER => false, - CURLOPT_HEADER => false, - CURLOPT_CONNECTTIMEOUT => 150, - ]; - - if (defined('CURLOPT_PROTOCOLS')) { - $conf[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS; - } - - $version = $easy->request->getProtocolVersion(); - if ($version == 1.1) { - $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; - } elseif ($version == 2.0) { - $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0; - } else { - $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; - } - - return $conf; - } - - private function applyMethod(EasyHandle $easy, array &$conf) - { - $body = $easy->request->getBody(); - $size = $body->getSize(); - - if ($size === null || $size > 0) { - $this->applyBody($easy->request, $easy->options, $conf); - return; - } - - $method = $easy->request->getMethod(); - if ($method === 'PUT' || $method === 'POST') { - // See http://tools.ietf.org/html/rfc7230#section-3.3.2 - if (!$easy->request->hasHeader('Content-Length')) { - $conf[CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; - } - } elseif ($method === 'HEAD') { - $conf[CURLOPT_NOBODY] = true; - unset( - $conf[CURLOPT_WRITEFUNCTION], - $conf[CURLOPT_READFUNCTION], - $conf[CURLOPT_FILE], - $conf[CURLOPT_INFILE] - ); - } - } - - private function applyBody(RequestInterface $request, array $options, array &$conf) - { - $size = $request->hasHeader('Content-Length') - ? (int) $request->getHeaderLine('Content-Length') - : null; - - // Send the body as a string if the size is less than 1MB OR if the - // [curl][body_as_string] request value is set. - if (($size !== null && $size < 1000000) || - !empty($options['_body_as_string']) - ) { - $conf[CURLOPT_POSTFIELDS] = (string) $request->getBody(); - // Don't duplicate the Content-Length header - $this->removeHeader('Content-Length', $conf); - $this->removeHeader('Transfer-Encoding', $conf); - } else { - $conf[CURLOPT_UPLOAD] = true; - if ($size !== null) { - $conf[CURLOPT_INFILESIZE] = $size; - $this->removeHeader('Content-Length', $conf); - } - $body = $request->getBody(); - if ($body->isSeekable()) { - $body->rewind(); - } - $conf[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) { - return $body->read($length); - }; - } - - // If the Expect header is not present, prevent curl from adding it - if (!$request->hasHeader('Expect')) { - $conf[CURLOPT_HTTPHEADER][] = 'Expect:'; - } - - // cURL sometimes adds a content-type by default. Prevent this. - if (!$request->hasHeader('Content-Type')) { - $conf[CURLOPT_HTTPHEADER][] = 'Content-Type:'; - } - } - - private function applyHeaders(EasyHandle $easy, array &$conf) - { - foreach ($conf['_headers'] as $name => $values) { - foreach ($values as $value) { - $value = (string) $value; - if ($value === '') { - // cURL requires a special format for empty headers. - // See https://github.com/guzzle/guzzle/issues/1882 for more details. - $conf[CURLOPT_HTTPHEADER][] = "$name;"; - } else { - $conf[CURLOPT_HTTPHEADER][] = "$name: $value"; - } - } - } - - // Remove the Accept header if one was not set - if (!$easy->request->hasHeader('Accept')) { - $conf[CURLOPT_HTTPHEADER][] = 'Accept:'; - } - } - - /** - * Remove a header from the options array. - * - * @param string $name Case-insensitive header to remove - * @param array $options Array of options to modify - */ - private function removeHeader($name, array &$options) - { - foreach (array_keys($options['_headers']) as $key) { - if (!strcasecmp($key, $name)) { - unset($options['_headers'][$key]); - return; - } - } - } - - private function applyHandlerOptions(EasyHandle $easy, array &$conf) - { - $options = $easy->options; - if (isset($options['verify'])) { - if ($options['verify'] === false) { - unset($conf[CURLOPT_CAINFO]); - $conf[CURLOPT_SSL_VERIFYHOST] = 0; - $conf[CURLOPT_SSL_VERIFYPEER] = false; - } else { - $conf[CURLOPT_SSL_VERIFYHOST] = 2; - $conf[CURLOPT_SSL_VERIFYPEER] = true; - if (is_string($options['verify'])) { - // Throw an error if the file/folder/link path is not valid or doesn't exist. - if (!file_exists($options['verify'])) { - throw new \InvalidArgumentException( - "SSL CA bundle not found: {$options['verify']}" - ); - } - // If it's a directory or a link to a directory use CURLOPT_CAPATH. - // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. - if (is_dir($options['verify']) || - (is_link($options['verify']) && is_dir(readlink($options['verify'])))) { - $conf[CURLOPT_CAPATH] = $options['verify']; - } else { - $conf[CURLOPT_CAINFO] = $options['verify']; - } - } - } - } - - if (!empty($options['decode_content'])) { - $accept = $easy->request->getHeaderLine('Accept-Encoding'); - if ($accept) { - $conf[CURLOPT_ENCODING] = $accept; - } else { - $conf[CURLOPT_ENCODING] = ''; - // Don't let curl send the header over the wire - $conf[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; - } - } - - if (isset($options['sink'])) { - $sink = $options['sink']; - if (!is_string($sink)) { - $sink = \GuzzleHttp\Psr7\stream_for($sink); - } elseif (!is_dir(dirname($sink))) { - // Ensure that the directory exists before failing in curl. - throw new \RuntimeException(sprintf( - 'Directory %s does not exist for sink value of %s', - dirname($sink), - $sink - )); - } else { - $sink = new LazyOpenStream($sink, 'w+'); - } - $easy->sink = $sink; - $conf[CURLOPT_WRITEFUNCTION] = function ($ch, $write) use ($sink) { - return $sink->write($write); - }; - } else { - // Use a default temp stream if no sink was set. - $conf[CURLOPT_FILE] = fopen('php://temp', 'w+'); - $easy->sink = Psr7\stream_for($conf[CURLOPT_FILE]); - } - $timeoutRequiresNoSignal = false; - if (isset($options['timeout'])) { - $timeoutRequiresNoSignal |= $options['timeout'] < 1; - $conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; - } - - // CURL default value is CURL_IPRESOLVE_WHATEVER - if (isset($options['force_ip_resolve'])) { - if ('v4' === $options['force_ip_resolve']) { - $conf[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4; - } elseif ('v6' === $options['force_ip_resolve']) { - $conf[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V6; - } - } - - if (isset($options['connect_timeout'])) { - $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; - $conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; - } - - if ($timeoutRequiresNoSignal && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { - $conf[CURLOPT_NOSIGNAL] = true; - } - - if (isset($options['proxy'])) { - if (!is_array($options['proxy'])) { - $conf[CURLOPT_PROXY] = $options['proxy']; - } else { - $scheme = $easy->request->getUri()->getScheme(); - if (isset($options['proxy'][$scheme])) { - $host = $easy->request->getUri()->getHost(); - if (!isset($options['proxy']['no']) || - !\GuzzleHttp\is_host_in_noproxy($host, $options['proxy']['no']) - ) { - $conf[CURLOPT_PROXY] = $options['proxy'][$scheme]; - } - } - } - } - - if (isset($options['cert'])) { - $cert = $options['cert']; - if (is_array($cert)) { - $conf[CURLOPT_SSLCERTPASSWD] = $cert[1]; - $cert = $cert[0]; - } - if (!file_exists($cert)) { - throw new \InvalidArgumentException( - "SSL certificate not found: {$cert}" - ); - } - $conf[CURLOPT_SSLCERT] = $cert; - } - - if (isset($options['ssl_key'])) { - if (is_array($options['ssl_key'])) { - if (count($options['ssl_key']) === 2) { - list($sslKey, $conf[CURLOPT_SSLKEYPASSWD]) = $options['ssl_key']; - } else { - list($sslKey) = $options['ssl_key']; - } - } - - $sslKey = isset($sslKey) ? $sslKey: $options['ssl_key']; - - if (!file_exists($sslKey)) { - throw new \InvalidArgumentException( - "SSL private key not found: {$sslKey}" - ); - } - $conf[CURLOPT_SSLKEY] = $sslKey; - } - - if (isset($options['progress'])) { - $progress = $options['progress']; - if (!is_callable($progress)) { - throw new \InvalidArgumentException( - 'progress client option must be callable' - ); - } - $conf[CURLOPT_NOPROGRESS] = false; - $conf[CURLOPT_PROGRESSFUNCTION] = function () use ($progress) { - $args = func_get_args(); - // PHP 5.5 pushed the handle onto the start of the args - if (is_resource($args[0])) { - array_shift($args); - } - call_user_func_array($progress, $args); - }; - } - - if (!empty($options['debug'])) { - $conf[CURLOPT_STDERR] = \GuzzleHttp\debug_resource($options['debug']); - $conf[CURLOPT_VERBOSE] = true; - } - } - - /** - * This function ensures that a response was set on a transaction. If one - * was not set, then the request is retried if possible. This error - * typically means you are sending a payload, curl encountered a - * "Connection died, retrying a fresh connect" error, tried to rewind the - * stream, and then encountered a "necessary data rewind wasn't possible" - * error, causing the request to be sent through curl_multi_info_read() - * without an error status. - */ - private static function retryFailedRewind( - callable $handler, - EasyHandle $easy, - array $ctx - ) { - try { - // Only rewind if the body has been read from. - $body = $easy->request->getBody(); - if ($body->tell() > 0) { - $body->rewind(); - } - } catch (\RuntimeException $e) { - $ctx['error'] = 'The connection unexpectedly failed without ' - . 'providing an error. The request would have been retried, ' - . 'but attempting to rewind the request body failed. ' - . 'Exception: ' . $e; - return self::createRejection($easy, $ctx); - } - - // Retry no more than 3 times before giving up. - if (!isset($easy->options['_curl_retries'])) { - $easy->options['_curl_retries'] = 1; - } elseif ($easy->options['_curl_retries'] == 2) { - $ctx['error'] = 'The cURL request was retried 3 times ' - . 'and did not succeed. The most likely reason for the failure ' - . 'is that cURL was unable to rewind the body of the request ' - . 'and subsequent retries resulted in the same error. Turn on ' - . 'the debug option to see what went wrong. See ' - . 'https://bugs.php.net/bug.php?id=47204 for more information.'; - return self::createRejection($easy, $ctx); - } else { - $easy->options['_curl_retries']++; - } - - return $handler($easy->request, $easy->options); - } - - private function createHeaderFn(EasyHandle $easy) - { - if (isset($easy->options['on_headers'])) { - $onHeaders = $easy->options['on_headers']; - - if (!is_callable($onHeaders)) { - throw new \InvalidArgumentException('on_headers must be callable'); - } - } else { - $onHeaders = null; - } - - return function ($ch, $h) use ( - $onHeaders, - $easy, - &$startingResponse - ) { - $value = trim($h); - if ($value === '') { - $startingResponse = true; - $easy->createResponse(); - if ($onHeaders !== null) { - try { - $onHeaders($easy->response); - } catch (\Exception $e) { - // Associate the exception with the handle and trigger - // a curl header write error by returning 0. - $easy->onHeadersException = $e; - return -1; - } - } - } elseif ($startingResponse) { - $startingResponse = false; - $easy->headers = [$value]; - } else { - $easy->headers[] = $value; - } - return strlen($h); - }; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php deleted file mode 100644 index b0fc236..0000000 --- a/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php +++ /dev/null @@ -1,27 +0,0 @@ -factory = isset($options['handle_factory']) - ? $options['handle_factory'] - : new CurlFactory(3); - } - - public function __invoke(RequestInterface $request, array $options) - { - if (isset($options['delay'])) { - usleep($options['delay'] * 1000); - } - - $easy = $this->factory->create($request, $options); - curl_exec($easy->handle); - $easy->errno = curl_errno($easy->handle); - - return CurlFactory::finish($this, $easy, $this->factory); - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php deleted file mode 100644 index 564c95f..0000000 --- a/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php +++ /dev/null @@ -1,219 +0,0 @@ -factory = isset($options['handle_factory']) - ? $options['handle_factory'] : new CurlFactory(50); - - if (isset($options['select_timeout'])) { - $this->selectTimeout = $options['select_timeout']; - } elseif ($selectTimeout = getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { - $this->selectTimeout = $selectTimeout; - } else { - $this->selectTimeout = 1; - } - - $this->options = isset($options['options']) ? $options['options'] : []; - } - - public function __get($name) - { - if ($name === '_mh') { - $this->_mh = curl_multi_init(); - - foreach ($this->options as $option => $value) { - // A warning is raised in case of a wrong option. - curl_multi_setopt($this->_mh, $option, $value); - } - - // Further calls to _mh will return the value directly, without entering the - // __get() method at all. - return $this->_mh; - } - - throw new \BadMethodCallException(); - } - - public function __destruct() - { - if (isset($this->_mh)) { - curl_multi_close($this->_mh); - unset($this->_mh); - } - } - - public function __invoke(RequestInterface $request, array $options) - { - $easy = $this->factory->create($request, $options); - $id = (int) $easy->handle; - - $promise = new Promise( - [$this, 'execute'], - function () use ($id) { - return $this->cancel($id); - } - ); - - $this->addRequest(['easy' => $easy, 'deferred' => $promise]); - - return $promise; - } - - /** - * Ticks the curl event loop. - */ - public function tick() - { - // Add any delayed handles if needed. - if ($this->delays) { - $currentTime = Utils::currentTime(); - foreach ($this->delays as $id => $delay) { - if ($currentTime >= $delay) { - unset($this->delays[$id]); - curl_multi_add_handle( - $this->_mh, - $this->handles[$id]['easy']->handle - ); - } - } - } - - // Step through the task queue which may add additional requests. - P\queue()->run(); - - if ($this->active && - curl_multi_select($this->_mh, $this->selectTimeout) === -1 - ) { - // Perform a usleep if a select returns -1. - // See: https://bugs.php.net/bug.php?id=61141 - usleep(250); - } - - while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM); - - $this->processMessages(); - } - - /** - * Runs until all outstanding connections have completed. - */ - public function execute() - { - $queue = P\queue(); - - while ($this->handles || !$queue->isEmpty()) { - // If there are no transfers, then sleep for the next delay - if (!$this->active && $this->delays) { - usleep($this->timeToNext()); - } - $this->tick(); - } - } - - private function addRequest(array $entry) - { - $easy = $entry['easy']; - $id = (int) $easy->handle; - $this->handles[$id] = $entry; - if (empty($easy->options['delay'])) { - curl_multi_add_handle($this->_mh, $easy->handle); - } else { - $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); - } - } - - /** - * Cancels a handle from sending and removes references to it. - * - * @param int $id Handle ID to cancel and remove. - * - * @return bool True on success, false on failure. - */ - private function cancel($id) - { - // Cannot cancel if it has been processed. - if (!isset($this->handles[$id])) { - return false; - } - - $handle = $this->handles[$id]['easy']->handle; - unset($this->delays[$id], $this->handles[$id]); - curl_multi_remove_handle($this->_mh, $handle); - curl_close($handle); - - return true; - } - - private function processMessages() - { - while ($done = curl_multi_info_read($this->_mh)) { - $id = (int) $done['handle']; - curl_multi_remove_handle($this->_mh, $done['handle']); - - if (!isset($this->handles[$id])) { - // Probably was cancelled. - continue; - } - - $entry = $this->handles[$id]; - unset($this->handles[$id], $this->delays[$id]); - $entry['easy']->errno = $done['result']; - $entry['deferred']->resolve( - CurlFactory::finish( - $this, - $entry['easy'], - $this->factory - ) - ); - } - } - - private function timeToNext() - { - $currentTime = Utils::currentTime(); - $nextTime = PHP_INT_MAX; - foreach ($this->delays as $time) { - if ($time < $nextTime) { - $nextTime = $time; - } - } - - return max(0, $nextTime - $currentTime) * 1000000; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php deleted file mode 100644 index 7754e91..0000000 --- a/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php +++ /dev/null @@ -1,92 +0,0 @@ -headers)) { - throw new \RuntimeException('No headers have been received'); - } - - // HTTP-version SP status-code SP reason-phrase - $startLine = explode(' ', array_shift($this->headers), 3); - $headers = \GuzzleHttp\headers_from_lines($this->headers); - $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers); - - if (!empty($this->options['decode_content']) - && isset($normalizedKeys['content-encoding']) - ) { - $headers['x-encoded-content-encoding'] - = $headers[$normalizedKeys['content-encoding']]; - unset($headers[$normalizedKeys['content-encoding']]); - if (isset($normalizedKeys['content-length'])) { - $headers['x-encoded-content-length'] - = $headers[$normalizedKeys['content-length']]; - - $bodyLength = (int) $this->sink->getSize(); - if ($bodyLength) { - $headers[$normalizedKeys['content-length']] = $bodyLength; - } else { - unset($headers[$normalizedKeys['content-length']]); - } - } - } - - // Attach a response to the easy handle with the parsed headers. - $this->response = new Response( - $startLine[1], - $headers, - $this->sink, - substr($startLine[0], 5), - isset($startLine[2]) ? (string) $startLine[2] : null - ); - } - - public function __get($name) - { - $msg = $name === 'handle' - ? 'The EasyHandle has been released' - : 'Invalid property: ' . $name; - throw new \BadMethodCallException($msg); - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php deleted file mode 100644 index 5b312bc..0000000 --- a/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php +++ /dev/null @@ -1,195 +0,0 @@ -onFulfilled = $onFulfilled; - $this->onRejected = $onRejected; - - if ($queue) { - call_user_func_array([$this, 'append'], $queue); - } - } - - public function __invoke(RequestInterface $request, array $options) - { - if (!$this->queue) { - throw new \OutOfBoundsException('Mock queue is empty'); - } - - if (isset($options['delay']) && is_numeric($options['delay'])) { - usleep($options['delay'] * 1000); - } - - $this->lastRequest = $request; - $this->lastOptions = $options; - $response = array_shift($this->queue); - - if (isset($options['on_headers'])) { - if (!is_callable($options['on_headers'])) { - throw new \InvalidArgumentException('on_headers must be callable'); - } - try { - $options['on_headers']($response); - } catch (\Exception $e) { - $msg = 'An error was encountered during the on_headers event'; - $response = new RequestException($msg, $request, $response, $e); - } - } - - if (is_callable($response)) { - $response = call_user_func($response, $request, $options); - } - - $response = $response instanceof \Exception - ? \GuzzleHttp\Promise\rejection_for($response) - : \GuzzleHttp\Promise\promise_for($response); - - return $response->then( - function ($value) use ($request, $options) { - $this->invokeStats($request, $options, $value); - if ($this->onFulfilled) { - call_user_func($this->onFulfilled, $value); - } - if (isset($options['sink'])) { - $contents = (string) $value->getBody(); - $sink = $options['sink']; - - if (is_resource($sink)) { - fwrite($sink, $contents); - } elseif (is_string($sink)) { - file_put_contents($sink, $contents); - } elseif ($sink instanceof \Psr\Http\Message\StreamInterface) { - $sink->write($contents); - } - } - - return $value; - }, - function ($reason) use ($request, $options) { - $this->invokeStats($request, $options, null, $reason); - if ($this->onRejected) { - call_user_func($this->onRejected, $reason); - } - return \GuzzleHttp\Promise\rejection_for($reason); - } - ); - } - - /** - * Adds one or more variadic requests, exceptions, callables, or promises - * to the queue. - */ - public function append() - { - foreach (func_get_args() as $value) { - if ($value instanceof ResponseInterface - || $value instanceof \Exception - || $value instanceof PromiseInterface - || is_callable($value) - ) { - $this->queue[] = $value; - } else { - throw new \InvalidArgumentException('Expected a response or ' - . 'exception. Found ' . \GuzzleHttp\describe_type($value)); - } - } - } - - /** - * Get the last received request. - * - * @return RequestInterface - */ - public function getLastRequest() - { - return $this->lastRequest; - } - - /** - * Get the last received request options. - * - * @return array - */ - public function getLastOptions() - { - return $this->lastOptions; - } - - /** - * Returns the number of remaining items in the queue. - * - * @return int - */ - public function count() - { - return count($this->queue); - } - - public function reset() - { - $this->queue = []; - } - - private function invokeStats( - RequestInterface $request, - array $options, - ResponseInterface $response = null, - $reason = null - ) { - if (isset($options['on_stats'])) { - $transferTime = isset($options['transfer_time']) ? $options['transfer_time'] : 0; - $stats = new TransferStats($request, $response, $transferTime, $reason); - call_user_func($options['on_stats'], $stats); - } - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php b/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php deleted file mode 100644 index f8b00be..0000000 --- a/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php +++ /dev/null @@ -1,55 +0,0 @@ -withoutHeader('Expect'); - - // Append a content-length header if body size is zero to match - // cURL's behavior. - if (0 === $request->getBody()->getSize()) { - $request = $request->withHeader('Content-Length', '0'); - } - - return $this->createResponse( - $request, - $options, - $this->createStream($request, $options), - $startTime - ); - } catch (\InvalidArgumentException $e) { - throw $e; - } catch (\Exception $e) { - // Determine if the error was a networking error. - $message = $e->getMessage(); - // This list can probably get more comprehensive. - if (strpos($message, 'getaddrinfo') // DNS lookup failed - || strpos($message, 'Connection refused') - || strpos($message, "couldn't connect to host") // error on HHVM - || strpos($message, "connection attempt failed") - ) { - $e = new ConnectException($e->getMessage(), $request, $e); - } - $e = RequestException::wrapException($request, $e); - $this->invokeStats($options, $request, $startTime, null, $e); - - return \GuzzleHttp\Promise\rejection_for($e); - } - } - - private function invokeStats( - array $options, - RequestInterface $request, - $startTime, - ResponseInterface $response = null, - $error = null - ) { - if (isset($options['on_stats'])) { - $stats = new TransferStats( - $request, - $response, - Utils::currentTime() - $startTime, - $error, - [] - ); - call_user_func($options['on_stats'], $stats); - } - } - - private function createResponse( - RequestInterface $request, - array $options, - $stream, - $startTime - ) { - $hdrs = $this->lastHeaders; - $this->lastHeaders = []; - $parts = explode(' ', array_shift($hdrs), 3); - $ver = explode('/', $parts[0])[1]; - $status = $parts[1]; - $reason = isset($parts[2]) ? $parts[2] : null; - $headers = \GuzzleHttp\headers_from_lines($hdrs); - list($stream, $headers) = $this->checkDecode($options, $headers, $stream); - $stream = Psr7\stream_for($stream); - $sink = $stream; - - if (strcasecmp('HEAD', $request->getMethod())) { - $sink = $this->createSink($stream, $options); - } - - $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); - - if (isset($options['on_headers'])) { - try { - $options['on_headers']($response); - } catch (\Exception $e) { - $msg = 'An error was encountered during the on_headers event'; - $ex = new RequestException($msg, $request, $response, $e); - return \GuzzleHttp\Promise\rejection_for($ex); - } - } - - // Do not drain when the request is a HEAD request because they have - // no body. - if ($sink !== $stream) { - $this->drain( - $stream, - $sink, - $response->getHeaderLine('Content-Length') - ); - } - - $this->invokeStats($options, $request, $startTime, $response, null); - - return new FulfilledPromise($response); - } - - private function createSink(StreamInterface $stream, array $options) - { - if (!empty($options['stream'])) { - return $stream; - } - - $sink = isset($options['sink']) - ? $options['sink'] - : fopen('php://temp', 'r+'); - - return is_string($sink) - ? new Psr7\LazyOpenStream($sink, 'w+') - : Psr7\stream_for($sink); - } - - private function checkDecode(array $options, array $headers, $stream) - { - // Automatically decode responses when instructed. - if (!empty($options['decode_content'])) { - $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers); - if (isset($normalizedKeys['content-encoding'])) { - $encoding = $headers[$normalizedKeys['content-encoding']]; - if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { - $stream = new Psr7\InflateStream( - Psr7\stream_for($stream) - ); - $headers['x-encoded-content-encoding'] - = $headers[$normalizedKeys['content-encoding']]; - // Remove content-encoding header - unset($headers[$normalizedKeys['content-encoding']]); - // Fix content-length header - if (isset($normalizedKeys['content-length'])) { - $headers['x-encoded-content-length'] - = $headers[$normalizedKeys['content-length']]; - - $length = (int) $stream->getSize(); - if ($length === 0) { - unset($headers[$normalizedKeys['content-length']]); - } else { - $headers[$normalizedKeys['content-length']] = [$length]; - } - } - } - } - } - - return [$stream, $headers]; - } - - /** - * Drains the source stream into the "sink" client option. - * - * @param StreamInterface $source - * @param StreamInterface $sink - * @param string $contentLength Header specifying the amount of - * data to read. - * - * @return StreamInterface - * @throws \RuntimeException when the sink option is invalid. - */ - private function drain( - StreamInterface $source, - StreamInterface $sink, - $contentLength - ) { - // If a content-length header is provided, then stop reading once - // that number of bytes has been read. This can prevent infinitely - // reading from a stream when dealing with servers that do not honor - // Connection: Close headers. - Psr7\copy_to_stream( - $source, - $sink, - (strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 - ); - - $sink->seek(0); - $source->close(); - - return $sink; - } - - /** - * Create a resource and check to ensure it was created successfully - * - * @param callable $callback Callable that returns stream resource - * - * @return resource - * @throws \RuntimeException on error - */ - private function createResource(callable $callback) - { - $errors = null; - set_error_handler(function ($_, $msg, $file, $line) use (&$errors) { - $errors[] = [ - 'message' => $msg, - 'file' => $file, - 'line' => $line - ]; - return true; - }); - - $resource = $callback(); - restore_error_handler(); - - if (!$resource) { - $message = 'Error creating resource: '; - foreach ($errors as $err) { - foreach ($err as $key => $value) { - $message .= "[$key] $value" . PHP_EOL; - } - } - throw new \RuntimeException(trim($message)); - } - - return $resource; - } - - private function createStream(RequestInterface $request, array $options) - { - static $methods; - if (!$methods) { - $methods = array_flip(get_class_methods(__CLASS__)); - } - - // HTTP/1.1 streams using the PHP stream wrapper require a - // Connection: close header - if ($request->getProtocolVersion() == '1.1' - && !$request->hasHeader('Connection') - ) { - $request = $request->withHeader('Connection', 'close'); - } - - // Ensure SSL is verified by default - if (!isset($options['verify'])) { - $options['verify'] = true; - } - - $params = []; - $context = $this->getDefaultContext($request); - - if (isset($options['on_headers']) && !is_callable($options['on_headers'])) { - throw new \InvalidArgumentException('on_headers must be callable'); - } - - if (!empty($options)) { - foreach ($options as $key => $value) { - $method = "add_{$key}"; - if (isset($methods[$method])) { - $this->{$method}($request, $context, $value, $params); - } - } - } - - if (isset($options['stream_context'])) { - if (!is_array($options['stream_context'])) { - throw new \InvalidArgumentException('stream_context must be an array'); - } - $context = array_replace_recursive( - $context, - $options['stream_context'] - ); - } - - // Microsoft NTLM authentication only supported with curl handler - if (isset($options['auth']) - && is_array($options['auth']) - && isset($options['auth'][2]) - && 'ntlm' == $options['auth'][2] - ) { - throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); - } - - $uri = $this->resolveHost($request, $options); - - $context = $this->createResource( - function () use ($context, $params) { - return stream_context_create($context, $params); - } - ); - - return $this->createResource( - function () use ($uri, &$http_response_header, $context, $options) { - $resource = fopen((string) $uri, 'r', null, $context); - $this->lastHeaders = $http_response_header; - - if (isset($options['read_timeout'])) { - $readTimeout = $options['read_timeout']; - $sec = (int) $readTimeout; - $usec = ($readTimeout - $sec) * 100000; - stream_set_timeout($resource, $sec, $usec); - } - - return $resource; - } - ); - } - - private function resolveHost(RequestInterface $request, array $options) - { - $uri = $request->getUri(); - - if (isset($options['force_ip_resolve']) && !filter_var($uri->getHost(), FILTER_VALIDATE_IP)) { - if ('v4' === $options['force_ip_resolve']) { - $records = dns_get_record($uri->getHost(), DNS_A); - if (!isset($records[0]['ip'])) { - throw new ConnectException( - sprintf( - "Could not resolve IPv4 address for host '%s'", - $uri->getHost() - ), - $request - ); - } - $uri = $uri->withHost($records[0]['ip']); - } elseif ('v6' === $options['force_ip_resolve']) { - $records = dns_get_record($uri->getHost(), DNS_AAAA); - if (!isset($records[0]['ipv6'])) { - throw new ConnectException( - sprintf( - "Could not resolve IPv6 address for host '%s'", - $uri->getHost() - ), - $request - ); - } - $uri = $uri->withHost('[' . $records[0]['ipv6'] . ']'); - } - } - - return $uri; - } - - private function getDefaultContext(RequestInterface $request) - { - $headers = ''; - foreach ($request->getHeaders() as $name => $value) { - foreach ($value as $val) { - $headers .= "$name: $val\r\n"; - } - } - - $context = [ - 'http' => [ - 'method' => $request->getMethod(), - 'header' => $headers, - 'protocol_version' => $request->getProtocolVersion(), - 'ignore_errors' => true, - 'follow_location' => 0, - ], - ]; - - $body = (string) $request->getBody(); - - if (!empty($body)) { - $context['http']['content'] = $body; - // Prevent the HTTP handler from adding a Content-Type header. - if (!$request->hasHeader('Content-Type')) { - $context['http']['header'] .= "Content-Type:\r\n"; - } - } - - $context['http']['header'] = rtrim($context['http']['header']); - - return $context; - } - - private function add_proxy(RequestInterface $request, &$options, $value, &$params) - { - if (!is_array($value)) { - $options['http']['proxy'] = $value; - } else { - $scheme = $request->getUri()->getScheme(); - if (isset($value[$scheme])) { - if (!isset($value['no']) - || !\GuzzleHttp\is_host_in_noproxy( - $request->getUri()->getHost(), - $value['no'] - ) - ) { - $options['http']['proxy'] = $value[$scheme]; - } - } - } - } - - private function add_timeout(RequestInterface $request, &$options, $value, &$params) - { - if ($value > 0) { - $options['http']['timeout'] = $value; - } - } - - private function add_verify(RequestInterface $request, &$options, $value, &$params) - { - if ($value === true) { - // PHP 5.6 or greater will find the system cert by default. When - // < 5.6, use the Guzzle bundled cacert. - if (PHP_VERSION_ID < 50600) { - $options['ssl']['cafile'] = \GuzzleHttp\default_ca_bundle(); - } - } elseif (is_string($value)) { - $options['ssl']['cafile'] = $value; - if (!file_exists($value)) { - throw new \RuntimeException("SSL CA bundle not found: $value"); - } - } elseif ($value === false) { - $options['ssl']['verify_peer'] = false; - $options['ssl']['verify_peer_name'] = false; - return; - } else { - throw new \InvalidArgumentException('Invalid verify request option'); - } - - $options['ssl']['verify_peer'] = true; - $options['ssl']['verify_peer_name'] = true; - $options['ssl']['allow_self_signed'] = false; - } - - private function add_cert(RequestInterface $request, &$options, $value, &$params) - { - if (is_array($value)) { - $options['ssl']['passphrase'] = $value[1]; - $value = $value[0]; - } - - if (!file_exists($value)) { - throw new \RuntimeException("SSL certificate not found: {$value}"); - } - - $options['ssl']['local_cert'] = $value; - } - - private function add_progress(RequestInterface $request, &$options, $value, &$params) - { - $this->addNotification( - $params, - function ($code, $a, $b, $c, $transferred, $total) use ($value) { - if ($code == STREAM_NOTIFY_PROGRESS) { - $value($total, $transferred, null, null); - } - } - ); - } - - private function add_debug(RequestInterface $request, &$options, $value, &$params) - { - if ($value === false) { - return; - } - - static $map = [ - STREAM_NOTIFY_CONNECT => 'CONNECT', - STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', - STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', - STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', - STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', - STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', - STREAM_NOTIFY_PROGRESS => 'PROGRESS', - STREAM_NOTIFY_FAILURE => 'FAILURE', - STREAM_NOTIFY_COMPLETED => 'COMPLETED', - STREAM_NOTIFY_RESOLVE => 'RESOLVE', - ]; - static $args = ['severity', 'message', 'message_code', - 'bytes_transferred', 'bytes_max']; - - $value = \GuzzleHttp\debug_resource($value); - $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); - $this->addNotification( - $params, - function () use ($ident, $value, $map, $args) { - $passed = func_get_args(); - $code = array_shift($passed); - fprintf($value, '<%s> [%s] ', $ident, $map[$code]); - foreach (array_filter($passed) as $i => $v) { - fwrite($value, $args[$i] . ': "' . $v . '" '); - } - fwrite($value, "\n"); - } - ); - } - - private function addNotification(array &$params, callable $notify) - { - // Wrap the existing function if needed. - if (!isset($params['notification'])) { - $params['notification'] = $notify; - } else { - $params['notification'] = $this->callArray([ - $params['notification'], - $notify - ]); - } - } - - private function callArray(array $functions) - { - return function () use ($functions) { - $args = func_get_args(); - foreach ($functions as $fn) { - call_user_func_array($fn, $args); - } - }; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/HandlerStack.php b/vendor/guzzlehttp/guzzle/src/HandlerStack.php deleted file mode 100644 index 6a49cc0..0000000 --- a/vendor/guzzlehttp/guzzle/src/HandlerStack.php +++ /dev/null @@ -1,277 +0,0 @@ -push(Middleware::httpErrors(), 'http_errors'); - $stack->push(Middleware::redirect(), 'allow_redirects'); - $stack->push(Middleware::cookies(), 'cookies'); - $stack->push(Middleware::prepareBody(), 'prepare_body'); - - return $stack; - } - - /** - * @param callable $handler Underlying HTTP handler. - */ - public function __construct(callable $handler = null) - { - $this->handler = $handler; - } - - /** - * Invokes the handler stack as a composed handler - * - * @param RequestInterface $request - * @param array $options - * - * @return ResponseInterface|PromiseInterface - */ - public function __invoke(RequestInterface $request, array $options) - { - $handler = $this->resolve(); - - return $handler($request, $options); - } - - /** - * Dumps a string representation of the stack. - * - * @return string - */ - public function __toString() - { - $depth = 0; - $stack = []; - if ($this->handler) { - $stack[] = "0) Handler: " . $this->debugCallable($this->handler); - } - - $result = ''; - foreach (array_reverse($this->stack) as $tuple) { - $depth++; - $str = "{$depth}) Name: '{$tuple[1]}', "; - $str .= "Function: " . $this->debugCallable($tuple[0]); - $result = "> {$str}\n{$result}"; - $stack[] = $str; - } - - foreach (array_keys($stack) as $k) { - $result .= "< {$stack[$k]}\n"; - } - - return $result; - } - - /** - * Set the HTTP handler that actually returns a promise. - * - * @param callable $handler Accepts a request and array of options and - * returns a Promise. - */ - public function setHandler(callable $handler) - { - $this->handler = $handler; - $this->cached = null; - } - - /** - * Returns true if the builder has a handler. - * - * @return bool - */ - public function hasHandler() - { - return (bool) $this->handler; - } - - /** - * Unshift a middleware to the bottom of the stack. - * - * @param callable $middleware Middleware function - * @param string $name Name to register for this middleware. - */ - public function unshift(callable $middleware, $name = null) - { - array_unshift($this->stack, [$middleware, $name]); - $this->cached = null; - } - - /** - * Push a middleware to the top of the stack. - * - * @param callable $middleware Middleware function - * @param string $name Name to register for this middleware. - */ - public function push(callable $middleware, $name = '') - { - $this->stack[] = [$middleware, $name]; - $this->cached = null; - } - - /** - * Add a middleware before another middleware by name. - * - * @param string $findName Middleware to find - * @param callable $middleware Middleware function - * @param string $withName Name to register for this middleware. - */ - public function before($findName, callable $middleware, $withName = '') - { - $this->splice($findName, $withName, $middleware, true); - } - - /** - * Add a middleware after another middleware by name. - * - * @param string $findName Middleware to find - * @param callable $middleware Middleware function - * @param string $withName Name to register for this middleware. - */ - public function after($findName, callable $middleware, $withName = '') - { - $this->splice($findName, $withName, $middleware, false); - } - - /** - * Remove a middleware by instance or name from the stack. - * - * @param callable|string $remove Middleware to remove by instance or name. - */ - public function remove($remove) - { - $this->cached = null; - $idx = is_callable($remove) ? 0 : 1; - $this->stack = array_values(array_filter( - $this->stack, - function ($tuple) use ($idx, $remove) { - return $tuple[$idx] !== $remove; - } - )); - } - - /** - * Compose the middleware and handler into a single callable function. - * - * @return callable - */ - public function resolve() - { - if (!$this->cached) { - if (!($prev = $this->handler)) { - throw new \LogicException('No handler has been specified'); - } - - foreach (array_reverse($this->stack) as $fn) { - $prev = $fn[0]($prev); - } - - $this->cached = $prev; - } - - return $this->cached; - } - - /** - * @param string $name - * @return int - */ - private function findByName($name) - { - foreach ($this->stack as $k => $v) { - if ($v[1] === $name) { - return $k; - } - } - - throw new \InvalidArgumentException("Middleware not found: $name"); - } - - /** - * Splices a function into the middleware list at a specific position. - * - * @param string $findName - * @param string $withName - * @param callable $middleware - * @param bool $before - */ - private function splice($findName, $withName, callable $middleware, $before) - { - $this->cached = null; - $idx = $this->findByName($findName); - $tuple = [$middleware, $withName]; - - if ($before) { - if ($idx === 0) { - array_unshift($this->stack, $tuple); - } else { - $replacement = [$tuple, $this->stack[$idx]]; - array_splice($this->stack, $idx, 1, $replacement); - } - } elseif ($idx === count($this->stack) - 1) { - $this->stack[] = $tuple; - } else { - $replacement = [$this->stack[$idx], $tuple]; - array_splice($this->stack, $idx, 1, $replacement); - } - } - - /** - * Provides a debug string for a given callable. - * - * @param array|callable $fn Function to write as a string. - * - * @return string - */ - private function debugCallable($fn) - { - if (is_string($fn)) { - return "callable({$fn})"; - } - - if (is_array($fn)) { - return is_string($fn[0]) - ? "callable({$fn[0]}::{$fn[1]})" - : "callable(['" . get_class($fn[0]) . "', '{$fn[1]}'])"; - } - - return 'callable(' . spl_object_hash($fn) . ')'; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/MessageFormatter.php b/vendor/guzzlehttp/guzzle/src/MessageFormatter.php deleted file mode 100644 index dc36bb5..0000000 --- a/vendor/guzzlehttp/guzzle/src/MessageFormatter.php +++ /dev/null @@ -1,185 +0,0 @@ ->>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; - const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; - - /** @var string Template used to format log messages */ - private $template; - - /** - * @param string $template Log message template - */ - public function __construct($template = self::CLF) - { - $this->template = $template ?: self::CLF; - } - - /** - * Returns a formatted message string. - * - * @param RequestInterface $request Request that was sent - * @param ResponseInterface $response Response that was received - * @param \Exception $error Exception that was received - * - * @return string - */ - public function format( - RequestInterface $request, - ResponseInterface $response = null, - \Exception $error = null - ) { - $cache = []; - - return preg_replace_callback( - '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', - function (array $matches) use ($request, $response, $error, &$cache) { - if (isset($cache[$matches[1]])) { - return $cache[$matches[1]]; - } - - $result = ''; - switch ($matches[1]) { - case 'request': - $result = Psr7\str($request); - break; - case 'response': - $result = $response ? Psr7\str($response) : ''; - break; - case 'req_headers': - $result = trim($request->getMethod() - . ' ' . $request->getRequestTarget()) - . ' HTTP/' . $request->getProtocolVersion() . "\r\n" - . $this->headers($request); - break; - case 'res_headers': - $result = $response ? - sprintf( - 'HTTP/%s %d %s', - $response->getProtocolVersion(), - $response->getStatusCode(), - $response->getReasonPhrase() - ) . "\r\n" . $this->headers($response) - : 'NULL'; - break; - case 'req_body': - $result = $request->getBody(); - break; - case 'res_body': - $result = $response ? $response->getBody() : 'NULL'; - break; - case 'ts': - case 'date_iso_8601': - $result = gmdate('c'); - break; - case 'date_common_log': - $result = date('d/M/Y:H:i:s O'); - break; - case 'method': - $result = $request->getMethod(); - break; - case 'version': - $result = $request->getProtocolVersion(); - break; - case 'uri': - case 'url': - $result = $request->getUri(); - break; - case 'target': - $result = $request->getRequestTarget(); - break; - case 'req_version': - $result = $request->getProtocolVersion(); - break; - case 'res_version': - $result = $response - ? $response->getProtocolVersion() - : 'NULL'; - break; - case 'host': - $result = $request->getHeaderLine('Host'); - break; - case 'hostname': - $result = gethostname(); - break; - case 'code': - $result = $response ? $response->getStatusCode() : 'NULL'; - break; - case 'phrase': - $result = $response ? $response->getReasonPhrase() : 'NULL'; - break; - case 'error': - $result = $error ? $error->getMessage() : 'NULL'; - break; - default: - // handle prefixed dynamic headers - if (strpos($matches[1], 'req_header_') === 0) { - $result = $request->getHeaderLine(substr($matches[1], 11)); - } elseif (strpos($matches[1], 'res_header_') === 0) { - $result = $response - ? $response->getHeaderLine(substr($matches[1], 11)) - : 'NULL'; - } - } - - $cache[$matches[1]] = $result; - return $result; - }, - $this->template - ); - } - - /** - * Get headers from message as string - * - * @return string - */ - private function headers(MessageInterface $message) - { - $result = ''; - foreach ($message->getHeaders() as $name => $values) { - $result .= $name . ': ' . implode(', ', $values) . "\r\n"; - } - - return trim($result); - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Middleware.php b/vendor/guzzlehttp/guzzle/src/Middleware.php deleted file mode 100644 index bffc197..0000000 --- a/vendor/guzzlehttp/guzzle/src/Middleware.php +++ /dev/null @@ -1,254 +0,0 @@ -withCookieHeader($request); - return $handler($request, $options) - ->then( - function ($response) use ($cookieJar, $request) { - $cookieJar->extractCookies($request, $response); - return $response; - } - ); - }; - }; - } - - /** - * Middleware that throws exceptions for 4xx or 5xx responses when the - * "http_error" request option is set to true. - * - * @return callable Returns a function that accepts the next handler. - */ - public static function httpErrors() - { - return function (callable $handler) { - return function ($request, array $options) use ($handler) { - if (empty($options['http_errors'])) { - return $handler($request, $options); - } - return $handler($request, $options)->then( - function (ResponseInterface $response) use ($request) { - $code = $response->getStatusCode(); - if ($code < 400) { - return $response; - } - throw RequestException::create($request, $response); - } - ); - }; - }; - } - - /** - * Middleware that pushes history data to an ArrayAccess container. - * - * @param array|\ArrayAccess $container Container to hold the history (by reference). - * - * @return callable Returns a function that accepts the next handler. - * @throws \InvalidArgumentException if container is not an array or ArrayAccess. - */ - public static function history(&$container) - { - if (!is_array($container) && !$container instanceof \ArrayAccess) { - throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); - } - - return function (callable $handler) use (&$container) { - return function ($request, array $options) use ($handler, &$container) { - return $handler($request, $options)->then( - function ($value) use ($request, &$container, $options) { - $container[] = [ - 'request' => $request, - 'response' => $value, - 'error' => null, - 'options' => $options - ]; - return $value; - }, - function ($reason) use ($request, &$container, $options) { - $container[] = [ - 'request' => $request, - 'response' => null, - 'error' => $reason, - 'options' => $options - ]; - return \GuzzleHttp\Promise\rejection_for($reason); - } - ); - }; - }; - } - - /** - * Middleware that invokes a callback before and after sending a request. - * - * The provided listener cannot modify or alter the response. It simply - * "taps" into the chain to be notified before returning the promise. The - * before listener accepts a request and options array, and the after - * listener accepts a request, options array, and response promise. - * - * @param callable $before Function to invoke before forwarding the request. - * @param callable $after Function invoked after forwarding. - * - * @return callable Returns a function that accepts the next handler. - */ - public static function tap(callable $before = null, callable $after = null) - { - return function (callable $handler) use ($before, $after) { - return function ($request, array $options) use ($handler, $before, $after) { - if ($before) { - $before($request, $options); - } - $response = $handler($request, $options); - if ($after) { - $after($request, $options, $response); - } - return $response; - }; - }; - } - - /** - * Middleware that handles request redirects. - * - * @return callable Returns a function that accepts the next handler. - */ - public static function redirect() - { - return function (callable $handler) { - return new RedirectMiddleware($handler); - }; - } - - /** - * Middleware that retries requests based on the boolean result of - * invoking the provided "decider" function. - * - * If no delay function is provided, a simple implementation of exponential - * backoff will be utilized. - * - * @param callable $decider Function that accepts the number of retries, - * a request, [response], and [exception] and - * returns true if the request is to be retried. - * @param callable $delay Function that accepts the number of retries and - * returns the number of milliseconds to delay. - * - * @return callable Returns a function that accepts the next handler. - */ - public static function retry(callable $decider, callable $delay = null) - { - return function (callable $handler) use ($decider, $delay) { - return new RetryMiddleware($decider, $handler, $delay); - }; - } - - /** - * Middleware that logs requests, responses, and errors using a message - * formatter. - * - * @param LoggerInterface $logger Logs messages. - * @param MessageFormatter $formatter Formatter used to create message strings. - * @param string $logLevel Level at which to log requests. - * - * @return callable Returns a function that accepts the next handler. - */ - public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = 'info' /* \Psr\Log\LogLevel::INFO */) - { - return function (callable $handler) use ($logger, $formatter, $logLevel) { - return function ($request, array $options) use ($handler, $logger, $formatter, $logLevel) { - return $handler($request, $options)->then( - function ($response) use ($logger, $request, $formatter, $logLevel) { - $message = $formatter->format($request, $response); - $logger->log($logLevel, $message); - return $response; - }, - function ($reason) use ($logger, $request, $formatter) { - $response = $reason instanceof RequestException - ? $reason->getResponse() - : null; - $message = $formatter->format($request, $response, $reason); - $logger->notice($message); - return \GuzzleHttp\Promise\rejection_for($reason); - } - ); - }; - }; - } - - /** - * This middleware adds a default content-type if possible, a default - * content-length or transfer-encoding header, and the expect header. - * - * @return callable - */ - public static function prepareBody() - { - return function (callable $handler) { - return new PrepareBodyMiddleware($handler); - }; - } - - /** - * Middleware that applies a map function to the request before passing to - * the next handler. - * - * @param callable $fn Function that accepts a RequestInterface and returns - * a RequestInterface. - * @return callable - */ - public static function mapRequest(callable $fn) - { - return function (callable $handler) use ($fn) { - return function ($request, array $options) use ($handler, $fn) { - return $handler($fn($request), $options); - }; - }; - } - - /** - * Middleware that applies a map function to the resolved promise's - * response. - * - * @param callable $fn Function that accepts a ResponseInterface and - * returns a ResponseInterface. - * @return callable - */ - public static function mapResponse(callable $fn) - { - return function (callable $handler) use ($fn) { - return function ($request, array $options) use ($handler, $fn) { - return $handler($request, $options)->then($fn); - }; - }; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Pool.php b/vendor/guzzlehttp/guzzle/src/Pool.php deleted file mode 100644 index 5838db4..0000000 --- a/vendor/guzzlehttp/guzzle/src/Pool.php +++ /dev/null @@ -1,134 +0,0 @@ - $rfn) { - if ($rfn instanceof RequestInterface) { - yield $key => $client->sendAsync($rfn, $opts); - } elseif (is_callable($rfn)) { - yield $key => $rfn($opts); - } else { - throw new \InvalidArgumentException('Each value yielded by ' - . 'the iterator must be a Psr7\Http\Message\RequestInterface ' - . 'or a callable that returns a promise that fulfills ' - . 'with a Psr7\Message\Http\ResponseInterface object.'); - } - } - }; - - $this->each = new EachPromise($requests(), $config); - } - - /** - * Get promise - * - * @return PromiseInterface - */ - public function promise() - { - return $this->each->promise(); - } - - /** - * Sends multiple requests concurrently and returns an array of responses - * and exceptions that uses the same ordering as the provided requests. - * - * IMPORTANT: This method keeps every request and response in memory, and - * as such, is NOT recommended when sending a large number or an - * indeterminate number of requests concurrently. - * - * @param ClientInterface $client Client used to send the requests - * @param array|\Iterator $requests Requests to send concurrently. - * @param array $options Passes through the options available in - * {@see GuzzleHttp\Pool::__construct} - * - * @return array Returns an array containing the response or an exception - * in the same order that the requests were sent. - * @throws \InvalidArgumentException if the event format is incorrect. - */ - public static function batch( - ClientInterface $client, - $requests, - array $options = [] - ) { - $res = []; - self::cmpCallback($options, 'fulfilled', $res); - self::cmpCallback($options, 'rejected', $res); - $pool = new static($client, $requests, $options); - $pool->promise()->wait(); - ksort($res); - - return $res; - } - - /** - * Execute callback(s) - * - * @return void - */ - private static function cmpCallback(array &$options, $name, array &$results) - { - if (!isset($options[$name])) { - $options[$name] = function ($v, $k) use (&$results) { - $results[$k] = $v; - }; - } else { - $currentFn = $options[$name]; - $options[$name] = function ($v, $k) use (&$results, $currentFn) { - $currentFn($v, $k); - $results[$k] = $v; - }; - } - } -} diff --git a/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php deleted file mode 100644 index 568a1e9..0000000 --- a/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php +++ /dev/null @@ -1,111 +0,0 @@ -nextHandler = $nextHandler; - } - - /** - * @param RequestInterface $request - * @param array $options - * - * @return PromiseInterface - */ - public function __invoke(RequestInterface $request, array $options) - { - $fn = $this->nextHandler; - - // Don't do anything if the request has no body. - if ($request->getBody()->getSize() === 0) { - return $fn($request, $options); - } - - $modify = []; - - // Add a default content-type if possible. - if (!$request->hasHeader('Content-Type')) { - if ($uri = $request->getBody()->getMetadata('uri')) { - if ($type = Psr7\mimetype_from_filename($uri)) { - $modify['set_headers']['Content-Type'] = $type; - } - } - } - - // Add a default content-length or transfer-encoding header. - if (!$request->hasHeader('Content-Length') - && !$request->hasHeader('Transfer-Encoding') - ) { - $size = $request->getBody()->getSize(); - if ($size !== null) { - $modify['set_headers']['Content-Length'] = $size; - } else { - $modify['set_headers']['Transfer-Encoding'] = 'chunked'; - } - } - - // Add the expect header if needed. - $this->addExpectHeader($request, $options, $modify); - - return $fn(Psr7\modify_request($request, $modify), $options); - } - - /** - * Add expect header - * - * @return void - */ - private function addExpectHeader( - RequestInterface $request, - array $options, - array &$modify - ) { - // Determine if the Expect header should be used - if ($request->hasHeader('Expect')) { - return; - } - - $expect = isset($options['expect']) ? $options['expect'] : null; - - // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 - if ($expect === false || $request->getProtocolVersion() < 1.1) { - return; - } - - // The expect header is unconditionally enabled - if ($expect === true) { - $modify['set_headers']['Expect'] = '100-Continue'; - return; - } - - // By default, send the expect header when the payload is > 1mb - if ($expect === null) { - $expect = 1048576; - } - - // Always add if the body cannot be rewound, the size cannot be - // determined, or the size is greater than the cutoff threshold - $body = $request->getBody(); - $size = $body->getSize(); - - if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { - $modify['set_headers']['Expect'] = '100-Continue'; - } - } -} diff --git a/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php b/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php deleted file mode 100644 index e4644b7..0000000 --- a/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php +++ /dev/null @@ -1,255 +0,0 @@ - 5, - 'protocols' => ['http', 'https'], - 'strict' => false, - 'referer' => false, - 'track_redirects' => false, - ]; - - /** @var callable */ - private $nextHandler; - - /** - * @param callable $nextHandler Next handler to invoke. - */ - public function __construct(callable $nextHandler) - { - $this->nextHandler = $nextHandler; - } - - /** - * @param RequestInterface $request - * @param array $options - * - * @return PromiseInterface - */ - public function __invoke(RequestInterface $request, array $options) - { - $fn = $this->nextHandler; - - if (empty($options['allow_redirects'])) { - return $fn($request, $options); - } - - if ($options['allow_redirects'] === true) { - $options['allow_redirects'] = self::$defaultSettings; - } elseif (!is_array($options['allow_redirects'])) { - throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); - } else { - // Merge the default settings with the provided settings - $options['allow_redirects'] += self::$defaultSettings; - } - - if (empty($options['allow_redirects']['max'])) { - return $fn($request, $options); - } - - return $fn($request, $options) - ->then(function (ResponseInterface $response) use ($request, $options) { - return $this->checkRedirect($request, $options, $response); - }); - } - - /** - * @param RequestInterface $request - * @param array $options - * @param ResponseInterface $response - * - * @return ResponseInterface|PromiseInterface - */ - public function checkRedirect( - RequestInterface $request, - array $options, - ResponseInterface $response - ) { - if (substr($response->getStatusCode(), 0, 1) != '3' - || !$response->hasHeader('Location') - ) { - return $response; - } - - $this->guardMax($request, $options); - $nextRequest = $this->modifyRequest($request, $options, $response); - - if (isset($options['allow_redirects']['on_redirect'])) { - call_user_func( - $options['allow_redirects']['on_redirect'], - $request, - $response, - $nextRequest->getUri() - ); - } - - /** @var PromiseInterface|ResponseInterface $promise */ - $promise = $this($nextRequest, $options); - - // Add headers to be able to track history of redirects. - if (!empty($options['allow_redirects']['track_redirects'])) { - return $this->withTracking( - $promise, - (string) $nextRequest->getUri(), - $response->getStatusCode() - ); - } - - return $promise; - } - - /** - * Enable tracking on promise. - * - * @return PromiseInterface - */ - private function withTracking(PromiseInterface $promise, $uri, $statusCode) - { - return $promise->then( - function (ResponseInterface $response) use ($uri, $statusCode) { - // Note that we are pushing to the front of the list as this - // would be an earlier response than what is currently present - // in the history header. - $historyHeader = $response->getHeader(self::HISTORY_HEADER); - $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); - array_unshift($historyHeader, $uri); - array_unshift($statusHeader, $statusCode); - return $response->withHeader(self::HISTORY_HEADER, $historyHeader) - ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); - } - ); - } - - /** - * Check for too many redirects - * - * @return void - * - * @throws TooManyRedirectsException Too many redirects. - */ - private function guardMax(RequestInterface $request, array &$options) - { - $current = isset($options['__redirect_count']) - ? $options['__redirect_count'] - : 0; - $options['__redirect_count'] = $current + 1; - $max = $options['allow_redirects']['max']; - - if ($options['__redirect_count'] > $max) { - throw new TooManyRedirectsException( - "Will not follow more than {$max} redirects", - $request - ); - } - } - - /** - * @param RequestInterface $request - * @param array $options - * @param ResponseInterface $response - * - * @return RequestInterface - */ - public function modifyRequest( - RequestInterface $request, - array $options, - ResponseInterface $response - ) { - // Request modifications to apply. - $modify = []; - $protocols = $options['allow_redirects']['protocols']; - - // Use a GET request if this is an entity enclosing request and we are - // not forcing RFC compliance, but rather emulating what all browsers - // would do. - $statusCode = $response->getStatusCode(); - if ($statusCode == 303 || - ($statusCode <= 302 && !$options['allow_redirects']['strict']) - ) { - $modify['method'] = 'GET'; - $modify['body'] = ''; - } - - $uri = $this->redirectUri($request, $response, $protocols); - if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { - $idnOptions = ($options['idn_conversion'] === true) ? IDNA_DEFAULT : $options['idn_conversion']; - $uri = Utils::idnUriConvert($uri, $idnOptions); - } - - $modify['uri'] = $uri; - Psr7\rewind_body($request); - - // Add the Referer header if it is told to do so and only - // add the header if we are not redirecting from https to http. - if ($options['allow_redirects']['referer'] - && $modify['uri']->getScheme() === $request->getUri()->getScheme() - ) { - $uri = $request->getUri()->withUserInfo(''); - $modify['set_headers']['Referer'] = (string) $uri; - } else { - $modify['remove_headers'][] = 'Referer'; - } - - // Remove Authorization header if host is different. - if ($request->getUri()->getHost() !== $modify['uri']->getHost()) { - $modify['remove_headers'][] = 'Authorization'; - } - - return Psr7\modify_request($request, $modify); - } - - /** - * Set the appropriate URL on the request based on the location header - * - * @param RequestInterface $request - * @param ResponseInterface $response - * @param array $protocols - * - * @return UriInterface - */ - private function redirectUri( - RequestInterface $request, - ResponseInterface $response, - array $protocols - ) { - $location = Psr7\UriResolver::resolve( - $request->getUri(), - new Psr7\Uri($response->getHeaderLine('Location')) - ); - - // Ensure that the redirect URI is allowed based on the protocols. - if (!in_array($location->getScheme(), $protocols)) { - throw new BadResponseException( - sprintf( - 'Redirect URI, %s, does not use one of the allowed redirect protocols: %s', - $location, - implode(', ', $protocols) - ), - $request, - $response - ); - } - - return $location; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/RequestOptions.php b/vendor/guzzlehttp/guzzle/src/RequestOptions.php deleted file mode 100644 index 355f658..0000000 --- a/vendor/guzzlehttp/guzzle/src/RequestOptions.php +++ /dev/null @@ -1,263 +0,0 @@ -decider = $decider; - $this->nextHandler = $nextHandler; - $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; - } - - /** - * Default exponential backoff delay function. - * - * @param int $retries - * - * @return int milliseconds. - */ - public static function exponentialDelay($retries) - { - return (int) pow(2, $retries - 1) * 1000; - } - - /** - * @param RequestInterface $request - * @param array $options - * - * @return PromiseInterface - */ - public function __invoke(RequestInterface $request, array $options) - { - if (!isset($options['retries'])) { - $options['retries'] = 0; - } - - $fn = $this->nextHandler; - return $fn($request, $options) - ->then( - $this->onFulfilled($request, $options), - $this->onRejected($request, $options) - ); - } - - /** - * Execute fulfilled closure - * - * @return mixed - */ - private function onFulfilled(RequestInterface $req, array $options) - { - return function ($value) use ($req, $options) { - if (!call_user_func( - $this->decider, - $options['retries'], - $req, - $value, - null - )) { - return $value; - } - return $this->doRetry($req, $options, $value); - }; - } - - /** - * Execute rejected closure - * - * @return callable - */ - private function onRejected(RequestInterface $req, array $options) - { - return function ($reason) use ($req, $options) { - if (!call_user_func( - $this->decider, - $options['retries'], - $req, - null, - $reason - )) { - return \GuzzleHttp\Promise\rejection_for($reason); - } - return $this->doRetry($req, $options); - }; - } - - /** - * @return self - */ - private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null) - { - $options['delay'] = call_user_func($this->delay, ++$options['retries'], $response); - - return $this($request, $options); - } -} diff --git a/vendor/guzzlehttp/guzzle/src/TransferStats.php b/vendor/guzzlehttp/guzzle/src/TransferStats.php deleted file mode 100644 index 87fb3c0..0000000 --- a/vendor/guzzlehttp/guzzle/src/TransferStats.php +++ /dev/null @@ -1,126 +0,0 @@ -request = $request; - $this->response = $response; - $this->transferTime = $transferTime; - $this->handlerErrorData = $handlerErrorData; - $this->handlerStats = $handlerStats; - } - - /** - * @return RequestInterface - */ - public function getRequest() - { - return $this->request; - } - - /** - * Returns the response that was received (if any). - * - * @return ResponseInterface|null - */ - public function getResponse() - { - return $this->response; - } - - /** - * Returns true if a response was received. - * - * @return bool - */ - public function hasResponse() - { - return $this->response !== null; - } - - /** - * Gets handler specific error data. - * - * This might be an exception, a integer representing an error code, or - * anything else. Relying on this value assumes that you know what handler - * you are using. - * - * @return mixed - */ - public function getHandlerErrorData() - { - return $this->handlerErrorData; - } - - /** - * Get the effective URI the request was sent to. - * - * @return UriInterface - */ - public function getEffectiveUri() - { - return $this->request->getUri(); - } - - /** - * Get the estimated time the request was being transferred by the handler. - * - * @return float|null Time in seconds. - */ - public function getTransferTime() - { - return $this->transferTime; - } - - /** - * Gets an array of all of the handler specific transfer data. - * - * @return array - */ - public function getHandlerStats() - { - return $this->handlerStats; - } - - /** - * Get a specific handler statistic from the handler by name. - * - * @param string $stat Handler specific transfer stat to retrieve. - * - * @return mixed|null - */ - public function getHandlerStat($stat) - { - return isset($this->handlerStats[$stat]) - ? $this->handlerStats[$stat] - : null; - } -} diff --git a/vendor/guzzlehttp/guzzle/src/UriTemplate.php b/vendor/guzzlehttp/guzzle/src/UriTemplate.php deleted file mode 100644 index 96dcfd0..0000000 --- a/vendor/guzzlehttp/guzzle/src/UriTemplate.php +++ /dev/null @@ -1,237 +0,0 @@ - ['prefix' => '', 'joiner' => ',', 'query' => false], - '+' => ['prefix' => '', 'joiner' => ',', 'query' => false], - '#' => ['prefix' => '#', 'joiner' => ',', 'query' => false], - '.' => ['prefix' => '.', 'joiner' => '.', 'query' => false], - '/' => ['prefix' => '/', 'joiner' => '/', 'query' => false], - ';' => ['prefix' => ';', 'joiner' => ';', 'query' => true], - '?' => ['prefix' => '?', 'joiner' => '&', 'query' => true], - '&' => ['prefix' => '&', 'joiner' => '&', 'query' => true] - ]; - - /** @var array Delimiters */ - private static $delims = [':', '/', '?', '#', '[', ']', '@', '!', '$', - '&', '\'', '(', ')', '*', '+', ',', ';', '=']; - - /** @var array Percent encoded delimiters */ - private static $delimsPct = ['%3A', '%2F', '%3F', '%23', '%5B', '%5D', - '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', - '%3B', '%3D']; - - public function expand($template, array $variables) - { - if (false === strpos($template, '{')) { - return $template; - } - - $this->template = $template; - $this->variables = $variables; - - return preg_replace_callback( - '/\{([^\}]+)\}/', - [$this, 'expandMatch'], - $this->template - ); - } - - /** - * Parse an expression into parts - * - * @param string $expression Expression to parse - * - * @return array Returns an associative array of parts - */ - private function parseExpression($expression) - { - $result = []; - - if (isset(self::$operatorHash[$expression[0]])) { - $result['operator'] = $expression[0]; - $expression = substr($expression, 1); - } else { - $result['operator'] = ''; - } - - foreach (explode(',', $expression) as $value) { - $value = trim($value); - $varspec = []; - if ($colonPos = strpos($value, ':')) { - $varspec['value'] = substr($value, 0, $colonPos); - $varspec['modifier'] = ':'; - $varspec['position'] = (int) substr($value, $colonPos + 1); - } elseif (substr($value, -1) === '*') { - $varspec['modifier'] = '*'; - $varspec['value'] = substr($value, 0, -1); - } else { - $varspec['value'] = (string) $value; - $varspec['modifier'] = ''; - } - $result['values'][] = $varspec; - } - - return $result; - } - - /** - * Process an expansion - * - * @param array $matches Matches met in the preg_replace_callback - * - * @return string Returns the replacement string - */ - private function expandMatch(array $matches) - { - static $rfc1738to3986 = ['+' => '%20', '%7e' => '~']; - - $replacements = []; - $parsed = self::parseExpression($matches[1]); - $prefix = self::$operatorHash[$parsed['operator']]['prefix']; - $joiner = self::$operatorHash[$parsed['operator']]['joiner']; - $useQuery = self::$operatorHash[$parsed['operator']]['query']; - - foreach ($parsed['values'] as $value) { - if (!isset($this->variables[$value['value']])) { - continue; - } - - $variable = $this->variables[$value['value']]; - $actuallyUseQuery = $useQuery; - $expanded = ''; - - if (is_array($variable)) { - $isAssoc = $this->isAssoc($variable); - $kvp = []; - foreach ($variable as $key => $var) { - if ($isAssoc) { - $key = rawurlencode($key); - $isNestedArray = is_array($var); - } else { - $isNestedArray = false; - } - - if (!$isNestedArray) { - $var = rawurlencode($var); - if ($parsed['operator'] === '+' || - $parsed['operator'] === '#' - ) { - $var = $this->decodeReserved($var); - } - } - - if ($value['modifier'] === '*') { - if ($isAssoc) { - if ($isNestedArray) { - // Nested arrays must allow for deeply nested - // structures. - $var = strtr( - http_build_query([$key => $var]), - $rfc1738to3986 - ); - } else { - $var = $key . '=' . $var; - } - } elseif ($key > 0 && $actuallyUseQuery) { - $var = $value['value'] . '=' . $var; - } - } - - $kvp[$key] = $var; - } - - if (empty($variable)) { - $actuallyUseQuery = false; - } elseif ($value['modifier'] === '*') { - $expanded = implode($joiner, $kvp); - if ($isAssoc) { - // Don't prepend the value name when using the explode - // modifier with an associative array. - $actuallyUseQuery = false; - } - } else { - if ($isAssoc) { - // When an associative array is encountered and the - // explode modifier is not set, then the result must be - // a comma separated list of keys followed by their - // respective values. - foreach ($kvp as $k => &$v) { - $v = $k . ',' . $v; - } - } - $expanded = implode(',', $kvp); - } - } else { - if ($value['modifier'] === ':') { - $variable = substr($variable, 0, $value['position']); - } - $expanded = rawurlencode($variable); - if ($parsed['operator'] === '+' || $parsed['operator'] === '#') { - $expanded = $this->decodeReserved($expanded); - } - } - - if ($actuallyUseQuery) { - if (!$expanded && $joiner !== '&') { - $expanded = $value['value']; - } else { - $expanded = $value['value'] . '=' . $expanded; - } - } - - $replacements[] = $expanded; - } - - $ret = implode($joiner, $replacements); - if ($ret && $prefix) { - return $prefix . $ret; - } - - return $ret; - } - - /** - * Determines if an array is associative. - * - * This makes the assumption that input arrays are sequences or hashes. - * This assumption is a tradeoff for accuracy in favor of speed, but it - * should work in almost every case where input is supplied for a URI - * template. - * - * @param array $array Array to check - * - * @return bool - */ - private function isAssoc(array $array) - { - return $array && array_keys($array)[0] !== 0; - } - - /** - * Removes percent encoding on reserved characters (used with + and # - * modifiers). - * - * @param string $string String to fix - * - * @return string - */ - private function decodeReserved($string) - { - return str_replace(self::$delimsPct, self::$delims, $string); - } -} diff --git a/vendor/guzzlehttp/guzzle/src/Utils.php b/vendor/guzzlehttp/guzzle/src/Utils.php deleted file mode 100644 index c698acb..0000000 --- a/vendor/guzzlehttp/guzzle/src/Utils.php +++ /dev/null @@ -1,92 +0,0 @@ -getHost()) { - $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); - if ($asciiHost === false) { - $errorBitSet = isset($info['errors']) ? $info['errors'] : 0; - - $errorConstants = array_filter(array_keys(get_defined_constants()), function ($name) { - return substr($name, 0, 11) === 'IDNA_ERROR_'; - }); - - $errors = []; - foreach ($errorConstants as $errorConstant) { - if ($errorBitSet & constant($errorConstant)) { - $errors[] = $errorConstant; - } - } - - $errorMessage = 'IDN conversion failed'; - if ($errors) { - $errorMessage .= ' (errors: ' . implode(', ', $errors) . ')'; - } - - throw new InvalidArgumentException($errorMessage); - } else { - if ($uri->getHost() !== $asciiHost) { - // Replace URI only if the ASCII version is different - $uri = $uri->withHost($asciiHost); - } - } - } - - return $uri; - } - - /** - * @param string $domain - * @param int $options - * @param array $info - * - * @return string|false - */ - private static function idnToAsci($domain, $options, &$info = []) - { - if (\preg_match('%^[ -~]+$%', $domain) === 1) { - return $domain; - } - - if (\extension_loaded('intl') && defined('INTL_IDNA_VARIANT_UTS46')) { - return \idn_to_ascii($domain, $options, INTL_IDNA_VARIANT_UTS46, $info); - } - - /* - * The Idn class is marked as @internal. Verify that class and method exists. - */ - if (method_exists(Idn::class, 'idn_to_ascii')) { - return Idn::idn_to_ascii($domain, $options, Idn::INTL_IDNA_VARIANT_UTS46, $info); - } - - throw new \RuntimeException('ext-intl or symfony/polyfill-intl-idn not loaded or too old'); - } -} diff --git a/vendor/guzzlehttp/guzzle/src/functions.php b/vendor/guzzlehttp/guzzle/src/functions.php deleted file mode 100644 index c2afd8c..0000000 --- a/vendor/guzzlehttp/guzzle/src/functions.php +++ /dev/null @@ -1,334 +0,0 @@ -expand($template, $variables); -} - -/** - * Debug function used to describe the provided value type and class. - * - * @param mixed $input - * - * @return string Returns a string containing the type of the variable and - * if a class is provided, the class name. - */ -function describe_type($input) -{ - switch (gettype($input)) { - case 'object': - return 'object(' . get_class($input) . ')'; - case 'array': - return 'array(' . count($input) . ')'; - default: - ob_start(); - var_dump($input); - // normalize float vs double - return str_replace('double(', 'float(', rtrim(ob_get_clean())); - } -} - -/** - * Parses an array of header lines into an associative array of headers. - * - * @param iterable $lines Header lines array of strings in the following - * format: "Name: Value" - * @return array - */ -function headers_from_lines($lines) -{ - $headers = []; - - foreach ($lines as $line) { - $parts = explode(':', $line, 2); - $headers[trim($parts[0])][] = isset($parts[1]) - ? trim($parts[1]) - : null; - } - - return $headers; -} - -/** - * Returns a debug stream based on the provided variable. - * - * @param mixed $value Optional value - * - * @return resource - */ -function debug_resource($value = null) -{ - if (is_resource($value)) { - return $value; - } elseif (defined('STDOUT')) { - return STDOUT; - } - - return fopen('php://output', 'w'); -} - -/** - * Chooses and creates a default handler to use based on the environment. - * - * The returned handler is not wrapped by any default middlewares. - * - * @return callable Returns the best handler for the given system. - * @throws \RuntimeException if no viable Handler is available. - */ -function choose_handler() -{ - $handler = null; - if (function_exists('curl_multi_exec') && function_exists('curl_exec')) { - $handler = Proxy::wrapSync(new CurlMultiHandler(), new CurlHandler()); - } elseif (function_exists('curl_exec')) { - $handler = new CurlHandler(); - } elseif (function_exists('curl_multi_exec')) { - $handler = new CurlMultiHandler(); - } - - if (ini_get('allow_url_fopen')) { - $handler = $handler - ? Proxy::wrapStreaming($handler, new StreamHandler()) - : new StreamHandler(); - } elseif (!$handler) { - throw new \RuntimeException('GuzzleHttp requires cURL, the ' - . 'allow_url_fopen ini setting, or a custom HTTP handler.'); - } - - return $handler; -} - -/** - * Get the default User-Agent string to use with Guzzle - * - * @return string - */ -function default_user_agent() -{ - static $defaultAgent = ''; - - if (!$defaultAgent) { - $defaultAgent = 'GuzzleHttp/' . Client::VERSION; - if (extension_loaded('curl') && function_exists('curl_version')) { - $defaultAgent .= ' curl/' . \curl_version()['version']; - } - $defaultAgent .= ' PHP/' . PHP_VERSION; - } - - return $defaultAgent; -} - -/** - * Returns the default cacert bundle for the current system. - * - * First, the openssl.cafile and curl.cainfo php.ini settings are checked. - * If those settings are not configured, then the common locations for - * bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X - * and Windows are checked. If any of these file locations are found on - * disk, they will be utilized. - * - * Note: the result of this function is cached for subsequent calls. - * - * @return string - * @throws \RuntimeException if no bundle can be found. - */ -function default_ca_bundle() -{ - static $cached = null; - static $cafiles = [ - // Red Hat, CentOS, Fedora (provided by the ca-certificates package) - '/etc/pki/tls/certs/ca-bundle.crt', - // Ubuntu, Debian (provided by the ca-certificates package) - '/etc/ssl/certs/ca-certificates.crt', - // FreeBSD (provided by the ca_root_nss package) - '/usr/local/share/certs/ca-root-nss.crt', - // SLES 12 (provided by the ca-certificates package) - '/var/lib/ca-certificates/ca-bundle.pem', - // OS X provided by homebrew (using the default path) - '/usr/local/etc/openssl/cert.pem', - // Google app engine - '/etc/ca-certificates.crt', - // Windows? - 'C:\\windows\\system32\\curl-ca-bundle.crt', - 'C:\\windows\\curl-ca-bundle.crt', - ]; - - if ($cached) { - return $cached; - } - - if ($ca = ini_get('openssl.cafile')) { - return $cached = $ca; - } - - if ($ca = ini_get('curl.cainfo')) { - return $cached = $ca; - } - - foreach ($cafiles as $filename) { - if (file_exists($filename)) { - return $cached = $filename; - } - } - - throw new \RuntimeException( - <<< EOT -No system CA bundle could be found in any of the the common system locations. -PHP versions earlier than 5.6 are not properly configured to use the system's -CA bundle by default. In order to verify peer certificates, you will need to -supply the path on disk to a certificate bundle to the 'verify' request -option: http://docs.guzzlephp.org/en/latest/clients.html#verify. If you do not -need a specific certificate bundle, then Mozilla provides a commonly used CA -bundle which can be downloaded here (provided by the maintainer of cURL): -https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt. Once -you have a CA bundle available on disk, you can set the 'openssl.cafile' PHP -ini setting to point to the path to the file, allowing you to omit the 'verify' -request option. See http://curl.haxx.se/docs/sslcerts.html for more -information. -EOT - ); -} - -/** - * Creates an associative array of lowercase header names to the actual - * header casing. - * - * @param array $headers - * - * @return array - */ -function normalize_header_keys(array $headers) -{ - $result = []; - foreach (array_keys($headers) as $key) { - $result[strtolower($key)] = $key; - } - - return $result; -} - -/** - * Returns true if the provided host matches any of the no proxy areas. - * - * This method will strip a port from the host if it is present. Each pattern - * can be matched with an exact match (e.g., "foo.com" == "foo.com") or a - * partial match: (e.g., "foo.com" == "baz.foo.com" and ".foo.com" == - * "baz.foo.com", but ".foo.com" != "foo.com"). - * - * Areas are matched in the following cases: - * 1. "*" (without quotes) always matches any hosts. - * 2. An exact match. - * 3. The area starts with "." and the area is the last part of the host. e.g. - * '.mit.edu' will match any host that ends with '.mit.edu'. - * - * @param string $host Host to check against the patterns. - * @param array $noProxyArray An array of host patterns. - * - * @return bool - */ -function is_host_in_noproxy($host, array $noProxyArray) -{ - if (strlen($host) === 0) { - throw new \InvalidArgumentException('Empty host provided'); - } - - // Strip port if present. - if (strpos($host, ':')) { - $host = explode($host, ':', 2)[0]; - } - - foreach ($noProxyArray as $area) { - // Always match on wildcards. - if ($area === '*') { - return true; - } elseif (empty($area)) { - // Don't match on empty values. - continue; - } elseif ($area === $host) { - // Exact matches. - return true; - } else { - // Special match if the area when prefixed with ".". Remove any - // existing leading "." and add a new leading ".". - $area = '.' . ltrim($area, '.'); - if (substr($host, -(strlen($area))) === $area) { - return true; - } - } - } - - return false; -} - -/** - * Wrapper for json_decode that throws when an error occurs. - * - * @param string $json JSON data to parse - * @param bool $assoc When true, returned objects will be converted - * into associative arrays. - * @param int $depth User specified recursion depth. - * @param int $options Bitmask of JSON decode options. - * - * @return mixed - * @throws Exception\InvalidArgumentException if the JSON cannot be decoded. - * @link http://www.php.net/manual/en/function.json-decode.php - */ -function json_decode($json, $assoc = false, $depth = 512, $options = 0) -{ - $data = \json_decode($json, $assoc, $depth, $options); - if (JSON_ERROR_NONE !== json_last_error()) { - throw new Exception\InvalidArgumentException( - 'json_decode error: ' . json_last_error_msg() - ); - } - - return $data; -} - -/** - * Wrapper for JSON encoding that throws when an error occurs. - * - * @param mixed $value The value being encoded - * @param int $options JSON encode option bitmask - * @param int $depth Set the maximum depth. Must be greater than zero. - * - * @return string - * @throws Exception\InvalidArgumentException if the JSON cannot be encoded. - * @link http://www.php.net/manual/en/function.json-encode.php - */ -function json_encode($value, $options = 0, $depth = 512) -{ - $json = \json_encode($value, $options, $depth); - if (JSON_ERROR_NONE !== json_last_error()) { - throw new Exception\InvalidArgumentException( - 'json_encode error: ' . json_last_error_msg() - ); - } - - return $json; -} diff --git a/vendor/guzzlehttp/guzzle/src/functions_include.php b/vendor/guzzlehttp/guzzle/src/functions_include.php deleted file mode 100644 index a93393a..0000000 --- a/vendor/guzzlehttp/guzzle/src/functions_include.php +++ /dev/null @@ -1,6 +0,0 @@ - - -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/guzzlehttp/promises/Makefile b/vendor/guzzlehttp/promises/Makefile deleted file mode 100644 index 8d5b3ef..0000000 --- a/vendor/guzzlehttp/promises/Makefile +++ /dev/null @@ -1,13 +0,0 @@ -all: clean test - -test: - vendor/bin/phpunit - -coverage: - vendor/bin/phpunit --coverage-html=artifacts/coverage - -view-coverage: - open artifacts/coverage/index.html - -clean: - rm -rf artifacts/* diff --git a/vendor/guzzlehttp/promises/README.md b/vendor/guzzlehttp/promises/README.md deleted file mode 100644 index 7b607e2..0000000 --- a/vendor/guzzlehttp/promises/README.md +++ /dev/null @@ -1,504 +0,0 @@ -# Guzzle Promises - -[Promises/A+](https://promisesaplus.com/) implementation that handles promise -chaining and resolution iteratively, allowing for "infinite" promise chaining -while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/) -for a general introduction to promises. - -- [Features](#features) -- [Quick start](#quick-start) -- [Synchronous wait](#synchronous-wait) -- [Cancellation](#cancellation) -- [API](#api) - - [Promise](#promise) - - [FulfilledPromise](#fulfilledpromise) - - [RejectedPromise](#rejectedpromise) -- [Promise interop](#promise-interop) -- [Implementation notes](#implementation-notes) - - -# Features - -- [Promises/A+](https://promisesaplus.com/) implementation. -- Promise resolution and chaining is handled iteratively, allowing for - "infinite" promise chaining. -- Promises have a synchronous `wait` method. -- Promises can be cancelled. -- Works with any object that has a `then` function. -- C# style async/await coroutine promises using - `GuzzleHttp\Promise\coroutine()`. - - -# Quick start - -A *promise* represents the eventual result of an asynchronous operation. The -primary way of interacting with a promise is through its `then` method, which -registers callbacks to receive either a promise's eventual value or the reason -why the promise cannot be fulfilled. - - -## Callbacks - -Callbacks are registered with the `then` method by providing an optional -`$onFulfilled` followed by an optional `$onRejected` function. - - -```php -use GuzzleHttp\Promise\Promise; - -$promise = new Promise(); -$promise->then( - // $onFulfilled - function ($value) { - echo 'The promise was fulfilled.'; - }, - // $onRejected - function ($reason) { - echo 'The promise was rejected.'; - } -); -``` - -*Resolving* a promise means that you either fulfill a promise with a *value* or -reject a promise with a *reason*. Resolving a promises triggers callbacks -registered with the promises's `then` method. These callbacks are triggered -only once and in the order in which they were added. - - -## Resolving a promise - -Promises are fulfilled using the `resolve($value)` method. Resolving a promise -with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger -all of the onFulfilled callbacks (resolving a promise with a rejected promise -will reject the promise and trigger the `$onRejected` callbacks). - -```php -use GuzzleHttp\Promise\Promise; - -$promise = new Promise(); -$promise - ->then(function ($value) { - // Return a value and don't break the chain - return "Hello, " . $value; - }) - // This then is executed after the first then and receives the value - // returned from the first then. - ->then(function ($value) { - echo $value; - }); - -// Resolving the promise triggers the $onFulfilled callbacks and outputs -// "Hello, reader". -$promise->resolve('reader.'); -``` - - -## Promise forwarding - -Promises can be chained one after the other. Each then in the chain is a new -promise. The return value of a promise is what's forwarded to the next -promise in the chain. Returning a promise in a `then` callback will cause the -subsequent promises in the chain to only be fulfilled when the returned promise -has been fulfilled. The next promise in the chain will be invoked with the -resolved value of the promise. - -```php -use GuzzleHttp\Promise\Promise; - -$promise = new Promise(); -$nextPromise = new Promise(); - -$promise - ->then(function ($value) use ($nextPromise) { - echo $value; - return $nextPromise; - }) - ->then(function ($value) { - echo $value; - }); - -// Triggers the first callback and outputs "A" -$promise->resolve('A'); -// Triggers the second callback and outputs "B" -$nextPromise->resolve('B'); -``` - -## Promise rejection - -When a promise is rejected, the `$onRejected` callbacks are invoked with the -rejection reason. - -```php -use GuzzleHttp\Promise\Promise; - -$promise = new Promise(); -$promise->then(null, function ($reason) { - echo $reason; -}); - -$promise->reject('Error!'); -// Outputs "Error!" -``` - -## Rejection forwarding - -If an exception is thrown in an `$onRejected` callback, subsequent -`$onRejected` callbacks are invoked with the thrown exception as the reason. - -```php -use GuzzleHttp\Promise\Promise; - -$promise = new Promise(); -$promise->then(null, function ($reason) { - throw new \Exception($reason); -})->then(null, function ($reason) { - assert($reason->getMessage() === 'Error!'); -}); - -$promise->reject('Error!'); -``` - -You can also forward a rejection down the promise chain by returning a -`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or -`$onRejected` callback. - -```php -use GuzzleHttp\Promise\Promise; -use GuzzleHttp\Promise\RejectedPromise; - -$promise = new Promise(); -$promise->then(null, function ($reason) { - return new RejectedPromise($reason); -})->then(null, function ($reason) { - assert($reason === 'Error!'); -}); - -$promise->reject('Error!'); -``` - -If an exception is not thrown in a `$onRejected` callback and the callback -does not return a rejected promise, downstream `$onFulfilled` callbacks are -invoked using the value returned from the `$onRejected` callback. - -```php -use GuzzleHttp\Promise\Promise; -use GuzzleHttp\Promise\RejectedPromise; - -$promise = new Promise(); -$promise - ->then(null, function ($reason) { - return "It's ok"; - }) - ->then(function ($value) { - assert($value === "It's ok"); - }); - -$promise->reject('Error!'); -``` - -# Synchronous wait - -You can synchronously force promises to complete using a promise's `wait` -method. When creating a promise, you can provide a wait function that is used -to synchronously force a promise to complete. When a wait function is invoked -it is expected to deliver a value to the promise or reject the promise. If the -wait function does not deliver a value, then an exception is thrown. The wait -function provided to a promise constructor is invoked when the `wait` function -of the promise is called. - -```php -$promise = new Promise(function () use (&$promise) { - $promise->resolve('foo'); -}); - -// Calling wait will return the value of the promise. -echo $promise->wait(); // outputs "foo" -``` - -If an exception is encountered while invoking the wait function of a promise, -the promise is rejected with the exception and the exception is thrown. - -```php -$promise = new Promise(function () use (&$promise) { - throw new \Exception('foo'); -}); - -$promise->wait(); // throws the exception. -``` - -Calling `wait` on a promise that has been fulfilled will not trigger the wait -function. It will simply return the previously resolved value. - -```php -$promise = new Promise(function () { die('this is not called!'); }); -$promise->resolve('foo'); -echo $promise->wait(); // outputs "foo" -``` - -Calling `wait` on a promise that has been rejected will throw an exception. If -the rejection reason is an instance of `\Exception` the reason is thrown. -Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason -can be obtained by calling the `getReason` method of the exception. - -```php -$promise = new Promise(); -$promise->reject('foo'); -$promise->wait(); -``` - -> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo' - - -## Unwrapping a promise - -When synchronously waiting on a promise, you are joining the state of the -promise into the current state of execution (i.e., return the value of the -promise if it was fulfilled or throw an exception if it was rejected). This is -called "unwrapping" the promise. Waiting on a promise will by default unwrap -the promise state. - -You can force a promise to resolve and *not* unwrap the state of the promise -by passing `false` to the first argument of the `wait` function: - -```php -$promise = new Promise(); -$promise->reject('foo'); -// This will not throw an exception. It simply ensures the promise has -// been resolved. -$promise->wait(false); -``` - -When unwrapping a promise, the resolved value of the promise will be waited -upon until the unwrapped value is not a promise. This means that if you resolve -promise A with a promise B and unwrap promise A, the value returned by the -wait function will be the value delivered to promise B. - -**Note**: when you do not unwrap the promise, no value is returned. - - -# Cancellation - -You can cancel a promise that has not yet been fulfilled using the `cancel()` -method of a promise. When creating a promise you can provide an optional -cancel function that when invoked cancels the action of computing a resolution -of the promise. - - -# API - - -## Promise - -When creating a promise object, you can provide an optional `$waitFn` and -`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is -expected to resolve the promise. `$cancelFn` is a function with no arguments -that is expected to cancel the computation of a promise. It is invoked when the -`cancel()` method of a promise is called. - -```php -use GuzzleHttp\Promise\Promise; - -$promise = new Promise( - function () use (&$promise) { - $promise->resolve('waited'); - }, - function () { - // do something that will cancel the promise computation (e.g., close - // a socket, cancel a database query, etc...) - } -); - -assert('waited' === $promise->wait()); -``` - -A promise has the following methods: - -- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface` - - Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. - -- `otherwise(callable $onRejected) : PromiseInterface` - - Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. - -- `wait($unwrap = true) : mixed` - - Synchronously waits on the promise to complete. - - `$unwrap` controls whether or not the value of the promise is returned for a - fulfilled promise or if an exception is thrown if the promise is rejected. - This is set to `true` by default. - -- `cancel()` - - Attempts to cancel the promise if possible. The promise being cancelled and - the parent most ancestor that has not yet been resolved will also be - cancelled. Any promises waiting on the cancelled promise to resolve will also - be cancelled. - -- `getState() : string` - - Returns the state of the promise. One of `pending`, `fulfilled`, or - `rejected`. - -- `resolve($value)` - - Fulfills the promise with the given `$value`. - -- `reject($reason)` - - Rejects the promise with the given `$reason`. - - -## FulfilledPromise - -A fulfilled promise can be created to represent a promise that has been -fulfilled. - -```php -use GuzzleHttp\Promise\FulfilledPromise; - -$promise = new FulfilledPromise('value'); - -// Fulfilled callbacks are immediately invoked. -$promise->then(function ($value) { - echo $value; -}); -``` - - -## RejectedPromise - -A rejected promise can be created to represent a promise that has been -rejected. - -```php -use GuzzleHttp\Promise\RejectedPromise; - -$promise = new RejectedPromise('Error'); - -// Rejected callbacks are immediately invoked. -$promise->then(null, function ($reason) { - echo $reason; -}); -``` - - -# Promise interop - -This library works with foreign promises that have a `then` method. This means -you can use Guzzle promises with [React promises](https://github.com/reactphp/promise) -for example. When a foreign promise is returned inside of a then method -callback, promise resolution will occur recursively. - -```php -// Create a React promise -$deferred = new React\Promise\Deferred(); -$reactPromise = $deferred->promise(); - -// Create a Guzzle promise that is fulfilled with a React promise. -$guzzlePromise = new \GuzzleHttp\Promise\Promise(); -$guzzlePromise->then(function ($value) use ($reactPromise) { - // Do something something with the value... - // Return the React promise - return $reactPromise; -}); -``` - -Please note that wait and cancel chaining is no longer possible when forwarding -a foreign promise. You will need to wrap a third-party promise with a Guzzle -promise in order to utilize wait and cancel functions with foreign promises. - - -## Event Loop Integration - -In order to keep the stack size constant, Guzzle promises are resolved -asynchronously using a task queue. When waiting on promises synchronously, the -task queue will be automatically run to ensure that the blocking promise and -any forwarded promises are resolved. When using promises asynchronously in an -event loop, you will need to run the task queue on each tick of the loop. If -you do not run the task queue, then promises will not be resolved. - -You can run the task queue using the `run()` method of the global task queue -instance. - -```php -// Get the global task queue -$queue = \GuzzleHttp\Promise\queue(); -$queue->run(); -``` - -For example, you could use Guzzle promises with React using a periodic timer: - -```php -$loop = React\EventLoop\Factory::create(); -$loop->addPeriodicTimer(0, [$queue, 'run']); -``` - -*TODO*: Perhaps adding a `futureTick()` on each tick would be faster? - - -# Implementation notes - - -## Promise resolution and chaining is handled iteratively - -By shuffling pending handlers from one owner to another, promises are -resolved iteratively, allowing for "infinite" then chaining. - -```php -then(function ($v) { - // The stack size remains constant (a good thing) - echo xdebug_get_stack_depth() . ', '; - return $v + 1; - }); -} - -$parent->resolve(0); -var_dump($p->wait()); // int(1000) - -``` - -When a promise is fulfilled or rejected with a non-promise value, the promise -then takes ownership of the handlers of each child promise and delivers values -down the chain without using recursion. - -When a promise is resolved with another promise, the original promise transfers -all of its pending handlers to the new promise. When the new promise is -eventually resolved, all of the pending handlers are delivered the forwarded -value. - - -## A promise is the deferred. - -Some promise libraries implement promises using a deferred object to represent -a computation and a promise object to represent the delivery of the result of -the computation. This is a nice separation of computation and delivery because -consumers of the promise cannot modify the value that will be eventually -delivered. - -One side effect of being able to implement promise resolution and chaining -iteratively is that you need to be able for one promise to reach into the state -of another promise to shuffle around ownership of handlers. In order to achieve -this without making the handlers of a promise publicly mutable, a promise is -also the deferred value, allowing promises of the same parent class to reach -into and modify the private properties of promises of the same type. While this -does allow consumers of the value to modify the resolution or rejection of the -deferred, it is a small price to pay for keeping the stack size constant. - -```php -$promise = new Promise(); -$promise->then(function ($value) { echo $value; }); -// The promise is the deferred value, so you can deliver a value to it. -$promise->resolve('foo'); -// prints "foo" -``` diff --git a/vendor/guzzlehttp/promises/composer.json b/vendor/guzzlehttp/promises/composer.json deleted file mode 100644 index ec41a61..0000000 --- a/vendor/guzzlehttp/promises/composer.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "guzzlehttp/promises", - "description": "Guzzle promises library", - "keywords": ["promise"], - "license": "MIT", - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - } - ], - "require": { - "php": ">=5.5.0" - }, - "require-dev": { - "phpunit/phpunit": "^4.0" - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\Promise\\": "src/" - }, - "files": ["src/functions_include.php"] - }, - "scripts": { - "test": "vendor/bin/phpunit", - "test-ci": "vendor/bin/phpunit --coverage-text" - }, - "extra": { - "branch-alias": { - "dev-master": "1.4-dev" - } - } -} diff --git a/vendor/guzzlehttp/promises/src/AggregateException.php b/vendor/guzzlehttp/promises/src/AggregateException.php deleted file mode 100644 index 6a5690c..0000000 --- a/vendor/guzzlehttp/promises/src/AggregateException.php +++ /dev/null @@ -1,16 +0,0 @@ -then(function ($v) { echo $v; }); - * - * @param callable $generatorFn Generator function to wrap into a promise. - * - * @return Promise - * @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration - */ -final class Coroutine implements PromiseInterface -{ - /** - * @var PromiseInterface|null - */ - private $currentPromise; - - /** - * @var Generator - */ - private $generator; - - /** - * @var Promise - */ - private $result; - - public function __construct(callable $generatorFn) - { - $this->generator = $generatorFn(); - $this->result = new Promise(function () { - while (isset($this->currentPromise)) { - $this->currentPromise->wait(); - } - }); - $this->nextCoroutine($this->generator->current()); - } - - public function then( - callable $onFulfilled = null, - callable $onRejected = null - ) { - return $this->result->then($onFulfilled, $onRejected); - } - - public function otherwise(callable $onRejected) - { - return $this->result->otherwise($onRejected); - } - - public function wait($unwrap = true) - { - return $this->result->wait($unwrap); - } - - public function getState() - { - return $this->result->getState(); - } - - public function resolve($value) - { - $this->result->resolve($value); - } - - public function reject($reason) - { - $this->result->reject($reason); - } - - public function cancel() - { - $this->currentPromise->cancel(); - $this->result->cancel(); - } - - private function nextCoroutine($yielded) - { - $this->currentPromise = promise_for($yielded) - ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); - } - - /** - * @internal - */ - public function _handleSuccess($value) - { - unset($this->currentPromise); - try { - $next = $this->generator->send($value); - if ($this->generator->valid()) { - $this->nextCoroutine($next); - } else { - $this->result->resolve($value); - } - } catch (Exception $exception) { - $this->result->reject($exception); - } catch (Throwable $throwable) { - $this->result->reject($throwable); - } - } - - /** - * @internal - */ - public function _handleFailure($reason) - { - unset($this->currentPromise); - try { - $nextYield = $this->generator->throw(exception_for($reason)); - // The throw was caught, so keep iterating on the coroutine - $this->nextCoroutine($nextYield); - } catch (Exception $exception) { - $this->result->reject($exception); - } catch (Throwable $throwable) { - $this->result->reject($throwable); - } - } -} diff --git a/vendor/guzzlehttp/promises/src/EachPromise.php b/vendor/guzzlehttp/promises/src/EachPromise.php deleted file mode 100644 index d0ddf60..0000000 --- a/vendor/guzzlehttp/promises/src/EachPromise.php +++ /dev/null @@ -1,229 +0,0 @@ -iterable = iter_for($iterable); - - if (isset($config['concurrency'])) { - $this->concurrency = $config['concurrency']; - } - - if (isset($config['fulfilled'])) { - $this->onFulfilled = $config['fulfilled']; - } - - if (isset($config['rejected'])) { - $this->onRejected = $config['rejected']; - } - } - - public function promise() - { - if ($this->aggregate) { - return $this->aggregate; - } - - try { - $this->createPromise(); - $this->iterable->rewind(); - $this->refillPending(); - } catch (\Throwable $e) { - $this->aggregate->reject($e); - } catch (\Exception $e) { - $this->aggregate->reject($e); - } - - return $this->aggregate; - } - - private function createPromise() - { - $this->mutex = false; - $this->aggregate = new Promise(function () { - reset($this->pending); - if (empty($this->pending) && !$this->iterable->valid()) { - $this->aggregate->resolve(null); - return; - } - - // Consume a potentially fluctuating list of promises while - // ensuring that indexes are maintained (precluding array_shift). - while ($promise = current($this->pending)) { - next($this->pending); - $promise->wait(); - if ($this->aggregate->getState() !== PromiseInterface::PENDING) { - return; - } - } - }); - - // Clear the references when the promise is resolved. - $clearFn = function () { - $this->iterable = $this->concurrency = $this->pending = null; - $this->onFulfilled = $this->onRejected = null; - }; - - $this->aggregate->then($clearFn, $clearFn); - } - - private function refillPending() - { - if (!$this->concurrency) { - // Add all pending promises. - while ($this->addPending() && $this->advanceIterator()); - return; - } - - // Add only up to N pending promises. - $concurrency = is_callable($this->concurrency) - ? call_user_func($this->concurrency, count($this->pending)) - : $this->concurrency; - $concurrency = max($concurrency - count($this->pending), 0); - // Concurrency may be set to 0 to disallow new promises. - if (!$concurrency) { - return; - } - // Add the first pending promise. - $this->addPending(); - // Note this is special handling for concurrency=1 so that we do - // not advance the iterator after adding the first promise. This - // helps work around issues with generators that might not have the - // next value to yield until promise callbacks are called. - while (--$concurrency - && $this->advanceIterator() - && $this->addPending()); - } - - private function addPending() - { - if (!$this->iterable || !$this->iterable->valid()) { - return false; - } - - $promise = promise_for($this->iterable->current()); - $idx = $this->iterable->key(); - - $this->pending[$idx] = $promise->then( - function ($value) use ($idx) { - if ($this->onFulfilled) { - call_user_func( - $this->onFulfilled, $value, $idx, $this->aggregate - ); - } - $this->step($idx); - }, - function ($reason) use ($idx) { - if ($this->onRejected) { - call_user_func( - $this->onRejected, $reason, $idx, $this->aggregate - ); - } - $this->step($idx); - } - ); - - return true; - } - - private function advanceIterator() - { - // Place a lock on the iterator so that we ensure to not recurse, - // preventing fatal generator errors. - if ($this->mutex) { - return false; - } - - $this->mutex = true; - - try { - $this->iterable->next(); - $this->mutex = false; - return true; - } catch (\Throwable $e) { - $this->aggregate->reject($e); - $this->mutex = false; - return false; - } catch (\Exception $e) { - $this->aggregate->reject($e); - $this->mutex = false; - return false; - } - } - - private function step($idx) - { - // If the promise was already resolved, then ignore this step. - if ($this->aggregate->getState() !== PromiseInterface::PENDING) { - return; - } - - unset($this->pending[$idx]); - - // Only refill pending promises if we are not locked, preventing the - // EachPromise to recursively invoke the provided iterator, which - // cause a fatal error: "Cannot resume an already running generator" - if ($this->advanceIterator() && !$this->checkIfFinished()) { - // Add more pending promises if possible. - $this->refillPending(); - } - } - - private function checkIfFinished() - { - if (!$this->pending && !$this->iterable->valid()) { - // Resolve the promise if there's nothing left to do. - $this->aggregate->resolve(null); - return true; - } - - return false; - } -} diff --git a/vendor/guzzlehttp/promises/src/FulfilledPromise.php b/vendor/guzzlehttp/promises/src/FulfilledPromise.php deleted file mode 100644 index dbbeeb9..0000000 --- a/vendor/guzzlehttp/promises/src/FulfilledPromise.php +++ /dev/null @@ -1,82 +0,0 @@ -value = $value; - } - - public function then( - callable $onFulfilled = null, - callable $onRejected = null - ) { - // Return itself if there is no onFulfilled function. - if (!$onFulfilled) { - return $this; - } - - $queue = queue(); - $p = new Promise([$queue, 'run']); - $value = $this->value; - $queue->add(static function () use ($p, $value, $onFulfilled) { - if ($p->getState() === self::PENDING) { - try { - $p->resolve($onFulfilled($value)); - } catch (\Throwable $e) { - $p->reject($e); - } catch (\Exception $e) { - $p->reject($e); - } - } - }); - - return $p; - } - - public function otherwise(callable $onRejected) - { - return $this->then(null, $onRejected); - } - - public function wait($unwrap = true, $defaultDelivery = null) - { - return $unwrap ? $this->value : null; - } - - public function getState() - { - return self::FULFILLED; - } - - public function resolve($value) - { - if ($value !== $this->value) { - throw new \LogicException("Cannot resolve a fulfilled promise"); - } - } - - public function reject($reason) - { - throw new \LogicException("Cannot reject a fulfilled promise"); - } - - public function cancel() - { - // pass - } -} diff --git a/vendor/guzzlehttp/promises/src/Promise.php b/vendor/guzzlehttp/promises/src/Promise.php deleted file mode 100644 index 844ada0..0000000 --- a/vendor/guzzlehttp/promises/src/Promise.php +++ /dev/null @@ -1,280 +0,0 @@ -waitFn = $waitFn; - $this->cancelFn = $cancelFn; - } - - public function then( - callable $onFulfilled = null, - callable $onRejected = null - ) { - if ($this->state === self::PENDING) { - $p = new Promise(null, [$this, 'cancel']); - $this->handlers[] = [$p, $onFulfilled, $onRejected]; - $p->waitList = $this->waitList; - $p->waitList[] = $this; - return $p; - } - - // Return a fulfilled promise and immediately invoke any callbacks. - if ($this->state === self::FULFILLED) { - return $onFulfilled - ? promise_for($this->result)->then($onFulfilled) - : promise_for($this->result); - } - - // It's either cancelled or rejected, so return a rejected promise - // and immediately invoke any callbacks. - $rejection = rejection_for($this->result); - return $onRejected ? $rejection->then(null, $onRejected) : $rejection; - } - - public function otherwise(callable $onRejected) - { - return $this->then(null, $onRejected); - } - - public function wait($unwrap = true) - { - $this->waitIfPending(); - - $inner = $this->result instanceof PromiseInterface - ? $this->result->wait($unwrap) - : $this->result; - - if ($unwrap) { - if ($this->result instanceof PromiseInterface - || $this->state === self::FULFILLED - ) { - return $inner; - } else { - // It's rejected so "unwrap" and throw an exception. - throw exception_for($inner); - } - } - } - - public function getState() - { - return $this->state; - } - - public function cancel() - { - if ($this->state !== self::PENDING) { - return; - } - - $this->waitFn = $this->waitList = null; - - if ($this->cancelFn) { - $fn = $this->cancelFn; - $this->cancelFn = null; - try { - $fn(); - } catch (\Throwable $e) { - $this->reject($e); - } catch (\Exception $e) { - $this->reject($e); - } - } - - // Reject the promise only if it wasn't rejected in a then callback. - if ($this->state === self::PENDING) { - $this->reject(new CancellationException('Promise has been cancelled')); - } - } - - public function resolve($value) - { - $this->settle(self::FULFILLED, $value); - } - - public function reject($reason) - { - $this->settle(self::REJECTED, $reason); - } - - private function settle($state, $value) - { - if ($this->state !== self::PENDING) { - // Ignore calls with the same resolution. - if ($state === $this->state && $value === $this->result) { - return; - } - throw $this->state === $state - ? new \LogicException("The promise is already {$state}.") - : new \LogicException("Cannot change a {$this->state} promise to {$state}"); - } - - if ($value === $this) { - throw new \LogicException('Cannot fulfill or reject a promise with itself'); - } - - // Clear out the state of the promise but stash the handlers. - $this->state = $state; - $this->result = $value; - $handlers = $this->handlers; - $this->handlers = null; - $this->waitList = $this->waitFn = null; - $this->cancelFn = null; - - if (!$handlers) { - return; - } - - // If the value was not a settled promise or a thenable, then resolve - // it in the task queue using the correct ID. - if (!method_exists($value, 'then')) { - $id = $state === self::FULFILLED ? 1 : 2; - // It's a success, so resolve the handlers in the queue. - queue()->add(static function () use ($id, $value, $handlers) { - foreach ($handlers as $handler) { - self::callHandler($id, $value, $handler); - } - }); - } elseif ($value instanceof Promise - && $value->getState() === self::PENDING - ) { - // We can just merge our handlers onto the next promise. - $value->handlers = array_merge($value->handlers, $handlers); - } else { - // Resolve the handlers when the forwarded promise is resolved. - $value->then( - static function ($value) use ($handlers) { - foreach ($handlers as $handler) { - self::callHandler(1, $value, $handler); - } - }, - static function ($reason) use ($handlers) { - foreach ($handlers as $handler) { - self::callHandler(2, $reason, $handler); - } - } - ); - } - } - - /** - * Call a stack of handlers using a specific callback index and value. - * - * @param int $index 1 (resolve) or 2 (reject). - * @param mixed $value Value to pass to the callback. - * @param array $handler Array of handler data (promise and callbacks). - * - * @return array Returns the next group to resolve. - */ - private static function callHandler($index, $value, array $handler) - { - /** @var PromiseInterface $promise */ - $promise = $handler[0]; - - // The promise may have been cancelled or resolved before placing - // this thunk in the queue. - if ($promise->getState() !== self::PENDING) { - return; - } - - try { - if (isset($handler[$index])) { - $promise->resolve($handler[$index]($value)); - } elseif ($index === 1) { - // Forward resolution values as-is. - $promise->resolve($value); - } else { - // Forward rejections down the chain. - $promise->reject($value); - } - } catch (\Throwable $reason) { - $promise->reject($reason); - } catch (\Exception $reason) { - $promise->reject($reason); - } - } - - private function waitIfPending() - { - if ($this->state !== self::PENDING) { - return; - } elseif ($this->waitFn) { - $this->invokeWaitFn(); - } elseif ($this->waitList) { - $this->invokeWaitList(); - } else { - // If there's not wait function, then reject the promise. - $this->reject('Cannot wait on a promise that has ' - . 'no internal wait function. You must provide a wait ' - . 'function when constructing the promise to be able to ' - . 'wait on a promise.'); - } - - queue()->run(); - - if ($this->state === self::PENDING) { - $this->reject('Invoking the wait callback did not resolve the promise'); - } - } - - private function invokeWaitFn() - { - try { - $wfn = $this->waitFn; - $this->waitFn = null; - $wfn(true); - } catch (\Exception $reason) { - if ($this->state === self::PENDING) { - // The promise has not been resolved yet, so reject the promise - // with the exception. - $this->reject($reason); - } else { - // The promise was already resolved, so there's a problem in - // the application. - throw $reason; - } - } - } - - private function invokeWaitList() - { - $waitList = $this->waitList; - $this->waitList = null; - - foreach ($waitList as $result) { - while (true) { - $result->waitIfPending(); - - if ($result->result instanceof Promise) { - $result = $result->result; - } else { - if ($result->result instanceof PromiseInterface) { - $result->result->wait(false); - } - break; - } - } - } - } -} diff --git a/vendor/guzzlehttp/promises/src/PromiseInterface.php b/vendor/guzzlehttp/promises/src/PromiseInterface.php deleted file mode 100644 index 8f5f4b9..0000000 --- a/vendor/guzzlehttp/promises/src/PromiseInterface.php +++ /dev/null @@ -1,93 +0,0 @@ -reason = $reason; - } - - public function then( - callable $onFulfilled = null, - callable $onRejected = null - ) { - // If there's no onRejected callback then just return self. - if (!$onRejected) { - return $this; - } - - $queue = queue(); - $reason = $this->reason; - $p = new Promise([$queue, 'run']); - $queue->add(static function () use ($p, $reason, $onRejected) { - if ($p->getState() === self::PENDING) { - try { - // Return a resolved promise if onRejected does not throw. - $p->resolve($onRejected($reason)); - } catch (\Throwable $e) { - // onRejected threw, so return a rejected promise. - $p->reject($e); - } catch (\Exception $e) { - // onRejected threw, so return a rejected promise. - $p->reject($e); - } - } - }); - - return $p; - } - - public function otherwise(callable $onRejected) - { - return $this->then(null, $onRejected); - } - - public function wait($unwrap = true, $defaultDelivery = null) - { - if ($unwrap) { - throw exception_for($this->reason); - } - } - - public function getState() - { - return self::REJECTED; - } - - public function resolve($value) - { - throw new \LogicException("Cannot resolve a rejected promise"); - } - - public function reject($reason) - { - if ($reason !== $this->reason) { - throw new \LogicException("Cannot reject a rejected promise"); - } - } - - public function cancel() - { - // pass - } -} diff --git a/vendor/guzzlehttp/promises/src/RejectionException.php b/vendor/guzzlehttp/promises/src/RejectionException.php deleted file mode 100644 index 07c1136..0000000 --- a/vendor/guzzlehttp/promises/src/RejectionException.php +++ /dev/null @@ -1,47 +0,0 @@ -reason = $reason; - - $message = 'The promise was rejected'; - - if ($description) { - $message .= ' with reason: ' . $description; - } elseif (is_string($reason) - || (is_object($reason) && method_exists($reason, '__toString')) - ) { - $message .= ' with reason: ' . $this->reason; - } elseif ($reason instanceof \JsonSerializable) { - $message .= ' with reason: ' - . json_encode($this->reason, JSON_PRETTY_PRINT); - } - - parent::__construct($message); - } - - /** - * Returns the rejection reason. - * - * @return mixed - */ - public function getReason() - { - return $this->reason; - } -} diff --git a/vendor/guzzlehttp/promises/src/TaskQueue.php b/vendor/guzzlehttp/promises/src/TaskQueue.php deleted file mode 100644 index 6e8a2a0..0000000 --- a/vendor/guzzlehttp/promises/src/TaskQueue.php +++ /dev/null @@ -1,66 +0,0 @@ -run(); - */ -class TaskQueue implements TaskQueueInterface -{ - private $enableShutdown = true; - private $queue = []; - - public function __construct($withShutdown = true) - { - if ($withShutdown) { - register_shutdown_function(function () { - if ($this->enableShutdown) { - // Only run the tasks if an E_ERROR didn't occur. - $err = error_get_last(); - if (!$err || ($err['type'] ^ E_ERROR)) { - $this->run(); - } - } - }); - } - } - - public function isEmpty() - { - return !$this->queue; - } - - public function add(callable $task) - { - $this->queue[] = $task; - } - - public function run() - { - /** @var callable $task */ - while ($task = array_shift($this->queue)) { - $task(); - } - } - - /** - * The task queue will be run and exhausted by default when the process - * exits IFF the exit is not the result of a PHP E_ERROR error. - * - * You can disable running the automatic shutdown of the queue by calling - * this function. If you disable the task queue shutdown process, then you - * MUST either run the task queue (as a result of running your event loop - * or manually using the run() method) or wait on each outstanding promise. - * - * Note: This shutdown will occur before any destructors are triggered. - */ - public function disableShutdown() - { - $this->enableShutdown = false; - } -} diff --git a/vendor/guzzlehttp/promises/src/TaskQueueInterface.php b/vendor/guzzlehttp/promises/src/TaskQueueInterface.php deleted file mode 100644 index ac8306e..0000000 --- a/vendor/guzzlehttp/promises/src/TaskQueueInterface.php +++ /dev/null @@ -1,25 +0,0 @@ - - * while ($eventLoop->isRunning()) { - * GuzzleHttp\Promise\queue()->run(); - * } - * - * - * @param TaskQueueInterface $assign Optionally specify a new queue instance. - * - * @return TaskQueueInterface - */ -function queue(TaskQueueInterface $assign = null) -{ - static $queue; - - if ($assign) { - $queue = $assign; - } elseif (!$queue) { - $queue = new TaskQueue(); - } - - return $queue; -} - -/** - * Adds a function to run in the task queue when it is next `run()` and returns - * a promise that is fulfilled or rejected with the result. - * - * @param callable $task Task function to run. - * - * @return PromiseInterface - */ -function task(callable $task) -{ - $queue = queue(); - $promise = new Promise([$queue, 'run']); - $queue->add(function () use ($task, $promise) { - try { - $promise->resolve($task()); - } catch (\Throwable $e) { - $promise->reject($e); - } catch (\Exception $e) { - $promise->reject($e); - } - }); - - return $promise; -} - -/** - * Creates a promise for a value if the value is not a promise. - * - * @param mixed $value Promise or value. - * - * @return PromiseInterface - */ -function promise_for($value) -{ - if ($value instanceof PromiseInterface) { - return $value; - } - - // Return a Guzzle promise that shadows the given promise. - if (method_exists($value, 'then')) { - $wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null; - $cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null; - $promise = new Promise($wfn, $cfn); - $value->then([$promise, 'resolve'], [$promise, 'reject']); - return $promise; - } - - return new FulfilledPromise($value); -} - -/** - * Creates a rejected promise for a reason if the reason is not a promise. If - * the provided reason is a promise, then it is returned as-is. - * - * @param mixed $reason Promise or reason. - * - * @return PromiseInterface - */ -function rejection_for($reason) -{ - if ($reason instanceof PromiseInterface) { - return $reason; - } - - return new RejectedPromise($reason); -} - -/** - * Create an exception for a rejected promise value. - * - * @param mixed $reason - * - * @return \Exception|\Throwable - */ -function exception_for($reason) -{ - return $reason instanceof \Exception || $reason instanceof \Throwable - ? $reason - : new RejectionException($reason); -} - -/** - * Returns an iterator for the given value. - * - * @param mixed $value - * - * @return \Iterator - */ -function iter_for($value) -{ - if ($value instanceof \Iterator) { - return $value; - } elseif (is_array($value)) { - return new \ArrayIterator($value); - } else { - return new \ArrayIterator([$value]); - } -} - -/** - * Synchronously waits on a promise to resolve and returns an inspection state - * array. - * - * Returns a state associative array containing a "state" key mapping to a - * valid promise state. If the state of the promise is "fulfilled", the array - * will contain a "value" key mapping to the fulfilled value of the promise. If - * the promise is rejected, the array will contain a "reason" key mapping to - * the rejection reason of the promise. - * - * @param PromiseInterface $promise Promise or value. - * - * @return array - */ -function inspect(PromiseInterface $promise) -{ - try { - return [ - 'state' => PromiseInterface::FULFILLED, - 'value' => $promise->wait() - ]; - } catch (RejectionException $e) { - return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()]; - } catch (\Throwable $e) { - return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; - } catch (\Exception $e) { - return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; - } -} - -/** - * Waits on all of the provided promises, but does not unwrap rejected promises - * as thrown exception. - * - * Returns an array of inspection state arrays. - * - * @param PromiseInterface[] $promises Traversable of promises to wait upon. - * - * @return array - * @see GuzzleHttp\Promise\inspect for the inspection state array format. - */ -function inspect_all($promises) -{ - $results = []; - foreach ($promises as $key => $promise) { - $results[$key] = inspect($promise); - } - - return $results; -} - -/** - * Waits on all of the provided promises and returns the fulfilled values. - * - * Returns an array that contains the value of each promise (in the same order - * the promises were provided). An exception is thrown if any of the promises - * are rejected. - * - * @param mixed $promises Iterable of PromiseInterface objects to wait on. - * - * @return array - * @throws \Exception on error - * @throws \Throwable on error in PHP >=7 - */ -function unwrap($promises) -{ - $results = []; - foreach ($promises as $key => $promise) { - $results[$key] = $promise->wait(); - } - - return $results; -} - -/** - * Given an array of promises, return a promise that is fulfilled when all the - * items in the array are fulfilled. - * - * The promise's fulfillment value is an array with fulfillment values at - * respective positions to the original array. If any promise in the array - * rejects, the returned promise is rejected with the rejection reason. - * - * @param mixed $promises Promises or values. - * - * @return PromiseInterface - */ -function all($promises) -{ - $results = []; - return each( - $promises, - function ($value, $idx) use (&$results) { - $results[$idx] = $value; - }, - function ($reason, $idx, Promise $aggregate) { - $aggregate->reject($reason); - } - )->then(function () use (&$results) { - ksort($results); - return $results; - }); -} - -/** - * Initiate a competitive race between multiple promises or values (values will - * become immediately fulfilled promises). - * - * When count amount of promises have been fulfilled, the returned promise is - * fulfilled with an array that contains the fulfillment values of the winners - * in order of resolution. - * - * This prommise is rejected with a {@see GuzzleHttp\Promise\AggregateException} - * if the number of fulfilled promises is less than the desired $count. - * - * @param int $count Total number of promises. - * @param mixed $promises Promises or values. - * - * @return PromiseInterface - */ -function some($count, $promises) -{ - $results = []; - $rejections = []; - - return each( - $promises, - function ($value, $idx, PromiseInterface $p) use (&$results, $count) { - if ($p->getState() !== PromiseInterface::PENDING) { - return; - } - $results[$idx] = $value; - if (count($results) >= $count) { - $p->resolve(null); - } - }, - function ($reason) use (&$rejections) { - $rejections[] = $reason; - } - )->then( - function () use (&$results, &$rejections, $count) { - if (count($results) !== $count) { - throw new AggregateException( - 'Not enough promises to fulfill count', - $rejections - ); - } - ksort($results); - return array_values($results); - } - ); -} - -/** - * Like some(), with 1 as count. However, if the promise fulfills, the - * fulfillment value is not an array of 1 but the value directly. - * - * @param mixed $promises Promises or values. - * - * @return PromiseInterface - */ -function any($promises) -{ - return some(1, $promises)->then(function ($values) { return $values[0]; }); -} - -/** - * Returns a promise that is fulfilled when all of the provided promises have - * been fulfilled or rejected. - * - * The returned promise is fulfilled with an array of inspection state arrays. - * - * @param mixed $promises Promises or values. - * - * @return PromiseInterface - * @see GuzzleHttp\Promise\inspect for the inspection state array format. - */ -function settle($promises) -{ - $results = []; - - return each( - $promises, - function ($value, $idx) use (&$results) { - $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; - }, - function ($reason, $idx) use (&$results) { - $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; - } - )->then(function () use (&$results) { - ksort($results); - return $results; - }); -} - -/** - * Given an iterator that yields promises or values, returns a promise that is - * fulfilled with a null value when the iterator has been consumed or the - * aggregate promise has been fulfilled or rejected. - * - * $onFulfilled is a function that accepts the fulfilled value, iterator - * index, and the aggregate promise. The callback can invoke any necessary side - * effects and choose to resolve or reject the aggregate promise if needed. - * - * $onRejected is a function that accepts the rejection reason, iterator - * index, and the aggregate promise. The callback can invoke any necessary side - * effects and choose to resolve or reject the aggregate promise if needed. - * - * @param mixed $iterable Iterator or array to iterate over. - * @param callable $onFulfilled - * @param callable $onRejected - * - * @return PromiseInterface - */ -function each( - $iterable, - callable $onFulfilled = null, - callable $onRejected = null -) { - return (new EachPromise($iterable, [ - 'fulfilled' => $onFulfilled, - 'rejected' => $onRejected - ]))->promise(); -} - -/** - * Like each, but only allows a certain number of outstanding promises at any - * given time. - * - * $concurrency may be an integer or a function that accepts the number of - * pending promises and returns a numeric concurrency limit value to allow for - * dynamic a concurrency size. - * - * @param mixed $iterable - * @param int|callable $concurrency - * @param callable $onFulfilled - * @param callable $onRejected - * - * @return PromiseInterface - */ -function each_limit( - $iterable, - $concurrency, - callable $onFulfilled = null, - callable $onRejected = null -) { - return (new EachPromise($iterable, [ - 'fulfilled' => $onFulfilled, - 'rejected' => $onRejected, - 'concurrency' => $concurrency - ]))->promise(); -} - -/** - * Like each_limit, but ensures that no promise in the given $iterable argument - * is rejected. If any promise is rejected, then the aggregate promise is - * rejected with the encountered rejection. - * - * @param mixed $iterable - * @param int|callable $concurrency - * @param callable $onFulfilled - * - * @return PromiseInterface - */ -function each_limit_all( - $iterable, - $concurrency, - callable $onFulfilled = null -) { - return each_limit( - $iterable, - $concurrency, - $onFulfilled, - function ($reason, $idx, PromiseInterface $aggregate) { - $aggregate->reject($reason); - } - ); -} - -/** - * Returns true if a promise is fulfilled. - * - * @param PromiseInterface $promise - * - * @return bool - */ -function is_fulfilled(PromiseInterface $promise) -{ - return $promise->getState() === PromiseInterface::FULFILLED; -} - -/** - * Returns true if a promise is rejected. - * - * @param PromiseInterface $promise - * - * @return bool - */ -function is_rejected(PromiseInterface $promise) -{ - return $promise->getState() === PromiseInterface::REJECTED; -} - -/** - * Returns true if a promise is fulfilled or rejected. - * - * @param PromiseInterface $promise - * - * @return bool - */ -function is_settled(PromiseInterface $promise) -{ - return $promise->getState() !== PromiseInterface::PENDING; -} - -/** - * @see Coroutine - * - * @param callable $generatorFn - * - * @return PromiseInterface - */ -function coroutine(callable $generatorFn) -{ - return new Coroutine($generatorFn); -} diff --git a/vendor/guzzlehttp/promises/src/functions_include.php b/vendor/guzzlehttp/promises/src/functions_include.php deleted file mode 100644 index 34cd171..0000000 --- a/vendor/guzzlehttp/promises/src/functions_include.php +++ /dev/null @@ -1,6 +0,0 @@ -withPath('foo')->withHost('example.com')` will throw an exception - because the path of a URI with an authority must start with a slash "/" or be empty - - `(new Uri())->withScheme('http')` will return `'http://localhost'` - -### Deprecated - -- `Uri::resolve` in favor of `UriResolver::resolve` -- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` - -### Fixed - -- `Stream::read` when length parameter <= 0. -- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. -- `ServerRequest::getUriFromGlobals` when `Host` header contains port. -- Compatibility of URIs with `file` scheme and empty host. - - -## [1.3.1] - 2016-06-25 - -### Fixed - -- `Uri::__toString` for network path references, e.g. `//example.org`. -- Missing lowercase normalization for host. -- Handling of URI components in case they are `'0'` in a lot of places, - e.g. as a user info password. -- `Uri::withAddedHeader` to correctly merge headers with different case. -- Trimming of header values in `Uri::withAddedHeader`. Header values may - be surrounded by whitespace which should be ignored according to RFC 7230 - Section 3.2.4. This does not apply to header names. -- `Uri::withAddedHeader` with an array of header values. -- `Uri::resolve` when base path has no slash and handling of fragment. -- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the - key/value both in encoded as well as decoded form to those methods. This is - consistent with withPath, withQuery etc. -- `ServerRequest::withoutAttribute` when attribute value is null. - - -## [1.3.0] - 2016-04-13 - -### Added - -- Remaining interfaces needed for full PSR7 compatibility - (ServerRequestInterface, UploadedFileInterface, etc.). -- Support for stream_for from scalars. - -### Changed - -- Can now extend Uri. - -### Fixed -- A bug in validating request methods by making it more permissive. - - -## [1.2.3] - 2016-02-18 - -### Fixed - -- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote - streams, which can sometimes return fewer bytes than requested with `fread`. -- Handling of gzipped responses with FNAME headers. - - -## [1.2.2] - 2016-01-22 - -### Added - -- Support for URIs without any authority. -- Support for HTTP 451 'Unavailable For Legal Reasons.' -- Support for using '0' as a filename. -- Support for including non-standard ports in Host headers. - - -## [1.2.1] - 2015-11-02 - -### Changes - -- Now supporting negative offsets when seeking to SEEK_END. - - -## [1.2.0] - 2015-08-15 - -### Changed - -- Body as `"0"` is now properly added to a response. -- Now allowing forward seeking in CachingStream. -- Now properly parsing HTTP requests that contain proxy targets in - `parse_request`. -- functions.php is now conditionally required. -- user-info is no longer dropped when resolving URIs. - - -## [1.1.0] - 2015-06-24 - -### Changed - -- URIs can now be relative. -- `multipart/form-data` headers are now overridden case-insensitively. -- URI paths no longer encode the following characters because they are allowed - in URIs: "(", ")", "*", "!", "'" -- A port is no longer added to a URI when the scheme is missing and no port is - present. - - -## 1.0.0 - 2015-05-19 - -Initial release. - -Currently unsupported: - -- `Psr\Http\Message\ServerRequestInterface` -- `Psr\Http\Message\UploadedFileInterface` - - - -[Unreleased]: https://github.com/guzzle/psr7/compare/1.6.0...HEAD -[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 -[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 -[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 -[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 -[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 -[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 -[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 -[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 -[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 -[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 -[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 -[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 -[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 -[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/vendor/guzzlehttp/psr7/LICENSE b/vendor/guzzlehttp/psr7/LICENSE deleted file mode 100644 index 581d95f..0000000 --- a/vendor/guzzlehttp/psr7/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2015 Michael Dowling, https://github.com/mtdowling - -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/guzzlehttp/psr7/README.md b/vendor/guzzlehttp/psr7/README.md deleted file mode 100644 index c60a6a3..0000000 --- a/vendor/guzzlehttp/psr7/README.md +++ /dev/null @@ -1,745 +0,0 @@ -# PSR-7 Message Implementation - -This repository contains a full [PSR-7](http://www.php-fig.org/psr/psr-7/) -message implementation, several stream decorators, and some helpful -functionality like query string parsing. - - -[![Build Status](https://travis-ci.org/guzzle/psr7.svg?branch=master)](https://travis-ci.org/guzzle/psr7) - - -# Stream implementation - -This package comes with a number of stream implementations and stream -decorators. - - -## AppendStream - -`GuzzleHttp\Psr7\AppendStream` - -Reads from multiple streams, one after the other. - -```php -use GuzzleHttp\Psr7; - -$a = Psr7\stream_for('abc, '); -$b = Psr7\stream_for('123.'); -$composed = new Psr7\AppendStream([$a, $b]); - -$composed->addStream(Psr7\stream_for(' Above all listen to me')); - -echo $composed; // abc, 123. Above all listen to me. -``` - - -## BufferStream - -`GuzzleHttp\Psr7\BufferStream` - -Provides a buffer stream that can be written to fill a buffer, and read -from to remove bytes from the buffer. - -This stream returns a "hwm" metadata value that tells upstream consumers -what the configured high water mark of the stream is, or the maximum -preferred size of the buffer. - -```php -use GuzzleHttp\Psr7; - -// When more than 1024 bytes are in the buffer, it will begin returning -// false to writes. This is an indication that writers should slow down. -$buffer = new Psr7\BufferStream(1024); -``` - - -## CachingStream - -The CachingStream is used to allow seeking over previously read bytes on -non-seekable streams. This can be useful when transferring a non-seekable -entity body fails due to needing to rewind the stream (for example, resulting -from a redirect). Data that is read from the remote stream will be buffered in -a PHP temp stream so that previously read bytes are cached first in memory, -then on disk. - -```php -use GuzzleHttp\Psr7; - -$original = Psr7\stream_for(fopen('http://www.google.com', 'r')); -$stream = new Psr7\CachingStream($original); - -$stream->read(1024); -echo $stream->tell(); -// 1024 - -$stream->seek(0); -echo $stream->tell(); -// 0 -``` - - -## DroppingStream - -`GuzzleHttp\Psr7\DroppingStream` - -Stream decorator that begins dropping data once the size of the underlying -stream becomes too full. - -```php -use GuzzleHttp\Psr7; - -// Create an empty stream -$stream = Psr7\stream_for(); - -// Start dropping data when the stream has more than 10 bytes -$dropping = new Psr7\DroppingStream($stream, 10); - -$dropping->write('01234567890123456789'); -echo $stream; // 0123456789 -``` - - -## FnStream - -`GuzzleHttp\Psr7\FnStream` - -Compose stream implementations based on a hash of functions. - -Allows for easy testing and extension of a provided stream without needing -to create a concrete class for a simple extension point. - -```php - -use GuzzleHttp\Psr7; - -$stream = Psr7\stream_for('hi'); -$fnStream = Psr7\FnStream::decorate($stream, [ - 'rewind' => function () use ($stream) { - echo 'About to rewind - '; - $stream->rewind(); - echo 'rewound!'; - } -]); - -$fnStream->rewind(); -// Outputs: About to rewind - rewound! -``` - - -## InflateStream - -`GuzzleHttp\Psr7\InflateStream` - -Uses PHP's zlib.inflate filter to inflate deflate or gzipped content. - -This stream decorator skips the first 10 bytes of the given stream to remove -the gzip header, converts the provided stream to a PHP stream resource, -then appends the zlib.inflate filter. The stream is then converted back -to a Guzzle stream resource to be used as a Guzzle stream. - - -## LazyOpenStream - -`GuzzleHttp\Psr7\LazyOpenStream` - -Lazily reads or writes to a file that is opened only after an IO operation -take place on the stream. - -```php -use GuzzleHttp\Psr7; - -$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); -// The file has not yet been opened... - -echo $stream->read(10); -// The file is opened and read from only when needed. -``` - - -## LimitStream - -`GuzzleHttp\Psr7\LimitStream` - -LimitStream can be used to read a subset or slice of an existing stream object. -This can be useful for breaking a large file into smaller pieces to be sent in -chunks (e.g. Amazon S3's multipart upload API). - -```php -use GuzzleHttp\Psr7; - -$original = Psr7\stream_for(fopen('/tmp/test.txt', 'r+')); -echo $original->getSize(); -// >>> 1048576 - -// Limit the size of the body to 1024 bytes and start reading from byte 2048 -$stream = new Psr7\LimitStream($original, 1024, 2048); -echo $stream->getSize(); -// >>> 1024 -echo $stream->tell(); -// >>> 0 -``` - - -## MultipartStream - -`GuzzleHttp\Psr7\MultipartStream` - -Stream that when read returns bytes for a streaming multipart or -multipart/form-data stream. - - -## NoSeekStream - -`GuzzleHttp\Psr7\NoSeekStream` - -NoSeekStream wraps a stream and does not allow seeking. - -```php -use GuzzleHttp\Psr7; - -$original = Psr7\stream_for('foo'); -$noSeek = new Psr7\NoSeekStream($original); - -echo $noSeek->read(3); -// foo -var_export($noSeek->isSeekable()); -// false -$noSeek->seek(0); -var_export($noSeek->read(3)); -// NULL -``` - - -## PumpStream - -`GuzzleHttp\Psr7\PumpStream` - -Provides a read only stream that pumps data from a PHP callable. - -When invoking the provided callable, the PumpStream will pass the amount of -data requested to read to the callable. The callable can choose to ignore -this value and return fewer or more bytes than requested. Any extra data -returned by the provided callable is buffered internally until drained using -the read() function of the PumpStream. The provided callable MUST return -false when there is no more data to read. - - -## Implementing stream decorators - -Creating a stream decorator is very easy thanks to the -`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that -implement `Psr\Http\Message\StreamInterface` by proxying to an underlying -stream. Just `use` the `StreamDecoratorTrait` and implement your custom -methods. - -For example, let's say we wanted to call a specific function each time the last -byte is read from a stream. This could be implemented by overriding the -`read()` method. - -```php -use Psr\Http\Message\StreamInterface; -use GuzzleHttp\Psr7\StreamDecoratorTrait; - -class EofCallbackStream implements StreamInterface -{ - use StreamDecoratorTrait; - - private $callback; - - public function __construct(StreamInterface $stream, callable $cb) - { - $this->stream = $stream; - $this->callback = $cb; - } - - public function read($length) - { - $result = $this->stream->read($length); - - // Invoke the callback when EOF is hit. - if ($this->eof()) { - call_user_func($this->callback); - } - - return $result; - } -} -``` - -This decorator could be added to any existing stream and used like so: - -```php -use GuzzleHttp\Psr7; - -$original = Psr7\stream_for('foo'); - -$eofStream = new EofCallbackStream($original, function () { - echo 'EOF!'; -}); - -$eofStream->read(2); -$eofStream->read(1); -// echoes "EOF!" -$eofStream->seek(0); -$eofStream->read(3); -// echoes "EOF!" -``` - - -## PHP StreamWrapper - -You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a -PSR-7 stream as a PHP stream resource. - -Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP -stream from a PSR-7 stream. - -```php -use GuzzleHttp\Psr7\StreamWrapper; - -$stream = GuzzleHttp\Psr7\stream_for('hello!'); -$resource = StreamWrapper::getResource($stream); -echo fread($resource, 6); // outputs hello! -``` - - -# Function API - -There are various functions available under the `GuzzleHttp\Psr7` namespace. - - -## `function str` - -`function str(MessageInterface $message)` - -Returns the string representation of an HTTP message. - -```php -$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); -echo GuzzleHttp\Psr7\str($request); -``` - - -## `function uri_for` - -`function uri_for($uri)` - -This function accepts a string or `Psr\Http\Message\UriInterface` and returns a -UriInterface for the given value. If the value is already a `UriInterface`, it -is returned as-is. - -```php -$uri = GuzzleHttp\Psr7\uri_for('http://example.com'); -assert($uri === GuzzleHttp\Psr7\uri_for($uri)); -``` - - -## `function stream_for` - -`function stream_for($resource = '', array $options = [])` - -Create a new stream based on the input type. - -Options is an associative array that can contain the following keys: - -* - metadata: Array of custom metadata. -* - size: Size of the stream. - -This method accepts the following `$resource` types: - -- `Psr\Http\Message\StreamInterface`: Returns the value as-is. -- `string`: Creates a stream object that uses the given string as the contents. -- `resource`: Creates a stream object that wraps the given PHP stream resource. -- `Iterator`: If the provided value implements `Iterator`, then a read-only - stream object will be created that wraps the given iterable. Each time the - stream is read from, data from the iterator will fill a buffer and will be - continuously called until the buffer is equal to the requested read size. - Subsequent read calls will first read from the buffer and then call `next` - on the underlying iterator until it is exhausted. -- `object` with `__toString()`: If the object has the `__toString()` method, - the object will be cast to a string and then a stream will be returned that - uses the string value. -- `NULL`: When `null` is passed, an empty stream object is returned. -- `callable` When a callable is passed, a read-only stream object will be - created that invokes the given callable. The callable is invoked with the - number of suggested bytes to read. The callable can return any number of - bytes, but MUST return `false` when there is no more data to return. The - stream object that wraps the callable will invoke the callable until the - number of requested bytes are available. Any additional bytes will be - buffered and used in subsequent reads. - -```php -$stream = GuzzleHttp\Psr7\stream_for('foo'); -$stream = GuzzleHttp\Psr7\stream_for(fopen('/path/to/file', 'r')); - -$generator = function ($bytes) { - for ($i = 0; $i < $bytes; $i++) { - yield ' '; - } -} - -$stream = GuzzleHttp\Psr7\stream_for($generator(100)); -``` - - -## `function parse_header` - -`function parse_header($header)` - -Parse an array of header values containing ";" separated data into an array of -associative arrays representing the header key value pair data of the header. -When a parameter does not contain a value, but just contains a key, this -function will inject a key with a '' string value. - - -## `function normalize_header` - -`function normalize_header($header)` - -Converts an array of header values that may contain comma separated headers -into an array of headers with no comma separated values. - - -## `function modify_request` - -`function modify_request(RequestInterface $request, array $changes)` - -Clone and modify a request with the given changes. This method is useful for -reducing the number of clones needed to mutate a message. - -The changes can be one of: - -- method: (string) Changes the HTTP method. -- set_headers: (array) Sets the given headers. -- remove_headers: (array) Remove the given headers. -- body: (mixed) Sets the given body. -- uri: (UriInterface) Set the URI. -- query: (string) Set the query string value of the URI. -- version: (string) Set the protocol version. - - -## `function rewind_body` - -`function rewind_body(MessageInterface $message)` - -Attempts to rewind a message body and throws an exception on failure. The body -of the message will only be rewound if a call to `tell()` returns a value other -than `0`. - - -## `function try_fopen` - -`function try_fopen($filename, $mode)` - -Safely opens a PHP stream resource using a filename. - -When fopen fails, PHP normally raises a warning. This function adds an error -handler that checks for errors and throws an exception instead. - - -## `function copy_to_string` - -`function copy_to_string(StreamInterface $stream, $maxLen = -1)` - -Copy the contents of a stream into a string until the given number of bytes -have been read. - - -## `function copy_to_stream` - -`function copy_to_stream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)` - -Copy the contents of a stream into another stream until the given number of -bytes have been read. - - -## `function hash` - -`function hash(StreamInterface $stream, $algo, $rawOutput = false)` - -Calculate a hash of a Stream. This method reads the entire stream to calculate -a rolling hash (based on PHP's hash_init functions). - - -## `function readline` - -`function readline(StreamInterface $stream, $maxLength = null)` - -Read a line from the stream up to the maximum allowed buffer length. - - -## `function parse_request` - -`function parse_request($message)` - -Parses a request message string into a request object. - - -## `function parse_response` - -`function parse_response($message)` - -Parses a response message string into a response object. - - -## `function parse_query` - -`function parse_query($str, $urlEncoding = true)` - -Parse a query string into an associative array. - -If multiple values are found for the same key, the value of that key value pair -will become an array. This function does not parse nested PHP style arrays into -an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed into -`['foo[a]' => '1', 'foo[b]' => '2']`). - - -## `function build_query` - -`function build_query(array $params, $encoding = PHP_QUERY_RFC3986)` - -Build a query string from an array of key value pairs. - -This function can use the return value of parse_query() to build a query string. -This function does not modify the provided keys when an array is encountered -(like http_build_query would). - - -## `function mimetype_from_filename` - -`function mimetype_from_filename($filename)` - -Determines the mimetype of a file by looking at its extension. - - -## `function mimetype_from_extension` - -`function mimetype_from_extension($extension)` - -Maps a file extensions to a mimetype. - - -# Additional URI Methods - -Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, -this library also provides additional functionality when working with URIs as static methods. - -## URI Types - -An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. -An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, -the base URI. Relative references can be divided into several forms according to -[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2): - -- network-path references, e.g. `//example.com/path` -- absolute-path references, e.g. `/path` -- relative-path references, e.g. `subpath` - -The following methods can be used to identify the type of the URI. - -### `GuzzleHttp\Psr7\Uri::isAbsolute` - -`public static function isAbsolute(UriInterface $uri): bool` - -Whether the URI is absolute, i.e. it has a scheme. - -### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` - -`public static function isNetworkPathReference(UriInterface $uri): bool` - -Whether the URI is a network-path reference. A relative reference that begins with two slash characters is -termed an network-path reference. - -### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` - -`public static function isAbsolutePathReference(UriInterface $uri): bool` - -Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is -termed an absolute-path reference. - -### `GuzzleHttp\Psr7\Uri::isRelativePathReference` - -`public static function isRelativePathReference(UriInterface $uri): bool` - -Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is -termed a relative-path reference. - -### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` - -`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` - -Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its -fragment component, identical to the base URI. When no base URI is given, only an empty URI reference -(apart from its fragment) is considered a same-document reference. - -## URI Components - -Additional methods to work with URI components. - -### `GuzzleHttp\Psr7\Uri::isDefaultPort` - -`public static function isDefaultPort(UriInterface $uri): bool` - -Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null -or the standard port. This method can be used independently of the implementation. - -### `GuzzleHttp\Psr7\Uri::composeComponents` - -`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` - -Composes a URI reference string from its various components according to -[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called -manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. - -### `GuzzleHttp\Psr7\Uri::fromParts` - -`public static function fromParts(array $parts): UriInterface` - -Creates a URI from a hash of [`parse_url`](http://php.net/manual/en/function.parse-url.php) components. - - -### `GuzzleHttp\Psr7\Uri::withQueryValue` - -`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` - -Creates a new URI with a specific query string value. Any existing query string values that exactly match the -provided key are removed and replaced with the given key value pair. A value of null will set the query string -key without a value, e.g. "key" instead of "key=value". - -### `GuzzleHttp\Psr7\Uri::withQueryValues` - -`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` - -Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an -associative array of key => value. - -### `GuzzleHttp\Psr7\Uri::withoutQueryValue` - -`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` - -Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the -provided key are removed. - -## Reference Resolution - -`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according -to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers -do when resolving a link in a website based on the current request URI. - -### `GuzzleHttp\Psr7\UriResolver::resolve` - -`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` - -Converts the relative URI into a new URI that is resolved against the base URI. - -### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` - -`public static function removeDotSegments(string $path): string` - -Removes dot segments from a path and returns the new path according to -[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4). - -### `GuzzleHttp\Psr7\UriResolver::relativize` - -`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` - -Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): - -```php -(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) -``` - -One use-case is to use the current request URI as base URI and then generate relative links in your documents -to reduce the document size or offer self-contained downloadable document archives. - -```php -$base = new Uri('http://example.com/a/b/'); -echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. -echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. -echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. -echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. -``` - -## Normalization and Comparison - -`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to -[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6). - -### `GuzzleHttp\Psr7\UriNormalizer::normalize` - -`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` - -Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. -This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask -of normalizations to apply. The following normalizations are available: - -- `UriNormalizer::PRESERVING_NORMALIZATIONS` - - Default normalizations which only include the ones that preserve semantics. - -- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` - - All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. - - Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` - -- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` - - Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of - ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should - not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved - characters by URI normalizers. - - Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` - -- `UriNormalizer::CONVERT_EMPTY_PATH` - - Converts the empty path to "/" for http and https URIs. - - Example: `http://example.org` → `http://example.org/` - -- `UriNormalizer::REMOVE_DEFAULT_HOST` - - Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host - "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to - RFC 3986. - - Example: `file://localhost/myfile` → `file:///myfile` - -- `UriNormalizer::REMOVE_DEFAULT_PORT` - - Removes the default port of the given URI scheme from the URI. - - Example: `http://example.org:80/` → `http://example.org/` - -- `UriNormalizer::REMOVE_DOT_SEGMENTS` - - Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would - change the semantics of the URI reference. - - Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` - -- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` - - Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes - and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization - may change the semantics. Encoded slashes (%2F) are not removed. - - Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` - -- `UriNormalizer::SORT_QUERY_PARAMETERS` - - Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be - significant (this is not defined by the standard). So this normalization is not safe and may change the semantics - of the URI. - - Example: `?lang=en&article=fred` → `?article=fred&lang=en` - -### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` - -`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` - -Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given -`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. -This of course assumes they will be resolved against the same base URI. If this is not the case, determination of -equivalence or difference of relative references does not mean anything. diff --git a/vendor/guzzlehttp/psr7/composer.json b/vendor/guzzlehttp/psr7/composer.json deleted file mode 100644 index 168a055..0000000 --- a/vendor/guzzlehttp/psr7/composer.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "guzzlehttp/psr7", - "type": "library", - "description": "PSR-7 message implementation that also provides common utility methods", - "keywords": ["request", "response", "message", "stream", "http", "uri", "url", "psr-7"], - "license": "MIT", - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - }, - { - "name": "Tobias Schultze", - "homepage": "https://github.com/Tobion" - } - ], - "require": { - "php": ">=5.4.0", - "psr/http-message": "~1.0", - "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" - }, - "require-dev": { - "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8", - "ext-zlib": "*" - }, - "provide": { - "psr/http-message-implementation": "1.0" - }, - "suggest": { - "zendframework/zend-httphandlerrunner": "Emit PSR-7 responses" - }, - "autoload": { - "psr-4": { - "GuzzleHttp\\Psr7\\": "src/" - }, - "files": ["src/functions_include.php"] - }, - "autoload-dev": { - "psr-4": { - "GuzzleHttp\\Tests\\Psr7\\": "tests/" - } - }, - "extra": { - "branch-alias": { - "dev-master": "1.6-dev" - } - } -} diff --git a/vendor/guzzlehttp/psr7/src/AppendStream.php b/vendor/guzzlehttp/psr7/src/AppendStream.php deleted file mode 100644 index 472a0d6..0000000 --- a/vendor/guzzlehttp/psr7/src/AppendStream.php +++ /dev/null @@ -1,241 +0,0 @@ -addStream($stream); - } - } - - public function __toString() - { - try { - $this->rewind(); - return $this->getContents(); - } catch (\Exception $e) { - return ''; - } - } - - /** - * Add a stream to the AppendStream - * - * @param StreamInterface $stream Stream to append. Must be readable. - * - * @throws \InvalidArgumentException if the stream is not readable - */ - public function addStream(StreamInterface $stream) - { - if (!$stream->isReadable()) { - throw new \InvalidArgumentException('Each stream must be readable'); - } - - // The stream is only seekable if all streams are seekable - if (!$stream->isSeekable()) { - $this->seekable = false; - } - - $this->streams[] = $stream; - } - - public function getContents() - { - return copy_to_string($this); - } - - /** - * Closes each attached stream. - * - * {@inheritdoc} - */ - public function close() - { - $this->pos = $this->current = 0; - $this->seekable = true; - - foreach ($this->streams as $stream) { - $stream->close(); - } - - $this->streams = []; - } - - /** - * Detaches each attached stream. - * - * Returns null as it's not clear which underlying stream resource to return. - * - * {@inheritdoc} - */ - public function detach() - { - $this->pos = $this->current = 0; - $this->seekable = true; - - foreach ($this->streams as $stream) { - $stream->detach(); - } - - $this->streams = []; - } - - public function tell() - { - return $this->pos; - } - - /** - * Tries to calculate the size by adding the size of each stream. - * - * If any of the streams do not return a valid number, then the size of the - * append stream cannot be determined and null is returned. - * - * {@inheritdoc} - */ - public function getSize() - { - $size = 0; - - foreach ($this->streams as $stream) { - $s = $stream->getSize(); - if ($s === null) { - return null; - } - $size += $s; - } - - return $size; - } - - public function eof() - { - return !$this->streams || - ($this->current >= count($this->streams) - 1 && - $this->streams[$this->current]->eof()); - } - - public function rewind() - { - $this->seek(0); - } - - /** - * Attempts to seek to the given position. Only supports SEEK_SET. - * - * {@inheritdoc} - */ - public function seek($offset, $whence = SEEK_SET) - { - if (!$this->seekable) { - throw new \RuntimeException('This AppendStream is not seekable'); - } elseif ($whence !== SEEK_SET) { - throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); - } - - $this->pos = $this->current = 0; - - // Rewind each stream - foreach ($this->streams as $i => $stream) { - try { - $stream->rewind(); - } catch (\Exception $e) { - throw new \RuntimeException('Unable to seek stream ' - . $i . ' of the AppendStream', 0, $e); - } - } - - // Seek to the actual position by reading from each stream - while ($this->pos < $offset && !$this->eof()) { - $result = $this->read(min(8096, $offset - $this->pos)); - if ($result === '') { - break; - } - } - } - - /** - * Reads from all of the appended streams until the length is met or EOF. - * - * {@inheritdoc} - */ - public function read($length) - { - $buffer = ''; - $total = count($this->streams) - 1; - $remaining = $length; - $progressToNext = false; - - while ($remaining > 0) { - - // Progress to the next stream if needed. - if ($progressToNext || $this->streams[$this->current]->eof()) { - $progressToNext = false; - if ($this->current === $total) { - break; - } - $this->current++; - } - - $result = $this->streams[$this->current]->read($remaining); - - // Using a loose comparison here to match on '', false, and null - if ($result == null) { - $progressToNext = true; - continue; - } - - $buffer .= $result; - $remaining = $length - strlen($buffer); - } - - $this->pos += strlen($buffer); - - return $buffer; - } - - public function isReadable() - { - return true; - } - - public function isWritable() - { - return false; - } - - public function isSeekable() - { - return $this->seekable; - } - - public function write($string) - { - throw new \RuntimeException('Cannot write to an AppendStream'); - } - - public function getMetadata($key = null) - { - return $key ? null : []; - } -} diff --git a/vendor/guzzlehttp/psr7/src/BufferStream.php b/vendor/guzzlehttp/psr7/src/BufferStream.php deleted file mode 100644 index af4d4c2..0000000 --- a/vendor/guzzlehttp/psr7/src/BufferStream.php +++ /dev/null @@ -1,137 +0,0 @@ -hwm = $hwm; - } - - public function __toString() - { - return $this->getContents(); - } - - public function getContents() - { - $buffer = $this->buffer; - $this->buffer = ''; - - return $buffer; - } - - public function close() - { - $this->buffer = ''; - } - - public function detach() - { - $this->close(); - } - - public function getSize() - { - return strlen($this->buffer); - } - - public function isReadable() - { - return true; - } - - public function isWritable() - { - return true; - } - - public function isSeekable() - { - return false; - } - - public function rewind() - { - $this->seek(0); - } - - public function seek($offset, $whence = SEEK_SET) - { - throw new \RuntimeException('Cannot seek a BufferStream'); - } - - public function eof() - { - return strlen($this->buffer) === 0; - } - - public function tell() - { - throw new \RuntimeException('Cannot determine the position of a BufferStream'); - } - - /** - * Reads data from the buffer. - */ - public function read($length) - { - $currentLength = strlen($this->buffer); - - if ($length >= $currentLength) { - // No need to slice the buffer because we don't have enough data. - $result = $this->buffer; - $this->buffer = ''; - } else { - // Slice up the result to provide a subset of the buffer. - $result = substr($this->buffer, 0, $length); - $this->buffer = substr($this->buffer, $length); - } - - return $result; - } - - /** - * Writes data to the buffer. - */ - public function write($string) - { - $this->buffer .= $string; - - // TODO: What should happen here? - if (strlen($this->buffer) >= $this->hwm) { - return false; - } - - return strlen($string); - } - - public function getMetadata($key = null) - { - if ($key == 'hwm') { - return $this->hwm; - } - - return $key ? null : []; - } -} diff --git a/vendor/guzzlehttp/psr7/src/CachingStream.php b/vendor/guzzlehttp/psr7/src/CachingStream.php deleted file mode 100644 index ed68f08..0000000 --- a/vendor/guzzlehttp/psr7/src/CachingStream.php +++ /dev/null @@ -1,138 +0,0 @@ -remoteStream = $stream; - $this->stream = $target ?: new Stream(fopen('php://temp', 'r+')); - } - - public function getSize() - { - return max($this->stream->getSize(), $this->remoteStream->getSize()); - } - - public function rewind() - { - $this->seek(0); - } - - public function seek($offset, $whence = SEEK_SET) - { - if ($whence == SEEK_SET) { - $byte = $offset; - } elseif ($whence == SEEK_CUR) { - $byte = $offset + $this->tell(); - } elseif ($whence == SEEK_END) { - $size = $this->remoteStream->getSize(); - if ($size === null) { - $size = $this->cacheEntireStream(); - } - $byte = $size + $offset; - } else { - throw new \InvalidArgumentException('Invalid whence'); - } - - $diff = $byte - $this->stream->getSize(); - - if ($diff > 0) { - // Read the remoteStream until we have read in at least the amount - // of bytes requested, or we reach the end of the file. - while ($diff > 0 && !$this->remoteStream->eof()) { - $this->read($diff); - $diff = $byte - $this->stream->getSize(); - } - } else { - // We can just do a normal seek since we've already seen this byte. - $this->stream->seek($byte); - } - } - - public function read($length) - { - // Perform a regular read on any previously read data from the buffer - $data = $this->stream->read($length); - $remaining = $length - strlen($data); - - // More data was requested so read from the remote stream - if ($remaining) { - // If data was written to the buffer in a position that would have - // been filled from the remote stream, then we must skip bytes on - // the remote stream to emulate overwriting bytes from that - // position. This mimics the behavior of other PHP stream wrappers. - $remoteData = $this->remoteStream->read( - $remaining + $this->skipReadBytes - ); - - if ($this->skipReadBytes) { - $len = strlen($remoteData); - $remoteData = substr($remoteData, $this->skipReadBytes); - $this->skipReadBytes = max(0, $this->skipReadBytes - $len); - } - - $data .= $remoteData; - $this->stream->write($remoteData); - } - - return $data; - } - - public function write($string) - { - // When appending to the end of the currently read stream, you'll want - // to skip bytes from being read from the remote stream to emulate - // other stream wrappers. Basically replacing bytes of data of a fixed - // length. - $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); - if ($overflow > 0) { - $this->skipReadBytes += $overflow; - } - - return $this->stream->write($string); - } - - public function eof() - { - return $this->stream->eof() && $this->remoteStream->eof(); - } - - /** - * Close both the remote stream and buffer stream - */ - public function close() - { - $this->remoteStream->close() && $this->stream->close(); - } - - private function cacheEntireStream() - { - $target = new FnStream(['write' => 'strlen']); - copy_to_stream($this, $target); - - return $this->tell(); - } -} diff --git a/vendor/guzzlehttp/psr7/src/DroppingStream.php b/vendor/guzzlehttp/psr7/src/DroppingStream.php deleted file mode 100644 index 8935c80..0000000 --- a/vendor/guzzlehttp/psr7/src/DroppingStream.php +++ /dev/null @@ -1,42 +0,0 @@ -stream = $stream; - $this->maxLength = $maxLength; - } - - public function write($string) - { - $diff = $this->maxLength - $this->stream->getSize(); - - // Begin returning 0 when the underlying stream is too large. - if ($diff <= 0) { - return 0; - } - - // Write the stream or a subset of the stream if needed. - if (strlen($string) < $diff) { - return $this->stream->write($string); - } - - return $this->stream->write(substr($string, 0, $diff)); - } -} diff --git a/vendor/guzzlehttp/psr7/src/FnStream.php b/vendor/guzzlehttp/psr7/src/FnStream.php deleted file mode 100644 index 73daea6..0000000 --- a/vendor/guzzlehttp/psr7/src/FnStream.php +++ /dev/null @@ -1,158 +0,0 @@ -methods = $methods; - - // Create the functions on the class - foreach ($methods as $name => $fn) { - $this->{'_fn_' . $name} = $fn; - } - } - - /** - * Lazily determine which methods are not implemented. - * @throws \BadMethodCallException - */ - public function __get($name) - { - throw new \BadMethodCallException(str_replace('_fn_', '', $name) - . '() is not implemented in the FnStream'); - } - - /** - * The close method is called on the underlying stream only if possible. - */ - public function __destruct() - { - if (isset($this->_fn_close)) { - call_user_func($this->_fn_close); - } - } - - /** - * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. - * @throws \LogicException - */ - public function __wakeup() - { - throw new \LogicException('FnStream should never be unserialized'); - } - - /** - * Adds custom functionality to an underlying stream by intercepting - * specific method calls. - * - * @param StreamInterface $stream Stream to decorate - * @param array $methods Hash of method name to a closure - * - * @return FnStream - */ - public static function decorate(StreamInterface $stream, array $methods) - { - // If any of the required methods were not provided, then simply - // proxy to the decorated stream. - foreach (array_diff(self::$slots, array_keys($methods)) as $diff) { - $methods[$diff] = [$stream, $diff]; - } - - return new self($methods); - } - - public function __toString() - { - return call_user_func($this->_fn___toString); - } - - public function close() - { - return call_user_func($this->_fn_close); - } - - public function detach() - { - return call_user_func($this->_fn_detach); - } - - public function getSize() - { - return call_user_func($this->_fn_getSize); - } - - public function tell() - { - return call_user_func($this->_fn_tell); - } - - public function eof() - { - return call_user_func($this->_fn_eof); - } - - public function isSeekable() - { - return call_user_func($this->_fn_isSeekable); - } - - public function rewind() - { - call_user_func($this->_fn_rewind); - } - - public function seek($offset, $whence = SEEK_SET) - { - call_user_func($this->_fn_seek, $offset, $whence); - } - - public function isWritable() - { - return call_user_func($this->_fn_isWritable); - } - - public function write($string) - { - return call_user_func($this->_fn_write, $string); - } - - public function isReadable() - { - return call_user_func($this->_fn_isReadable); - } - - public function read($length) - { - return call_user_func($this->_fn_read, $length); - } - - public function getContents() - { - return call_user_func($this->_fn_getContents); - } - - public function getMetadata($key = null) - { - return call_user_func($this->_fn_getMetadata, $key); - } -} diff --git a/vendor/guzzlehttp/psr7/src/InflateStream.php b/vendor/guzzlehttp/psr7/src/InflateStream.php deleted file mode 100644 index 5e4f602..0000000 --- a/vendor/guzzlehttp/psr7/src/InflateStream.php +++ /dev/null @@ -1,52 +0,0 @@ -read(10); - $filenameHeaderLength = $this->getLengthOfPossibleFilenameHeader($stream, $header); - // Skip the header, that is 10 + length of filename + 1 (nil) bytes - $stream = new LimitStream($stream, -1, 10 + $filenameHeaderLength); - $resource = StreamWrapper::getResource($stream); - stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ); - $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource)); - } - - /** - * @param StreamInterface $stream - * @param $header - * @return int - */ - private function getLengthOfPossibleFilenameHeader(StreamInterface $stream, $header) - { - $filename_header_length = 0; - - if (substr(bin2hex($header), 6, 2) === '08') { - // we have a filename, read until nil - $filename_header_length = 1; - while ($stream->read(1) !== chr(0)) { - $filename_header_length++; - } - } - - return $filename_header_length; - } -} diff --git a/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/vendor/guzzlehttp/psr7/src/LazyOpenStream.php deleted file mode 100644 index 02cec3a..0000000 --- a/vendor/guzzlehttp/psr7/src/LazyOpenStream.php +++ /dev/null @@ -1,39 +0,0 @@ -filename = $filename; - $this->mode = $mode; - } - - /** - * Creates the underlying stream lazily when required. - * - * @return StreamInterface - */ - protected function createStream() - { - return stream_for(try_fopen($this->filename, $this->mode)); - } -} diff --git a/vendor/guzzlehttp/psr7/src/LimitStream.php b/vendor/guzzlehttp/psr7/src/LimitStream.php deleted file mode 100644 index e4f239e..0000000 --- a/vendor/guzzlehttp/psr7/src/LimitStream.php +++ /dev/null @@ -1,155 +0,0 @@ -stream = $stream; - $this->setLimit($limit); - $this->setOffset($offset); - } - - public function eof() - { - // Always return true if the underlying stream is EOF - if ($this->stream->eof()) { - return true; - } - - // No limit and the underlying stream is not at EOF - if ($this->limit == -1) { - return false; - } - - return $this->stream->tell() >= $this->offset + $this->limit; - } - - /** - * Returns the size of the limited subset of data - * {@inheritdoc} - */ - public function getSize() - { - if (null === ($length = $this->stream->getSize())) { - return null; - } elseif ($this->limit == -1) { - return $length - $this->offset; - } else { - return min($this->limit, $length - $this->offset); - } - } - - /** - * Allow for a bounded seek on the read limited stream - * {@inheritdoc} - */ - public function seek($offset, $whence = SEEK_SET) - { - if ($whence !== SEEK_SET || $offset < 0) { - throw new \RuntimeException(sprintf( - 'Cannot seek to offset %s with whence %s', - $offset, - $whence - )); - } - - $offset += $this->offset; - - if ($this->limit !== -1) { - if ($offset > $this->offset + $this->limit) { - $offset = $this->offset + $this->limit; - } - } - - $this->stream->seek($offset); - } - - /** - * Give a relative tell() - * {@inheritdoc} - */ - public function tell() - { - return $this->stream->tell() - $this->offset; - } - - /** - * Set the offset to start limiting from - * - * @param int $offset Offset to seek to and begin byte limiting from - * - * @throws \RuntimeException if the stream cannot be seeked. - */ - public function setOffset($offset) - { - $current = $this->stream->tell(); - - if ($current !== $offset) { - // If the stream cannot seek to the offset position, then read to it - if ($this->stream->isSeekable()) { - $this->stream->seek($offset); - } elseif ($current > $offset) { - throw new \RuntimeException("Could not seek to stream offset $offset"); - } else { - $this->stream->read($offset - $current); - } - } - - $this->offset = $offset; - } - - /** - * Set the limit of bytes that the decorator allows to be read from the - * stream. - * - * @param int $limit Number of bytes to allow to be read from the stream. - * Use -1 for no limit. - */ - public function setLimit($limit) - { - $this->limit = $limit; - } - - public function read($length) - { - if ($this->limit == -1) { - return $this->stream->read($length); - } - - // Check if the current position is less than the total allowed - // bytes + original offset - $remaining = ($this->offset + $this->limit) - $this->stream->tell(); - if ($remaining > 0) { - // Only return the amount of requested data, ensuring that the byte - // limit is not exceeded - return $this->stream->read(min($remaining, $length)); - } - - return ''; - } -} diff --git a/vendor/guzzlehttp/psr7/src/MessageTrait.php b/vendor/guzzlehttp/psr7/src/MessageTrait.php deleted file mode 100644 index a7966d1..0000000 --- a/vendor/guzzlehttp/psr7/src/MessageTrait.php +++ /dev/null @@ -1,213 +0,0 @@ - array of values */ - private $headers = []; - - /** @var array Map of lowercase header name => original name at registration */ - private $headerNames = []; - - /** @var string */ - private $protocol = '1.1'; - - /** @var StreamInterface */ - private $stream; - - public function getProtocolVersion() - { - return $this->protocol; - } - - public function withProtocolVersion($version) - { - if ($this->protocol === $version) { - return $this; - } - - $new = clone $this; - $new->protocol = $version; - return $new; - } - - public function getHeaders() - { - return $this->headers; - } - - public function hasHeader($header) - { - return isset($this->headerNames[strtolower($header)]); - } - - public function getHeader($header) - { - $header = strtolower($header); - - if (!isset($this->headerNames[$header])) { - return []; - } - - $header = $this->headerNames[$header]; - - return $this->headers[$header]; - } - - public function getHeaderLine($header) - { - return implode(', ', $this->getHeader($header)); - } - - public function withHeader($header, $value) - { - $this->assertHeader($header); - $value = $this->normalizeHeaderValue($value); - $normalized = strtolower($header); - - $new = clone $this; - if (isset($new->headerNames[$normalized])) { - unset($new->headers[$new->headerNames[$normalized]]); - } - $new->headerNames[$normalized] = $header; - $new->headers[$header] = $value; - - return $new; - } - - public function withAddedHeader($header, $value) - { - $this->assertHeader($header); - $value = $this->normalizeHeaderValue($value); - $normalized = strtolower($header); - - $new = clone $this; - if (isset($new->headerNames[$normalized])) { - $header = $this->headerNames[$normalized]; - $new->headers[$header] = array_merge($this->headers[$header], $value); - } else { - $new->headerNames[$normalized] = $header; - $new->headers[$header] = $value; - } - - return $new; - } - - public function withoutHeader($header) - { - $normalized = strtolower($header); - - if (!isset($this->headerNames[$normalized])) { - return $this; - } - - $header = $this->headerNames[$normalized]; - - $new = clone $this; - unset($new->headers[$header], $new->headerNames[$normalized]); - - return $new; - } - - public function getBody() - { - if (!$this->stream) { - $this->stream = stream_for(''); - } - - return $this->stream; - } - - public function withBody(StreamInterface $body) - { - if ($body === $this->stream) { - return $this; - } - - $new = clone $this; - $new->stream = $body; - return $new; - } - - private function setHeaders(array $headers) - { - $this->headerNames = $this->headers = []; - foreach ($headers as $header => $value) { - if (is_int($header)) { - // Numeric array keys are converted to int by PHP but having a header name '123' is not forbidden by the spec - // and also allowed in withHeader(). So we need to cast it to string again for the following assertion to pass. - $header = (string) $header; - } - $this->assertHeader($header); - $value = $this->normalizeHeaderValue($value); - $normalized = strtolower($header); - if (isset($this->headerNames[$normalized])) { - $header = $this->headerNames[$normalized]; - $this->headers[$header] = array_merge($this->headers[$header], $value); - } else { - $this->headerNames[$normalized] = $header; - $this->headers[$header] = $value; - } - } - } - - private function normalizeHeaderValue($value) - { - if (!is_array($value)) { - return $this->trimHeaderValues([$value]); - } - - if (count($value) === 0) { - throw new \InvalidArgumentException('Header value can not be an empty array.'); - } - - return $this->trimHeaderValues($value); - } - - /** - * Trims whitespace from the header values. - * - * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. - * - * header-field = field-name ":" OWS field-value OWS - * OWS = *( SP / HTAB ) - * - * @param string[] $values Header values - * - * @return string[] Trimmed header values - * - * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 - */ - private function trimHeaderValues(array $values) - { - return array_map(function ($value) { - if (!is_scalar($value) && null !== $value) { - throw new \InvalidArgumentException(sprintf( - 'Header value must be scalar or null but %s provided.', - is_object($value) ? get_class($value) : gettype($value) - )); - } - - return trim((string) $value, " \t"); - }, $values); - } - - private function assertHeader($header) - { - if (!is_string($header)) { - throw new \InvalidArgumentException(sprintf( - 'Header name must be a string but %s provided.', - is_object($header) ? get_class($header) : gettype($header) - )); - } - - if ($header === '') { - throw new \InvalidArgumentException('Header name can not be empty.'); - } - } -} diff --git a/vendor/guzzlehttp/psr7/src/MultipartStream.php b/vendor/guzzlehttp/psr7/src/MultipartStream.php deleted file mode 100644 index c0fd584..0000000 --- a/vendor/guzzlehttp/psr7/src/MultipartStream.php +++ /dev/null @@ -1,153 +0,0 @@ -boundary = $boundary ?: sha1(uniqid('', true)); - $this->stream = $this->createStream($elements); - } - - /** - * Get the boundary - * - * @return string - */ - public function getBoundary() - { - return $this->boundary; - } - - public function isWritable() - { - return false; - } - - /** - * Get the headers needed before transferring the content of a POST file - */ - private function getHeaders(array $headers) - { - $str = ''; - foreach ($headers as $key => $value) { - $str .= "{$key}: {$value}\r\n"; - } - - return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n"; - } - - /** - * Create the aggregate stream that will be used to upload the POST data - */ - protected function createStream(array $elements) - { - $stream = new AppendStream(); - - foreach ($elements as $element) { - $this->addElement($stream, $element); - } - - // Add the trailing boundary with CRLF - $stream->addStream(stream_for("--{$this->boundary}--\r\n")); - - return $stream; - } - - private function addElement(AppendStream $stream, array $element) - { - foreach (['contents', 'name'] as $key) { - if (!array_key_exists($key, $element)) { - throw new \InvalidArgumentException("A '{$key}' key is required"); - } - } - - $element['contents'] = stream_for($element['contents']); - - if (empty($element['filename'])) { - $uri = $element['contents']->getMetadata('uri'); - if (substr($uri, 0, 6) !== 'php://') { - $element['filename'] = $uri; - } - } - - list($body, $headers) = $this->createElement( - $element['name'], - $element['contents'], - isset($element['filename']) ? $element['filename'] : null, - isset($element['headers']) ? $element['headers'] : [] - ); - - $stream->addStream(stream_for($this->getHeaders($headers))); - $stream->addStream($body); - $stream->addStream(stream_for("\r\n")); - } - - /** - * @return array - */ - private function createElement($name, StreamInterface $stream, $filename, array $headers) - { - // Set a default content-disposition header if one was no provided - $disposition = $this->getHeader($headers, 'content-disposition'); - if (!$disposition) { - $headers['Content-Disposition'] = ($filename === '0' || $filename) - ? sprintf('form-data; name="%s"; filename="%s"', - $name, - basename($filename)) - : "form-data; name=\"{$name}\""; - } - - // Set a default content-length header if one was no provided - $length = $this->getHeader($headers, 'content-length'); - if (!$length) { - if ($length = $stream->getSize()) { - $headers['Content-Length'] = (string) $length; - } - } - - // Set a default Content-Type if one was not supplied - $type = $this->getHeader($headers, 'content-type'); - if (!$type && ($filename === '0' || $filename)) { - if ($type = mimetype_from_filename($filename)) { - $headers['Content-Type'] = $type; - } - } - - return [$stream, $headers]; - } - - private function getHeader(array $headers, $key) - { - $lowercaseHeader = strtolower($key); - foreach ($headers as $k => $v) { - if (strtolower($k) === $lowercaseHeader) { - return $v; - } - } - - return null; - } -} diff --git a/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/vendor/guzzlehttp/psr7/src/NoSeekStream.php deleted file mode 100644 index 2332218..0000000 --- a/vendor/guzzlehttp/psr7/src/NoSeekStream.php +++ /dev/null @@ -1,22 +0,0 @@ -source = $source; - $this->size = isset($options['size']) ? $options['size'] : null; - $this->metadata = isset($options['metadata']) ? $options['metadata'] : []; - $this->buffer = new BufferStream(); - } - - public function __toString() - { - try { - return copy_to_string($this); - } catch (\Exception $e) { - return ''; - } - } - - public function close() - { - $this->detach(); - } - - public function detach() - { - $this->tellPos = false; - $this->source = null; - } - - public function getSize() - { - return $this->size; - } - - public function tell() - { - return $this->tellPos; - } - - public function eof() - { - return !$this->source; - } - - public function isSeekable() - { - return false; - } - - public function rewind() - { - $this->seek(0); - } - - public function seek($offset, $whence = SEEK_SET) - { - throw new \RuntimeException('Cannot seek a PumpStream'); - } - - public function isWritable() - { - return false; - } - - public function write($string) - { - throw new \RuntimeException('Cannot write to a PumpStream'); - } - - public function isReadable() - { - return true; - } - - public function read($length) - { - $data = $this->buffer->read($length); - $readLen = strlen($data); - $this->tellPos += $readLen; - $remaining = $length - $readLen; - - if ($remaining) { - $this->pump($remaining); - $data .= $this->buffer->read($remaining); - $this->tellPos += strlen($data) - $readLen; - } - - return $data; - } - - public function getContents() - { - $result = ''; - while (!$this->eof()) { - $result .= $this->read(1000000); - } - - return $result; - } - - public function getMetadata($key = null) - { - if (!$key) { - return $this->metadata; - } - - return isset($this->metadata[$key]) ? $this->metadata[$key] : null; - } - - private function pump($length) - { - if ($this->source) { - do { - $data = call_user_func($this->source, $length); - if ($data === false || $data === null) { - $this->source = null; - return; - } - $this->buffer->write($data); - $length -= strlen($data); - } while ($length > 0); - } - } -} diff --git a/vendor/guzzlehttp/psr7/src/Request.php b/vendor/guzzlehttp/psr7/src/Request.php deleted file mode 100644 index 59f337d..0000000 --- a/vendor/guzzlehttp/psr7/src/Request.php +++ /dev/null @@ -1,151 +0,0 @@ -assertMethod($method); - if (!($uri instanceof UriInterface)) { - $uri = new Uri($uri); - } - - $this->method = strtoupper($method); - $this->uri = $uri; - $this->setHeaders($headers); - $this->protocol = $version; - - if (!isset($this->headerNames['host'])) { - $this->updateHostFromUri(); - } - - if ($body !== '' && $body !== null) { - $this->stream = stream_for($body); - } - } - - public function getRequestTarget() - { - if ($this->requestTarget !== null) { - return $this->requestTarget; - } - - $target = $this->uri->getPath(); - if ($target == '') { - $target = '/'; - } - if ($this->uri->getQuery() != '') { - $target .= '?' . $this->uri->getQuery(); - } - - return $target; - } - - public function withRequestTarget($requestTarget) - { - if (preg_match('#\s#', $requestTarget)) { - throw new InvalidArgumentException( - 'Invalid request target provided; cannot contain whitespace' - ); - } - - $new = clone $this; - $new->requestTarget = $requestTarget; - return $new; - } - - public function getMethod() - { - return $this->method; - } - - public function withMethod($method) - { - $this->assertMethod($method); - $new = clone $this; - $new->method = strtoupper($method); - return $new; - } - - public function getUri() - { - return $this->uri; - } - - public function withUri(UriInterface $uri, $preserveHost = false) - { - if ($uri === $this->uri) { - return $this; - } - - $new = clone $this; - $new->uri = $uri; - - if (!$preserveHost || !isset($this->headerNames['host'])) { - $new->updateHostFromUri(); - } - - return $new; - } - - private function updateHostFromUri() - { - $host = $this->uri->getHost(); - - if ($host == '') { - return; - } - - if (($port = $this->uri->getPort()) !== null) { - $host .= ':' . $port; - } - - if (isset($this->headerNames['host'])) { - $header = $this->headerNames['host']; - } else { - $header = 'Host'; - $this->headerNames['host'] = 'Host'; - } - // Ensure Host is the first header. - // See: http://tools.ietf.org/html/rfc7230#section-5.4 - $this->headers = [$header => [$host]] + $this->headers; - } - - private function assertMethod($method) - { - if (!is_string($method) || $method === '') { - throw new \InvalidArgumentException('Method must be a non-empty string.'); - } - } -} diff --git a/vendor/guzzlehttp/psr7/src/Response.php b/vendor/guzzlehttp/psr7/src/Response.php deleted file mode 100644 index e7e04d8..0000000 --- a/vendor/guzzlehttp/psr7/src/Response.php +++ /dev/null @@ -1,154 +0,0 @@ - 'Continue', - 101 => 'Switching Protocols', - 102 => 'Processing', - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authoritative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - 207 => 'Multi-status', - 208 => 'Already Reported', - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - 306 => 'Switch Proxy', - 307 => 'Temporary Redirect', - 400 => 'Bad Request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Time-out', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Large', - 415 => 'Unsupported Media Type', - 416 => 'Requested range not satisfiable', - 417 => 'Expectation Failed', - 418 => 'I\'m a teapot', - 422 => 'Unprocessable Entity', - 423 => 'Locked', - 424 => 'Failed Dependency', - 425 => 'Unordered Collection', - 426 => 'Upgrade Required', - 428 => 'Precondition Required', - 429 => 'Too Many Requests', - 431 => 'Request Header Fields Too Large', - 451 => 'Unavailable For Legal Reasons', - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Time-out', - 505 => 'HTTP Version not supported', - 506 => 'Variant Also Negotiates', - 507 => 'Insufficient Storage', - 508 => 'Loop Detected', - 511 => 'Network Authentication Required', - ]; - - /** @var string */ - private $reasonPhrase = ''; - - /** @var int */ - private $statusCode = 200; - - /** - * @param int $status Status code - * @param array $headers Response headers - * @param string|null|resource|StreamInterface $body Response body - * @param string $version Protocol version - * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) - */ - public function __construct( - $status = 200, - array $headers = [], - $body = null, - $version = '1.1', - $reason = null - ) { - $this->assertStatusCodeIsInteger($status); - $status = (int) $status; - $this->assertStatusCodeRange($status); - - $this->statusCode = $status; - - if ($body !== '' && $body !== null) { - $this->stream = stream_for($body); - } - - $this->setHeaders($headers); - if ($reason == '' && isset(self::$phrases[$this->statusCode])) { - $this->reasonPhrase = self::$phrases[$this->statusCode]; - } else { - $this->reasonPhrase = (string) $reason; - } - - $this->protocol = $version; - } - - public function getStatusCode() - { - return $this->statusCode; - } - - public function getReasonPhrase() - { - return $this->reasonPhrase; - } - - public function withStatus($code, $reasonPhrase = '') - { - $this->assertStatusCodeIsInteger($code); - $code = (int) $code; - $this->assertStatusCodeRange($code); - - $new = clone $this; - $new->statusCode = $code; - if ($reasonPhrase == '' && isset(self::$phrases[$new->statusCode])) { - $reasonPhrase = self::$phrases[$new->statusCode]; - } - $new->reasonPhrase = $reasonPhrase; - return $new; - } - - private function assertStatusCodeIsInteger($statusCode) - { - if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) { - throw new \InvalidArgumentException('Status code must be an integer value.'); - } - } - - private function assertStatusCodeRange($statusCode) - { - if ($statusCode < 100 || $statusCode >= 600) { - throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); - } - } -} diff --git a/vendor/guzzlehttp/psr7/src/Rfc7230.php b/vendor/guzzlehttp/psr7/src/Rfc7230.php deleted file mode 100644 index 505e474..0000000 --- a/vendor/guzzlehttp/psr7/src/Rfc7230.php +++ /dev/null @@ -1,18 +0,0 @@ -@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; - const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; -} diff --git a/vendor/guzzlehttp/psr7/src/ServerRequest.php b/vendor/guzzlehttp/psr7/src/ServerRequest.php deleted file mode 100644 index 1a09a6c..0000000 --- a/vendor/guzzlehttp/psr7/src/ServerRequest.php +++ /dev/null @@ -1,376 +0,0 @@ -serverParams = $serverParams; - - parent::__construct($method, $uri, $headers, $body, $version); - } - - /** - * Return an UploadedFile instance array. - * - * @param array $files A array which respect $_FILES structure - * @throws InvalidArgumentException for unrecognized values - * @return array - */ - public static function normalizeFiles(array $files) - { - $normalized = []; - - foreach ($files as $key => $value) { - if ($value instanceof UploadedFileInterface) { - $normalized[$key] = $value; - } elseif (is_array($value) && isset($value['tmp_name'])) { - $normalized[$key] = self::createUploadedFileFromSpec($value); - } elseif (is_array($value)) { - $normalized[$key] = self::normalizeFiles($value); - continue; - } else { - throw new InvalidArgumentException('Invalid value in files specification'); - } - } - - return $normalized; - } - - /** - * Create and return an UploadedFile instance from a $_FILES specification. - * - * If the specification represents an array of values, this method will - * delegate to normalizeNestedFileSpec() and return that return value. - * - * @param array $value $_FILES struct - * @return array|UploadedFileInterface - */ - private static function createUploadedFileFromSpec(array $value) - { - if (is_array($value['tmp_name'])) { - return self::normalizeNestedFileSpec($value); - } - - return new UploadedFile( - $value['tmp_name'], - (int) $value['size'], - (int) $value['error'], - $value['name'], - $value['type'] - ); - } - - /** - * Normalize an array of file specifications. - * - * Loops through all nested files and returns a normalized array of - * UploadedFileInterface instances. - * - * @param array $files - * @return UploadedFileInterface[] - */ - private static function normalizeNestedFileSpec(array $files = []) - { - $normalizedFiles = []; - - foreach (array_keys($files['tmp_name']) as $key) { - $spec = [ - 'tmp_name' => $files['tmp_name'][$key], - 'size' => $files['size'][$key], - 'error' => $files['error'][$key], - 'name' => $files['name'][$key], - 'type' => $files['type'][$key], - ]; - $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); - } - - return $normalizedFiles; - } - - /** - * Return a ServerRequest populated with superglobals: - * $_GET - * $_POST - * $_COOKIE - * $_FILES - * $_SERVER - * - * @return ServerRequestInterface - */ - public static function fromGlobals() - { - $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; - $headers = getallheaders(); - $uri = self::getUriFromGlobals(); - $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); - $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; - - $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); - - return $serverRequest - ->withCookieParams($_COOKIE) - ->withQueryParams($_GET) - ->withParsedBody($_POST) - ->withUploadedFiles(self::normalizeFiles($_FILES)); - } - - private static function extractHostAndPortFromAuthority($authority) - { - $uri = 'http://'.$authority; - $parts = parse_url($uri); - if (false === $parts) { - return [null, null]; - } - - $host = isset($parts['host']) ? $parts['host'] : null; - $port = isset($parts['port']) ? $parts['port'] : null; - - return [$host, $port]; - } - - /** - * Get a Uri populated with values from $_SERVER. - * - * @return UriInterface - */ - public static function getUriFromGlobals() - { - $uri = new Uri(''); - - $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); - - $hasPort = false; - if (isset($_SERVER['HTTP_HOST'])) { - list($host, $port) = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); - if ($host !== null) { - $uri = $uri->withHost($host); - } - - if ($port !== null) { - $hasPort = true; - $uri = $uri->withPort($port); - } - } elseif (isset($_SERVER['SERVER_NAME'])) { - $uri = $uri->withHost($_SERVER['SERVER_NAME']); - } elseif (isset($_SERVER['SERVER_ADDR'])) { - $uri = $uri->withHost($_SERVER['SERVER_ADDR']); - } - - if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { - $uri = $uri->withPort($_SERVER['SERVER_PORT']); - } - - $hasQuery = false; - if (isset($_SERVER['REQUEST_URI'])) { - $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2); - $uri = $uri->withPath($requestUriParts[0]); - if (isset($requestUriParts[1])) { - $hasQuery = true; - $uri = $uri->withQuery($requestUriParts[1]); - } - } - - if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { - $uri = $uri->withQuery($_SERVER['QUERY_STRING']); - } - - return $uri; - } - - - /** - * {@inheritdoc} - */ - public function getServerParams() - { - return $this->serverParams; - } - - /** - * {@inheritdoc} - */ - public function getUploadedFiles() - { - return $this->uploadedFiles; - } - - /** - * {@inheritdoc} - */ - public function withUploadedFiles(array $uploadedFiles) - { - $new = clone $this; - $new->uploadedFiles = $uploadedFiles; - - return $new; - } - - /** - * {@inheritdoc} - */ - public function getCookieParams() - { - return $this->cookieParams; - } - - /** - * {@inheritdoc} - */ - public function withCookieParams(array $cookies) - { - $new = clone $this; - $new->cookieParams = $cookies; - - return $new; - } - - /** - * {@inheritdoc} - */ - public function getQueryParams() - { - return $this->queryParams; - } - - /** - * {@inheritdoc} - */ - public function withQueryParams(array $query) - { - $new = clone $this; - $new->queryParams = $query; - - return $new; - } - - /** - * {@inheritdoc} - */ - public function getParsedBody() - { - return $this->parsedBody; - } - - /** - * {@inheritdoc} - */ - public function withParsedBody($data) - { - $new = clone $this; - $new->parsedBody = $data; - - return $new; - } - - /** - * {@inheritdoc} - */ - public function getAttributes() - { - return $this->attributes; - } - - /** - * {@inheritdoc} - */ - public function getAttribute($attribute, $default = null) - { - if (false === array_key_exists($attribute, $this->attributes)) { - return $default; - } - - return $this->attributes[$attribute]; - } - - /** - * {@inheritdoc} - */ - public function withAttribute($attribute, $value) - { - $new = clone $this; - $new->attributes[$attribute] = $value; - - return $new; - } - - /** - * {@inheritdoc} - */ - public function withoutAttribute($attribute) - { - if (false === array_key_exists($attribute, $this->attributes)) { - return $this; - } - - $new = clone $this; - unset($new->attributes[$attribute]); - - return $new; - } -} diff --git a/vendor/guzzlehttp/psr7/src/Stream.php b/vendor/guzzlehttp/psr7/src/Stream.php deleted file mode 100644 index d9e7409..0000000 --- a/vendor/guzzlehttp/psr7/src/Stream.php +++ /dev/null @@ -1,267 +0,0 @@ -size = $options['size']; - } - - $this->customMetadata = isset($options['metadata']) - ? $options['metadata'] - : []; - - $this->stream = $stream; - $meta = stream_get_meta_data($this->stream); - $this->seekable = $meta['seekable']; - $this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']); - $this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']); - $this->uri = $this->getMetadata('uri'); - } - - /** - * Closes the stream when the destructed - */ - public function __destruct() - { - $this->close(); - } - - public function __toString() - { - try { - $this->seek(0); - return (string) stream_get_contents($this->stream); - } catch (\Exception $e) { - return ''; - } - } - - public function getContents() - { - if (!isset($this->stream)) { - throw new \RuntimeException('Stream is detached'); - } - - $contents = stream_get_contents($this->stream); - - if ($contents === false) { - throw new \RuntimeException('Unable to read stream contents'); - } - - return $contents; - } - - public function close() - { - if (isset($this->stream)) { - if (is_resource($this->stream)) { - fclose($this->stream); - } - $this->detach(); - } - } - - public function detach() - { - if (!isset($this->stream)) { - return null; - } - - $result = $this->stream; - unset($this->stream); - $this->size = $this->uri = null; - $this->readable = $this->writable = $this->seekable = false; - - return $result; - } - - public function getSize() - { - if ($this->size !== null) { - return $this->size; - } - - if (!isset($this->stream)) { - return null; - } - - // Clear the stat cache if the stream has a URI - if ($this->uri) { - clearstatcache(true, $this->uri); - } - - $stats = fstat($this->stream); - if (isset($stats['size'])) { - $this->size = $stats['size']; - return $this->size; - } - - return null; - } - - public function isReadable() - { - return $this->readable; - } - - public function isWritable() - { - return $this->writable; - } - - public function isSeekable() - { - return $this->seekable; - } - - public function eof() - { - if (!isset($this->stream)) { - throw new \RuntimeException('Stream is detached'); - } - - return feof($this->stream); - } - - public function tell() - { - if (!isset($this->stream)) { - throw new \RuntimeException('Stream is detached'); - } - - $result = ftell($this->stream); - - if ($result === false) { - throw new \RuntimeException('Unable to determine stream position'); - } - - return $result; - } - - public function rewind() - { - $this->seek(0); - } - - public function seek($offset, $whence = SEEK_SET) - { - $whence = (int) $whence; - - if (!isset($this->stream)) { - throw new \RuntimeException('Stream is detached'); - } - if (!$this->seekable) { - throw new \RuntimeException('Stream is not seekable'); - } - if (fseek($this->stream, $offset, $whence) === -1) { - throw new \RuntimeException('Unable to seek to stream position ' - . $offset . ' with whence ' . var_export($whence, true)); - } - } - - public function read($length) - { - if (!isset($this->stream)) { - throw new \RuntimeException('Stream is detached'); - } - if (!$this->readable) { - throw new \RuntimeException('Cannot read from non-readable stream'); - } - if ($length < 0) { - throw new \RuntimeException('Length parameter cannot be negative'); - } - - if (0 === $length) { - return ''; - } - - $string = fread($this->stream, $length); - if (false === $string) { - throw new \RuntimeException('Unable to read from stream'); - } - - return $string; - } - - public function write($string) - { - if (!isset($this->stream)) { - throw new \RuntimeException('Stream is detached'); - } - if (!$this->writable) { - throw new \RuntimeException('Cannot write to a non-writable stream'); - } - - // We can't know the size after writing anything - $this->size = null; - $result = fwrite($this->stream, $string); - - if ($result === false) { - throw new \RuntimeException('Unable to write to stream'); - } - - return $result; - } - - public function getMetadata($key = null) - { - if (!isset($this->stream)) { - return $key ? null : []; - } elseif (!$key) { - return $this->customMetadata + stream_get_meta_data($this->stream); - } elseif (isset($this->customMetadata[$key])) { - return $this->customMetadata[$key]; - } - - $meta = stream_get_meta_data($this->stream); - - return isset($meta[$key]) ? $meta[$key] : null; - } -} diff --git a/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php deleted file mode 100644 index daec6f5..0000000 --- a/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php +++ /dev/null @@ -1,149 +0,0 @@ -stream = $stream; - } - - /** - * Magic method used to create a new stream if streams are not added in - * the constructor of a decorator (e.g., LazyOpenStream). - * - * @param string $name Name of the property (allows "stream" only). - * - * @return StreamInterface - */ - public function __get($name) - { - if ($name == 'stream') { - $this->stream = $this->createStream(); - return $this->stream; - } - - throw new \UnexpectedValueException("$name not found on class"); - } - - public function __toString() - { - try { - if ($this->isSeekable()) { - $this->seek(0); - } - return $this->getContents(); - } catch (\Exception $e) { - // Really, PHP? https://bugs.php.net/bug.php?id=53648 - trigger_error('StreamDecorator::__toString exception: ' - . (string) $e, E_USER_ERROR); - return ''; - } - } - - public function getContents() - { - return copy_to_string($this); - } - - /** - * Allow decorators to implement custom methods - * - * @param string $method Missing method name - * @param array $args Method arguments - * - * @return mixed - */ - public function __call($method, array $args) - { - $result = call_user_func_array([$this->stream, $method], $args); - - // Always return the wrapped object if the result is a return $this - return $result === $this->stream ? $this : $result; - } - - public function close() - { - $this->stream->close(); - } - - public function getMetadata($key = null) - { - return $this->stream->getMetadata($key); - } - - public function detach() - { - return $this->stream->detach(); - } - - public function getSize() - { - return $this->stream->getSize(); - } - - public function eof() - { - return $this->stream->eof(); - } - - public function tell() - { - return $this->stream->tell(); - } - - public function isReadable() - { - return $this->stream->isReadable(); - } - - public function isWritable() - { - return $this->stream->isWritable(); - } - - public function isSeekable() - { - return $this->stream->isSeekable(); - } - - public function rewind() - { - $this->seek(0); - } - - public function seek($offset, $whence = SEEK_SET) - { - $this->stream->seek($offset, $whence); - } - - public function read($length) - { - return $this->stream->read($length); - } - - public function write($string) - { - return $this->stream->write($string); - } - - /** - * Implement in subclasses to dynamically create streams when requested. - * - * @return StreamInterface - * @throws \BadMethodCallException - */ - protected function createStream() - { - throw new \BadMethodCallException('Not implemented'); - } -} diff --git a/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/vendor/guzzlehttp/psr7/src/StreamWrapper.php deleted file mode 100644 index 0f3a285..0000000 --- a/vendor/guzzlehttp/psr7/src/StreamWrapper.php +++ /dev/null @@ -1,161 +0,0 @@ -isReadable()) { - $mode = $stream->isWritable() ? 'r+' : 'r'; - } elseif ($stream->isWritable()) { - $mode = 'w'; - } else { - throw new \InvalidArgumentException('The stream must be readable, ' - . 'writable, or both.'); - } - - return fopen('guzzle://stream', $mode, null, self::createStreamContext($stream)); - } - - /** - * Creates a stream context that can be used to open a stream as a php stream resource. - * - * @param StreamInterface $stream - * - * @return resource - */ - public static function createStreamContext(StreamInterface $stream) - { - return stream_context_create([ - 'guzzle' => ['stream' => $stream] - ]); - } - - /** - * Registers the stream wrapper if needed - */ - public static function register() - { - if (!in_array('guzzle', stream_get_wrappers())) { - stream_wrapper_register('guzzle', __CLASS__); - } - } - - public function stream_open($path, $mode, $options, &$opened_path) - { - $options = stream_context_get_options($this->context); - - if (!isset($options['guzzle']['stream'])) { - return false; - } - - $this->mode = $mode; - $this->stream = $options['guzzle']['stream']; - - return true; - } - - public function stream_read($count) - { - return $this->stream->read($count); - } - - public function stream_write($data) - { - return (int) $this->stream->write($data); - } - - public function stream_tell() - { - return $this->stream->tell(); - } - - public function stream_eof() - { - return $this->stream->eof(); - } - - public function stream_seek($offset, $whence) - { - $this->stream->seek($offset, $whence); - - return true; - } - - public function stream_cast($cast_as) - { - $stream = clone($this->stream); - - return $stream->detach(); - } - - public function stream_stat() - { - static $modeMap = [ - 'r' => 33060, - 'rb' => 33060, - 'r+' => 33206, - 'w' => 33188, - 'wb' => 33188 - ]; - - return [ - 'dev' => 0, - 'ino' => 0, - 'mode' => $modeMap[$this->mode], - 'nlink' => 0, - 'uid' => 0, - 'gid' => 0, - 'rdev' => 0, - 'size' => $this->stream->getSize() ?: 0, - 'atime' => 0, - 'mtime' => 0, - 'ctime' => 0, - 'blksize' => 0, - 'blocks' => 0 - ]; - } - - public function url_stat($path, $flags) - { - return [ - 'dev' => 0, - 'ino' => 0, - 'mode' => 0, - 'nlink' => 0, - 'uid' => 0, - 'gid' => 0, - 'rdev' => 0, - 'size' => 0, - 'atime' => 0, - 'mtime' => 0, - 'ctime' => 0, - 'blksize' => 0, - 'blocks' => 0 - ]; - } -} diff --git a/vendor/guzzlehttp/psr7/src/UploadedFile.php b/vendor/guzzlehttp/psr7/src/UploadedFile.php deleted file mode 100644 index e62bd5c..0000000 --- a/vendor/guzzlehttp/psr7/src/UploadedFile.php +++ /dev/null @@ -1,316 +0,0 @@ -setError($errorStatus); - $this->setSize($size); - $this->setClientFilename($clientFilename); - $this->setClientMediaType($clientMediaType); - - if ($this->isOk()) { - $this->setStreamOrFile($streamOrFile); - } - } - - /** - * Depending on the value set file or stream variable - * - * @param mixed $streamOrFile - * @throws InvalidArgumentException - */ - private function setStreamOrFile($streamOrFile) - { - if (is_string($streamOrFile)) { - $this->file = $streamOrFile; - } elseif (is_resource($streamOrFile)) { - $this->stream = new Stream($streamOrFile); - } elseif ($streamOrFile instanceof StreamInterface) { - $this->stream = $streamOrFile; - } else { - throw new InvalidArgumentException( - 'Invalid stream or file provided for UploadedFile' - ); - } - } - - /** - * @param int $error - * @throws InvalidArgumentException - */ - private function setError($error) - { - if (false === is_int($error)) { - throw new InvalidArgumentException( - 'Upload file error status must be an integer' - ); - } - - if (false === in_array($error, UploadedFile::$errors)) { - throw new InvalidArgumentException( - 'Invalid error status for UploadedFile' - ); - } - - $this->error = $error; - } - - /** - * @param int $size - * @throws InvalidArgumentException - */ - private function setSize($size) - { - if (false === is_int($size)) { - throw new InvalidArgumentException( - 'Upload file size must be an integer' - ); - } - - $this->size = $size; - } - - /** - * @param mixed $param - * @return boolean - */ - private function isStringOrNull($param) - { - return in_array(gettype($param), ['string', 'NULL']); - } - - /** - * @param mixed $param - * @return boolean - */ - private function isStringNotEmpty($param) - { - return is_string($param) && false === empty($param); - } - - /** - * @param string|null $clientFilename - * @throws InvalidArgumentException - */ - private function setClientFilename($clientFilename) - { - if (false === $this->isStringOrNull($clientFilename)) { - throw new InvalidArgumentException( - 'Upload file client filename must be a string or null' - ); - } - - $this->clientFilename = $clientFilename; - } - - /** - * @param string|null $clientMediaType - * @throws InvalidArgumentException - */ - private function setClientMediaType($clientMediaType) - { - if (false === $this->isStringOrNull($clientMediaType)) { - throw new InvalidArgumentException( - 'Upload file client media type must be a string or null' - ); - } - - $this->clientMediaType = $clientMediaType; - } - - /** - * Return true if there is no upload error - * - * @return boolean - */ - private function isOk() - { - return $this->error === UPLOAD_ERR_OK; - } - - /** - * @return boolean - */ - public function isMoved() - { - return $this->moved; - } - - /** - * @throws RuntimeException if is moved or not ok - */ - private function validateActive() - { - if (false === $this->isOk()) { - throw new RuntimeException('Cannot retrieve stream due to upload error'); - } - - if ($this->isMoved()) { - throw new RuntimeException('Cannot retrieve stream after it has already been moved'); - } - } - - /** - * {@inheritdoc} - * @throws RuntimeException if the upload was not successful. - */ - public function getStream() - { - $this->validateActive(); - - if ($this->stream instanceof StreamInterface) { - return $this->stream; - } - - return new LazyOpenStream($this->file, 'r+'); - } - - /** - * {@inheritdoc} - * - * @see http://php.net/is_uploaded_file - * @see http://php.net/move_uploaded_file - * @param string $targetPath Path to which to move the uploaded file. - * @throws RuntimeException if the upload was not successful. - * @throws InvalidArgumentException if the $path specified is invalid. - * @throws RuntimeException on any error during the move operation, or on - * the second or subsequent call to the method. - */ - public function moveTo($targetPath) - { - $this->validateActive(); - - if (false === $this->isStringNotEmpty($targetPath)) { - throw new InvalidArgumentException( - 'Invalid path provided for move operation; must be a non-empty string' - ); - } - - if ($this->file) { - $this->moved = php_sapi_name() == 'cli' - ? rename($this->file, $targetPath) - : move_uploaded_file($this->file, $targetPath); - } else { - copy_to_stream( - $this->getStream(), - new LazyOpenStream($targetPath, 'w') - ); - - $this->moved = true; - } - - if (false === $this->moved) { - throw new RuntimeException( - sprintf('Uploaded file could not be moved to %s', $targetPath) - ); - } - } - - /** - * {@inheritdoc} - * - * @return int|null The file size in bytes or null if unknown. - */ - public function getSize() - { - return $this->size; - } - - /** - * {@inheritdoc} - * - * @see http://php.net/manual/en/features.file-upload.errors.php - * @return int One of PHP's UPLOAD_ERR_XXX constants. - */ - public function getError() - { - return $this->error; - } - - /** - * {@inheritdoc} - * - * @return string|null The filename sent by the client or null if none - * was provided. - */ - public function getClientFilename() - { - return $this->clientFilename; - } - - /** - * {@inheritdoc} - */ - public function getClientMediaType() - { - return $this->clientMediaType; - } -} diff --git a/vendor/guzzlehttp/psr7/src/Uri.php b/vendor/guzzlehttp/psr7/src/Uri.php deleted file mode 100644 index 825a25e..0000000 --- a/vendor/guzzlehttp/psr7/src/Uri.php +++ /dev/null @@ -1,760 +0,0 @@ - 80, - 'https' => 443, - 'ftp' => 21, - 'gopher' => 70, - 'nntp' => 119, - 'news' => 119, - 'telnet' => 23, - 'tn3270' => 23, - 'imap' => 143, - 'pop' => 110, - 'ldap' => 389, - ]; - - private static $charUnreserved = 'a-zA-Z0-9_\-\.~'; - private static $charSubDelims = '!\$&\'\(\)\*\+,;='; - private static $replaceQuery = ['=' => '%3D', '&' => '%26']; - - /** @var string Uri scheme. */ - private $scheme = ''; - - /** @var string Uri user info. */ - private $userInfo = ''; - - /** @var string Uri host. */ - private $host = ''; - - /** @var int|null Uri port. */ - private $port; - - /** @var string Uri path. */ - private $path = ''; - - /** @var string Uri query string. */ - private $query = ''; - - /** @var string Uri fragment. */ - private $fragment = ''; - - /** - * @param string $uri URI to parse - */ - public function __construct($uri = '') - { - // weak type check to also accept null until we can add scalar type hints - if ($uri != '') { - $parts = parse_url($uri); - if ($parts === false) { - throw new \InvalidArgumentException("Unable to parse URI: $uri"); - } - $this->applyParts($parts); - } - } - - public function __toString() - { - return self::composeComponents( - $this->scheme, - $this->getAuthority(), - $this->path, - $this->query, - $this->fragment - ); - } - - /** - * Composes a URI reference string from its various components. - * - * Usually this method does not need to be called manually but instead is used indirectly via - * `Psr\Http\Message\UriInterface::__toString`. - * - * PSR-7 UriInterface treats an empty component the same as a missing component as - * getQuery(), getFragment() etc. always return a string. This explains the slight - * difference to RFC 3986 Section 5.3. - * - * Another adjustment is that the authority separator is added even when the authority is missing/empty - * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with - * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But - * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to - * that format). - * - * @param string $scheme - * @param string $authority - * @param string $path - * @param string $query - * @param string $fragment - * - * @return string - * - * @link https://tools.ietf.org/html/rfc3986#section-5.3 - */ - public static function composeComponents($scheme, $authority, $path, $query, $fragment) - { - $uri = ''; - - // weak type checks to also accept null until we can add scalar type hints - if ($scheme != '') { - $uri .= $scheme . ':'; - } - - if ($authority != ''|| $scheme === 'file') { - $uri .= '//' . $authority; - } - - $uri .= $path; - - if ($query != '') { - $uri .= '?' . $query; - } - - if ($fragment != '') { - $uri .= '#' . $fragment; - } - - return $uri; - } - - /** - * Whether the URI has the default port of the current scheme. - * - * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used - * independently of the implementation. - * - * @param UriInterface $uri - * - * @return bool - */ - public static function isDefaultPort(UriInterface $uri) - { - return $uri->getPort() === null - || (isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]); - } - - /** - * Whether the URI is absolute, i.e. it has a scheme. - * - * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true - * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative - * to another URI, the base URI. Relative references can be divided into several forms: - * - network-path references, e.g. '//example.com/path' - * - absolute-path references, e.g. '/path' - * - relative-path references, e.g. 'subpath' - * - * @param UriInterface $uri - * - * @return bool - * @see Uri::isNetworkPathReference - * @see Uri::isAbsolutePathReference - * @see Uri::isRelativePathReference - * @link https://tools.ietf.org/html/rfc3986#section-4 - */ - public static function isAbsolute(UriInterface $uri) - { - return $uri->getScheme() !== ''; - } - - /** - * Whether the URI is a network-path reference. - * - * A relative reference that begins with two slash characters is termed an network-path reference. - * - * @param UriInterface $uri - * - * @return bool - * @link https://tools.ietf.org/html/rfc3986#section-4.2 - */ - public static function isNetworkPathReference(UriInterface $uri) - { - return $uri->getScheme() === '' && $uri->getAuthority() !== ''; - } - - /** - * Whether the URI is a absolute-path reference. - * - * A relative reference that begins with a single slash character is termed an absolute-path reference. - * - * @param UriInterface $uri - * - * @return bool - * @link https://tools.ietf.org/html/rfc3986#section-4.2 - */ - public static function isAbsolutePathReference(UriInterface $uri) - { - return $uri->getScheme() === '' - && $uri->getAuthority() === '' - && isset($uri->getPath()[0]) - && $uri->getPath()[0] === '/'; - } - - /** - * Whether the URI is a relative-path reference. - * - * A relative reference that does not begin with a slash character is termed a relative-path reference. - * - * @param UriInterface $uri - * - * @return bool - * @link https://tools.ietf.org/html/rfc3986#section-4.2 - */ - public static function isRelativePathReference(UriInterface $uri) - { - return $uri->getScheme() === '' - && $uri->getAuthority() === '' - && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); - } - - /** - * Whether the URI is a same-document reference. - * - * A same-document reference refers to a URI that is, aside from its fragment - * component, identical to the base URI. When no base URI is given, only an empty - * URI reference (apart from its fragment) is considered a same-document reference. - * - * @param UriInterface $uri The URI to check - * @param UriInterface|null $base An optional base URI to compare against - * - * @return bool - * @link https://tools.ietf.org/html/rfc3986#section-4.4 - */ - public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null) - { - if ($base !== null) { - $uri = UriResolver::resolve($base, $uri); - - return ($uri->getScheme() === $base->getScheme()) - && ($uri->getAuthority() === $base->getAuthority()) - && ($uri->getPath() === $base->getPath()) - && ($uri->getQuery() === $base->getQuery()); - } - - return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; - } - - /** - * Removes dot segments from a path and returns the new path. - * - * @param string $path - * - * @return string - * - * @deprecated since version 1.4. Use UriResolver::removeDotSegments instead. - * @see UriResolver::removeDotSegments - */ - public static function removeDotSegments($path) - { - return UriResolver::removeDotSegments($path); - } - - /** - * Converts the relative URI into a new URI that is resolved against the base URI. - * - * @param UriInterface $base Base URI - * @param string|UriInterface $rel Relative URI - * - * @return UriInterface - * - * @deprecated since version 1.4. Use UriResolver::resolve instead. - * @see UriResolver::resolve - */ - public static function resolve(UriInterface $base, $rel) - { - if (!($rel instanceof UriInterface)) { - $rel = new self($rel); - } - - return UriResolver::resolve($base, $rel); - } - - /** - * Creates a new URI with a specific query string value removed. - * - * Any existing query string values that exactly match the provided key are - * removed. - * - * @param UriInterface $uri URI to use as a base. - * @param string $key Query string key to remove. - * - * @return UriInterface - */ - public static function withoutQueryValue(UriInterface $uri, $key) - { - $result = self::getFilteredQueryString($uri, [$key]); - - return $uri->withQuery(implode('&', $result)); - } - - /** - * Creates a new URI with a specific query string value. - * - * Any existing query string values that exactly match the provided key are - * removed and replaced with the given key value pair. - * - * A value of null will set the query string key without a value, e.g. "key" - * instead of "key=value". - * - * @param UriInterface $uri URI to use as a base. - * @param string $key Key to set. - * @param string|null $value Value to set - * - * @return UriInterface - */ - public static function withQueryValue(UriInterface $uri, $key, $value) - { - $result = self::getFilteredQueryString($uri, [$key]); - - $result[] = self::generateQueryString($key, $value); - - return $uri->withQuery(implode('&', $result)); - } - - /** - * Creates a new URI with multiple specific query string values. - * - * It has the same behavior as withQueryValue() but for an associative array of key => value. - * - * @param UriInterface $uri URI to use as a base. - * @param array $keyValueArray Associative array of key and values - * - * @return UriInterface - */ - public static function withQueryValues(UriInterface $uri, array $keyValueArray) - { - $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); - - foreach ($keyValueArray as $key => $value) { - $result[] = self::generateQueryString($key, $value); - } - - return $uri->withQuery(implode('&', $result)); - } - - /** - * Creates a URI from a hash of `parse_url` components. - * - * @param array $parts - * - * @return UriInterface - * @link http://php.net/manual/en/function.parse-url.php - * - * @throws \InvalidArgumentException If the components do not form a valid URI. - */ - public static function fromParts(array $parts) - { - $uri = new self(); - $uri->applyParts($parts); - $uri->validateState(); - - return $uri; - } - - public function getScheme() - { - return $this->scheme; - } - - public function getAuthority() - { - $authority = $this->host; - if ($this->userInfo !== '') { - $authority = $this->userInfo . '@' . $authority; - } - - if ($this->port !== null) { - $authority .= ':' . $this->port; - } - - return $authority; - } - - public function getUserInfo() - { - return $this->userInfo; - } - - public function getHost() - { - return $this->host; - } - - public function getPort() - { - return $this->port; - } - - public function getPath() - { - return $this->path; - } - - public function getQuery() - { - return $this->query; - } - - public function getFragment() - { - return $this->fragment; - } - - public function withScheme($scheme) - { - $scheme = $this->filterScheme($scheme); - - if ($this->scheme === $scheme) { - return $this; - } - - $new = clone $this; - $new->scheme = $scheme; - $new->removeDefaultPort(); - $new->validateState(); - - return $new; - } - - public function withUserInfo($user, $password = null) - { - $info = $this->filterUserInfoComponent($user); - if ($password !== null) { - $info .= ':' . $this->filterUserInfoComponent($password); - } - - if ($this->userInfo === $info) { - return $this; - } - - $new = clone $this; - $new->userInfo = $info; - $new->validateState(); - - return $new; - } - - public function withHost($host) - { - $host = $this->filterHost($host); - - if ($this->host === $host) { - return $this; - } - - $new = clone $this; - $new->host = $host; - $new->validateState(); - - return $new; - } - - public function withPort($port) - { - $port = $this->filterPort($port); - - if ($this->port === $port) { - return $this; - } - - $new = clone $this; - $new->port = $port; - $new->removeDefaultPort(); - $new->validateState(); - - return $new; - } - - public function withPath($path) - { - $path = $this->filterPath($path); - - if ($this->path === $path) { - return $this; - } - - $new = clone $this; - $new->path = $path; - $new->validateState(); - - return $new; - } - - public function withQuery($query) - { - $query = $this->filterQueryAndFragment($query); - - if ($this->query === $query) { - return $this; - } - - $new = clone $this; - $new->query = $query; - - return $new; - } - - public function withFragment($fragment) - { - $fragment = $this->filterQueryAndFragment($fragment); - - if ($this->fragment === $fragment) { - return $this; - } - - $new = clone $this; - $new->fragment = $fragment; - - return $new; - } - - /** - * Apply parse_url parts to a URI. - * - * @param array $parts Array of parse_url parts to apply. - */ - private function applyParts(array $parts) - { - $this->scheme = isset($parts['scheme']) - ? $this->filterScheme($parts['scheme']) - : ''; - $this->userInfo = isset($parts['user']) - ? $this->filterUserInfoComponent($parts['user']) - : ''; - $this->host = isset($parts['host']) - ? $this->filterHost($parts['host']) - : ''; - $this->port = isset($parts['port']) - ? $this->filterPort($parts['port']) - : null; - $this->path = isset($parts['path']) - ? $this->filterPath($parts['path']) - : ''; - $this->query = isset($parts['query']) - ? $this->filterQueryAndFragment($parts['query']) - : ''; - $this->fragment = isset($parts['fragment']) - ? $this->filterQueryAndFragment($parts['fragment']) - : ''; - if (isset($parts['pass'])) { - $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); - } - - $this->removeDefaultPort(); - } - - /** - * @param string $scheme - * - * @return string - * - * @throws \InvalidArgumentException If the scheme is invalid. - */ - private function filterScheme($scheme) - { - if (!is_string($scheme)) { - throw new \InvalidArgumentException('Scheme must be a string'); - } - - return strtolower($scheme); - } - - /** - * @param string $component - * - * @return string - * - * @throws \InvalidArgumentException If the user info is invalid. - */ - private function filterUserInfoComponent($component) - { - if (!is_string($component)) { - throw new \InvalidArgumentException('User info must be a string'); - } - - return preg_replace_callback( - '/(?:[^%' . self::$charUnreserved . self::$charSubDelims . ']+|%(?![A-Fa-f0-9]{2}))/', - [$this, 'rawurlencodeMatchZero'], - $component - ); - } - - /** - * @param string $host - * - * @return string - * - * @throws \InvalidArgumentException If the host is invalid. - */ - private function filterHost($host) - { - if (!is_string($host)) { - throw new \InvalidArgumentException('Host must be a string'); - } - - return strtolower($host); - } - - /** - * @param int|null $port - * - * @return int|null - * - * @throws \InvalidArgumentException If the port is invalid. - */ - private function filterPort($port) - { - if ($port === null) { - return null; - } - - $port = (int) $port; - if (0 > $port || 0xffff < $port) { - throw new \InvalidArgumentException( - sprintf('Invalid port: %d. Must be between 0 and 65535', $port) - ); - } - - return $port; - } - - /** - * @param UriInterface $uri - * @param array $keys - * - * @return array - */ - private static function getFilteredQueryString(UriInterface $uri, array $keys) - { - $current = $uri->getQuery(); - - if ($current === '') { - return []; - } - - $decodedKeys = array_map('rawurldecode', $keys); - - return array_filter(explode('&', $current), function ($part) use ($decodedKeys) { - return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); - }); - } - - /** - * @param string $key - * @param string|null $value - * - * @return string - */ - private static function generateQueryString($key, $value) - { - // Query string separators ("=", "&") within the key or value need to be encoded - // (while preventing double-encoding) before setting the query string. All other - // chars that need percent-encoding will be encoded by withQuery(). - $queryString = strtr($key, self::$replaceQuery); - - if ($value !== null) { - $queryString .= '=' . strtr($value, self::$replaceQuery); - } - - return $queryString; - } - - private function removeDefaultPort() - { - if ($this->port !== null && self::isDefaultPort($this)) { - $this->port = null; - } - } - - /** - * Filters the path of a URI - * - * @param string $path - * - * @return string - * - * @throws \InvalidArgumentException If the path is invalid. - */ - private function filterPath($path) - { - if (!is_string($path)) { - throw new \InvalidArgumentException('Path must be a string'); - } - - return preg_replace_callback( - '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', - [$this, 'rawurlencodeMatchZero'], - $path - ); - } - - /** - * Filters the query string or fragment of a URI. - * - * @param string $str - * - * @return string - * - * @throws \InvalidArgumentException If the query or fragment is invalid. - */ - private function filterQueryAndFragment($str) - { - if (!is_string($str)) { - throw new \InvalidArgumentException('Query and fragment must be a string'); - } - - return preg_replace_callback( - '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', - [$this, 'rawurlencodeMatchZero'], - $str - ); - } - - private function rawurlencodeMatchZero(array $match) - { - return rawurlencode($match[0]); - } - - private function validateState() - { - if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { - $this->host = self::HTTP_DEFAULT_HOST; - } - - if ($this->getAuthority() === '') { - if (0 === strpos($this->path, '//')) { - throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"'); - } - if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { - throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); - } - } elseif (isset($this->path[0]) && $this->path[0] !== '/') { - @trigger_error( - 'The path of a URI with an authority must start with a slash "/" or be empty. Automagically fixing the URI ' . - 'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.', - E_USER_DEPRECATED - ); - $this->path = '/'. $this->path; - //throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty'); - } - } -} diff --git a/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/vendor/guzzlehttp/psr7/src/UriNormalizer.php deleted file mode 100644 index 384c29e..0000000 --- a/vendor/guzzlehttp/psr7/src/UriNormalizer.php +++ /dev/null @@ -1,216 +0,0 @@ -getPath() === '' && - ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') - ) { - $uri = $uri->withPath('/'); - } - - if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { - $uri = $uri->withHost(''); - } - - if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { - $uri = $uri->withPort(null); - } - - if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { - $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); - } - - if ($flags & self::REMOVE_DUPLICATE_SLASHES) { - $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); - } - - if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { - $queryKeyValues = explode('&', $uri->getQuery()); - sort($queryKeyValues); - $uri = $uri->withQuery(implode('&', $queryKeyValues)); - } - - return $uri; - } - - /** - * Whether two URIs can be considered equivalent. - * - * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also - * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be - * resolved against the same base URI. If this is not the case, determination of equivalence or difference of - * relative references does not mean anything. - * - * @param UriInterface $uri1 An URI to compare - * @param UriInterface $uri2 An URI to compare - * @param int $normalizations A bitmask of normalizations to apply, see constants - * - * @return bool - * @link https://tools.ietf.org/html/rfc3986#section-6.1 - */ - public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS) - { - return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); - } - - private static function capitalizePercentEncoding(UriInterface $uri) - { - $regex = '/(?:%[A-Fa-f0-9]{2})++/'; - - $callback = function (array $match) { - return strtoupper($match[0]); - }; - - return - $uri->withPath( - preg_replace_callback($regex, $callback, $uri->getPath()) - )->withQuery( - preg_replace_callback($regex, $callback, $uri->getQuery()) - ); - } - - private static function decodeUnreservedCharacters(UriInterface $uri) - { - $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; - - $callback = function (array $match) { - return rawurldecode($match[0]); - }; - - return - $uri->withPath( - preg_replace_callback($regex, $callback, $uri->getPath()) - )->withQuery( - preg_replace_callback($regex, $callback, $uri->getQuery()) - ); - } - - private function __construct() - { - // cannot be instantiated - } -} diff --git a/vendor/guzzlehttp/psr7/src/UriResolver.php b/vendor/guzzlehttp/psr7/src/UriResolver.php deleted file mode 100644 index c1cb8a2..0000000 --- a/vendor/guzzlehttp/psr7/src/UriResolver.php +++ /dev/null @@ -1,219 +0,0 @@ -getScheme() != '') { - return $rel->withPath(self::removeDotSegments($rel->getPath())); - } - - if ($rel->getAuthority() != '') { - $targetAuthority = $rel->getAuthority(); - $targetPath = self::removeDotSegments($rel->getPath()); - $targetQuery = $rel->getQuery(); - } else { - $targetAuthority = $base->getAuthority(); - if ($rel->getPath() === '') { - $targetPath = $base->getPath(); - $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); - } else { - if ($rel->getPath()[0] === '/') { - $targetPath = $rel->getPath(); - } else { - if ($targetAuthority != '' && $base->getPath() === '') { - $targetPath = '/' . $rel->getPath(); - } else { - $lastSlashPos = strrpos($base->getPath(), '/'); - if ($lastSlashPos === false) { - $targetPath = $rel->getPath(); - } else { - $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath(); - } - } - } - $targetPath = self::removeDotSegments($targetPath); - $targetQuery = $rel->getQuery(); - } - } - - return new Uri(Uri::composeComponents( - $base->getScheme(), - $targetAuthority, - $targetPath, - $targetQuery, - $rel->getFragment() - )); - } - - /** - * Returns the target URI as a relative reference from the base URI. - * - * This method is the counterpart to resolve(): - * - * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) - * - * One use-case is to use the current request URI as base URI and then generate relative links in your documents - * to reduce the document size or offer self-contained downloadable document archives. - * - * $base = new Uri('http://example.com/a/b/'); - * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. - * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. - * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. - * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. - * - * This method also accepts a target that is already relative and will try to relativize it further. Only a - * relative-path reference will be returned as-is. - * - * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well - * - * @param UriInterface $base Base URI - * @param UriInterface $target Target URI - * - * @return UriInterface The relative URI reference - */ - public static function relativize(UriInterface $base, UriInterface $target) - { - if ($target->getScheme() !== '' && - ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') - ) { - return $target; - } - - if (Uri::isRelativePathReference($target)) { - // As the target is already highly relative we return it as-is. It would be possible to resolve - // the target with `$target = self::resolve($base, $target);` and then try make it more relative - // by removing a duplicate query. But let's not do that automatically. - return $target; - } - - if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { - return $target->withScheme(''); - } - - // We must remove the path before removing the authority because if the path starts with two slashes, the URI - // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also - // invalid. - $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); - - if ($base->getPath() !== $target->getPath()) { - return $emptyPathUri->withPath(self::getRelativePath($base, $target)); - } - - if ($base->getQuery() === $target->getQuery()) { - // Only the target fragment is left. And it must be returned even if base and target fragment are the same. - return $emptyPathUri->withQuery(''); - } - - // If the base URI has a query but the target has none, we cannot return an empty path reference as it would - // inherit the base query component when resolving. - if ($target->getQuery() === '') { - $segments = explode('/', $target->getPath()); - $lastSegment = end($segments); - - return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); - } - - return $emptyPathUri; - } - - private static function getRelativePath(UriInterface $base, UriInterface $target) - { - $sourceSegments = explode('/', $base->getPath()); - $targetSegments = explode('/', $target->getPath()); - array_pop($sourceSegments); - $targetLastSegment = array_pop($targetSegments); - foreach ($sourceSegments as $i => $segment) { - if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { - unset($sourceSegments[$i], $targetSegments[$i]); - } else { - break; - } - } - $targetSegments[] = $targetLastSegment; - $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments); - - // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". - // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used - // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. - if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { - $relativePath = "./$relativePath"; - } elseif ('/' === $relativePath[0]) { - if ($base->getAuthority() != '' && $base->getPath() === '') { - // In this case an extra slash is added by resolve() automatically. So we must not add one here. - $relativePath = ".$relativePath"; - } else { - $relativePath = "./$relativePath"; - } - } - - return $relativePath; - } - - private function __construct() - { - // cannot be instantiated - } -} diff --git a/vendor/guzzlehttp/psr7/src/functions.php b/vendor/guzzlehttp/psr7/src/functions.php deleted file mode 100644 index 8e6dafe..0000000 --- a/vendor/guzzlehttp/psr7/src/functions.php +++ /dev/null @@ -1,899 +0,0 @@ -getMethod() . ' ' - . $message->getRequestTarget()) - . ' HTTP/' . $message->getProtocolVersion(); - if (!$message->hasHeader('host')) { - $msg .= "\r\nHost: " . $message->getUri()->getHost(); - } - } elseif ($message instanceof ResponseInterface) { - $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' - . $message->getStatusCode() . ' ' - . $message->getReasonPhrase(); - } else { - throw new \InvalidArgumentException('Unknown message type'); - } - - foreach ($message->getHeaders() as $name => $values) { - $msg .= "\r\n{$name}: " . implode(', ', $values); - } - - return "{$msg}\r\n\r\n" . $message->getBody(); -} - -/** - * Returns a UriInterface for the given value. - * - * This function accepts a string or {@see Psr\Http\Message\UriInterface} and - * returns a UriInterface for the given value. If the value is already a - * `UriInterface`, it is returned as-is. - * - * @param string|UriInterface $uri - * - * @return UriInterface - * @throws \InvalidArgumentException - */ -function uri_for($uri) -{ - if ($uri instanceof UriInterface) { - return $uri; - } elseif (is_string($uri)) { - return new Uri($uri); - } - - throw new \InvalidArgumentException('URI must be a string or UriInterface'); -} - -/** - * Create a new stream based on the input type. - * - * Options is an associative array that can contain the following keys: - * - metadata: Array of custom metadata. - * - size: Size of the stream. - * - * @param resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource Entity body data - * @param array $options Additional options - * - * @return StreamInterface - * @throws \InvalidArgumentException if the $resource arg is not valid. - */ -function stream_for($resource = '', array $options = []) -{ - if (is_scalar($resource)) { - $stream = fopen('php://temp', 'r+'); - if ($resource !== '') { - fwrite($stream, $resource); - fseek($stream, 0); - } - return new Stream($stream, $options); - } - - switch (gettype($resource)) { - case 'resource': - return new Stream($resource, $options); - case 'object': - if ($resource instanceof StreamInterface) { - return $resource; - } elseif ($resource instanceof \Iterator) { - return new PumpStream(function () use ($resource) { - if (!$resource->valid()) { - return false; - } - $result = $resource->current(); - $resource->next(); - return $result; - }, $options); - } elseif (method_exists($resource, '__toString')) { - return stream_for((string) $resource, $options); - } - break; - case 'NULL': - return new Stream(fopen('php://temp', 'r+'), $options); - } - - if (is_callable($resource)) { - return new PumpStream($resource, $options); - } - - throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); -} - -/** - * Parse an array of header values containing ";" separated data into an - * array of associative arrays representing the header key value pair - * data of the header. When a parameter does not contain a value, but just - * contains a key, this function will inject a key with a '' string value. - * - * @param string|array $header Header to parse into components. - * - * @return array Returns the parsed header values. - */ -function parse_header($header) -{ - static $trimmed = "\"' \n\t\r"; - $params = $matches = []; - - foreach (normalize_header($header) as $val) { - $part = []; - foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) { - if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { - $m = $matches[0]; - if (isset($m[1])) { - $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); - } else { - $part[] = trim($m[0], $trimmed); - } - } - } - if ($part) { - $params[] = $part; - } - } - - return $params; -} - -/** - * Converts an array of header values that may contain comma separated - * headers into an array of headers with no comma separated values. - * - * @param string|array $header Header to normalize. - * - * @return array Returns the normalized header field values. - */ -function normalize_header($header) -{ - if (!is_array($header)) { - return array_map('trim', explode(',', $header)); - } - - $result = []; - foreach ($header as $value) { - foreach ((array) $value as $v) { - if (strpos($v, ',') === false) { - $result[] = $v; - continue; - } - foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) { - $result[] = trim($vv); - } - } - } - - return $result; -} - -/** - * Clone and modify a request with the given changes. - * - * The changes can be one of: - * - method: (string) Changes the HTTP method. - * - set_headers: (array) Sets the given headers. - * - remove_headers: (array) Remove the given headers. - * - body: (mixed) Sets the given body. - * - uri: (UriInterface) Set the URI. - * - query: (string) Set the query string value of the URI. - * - version: (string) Set the protocol version. - * - * @param RequestInterface $request Request to clone and modify. - * @param array $changes Changes to apply. - * - * @return RequestInterface - */ -function modify_request(RequestInterface $request, array $changes) -{ - if (!$changes) { - return $request; - } - - $headers = $request->getHeaders(); - - if (!isset($changes['uri'])) { - $uri = $request->getUri(); - } else { - // Remove the host header if one is on the URI - if ($host = $changes['uri']->getHost()) { - $changes['set_headers']['Host'] = $host; - - if ($port = $changes['uri']->getPort()) { - $standardPorts = ['http' => 80, 'https' => 443]; - $scheme = $changes['uri']->getScheme(); - if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { - $changes['set_headers']['Host'] .= ':'.$port; - } - } - } - $uri = $changes['uri']; - } - - if (!empty($changes['remove_headers'])) { - $headers = _caseless_remove($changes['remove_headers'], $headers); - } - - if (!empty($changes['set_headers'])) { - $headers = _caseless_remove(array_keys($changes['set_headers']), $headers); - $headers = $changes['set_headers'] + $headers; - } - - if (isset($changes['query'])) { - $uri = $uri->withQuery($changes['query']); - } - - if ($request instanceof ServerRequestInterface) { - return (new ServerRequest( - isset($changes['method']) ? $changes['method'] : $request->getMethod(), - $uri, - $headers, - isset($changes['body']) ? $changes['body'] : $request->getBody(), - isset($changes['version']) - ? $changes['version'] - : $request->getProtocolVersion(), - $request->getServerParams() - )) - ->withParsedBody($request->getParsedBody()) - ->withQueryParams($request->getQueryParams()) - ->withCookieParams($request->getCookieParams()) - ->withUploadedFiles($request->getUploadedFiles()); - } - - return new Request( - isset($changes['method']) ? $changes['method'] : $request->getMethod(), - $uri, - $headers, - isset($changes['body']) ? $changes['body'] : $request->getBody(), - isset($changes['version']) - ? $changes['version'] - : $request->getProtocolVersion() - ); -} - -/** - * Attempts to rewind a message body and throws an exception on failure. - * - * The body of the message will only be rewound if a call to `tell()` returns a - * value other than `0`. - * - * @param MessageInterface $message Message to rewind - * - * @throws \RuntimeException - */ -function rewind_body(MessageInterface $message) -{ - $body = $message->getBody(); - - if ($body->tell()) { - $body->rewind(); - } -} - -/** - * Safely opens a PHP stream resource using a filename. - * - * When fopen fails, PHP normally raises a warning. This function adds an - * error handler that checks for errors and throws an exception instead. - * - * @param string $filename File to open - * @param string $mode Mode used to open the file - * - * @return resource - * @throws \RuntimeException if the file cannot be opened - */ -function try_fopen($filename, $mode) -{ - $ex = null; - set_error_handler(function () use ($filename, $mode, &$ex) { - $ex = new \RuntimeException(sprintf( - 'Unable to open %s using mode %s: %s', - $filename, - $mode, - func_get_args()[1] - )); - }); - - $handle = fopen($filename, $mode); - restore_error_handler(); - - if ($ex) { - /** @var $ex \RuntimeException */ - throw $ex; - } - - return $handle; -} - -/** - * Copy the contents of a stream into a string until the given number of - * bytes have been read. - * - * @param StreamInterface $stream Stream to read - * @param int $maxLen Maximum number of bytes to read. Pass -1 - * to read the entire stream. - * @return string - * @throws \RuntimeException on error. - */ -function copy_to_string(StreamInterface $stream, $maxLen = -1) -{ - $buffer = ''; - - if ($maxLen === -1) { - while (!$stream->eof()) { - $buf = $stream->read(1048576); - // Using a loose equality here to match on '' and false. - if ($buf == null) { - break; - } - $buffer .= $buf; - } - return $buffer; - } - - $len = 0; - while (!$stream->eof() && $len < $maxLen) { - $buf = $stream->read($maxLen - $len); - // Using a loose equality here to match on '' and false. - if ($buf == null) { - break; - } - $buffer .= $buf; - $len = strlen($buffer); - } - - return $buffer; -} - -/** - * Copy the contents of a stream into another stream until the given number - * of bytes have been read. - * - * @param StreamInterface $source Stream to read from - * @param StreamInterface $dest Stream to write to - * @param int $maxLen Maximum number of bytes to read. Pass -1 - * to read the entire stream. - * - * @throws \RuntimeException on error. - */ -function copy_to_stream( - StreamInterface $source, - StreamInterface $dest, - $maxLen = -1 -) { - $bufferSize = 8192; - - if ($maxLen === -1) { - while (!$source->eof()) { - if (!$dest->write($source->read($bufferSize))) { - break; - } - } - } else { - $remaining = $maxLen; - while ($remaining > 0 && !$source->eof()) { - $buf = $source->read(min($bufferSize, $remaining)); - $len = strlen($buf); - if (!$len) { - break; - } - $remaining -= $len; - $dest->write($buf); - } - } -} - -/** - * Calculate a hash of a Stream - * - * @param StreamInterface $stream Stream to calculate the hash for - * @param string $algo Hash algorithm (e.g. md5, crc32, etc) - * @param bool $rawOutput Whether or not to use raw output - * - * @return string Returns the hash of the stream - * @throws \RuntimeException on error. - */ -function hash( - StreamInterface $stream, - $algo, - $rawOutput = false -) { - $pos = $stream->tell(); - - if ($pos > 0) { - $stream->rewind(); - } - - $ctx = hash_init($algo); - while (!$stream->eof()) { - hash_update($ctx, $stream->read(1048576)); - } - - $out = hash_final($ctx, (bool) $rawOutput); - $stream->seek($pos); - - return $out; -} - -/** - * Read a line from the stream up to the maximum allowed buffer length - * - * @param StreamInterface $stream Stream to read from - * @param int $maxLength Maximum buffer length - * - * @return string - */ -function readline(StreamInterface $stream, $maxLength = null) -{ - $buffer = ''; - $size = 0; - - while (!$stream->eof()) { - // Using a loose equality here to match on '' and false. - if (null == ($byte = $stream->read(1))) { - return $buffer; - } - $buffer .= $byte; - // Break when a new line is found or the max length - 1 is reached - if ($byte === "\n" || ++$size === $maxLength - 1) { - break; - } - } - - return $buffer; -} - -/** - * Parses a request message string into a request object. - * - * @param string $message Request message string. - * - * @return Request - */ -function parse_request($message) -{ - $data = _parse_message($message); - $matches = []; - if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { - throw new \InvalidArgumentException('Invalid request string'); - } - $parts = explode(' ', $data['start-line'], 3); - $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; - - $request = new Request( - $parts[0], - $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1], - $data['headers'], - $data['body'], - $version - ); - - return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); -} - -/** - * Parses a response message string into a response object. - * - * @param string $message Response message string. - * - * @return Response - */ -function parse_response($message) -{ - $data = _parse_message($message); - // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space - // between status-code and reason-phrase is required. But browsers accept - // responses without space and reason as well. - if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { - throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']); - } - $parts = explode(' ', $data['start-line'], 3); - - return new Response( - $parts[1], - $data['headers'], - $data['body'], - explode('/', $parts[0])[1], - isset($parts[2]) ? $parts[2] : null - ); -} - -/** - * Parse a query string into an associative array. - * - * If multiple values are found for the same key, the value of that key - * value pair will become an array. This function does not parse nested - * PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will - * be parsed into ['foo[a]' => '1', 'foo[b]' => '2']). - * - * @param string $str Query string to parse - * @param int|bool $urlEncoding How the query string is encoded - * - * @return array - */ -function parse_query($str, $urlEncoding = true) -{ - $result = []; - - if ($str === '') { - return $result; - } - - if ($urlEncoding === true) { - $decoder = function ($value) { - return rawurldecode(str_replace('+', ' ', $value)); - }; - } elseif ($urlEncoding === PHP_QUERY_RFC3986) { - $decoder = 'rawurldecode'; - } elseif ($urlEncoding === PHP_QUERY_RFC1738) { - $decoder = 'urldecode'; - } else { - $decoder = function ($str) { return $str; }; - } - - foreach (explode('&', $str) as $kvp) { - $parts = explode('=', $kvp, 2); - $key = $decoder($parts[0]); - $value = isset($parts[1]) ? $decoder($parts[1]) : null; - if (!isset($result[$key])) { - $result[$key] = $value; - } else { - if (!is_array($result[$key])) { - $result[$key] = [$result[$key]]; - } - $result[$key][] = $value; - } - } - - return $result; -} - -/** - * Build a query string from an array of key value pairs. - * - * This function can use the return value of parse_query() to build a query - * string. This function does not modify the provided keys when an array is - * encountered (like http_build_query would). - * - * @param array $params Query string parameters. - * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 - * to encode using RFC3986, or PHP_QUERY_RFC1738 - * to encode using RFC1738. - * @return string - */ -function build_query(array $params, $encoding = PHP_QUERY_RFC3986) -{ - if (!$params) { - return ''; - } - - if ($encoding === false) { - $encoder = function ($str) { return $str; }; - } elseif ($encoding === PHP_QUERY_RFC3986) { - $encoder = 'rawurlencode'; - } elseif ($encoding === PHP_QUERY_RFC1738) { - $encoder = 'urlencode'; - } else { - throw new \InvalidArgumentException('Invalid type'); - } - - $qs = ''; - foreach ($params as $k => $v) { - $k = $encoder($k); - if (!is_array($v)) { - $qs .= $k; - if ($v !== null) { - $qs .= '=' . $encoder($v); - } - $qs .= '&'; - } else { - foreach ($v as $vv) { - $qs .= $k; - if ($vv !== null) { - $qs .= '=' . $encoder($vv); - } - $qs .= '&'; - } - } - } - - return $qs ? (string) substr($qs, 0, -1) : ''; -} - -/** - * Determines the mimetype of a file by looking at its extension. - * - * @param $filename - * - * @return null|string - */ -function mimetype_from_filename($filename) -{ - return mimetype_from_extension(pathinfo($filename, PATHINFO_EXTENSION)); -} - -/** - * Maps a file extensions to a mimetype. - * - * @param $extension string The file extension. - * - * @return string|null - * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types - */ -function mimetype_from_extension($extension) -{ - static $mimetypes = [ - '3gp' => 'video/3gpp', - '7z' => 'application/x-7z-compressed', - 'aac' => 'audio/x-aac', - 'ai' => 'application/postscript', - 'aif' => 'audio/x-aiff', - 'asc' => 'text/plain', - 'asf' => 'video/x-ms-asf', - 'atom' => 'application/atom+xml', - 'avi' => 'video/x-msvideo', - 'bmp' => 'image/bmp', - 'bz2' => 'application/x-bzip2', - 'cer' => 'application/pkix-cert', - 'crl' => 'application/pkix-crl', - 'crt' => 'application/x-x509-ca-cert', - 'css' => 'text/css', - 'csv' => 'text/csv', - 'cu' => 'application/cu-seeme', - 'deb' => 'application/x-debian-package', - 'doc' => 'application/msword', - 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'dvi' => 'application/x-dvi', - 'eot' => 'application/vnd.ms-fontobject', - 'eps' => 'application/postscript', - 'epub' => 'application/epub+zip', - 'etx' => 'text/x-setext', - 'flac' => 'audio/flac', - 'flv' => 'video/x-flv', - 'gif' => 'image/gif', - 'gz' => 'application/gzip', - 'htm' => 'text/html', - 'html' => 'text/html', - 'ico' => 'image/x-icon', - 'ics' => 'text/calendar', - 'ini' => 'text/plain', - 'iso' => 'application/x-iso9660-image', - 'jar' => 'application/java-archive', - 'jpe' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'js' => 'text/javascript', - 'json' => 'application/json', - 'latex' => 'application/x-latex', - 'log' => 'text/plain', - 'm4a' => 'audio/mp4', - 'm4v' => 'video/mp4', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mov' => 'video/quicktime', - 'mkv' => 'video/x-matroska', - 'mp3' => 'audio/mpeg', - 'mp4' => 'video/mp4', - 'mp4a' => 'audio/mp4', - 'mp4v' => 'video/mp4', - 'mpe' => 'video/mpeg', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mpg4' => 'video/mp4', - 'oga' => 'audio/ogg', - 'ogg' => 'audio/ogg', - 'ogv' => 'video/ogg', - 'ogx' => 'application/ogg', - 'pbm' => 'image/x-portable-bitmap', - 'pdf' => 'application/pdf', - 'pgm' => 'image/x-portable-graymap', - 'png' => 'image/png', - 'pnm' => 'image/x-portable-anymap', - 'ppm' => 'image/x-portable-pixmap', - 'ppt' => 'application/vnd.ms-powerpoint', - 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - 'ps' => 'application/postscript', - 'qt' => 'video/quicktime', - 'rar' => 'application/x-rar-compressed', - 'ras' => 'image/x-cmu-raster', - 'rss' => 'application/rss+xml', - 'rtf' => 'application/rtf', - 'sgm' => 'text/sgml', - 'sgml' => 'text/sgml', - 'svg' => 'image/svg+xml', - 'swf' => 'application/x-shockwave-flash', - 'tar' => 'application/x-tar', - 'tif' => 'image/tiff', - 'tiff' => 'image/tiff', - 'torrent' => 'application/x-bittorrent', - 'ttf' => 'application/x-font-ttf', - 'txt' => 'text/plain', - 'wav' => 'audio/x-wav', - 'webm' => 'video/webm', - 'webp' => 'image/webp', - 'wma' => 'audio/x-ms-wma', - 'wmv' => 'video/x-ms-wmv', - 'woff' => 'application/x-font-woff', - 'wsdl' => 'application/wsdl+xml', - 'xbm' => 'image/x-xbitmap', - 'xls' => 'application/vnd.ms-excel', - 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'xml' => 'application/xml', - 'xpm' => 'image/x-xpixmap', - 'xwd' => 'image/x-xwindowdump', - 'yaml' => 'text/yaml', - 'yml' => 'text/yaml', - 'zip' => 'application/zip', - ]; - - $extension = strtolower($extension); - - return isset($mimetypes[$extension]) - ? $mimetypes[$extension] - : null; -} - -/** - * Parses an HTTP message into an associative array. - * - * The array contains the "start-line" key containing the start line of - * the message, "headers" key containing an associative array of header - * array values, and a "body" key containing the body of the message. - * - * @param string $message HTTP request or response to parse. - * - * @return array - * @internal - */ -function _parse_message($message) -{ - if (!$message) { - throw new \InvalidArgumentException('Invalid message'); - } - - $message = ltrim($message, "\r\n"); - - $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); - - if ($messageParts === false || count($messageParts) !== 2) { - throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); - } - - list($rawHeaders, $body) = $messageParts; - $rawHeaders .= "\r\n"; // Put back the delimiter we split previously - $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); - - if ($headerParts === false || count($headerParts) !== 2) { - throw new \InvalidArgumentException('Invalid message: Missing status line'); - } - - list($startLine, $rawHeaders) = $headerParts; - - if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { - // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 - $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); - } - - /** @var array[] $headerLines */ - $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); - - // If these aren't the same, then one line didn't match and there's an invalid header. - if ($count !== substr_count($rawHeaders, "\n")) { - // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4 - if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { - throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); - } - - throw new \InvalidArgumentException('Invalid header syntax'); - } - - $headers = []; - - foreach ($headerLines as $headerLine) { - $headers[$headerLine[1]][] = $headerLine[2]; - } - - return [ - 'start-line' => $startLine, - 'headers' => $headers, - 'body' => $body, - ]; -} - -/** - * Constructs a URI for an HTTP request message. - * - * @param string $path Path from the start-line - * @param array $headers Array of headers (each value an array). - * - * @return string - * @internal - */ -function _parse_request_uri($path, array $headers) -{ - $hostKey = array_filter(array_keys($headers), function ($k) { - return strtolower($k) === 'host'; - }); - - // If no host is found, then a full URI cannot be constructed. - if (!$hostKey) { - return $path; - } - - $host = $headers[reset($hostKey)][0]; - $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; - - return $scheme . '://' . $host . '/' . ltrim($path, '/'); -} - -/** - * Get a short summary of the message body - * - * Will return `null` if the response is not printable. - * - * @param MessageInterface $message The message to get the body summary - * @param int $truncateAt The maximum allowed size of the summary - * - * @return null|string - */ -function get_message_body_summary(MessageInterface $message, $truncateAt = 120) -{ - $body = $message->getBody(); - - if (!$body->isSeekable() || !$body->isReadable()) { - return null; - } - - $size = $body->getSize(); - - if ($size === 0) { - return null; - } - - $summary = $body->read($truncateAt); - $body->rewind(); - - if ($size > $truncateAt) { - $summary .= ' (truncated...)'; - } - - // Matches any printable character, including unicode characters: - // letters, marks, numbers, punctuation, spacing, and separators. - if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $summary)) { - return null; - } - - return $summary; -} - -/** @internal */ -function _caseless_remove($keys, array $data) -{ - $result = []; - - foreach ($keys as &$key) { - $key = strtolower($key); - } - - foreach ($data as $k => $v) { - if (!in_array(strtolower($k), $keys)) { - $result[$k] = $v; - } - } - - return $result; -} diff --git a/vendor/guzzlehttp/psr7/src/functions_include.php b/vendor/guzzlehttp/psr7/src/functions_include.php deleted file mode 100644 index 96a4a83..0000000 --- a/vendor/guzzlehttp/psr7/src/functions_include.php +++ /dev/null @@ -1,6 +0,0 @@ - - lighthouse-logo" + lighthouse-logo" @@ -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/paragonie/random_compat/LICENSE b/vendor/paragonie/random_compat/LICENSE deleted file mode 100644 index 45c7017..0000000 --- a/vendor/paragonie/random_compat/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Paragon Initiative Enterprises - -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/paragonie/random_compat/build-phar.sh b/vendor/paragonie/random_compat/build-phar.sh deleted file mode 100644 index b4a5ba3..0000000 --- a/vendor/paragonie/random_compat/build-phar.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -basedir=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) ) - -php -dphar.readonly=0 "$basedir/other/build_phar.php" $* \ No newline at end of file diff --git a/vendor/paragonie/random_compat/composer.json b/vendor/paragonie/random_compat/composer.json deleted file mode 100644 index 1fa8de9..0000000 --- a/vendor/paragonie/random_compat/composer.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "paragonie/random_compat", - "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", - "keywords": [ - "csprng", - "random", - "polyfill", - "pseudorandom" - ], - "license": "MIT", - "type": "library", - "authors": [ - { - "name": "Paragon Initiative Enterprises", - "email": "security@paragonie.com", - "homepage": "https://paragonie.com" - } - ], - "support": { - "issues": "https://github.com/paragonie/random_compat/issues", - "email": "info@paragonie.com", - "source": "https://github.com/paragonie/random_compat" - }, - "require": { - "php": "^7" - }, - "require-dev": { - "vimeo/psalm": "^1", - "phpunit/phpunit": "4.*|5.*" - }, - "suggest": { - "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." - } -} diff --git a/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey b/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey deleted file mode 100644 index eb50ebf..0000000 --- a/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN PUBLIC KEY----- -MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEEd+wCqJDrx5B4OldM0dQE0ZMX+lx1ZWm -pui0SUqD4G29L3NGsz9UhJ/0HjBdbnkhIK5xviT0X5vtjacF6ajgcCArbTB+ds+p -+h7Q084NuSuIpNb6YPfoUFgC/CL9kAoc ------END PUBLIC KEY----- diff --git a/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc b/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc deleted file mode 100644 index 6a1d7f3..0000000 --- a/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc +++ /dev/null @@ -1,11 +0,0 @@ ------BEGIN PGP SIGNATURE----- -Version: GnuPG v2.0.22 (MingW32) - -iQEcBAABAgAGBQJWtW1hAAoJEGuXocKCZATaJf0H+wbZGgskK1dcRTsuVJl9IWip -QwGw/qIKI280SD6/ckoUMxKDCJiFuPR14zmqnS36k7N5UNPnpdTJTS8T11jttSpg -1LCmgpbEIpgaTah+cELDqFCav99fS+bEiAL5lWDAHBTE/XPjGVCqeehyPYref4IW -NDBIEsvnHPHPLsn6X5jq4+Yj5oUixgxaMPiR+bcO4Sh+RzOVB6i2D0upWfRXBFXA -NNnsg9/zjvoC7ZW73y9uSH+dPJTt/Vgfeiv52/v41XliyzbUyLalf02GNPY+9goV -JHG1ulEEBJOCiUD9cE1PUIJwHA/HqyhHIvV350YoEFiHl8iSwm7SiZu5kPjaq74= -=B6+8 ------END PGP SIGNATURE----- diff --git a/vendor/paragonie/random_compat/lib/random.php b/vendor/paragonie/random_compat/lib/random.php deleted file mode 100644 index c7731a5..0000000 --- a/vendor/paragonie/random_compat/lib/random.php +++ /dev/null @@ -1,32 +0,0 @@ -buildFromDirectory(dirname(__DIR__).'/lib'); -rename( - dirname(__DIR__).'/lib/index.php', - dirname(__DIR__).'/lib/random.php' -); - -/** - * If we pass an (optional) path to a private key as a second argument, we will - * sign the Phar with OpenSSL. - * - * If you leave this out, it will produce an unsigned .phar! - */ -if ($argc > 1) { - if (!@is_readable($argv[1])) { - echo 'Could not read the private key file:', $argv[1], "\n"; - exit(255); - } - $pkeyFile = file_get_contents($argv[1]); - - $private = openssl_get_privatekey($pkeyFile); - if ($private !== false) { - $pkey = ''; - openssl_pkey_export($private, $pkey); - $phar->setSignatureAlgorithm(Phar::OPENSSL, $pkey); - - /** - * Save the corresponding public key to the file - */ - if (!@is_readable($dist.'/random_compat.phar.pubkey')) { - $details = openssl_pkey_get_details($private); - file_put_contents( - $dist.'/random_compat.phar.pubkey', - $details['key'] - ); - } - } else { - echo 'An error occurred reading the private key from OpenSSL.', "\n"; - exit(255); - } -} diff --git a/vendor/paragonie/random_compat/psalm-autoload.php b/vendor/paragonie/random_compat/psalm-autoload.php deleted file mode 100644 index d71d1b8..0000000 --- a/vendor/paragonie/random_compat/psalm-autoload.php +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/vendor/psr/http-message/CHANGELOG.md b/vendor/psr/http-message/CHANGELOG.md deleted file mode 100644 index 74b1ef9..0000000 --- a/vendor/psr/http-message/CHANGELOG.md +++ /dev/null @@ -1,36 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file, in reverse chronological order by release. - -## 1.0.1 - 2016-08-06 - -### Added - -- Nothing. - -### Deprecated - -- Nothing. - -### Removed - -- Nothing. - -### Fixed - -- Updated all `@return self` annotation references in interfaces to use - `@return static`, which more closelly follows the semantics of the - specification. -- Updated the `MessageInterface::getHeaders()` return annotation to use the - value `string[][]`, indicating the format is a nested array of strings. -- Updated the `@link` annotation for `RequestInterface::withRequestTarget()` - to point to the correct section of RFC 7230. -- Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation - to add the parameter name (`$uploadedFiles`). -- Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` - method to correctly reference the method parameter (it was referencing an - incorrect parameter name previously). - -## 1.0.0 - 2016-05-18 - -Initial stable release; reflects accepted PSR-7 specification. diff --git a/vendor/psr/http-message/LICENSE b/vendor/psr/http-message/LICENSE deleted file mode 100644 index c2d8e45..0000000 --- a/vendor/psr/http-message/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 PHP Framework Interoperability Group - -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/psr/http-message/README.md b/vendor/psr/http-message/README.md deleted file mode 100644 index 2818533..0000000 --- a/vendor/psr/http-message/README.md +++ /dev/null @@ -1,13 +0,0 @@ -PSR Http Message -================ - -This repository holds all interfaces/classes/traits related to -[PSR-7](http://www.php-fig.org/psr/psr-7/). - -Note that this is not a HTTP message implementation of its own. It is merely an -interface that describes a HTTP message. See the specification for more details. - -Usage ------ - -We'll certainly need some stuff in here. \ No newline at end of file diff --git a/vendor/psr/http-message/composer.json b/vendor/psr/http-message/composer.json deleted file mode 100644 index b0d2937..0000000 --- a/vendor/psr/http-message/composer.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "psr/http-message", - "description": "Common interface for HTTP messages", - "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], - "homepage": "https://github.com/php-fig/http-message", - "license": "MIT", - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "require": { - "php": ">=5.3.0" - }, - "autoload": { - "psr-4": { - "Psr\\Http\\Message\\": "src/" - } - }, - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - } -} diff --git a/vendor/psr/http-message/src/MessageInterface.php b/vendor/psr/http-message/src/MessageInterface.php deleted file mode 100644 index dd46e5e..0000000 --- a/vendor/psr/http-message/src/MessageInterface.php +++ /dev/null @@ -1,187 +0,0 @@ -getHeaders() as $name => $values) { - * echo $name . ": " . implode(", ", $values); - * } - * - * // Emit headers iteratively: - * foreach ($message->getHeaders() as $name => $values) { - * foreach ($values as $value) { - * header(sprintf('%s: %s', $name, $value), false); - * } - * } - * - * While header names are not case-sensitive, getHeaders() will preserve the - * exact case in which headers were originally specified. - * - * @return string[][] Returns an associative array of the message's headers. Each - * key MUST be a header name, and each value MUST be an array of strings - * for that header. - */ - public function getHeaders(); - - /** - * Checks if a header exists by the given case-insensitive name. - * - * @param string $name Case-insensitive header field name. - * @return bool Returns true if any header names match the given header - * name using a case-insensitive string comparison. Returns false if - * no matching header name is found in the message. - */ - public function hasHeader($name); - - /** - * Retrieves a message header value by the given case-insensitive name. - * - * This method returns an array of all the header values of the given - * case-insensitive header name. - * - * If the header does not appear in the message, this method MUST return an - * empty array. - * - * @param string $name Case-insensitive header field name. - * @return string[] An array of string values as provided for the given - * header. If the header does not appear in the message, this method MUST - * return an empty array. - */ - public function getHeader($name); - - /** - * Retrieves a comma-separated string of the values for a single header. - * - * This method returns all of the header values of the given - * case-insensitive header name as a string concatenated together using - * a comma. - * - * NOTE: Not all header values may be appropriately represented using - * comma concatenation. For such headers, use getHeader() instead - * and supply your own delimiter when concatenating. - * - * If the header does not appear in the message, this method MUST return - * an empty string. - * - * @param string $name Case-insensitive header field name. - * @return string A string of values as provided for the given header - * concatenated together using a comma. If the header does not appear in - * the message, this method MUST return an empty string. - */ - public function getHeaderLine($name); - - /** - * Return an instance with the provided value replacing the specified header. - * - * While header names are case-insensitive, the casing of the header will - * be preserved by this function, and returned from getHeaders(). - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that has the - * new and/or updated header and value. - * - * @param string $name Case-insensitive header field name. - * @param string|string[] $value Header value(s). - * @return static - * @throws \InvalidArgumentException for invalid header names or values. - */ - public function withHeader($name, $value); - - /** - * Return an instance with the specified header appended with the given value. - * - * Existing values for the specified header will be maintained. The new - * value(s) will be appended to the existing list. If the header did not - * exist previously, it will be added. - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that has the - * new header and/or value. - * - * @param string $name Case-insensitive header field name to add. - * @param string|string[] $value Header value(s). - * @return static - * @throws \InvalidArgumentException for invalid header names or values. - */ - public function withAddedHeader($name, $value); - - /** - * Return an instance without the specified header. - * - * Header resolution MUST be done without case-sensitivity. - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that removes - * the named header. - * - * @param string $name Case-insensitive header field name to remove. - * @return static - */ - public function withoutHeader($name); - - /** - * Gets the body of the message. - * - * @return StreamInterface Returns the body as a stream. - */ - public function getBody(); - - /** - * Return an instance with the specified message body. - * - * The body MUST be a StreamInterface object. - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return a new instance that has the - * new body stream. - * - * @param StreamInterface $body Body. - * @return static - * @throws \InvalidArgumentException When the body is not valid. - */ - public function withBody(StreamInterface $body); -} diff --git a/vendor/psr/http-message/src/RequestInterface.php b/vendor/psr/http-message/src/RequestInterface.php deleted file mode 100644 index a96d4fd..0000000 --- a/vendor/psr/http-message/src/RequestInterface.php +++ /dev/null @@ -1,129 +0,0 @@ -getQuery()` - * or from the `QUERY_STRING` server param. - * - * @return array - */ - public function getQueryParams(); - - /** - * Return an instance with the specified query string arguments. - * - * These values SHOULD remain immutable over the course of the incoming - * request. They MAY be injected during instantiation, such as from PHP's - * $_GET superglobal, or MAY be derived from some other value such as the - * URI. In cases where the arguments are parsed from the URI, the data - * MUST be compatible with what PHP's parse_str() would return for - * purposes of how duplicate query parameters are handled, and how nested - * sets are handled. - * - * Setting query string arguments MUST NOT change the URI stored by the - * request, nor the values in the server params. - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that has the - * updated query string arguments. - * - * @param array $query Array of query string arguments, typically from - * $_GET. - * @return static - */ - public function withQueryParams(array $query); - - /** - * Retrieve normalized file upload data. - * - * This method returns upload metadata in a normalized tree, with each leaf - * an instance of Psr\Http\Message\UploadedFileInterface. - * - * These values MAY be prepared from $_FILES or the message body during - * instantiation, or MAY be injected via withUploadedFiles(). - * - * @return array An array tree of UploadedFileInterface instances; an empty - * array MUST be returned if no data is present. - */ - public function getUploadedFiles(); - - /** - * Create a new instance with the specified uploaded files. - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that has the - * updated body parameters. - * - * @param array $uploadedFiles An array tree of UploadedFileInterface instances. - * @return static - * @throws \InvalidArgumentException if an invalid structure is provided. - */ - public function withUploadedFiles(array $uploadedFiles); - - /** - * Retrieve any parameters provided in the request body. - * - * If the request Content-Type is either application/x-www-form-urlencoded - * or multipart/form-data, and the request method is POST, this method MUST - * return the contents of $_POST. - * - * Otherwise, this method may return any results of deserializing - * the request body content; as parsing returns structured content, the - * potential types MUST be arrays or objects only. A null value indicates - * the absence of body content. - * - * @return null|array|object The deserialized body parameters, if any. - * These will typically be an array or object. - */ - public function getParsedBody(); - - /** - * Return an instance with the specified body parameters. - * - * These MAY be injected during instantiation. - * - * If the request Content-Type is either application/x-www-form-urlencoded - * or multipart/form-data, and the request method is POST, use this method - * ONLY to inject the contents of $_POST. - * - * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of - * deserializing the request body content. Deserialization/parsing returns - * structured data, and, as such, this method ONLY accepts arrays or objects, - * or a null value if nothing was available to parse. - * - * As an example, if content negotiation determines that the request data - * is a JSON payload, this method could be used to create a request - * instance with the deserialized parameters. - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that has the - * updated body parameters. - * - * @param null|array|object $data The deserialized body data. This will - * typically be in an array or object. - * @return static - * @throws \InvalidArgumentException if an unsupported argument type is - * provided. - */ - public function withParsedBody($data); - - /** - * Retrieve attributes derived from the request. - * - * The request "attributes" may be used to allow injection of any - * parameters derived from the request: e.g., the results of path - * match operations; the results of decrypting cookies; the results of - * deserializing non-form-encoded message bodies; etc. Attributes - * will be application and request specific, and CAN be mutable. - * - * @return array Attributes derived from the request. - */ - public function getAttributes(); - - /** - * Retrieve a single derived request attribute. - * - * Retrieves a single derived request attribute as described in - * getAttributes(). If the attribute has not been previously set, returns - * the default value as provided. - * - * This method obviates the need for a hasAttribute() method, as it allows - * specifying a default value to return if the attribute is not found. - * - * @see getAttributes() - * @param string $name The attribute name. - * @param mixed $default Default value to return if the attribute does not exist. - * @return mixed - */ - public function getAttribute($name, $default = null); - - /** - * Return an instance with the specified derived request attribute. - * - * This method allows setting a single derived request attribute as - * described in getAttributes(). - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that has the - * updated attribute. - * - * @see getAttributes() - * @param string $name The attribute name. - * @param mixed $value The value of the attribute. - * @return static - */ - public function withAttribute($name, $value); - - /** - * Return an instance that removes the specified derived request attribute. - * - * This method allows removing a single derived request attribute as - * described in getAttributes(). - * - * This method MUST be implemented in such a way as to retain the - * immutability of the message, and MUST return an instance that removes - * the attribute. - * - * @see getAttributes() - * @param string $name The attribute name. - * @return static - */ - public function withoutAttribute($name); -} diff --git a/vendor/psr/http-message/src/StreamInterface.php b/vendor/psr/http-message/src/StreamInterface.php deleted file mode 100644 index f68f391..0000000 --- a/vendor/psr/http-message/src/StreamInterface.php +++ /dev/null @@ -1,158 +0,0 @@ - - * [user-info@]host[:port] - * - * - * If the port component is not set or is the standard port for the current - * scheme, it SHOULD NOT be included. - * - * @see https://tools.ietf.org/html/rfc3986#section-3.2 - * @return string The URI authority, in "[user-info@]host[:port]" format. - */ - public function getAuthority(); - - /** - * Retrieve the user information component of the URI. - * - * If no user information is present, this method MUST return an empty - * string. - * - * If a user is present in the URI, this will return that value; - * additionally, if the password is also present, it will be appended to the - * user value, with a colon (":") separating the values. - * - * The trailing "@" character is not part of the user information and MUST - * NOT be added. - * - * @return string The URI user information, in "username[:password]" format. - */ - public function getUserInfo(); - - /** - * Retrieve the host component of the URI. - * - * If no host is present, this method MUST return an empty string. - * - * The value returned MUST be normalized to lowercase, per RFC 3986 - * Section 3.2.2. - * - * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 - * @return string The URI host. - */ - public function getHost(); - - /** - * Retrieve the port component of the URI. - * - * If a port is present, and it is non-standard for the current scheme, - * this method MUST return it as an integer. If the port is the standard port - * used with the current scheme, this method SHOULD return null. - * - * If no port is present, and no scheme is present, this method MUST return - * a null value. - * - * If no port is present, but a scheme is present, this method MAY return - * the standard port for that scheme, but SHOULD return null. - * - * @return null|int The URI port. - */ - public function getPort(); - - /** - * Retrieve the path component of the URI. - * - * The path can either be empty or absolute (starting with a slash) or - * rootless (not starting with a slash). Implementations MUST support all - * three syntaxes. - * - * Normally, the empty path "" and absolute path "/" are considered equal as - * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically - * do this normalization because in contexts with a trimmed base path, e.g. - * the front controller, this difference becomes significant. It's the task - * of the user to handle both "" and "/". - * - * The value returned MUST be percent-encoded, but MUST NOT double-encode - * any characters. To determine what characters to encode, please refer to - * RFC 3986, Sections 2 and 3.3. - * - * As an example, if the value should include a slash ("/") not intended as - * delimiter between path segments, that value MUST be passed in encoded - * form (e.g., "%2F") to the instance. - * - * @see https://tools.ietf.org/html/rfc3986#section-2 - * @see https://tools.ietf.org/html/rfc3986#section-3.3 - * @return string The URI path. - */ - public function getPath(); - - /** - * Retrieve the query string of the URI. - * - * If no query string is present, this method MUST return an empty string. - * - * The leading "?" character is not part of the query and MUST NOT be - * added. - * - * The value returned MUST be percent-encoded, but MUST NOT double-encode - * any characters. To determine what characters to encode, please refer to - * RFC 3986, Sections 2 and 3.4. - * - * As an example, if a value in a key/value pair of the query string should - * include an ampersand ("&") not intended as a delimiter between values, - * that value MUST be passed in encoded form (e.g., "%26") to the instance. - * - * @see https://tools.ietf.org/html/rfc3986#section-2 - * @see https://tools.ietf.org/html/rfc3986#section-3.4 - * @return string The URI query string. - */ - public function getQuery(); - - /** - * Retrieve the fragment component of the URI. - * - * If no fragment is present, this method MUST return an empty string. - * - * The leading "#" character is not part of the fragment and MUST NOT be - * added. - * - * The value returned MUST be percent-encoded, but MUST NOT double-encode - * any characters. To determine what characters to encode, please refer to - * RFC 3986, Sections 2 and 3.5. - * - * @see https://tools.ietf.org/html/rfc3986#section-2 - * @see https://tools.ietf.org/html/rfc3986#section-3.5 - * @return string The URI fragment. - */ - public function getFragment(); - - /** - * Return an instance with the specified scheme. - * - * This method MUST retain the state of the current instance, and return - * an instance that contains the specified scheme. - * - * Implementations MUST support the schemes "http" and "https" case - * insensitively, and MAY accommodate other schemes if required. - * - * An empty scheme is equivalent to removing the scheme. - * - * @param string $scheme The scheme to use with the new instance. - * @return static A new instance with the specified scheme. - * @throws \InvalidArgumentException for invalid or unsupported schemes. - */ - public function withScheme($scheme); - - /** - * Return an instance with the specified user information. - * - * This method MUST retain the state of the current instance, and return - * an instance that contains the specified user information. - * - * Password is optional, but the user information MUST include the - * user; an empty string for the user is equivalent to removing user - * information. - * - * @param string $user The user name to use for authority. - * @param null|string $password The password associated with $user. - * @return static A new instance with the specified user information. - */ - public function withUserInfo($user, $password = null); - - /** - * Return an instance with the specified host. - * - * This method MUST retain the state of the current instance, and return - * an instance that contains the specified host. - * - * An empty host value is equivalent to removing the host. - * - * @param string $host The hostname to use with the new instance. - * @return static A new instance with the specified host. - * @throws \InvalidArgumentException for invalid hostnames. - */ - public function withHost($host); - - /** - * Return an instance with the specified port. - * - * This method MUST retain the state of the current instance, and return - * an instance that contains the specified port. - * - * Implementations MUST raise an exception for ports outside the - * established TCP and UDP port ranges. - * - * A null value provided for the port is equivalent to removing the port - * information. - * - * @param null|int $port The port to use with the new instance; a null value - * removes the port information. - * @return static A new instance with the specified port. - * @throws \InvalidArgumentException for invalid ports. - */ - public function withPort($port); - - /** - * Return an instance with the specified path. - * - * This method MUST retain the state of the current instance, and return - * an instance that contains the specified path. - * - * The path can either be empty or absolute (starting with a slash) or - * rootless (not starting with a slash). Implementations MUST support all - * three syntaxes. - * - * If the path is intended to be domain-relative rather than path relative then - * it must begin with a slash ("/"). Paths not starting with a slash ("/") - * are assumed to be relative to some base path known to the application or - * consumer. - * - * Users can provide both encoded and decoded path characters. - * Implementations ensure the correct encoding as outlined in getPath(). - * - * @param string $path The path to use with the new instance. - * @return static A new instance with the specified path. - * @throws \InvalidArgumentException for invalid paths. - */ - public function withPath($path); - - /** - * Return an instance with the specified query string. - * - * This method MUST retain the state of the current instance, and return - * an instance that contains the specified query string. - * - * Users can provide both encoded and decoded query characters. - * Implementations ensure the correct encoding as outlined in getQuery(). - * - * An empty query string value is equivalent to removing the query string. - * - * @param string $query The query string to use with the new instance. - * @return static A new instance with the specified query string. - * @throws \InvalidArgumentException for invalid query strings. - */ - public function withQuery($query); - - /** - * Return an instance with the specified URI fragment. - * - * This method MUST retain the state of the current instance, and return - * an instance that contains the specified URI fragment. - * - * Users can provide both encoded and decoded fragment characters. - * Implementations ensure the correct encoding as outlined in getFragment(). - * - * An empty fragment value is equivalent to removing the fragment. - * - * @param string $fragment The fragment to use with the new instance. - * @return static A new instance with the specified fragment. - */ - public function withFragment($fragment); - - /** - * Return the string representation as a URI reference. - * - * Depending on which components of the URI are present, the resulting - * string is either a full URI or relative reference according to RFC 3986, - * Section 4.1. The method concatenates the various components of the URI, - * using the appropriate delimiters: - * - * - If a scheme is present, it MUST be suffixed by ":". - * - If an authority is present, it MUST be prefixed by "//". - * - The path can be concatenated without delimiters. But there are two - * cases where the path has to be adjusted to make the URI reference - * valid as PHP does not allow to throw an exception in __toString(): - * - If the path is rootless and an authority is present, the path MUST - * be prefixed by "/". - * - If the path is starting with more than one "/" and no authority is - * present, the starting slashes MUST be reduced to one. - * - If a query is present, it MUST be prefixed by "?". - * - If a fragment is present, it MUST be prefixed by "#". - * - * @see http://tools.ietf.org/html/rfc3986#section-4.1 - * @return string - */ - public function __toString(); -} diff --git a/vendor/ralouphie/getallheaders/LICENSE b/vendor/ralouphie/getallheaders/LICENSE deleted file mode 100644 index be5540c..0000000 --- a/vendor/ralouphie/getallheaders/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Ralph Khattar - -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/ralouphie/getallheaders/README.md b/vendor/ralouphie/getallheaders/README.md deleted file mode 100644 index 9430d76..0000000 --- a/vendor/ralouphie/getallheaders/README.md +++ /dev/null @@ -1,27 +0,0 @@ -getallheaders -============= - -PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. - -[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) -[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) -[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) -[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) -[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) - - -This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). - -## Install - -For PHP version **`>= 5.6`**: - -``` -composer require ralouphie/getallheaders -``` - -For PHP version **`< 5.6`**: - -``` -composer require ralouphie/getallheaders "^2" -``` diff --git a/vendor/ralouphie/getallheaders/composer.json b/vendor/ralouphie/getallheaders/composer.json deleted file mode 100644 index de8ce62..0000000 --- a/vendor/ralouphie/getallheaders/composer.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "ralouphie/getallheaders", - "description": "A polyfill for getallheaders.", - "license": "MIT", - "authors": [ - { - "name": "Ralph Khattar", - "email": "ralph.khattar@gmail.com" - } - ], - "require": { - "php": ">=5.6" - }, - "require-dev": { - "phpunit/phpunit": "^5 || ^6.5", - "php-coveralls/php-coveralls": "^2.1" - }, - "autoload": { - "files": ["src/getallheaders.php"] - }, - "autoload-dev": { - "psr-4": { - "getallheaders\\Tests\\": "tests/" - } - } -} diff --git a/vendor/ralouphie/getallheaders/src/getallheaders.php b/vendor/ralouphie/getallheaders/src/getallheaders.php deleted file mode 100644 index c7285a5..0000000 --- a/vendor/ralouphie/getallheaders/src/getallheaders.php +++ /dev/null @@ -1,46 +0,0 @@ - 'Content-Type', - 'CONTENT_LENGTH' => 'Content-Length', - 'CONTENT_MD5' => 'Content-Md5', - ); - - foreach ($_SERVER as $key => $value) { - if (substr($key, 0, 5) === 'HTTP_') { - $key = substr($key, 5); - if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { - $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); - $headers[$key] = $value; - } - } elseif (isset($copy_server[$key])) { - $headers[$copy_server[$key]] = $value; - } - } - - if (!isset($headers['Authorization'])) { - if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { - $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; - } elseif (isset($_SERVER['PHP_AUTH_USER'])) { - $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; - $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); - } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { - $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; - } - } - - return $headers; - } - -} diff --git a/vendor/symfony/polyfill-intl-idn/Idn.php b/vendor/symfony/polyfill-intl-idn/Idn.php index 6720af9..fee3026 100644 --- a/vendor/symfony/polyfill-intl-idn/Idn.php +++ b/vendor/symfony/polyfill-intl-idn/Idn.php @@ -23,37 +23,45 @@ use Symfony\Polyfill\Intl\Idn\Resources\unidata\Regex; */ final class Idn { - const ERROR_EMPTY_LABEL = 1; - const ERROR_LABEL_TOO_LONG = 2; - const ERROR_DOMAIN_NAME_TOO_LONG = 4; - const ERROR_LEADING_HYPHEN = 8; - const ERROR_TRAILING_HYPHEN = 0x10; - const ERROR_HYPHEN_3_4 = 0x20; - const ERROR_LEADING_COMBINING_MARK = 0x40; - const ERROR_DISALLOWED = 0x80; - const ERROR_PUNYCODE = 0x100; - const ERROR_LABEL_HAS_DOT = 0x200; - const ERROR_INVALID_ACE_LABEL = 0x400; - const ERROR_BIDI = 0x800; - const ERROR_CONTEXTJ = 0x1000; - const ERROR_CONTEXTO_PUNCTUATION = 0x2000; - const ERROR_CONTEXTO_DIGITS = 0x4000; + public const ERROR_EMPTY_LABEL = 1; + public const ERROR_LABEL_TOO_LONG = 2; + public const ERROR_DOMAIN_NAME_TOO_LONG = 4; + public const ERROR_LEADING_HYPHEN = 8; + public const ERROR_TRAILING_HYPHEN = 0x10; + public const ERROR_HYPHEN_3_4 = 0x20; + public const ERROR_LEADING_COMBINING_MARK = 0x40; + public const ERROR_DISALLOWED = 0x80; + public const ERROR_PUNYCODE = 0x100; + public const ERROR_LABEL_HAS_DOT = 0x200; + public const ERROR_INVALID_ACE_LABEL = 0x400; + public const ERROR_BIDI = 0x800; + public const ERROR_CONTEXTJ = 0x1000; + public const ERROR_CONTEXTO_PUNCTUATION = 0x2000; + public const ERROR_CONTEXTO_DIGITS = 0x4000; - const INTL_IDNA_VARIANT_2003 = 0; - const INTL_IDNA_VARIANT_UTS46 = 1; + public const INTL_IDNA_VARIANT_2003 = 0; + public const INTL_IDNA_VARIANT_UTS46 = 1; - const MAX_DOMAIN_SIZE = 253; - const MAX_LABEL_SIZE = 63; + public const IDNA_DEFAULT = 0; + public const IDNA_ALLOW_UNASSIGNED = 1; + public const IDNA_USE_STD3_RULES = 2; + public const IDNA_CHECK_BIDI = 4; + public const IDNA_CHECK_CONTEXTJ = 8; + public const IDNA_NONTRANSITIONAL_TO_ASCII = 16; + public const IDNA_NONTRANSITIONAL_TO_UNICODE = 32; - const BASE = 36; - const TMIN = 1; - const TMAX = 26; - const SKEW = 38; - const DAMP = 700; - const INITIAL_BIAS = 72; - const INITIAL_N = 128; - const DELIMITER = '-'; - const MAX_INT = 2147483647; + public const MAX_DOMAIN_SIZE = 253; + public const MAX_LABEL_SIZE = 63; + + public const BASE = 36; + public const TMIN = 1; + public const TMAX = 26; + public const SKEW = 38; + public const DAMP = 700; + public const INITIAL_BIAS = 72; + public const INITIAL_N = 128; + public const DELIMITER = '-'; + public const MAX_INT = 2147483647; /** * Contains the numeric value of a basic code point (for use in representing integers) in the @@ -61,7 +69,7 @@ final class Idn * * @var array */ - private static $basicToDigit = array( + private static $basicToDigit = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, @@ -85,7 +93,7 @@ final class Idn -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - ); + ]; /** * @var array @@ -137,32 +145,26 @@ final class Idn * * @return string|false */ - public static function idn_to_ascii($domainName, $options = IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = array()) + public static function idn_to_ascii($domainName, $options = self::IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = []) { if (\PHP_VERSION_ID >= 70200 && self::INTL_IDNA_VARIANT_2003 === $variant) { - @trigger_error('idn_to_ascii(): INTL_IDNA_VARIANT_2003 is deprecated', E_USER_DEPRECATED); + @trigger_error('idn_to_ascii(): INTL_IDNA_VARIANT_2003 is deprecated', \E_USER_DEPRECATED); } - $options = array( + $options = [ 'CheckHyphens' => true, - 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & \IDNA_CHECK_BIDI), - 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & \IDNA_CHECK_CONTEXTJ), - 'UseSTD3ASCIIRules' => 0 !== ($options & \IDNA_USE_STD3_RULES), - 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & \IDNA_NONTRANSITIONAL_TO_ASCII), + 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & self::IDNA_CHECK_BIDI), + 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & self::IDNA_CHECK_CONTEXTJ), + 'UseSTD3ASCIIRules' => 0 !== ($options & self::IDNA_USE_STD3_RULES), + 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & self::IDNA_NONTRANSITIONAL_TO_ASCII), 'VerifyDnsLength' => true, - ); + ]; $info = new Info(); $labels = self::process((string) $domainName, $options, $info); foreach ($labels as $i => $label) { - // Only convert labels to punycode that contain non-ASCII code points and only if that - // label does not contain a character from the gen-delims set specified in - // {@link https://ietf.org/rfc/rfc3987.html#section-2.2} + // Only convert labels to punycode that contain non-ASCII code points if (1 === preg_match('/[^\x00-\x7F]/', $label)) { - if (false !== strpbrk($label, ':/?#[]@')) { - continue; - } - try { $label = 'xn--'.self::punycodeEncode($label); } catch (Exception $e) { @@ -177,11 +179,11 @@ final class Idn self::validateDomainAndLabelLength($labels, $info); } - $idna_info = array( + $idna_info = [ 'result' => implode('.', $labels), 'isTransitionalDifferent' => $info->transitionalDifferent, 'errors' => $info->errors, - ); + ]; return 0 === $info->errors ? $idna_info['result'] : false; } @@ -196,25 +198,25 @@ final class Idn * * @return string|false */ - public static function idn_to_utf8($domainName, $options = IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = array()) + public static function idn_to_utf8($domainName, $options = self::IDNA_DEFAULT, $variant = self::INTL_IDNA_VARIANT_UTS46, &$idna_info = []) { if (\PHP_VERSION_ID >= 70200 && self::INTL_IDNA_VARIANT_2003 === $variant) { - @trigger_error('idn_to_utf8(): INTL_IDNA_VARIANT_2003 is deprecated', E_USER_DEPRECATED); + @trigger_error('idn_to_utf8(): INTL_IDNA_VARIANT_2003 is deprecated', \E_USER_DEPRECATED); } $info = new Info(); - $labels = self::process((string) $domainName, array( + $labels = self::process((string) $domainName, [ 'CheckHyphens' => true, - 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & \IDNA_CHECK_BIDI), - 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & \IDNA_CHECK_CONTEXTJ), - 'UseSTD3ASCIIRules' => 0 !== ($options & \IDNA_USE_STD3_RULES), - 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & \IDNA_NONTRANSITIONAL_TO_UNICODE), - ), $info); - $idna_info = array( + 'CheckBidi' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 !== ($options & self::IDNA_CHECK_BIDI), + 'CheckJoiners' => self::INTL_IDNA_VARIANT_UTS46 === $variant && 0 !== ($options & self::IDNA_CHECK_CONTEXTJ), + 'UseSTD3ASCIIRules' => 0 !== ($options & self::IDNA_USE_STD3_RULES), + 'Transitional_Processing' => self::INTL_IDNA_VARIANT_2003 === $variant || 0 === ($options & self::IDNA_NONTRANSITIONAL_TO_UNICODE), + ], $info); + $idna_info = [ 'result' => implode('.', $labels), 'isTransitionalDifferent' => $info->transitionalDifferent, 'errors' => $info->errors, - ); + ]; return 0 === $info->errors ? $idna_info['result'] : false; } @@ -249,7 +251,7 @@ final class Idn // If RegExpMatch((Joining_Type:{L,D})(Joining_Type:T)*\u200C(Joining_Type:T)*(Joining_Type:{R,D})) Then // True; // Generated RegExp = ([Joining_Type:{L,D}][Joining_Type:T]*\u200C[Joining_Type:T]*)[Joining_Type:{R,D}] - if (0x200C === $codePoint && 1 === preg_match(Regex::ZWNJ, $label, $matches, PREG_OFFSET_CAPTURE, $offset)) { + if (0x200C === $codePoint && 1 === preg_match(Regex::ZWNJ, $label, $matches, \PREG_OFFSET_CAPTURE, $offset)) { $offset += \strlen($matches[1][0]); continue; @@ -326,7 +328,7 @@ final class Idn if ($checkForEmptyLabels && '' === $domain) { $info->errors |= self::ERROR_EMPTY_LABEL; - return array($domain); + return [$domain]; } // Step 1. Map each code point in the domain name string @@ -576,7 +578,7 @@ final class Idn $lastDelimIndex = strrpos($input, self::DELIMITER); $b = false === $lastDelimIndex ? 0 : $lastDelimIndex; $inputLength = \strlen($input); - $output = array(); + $output = []; $bytes = array_map('ord', str_split($input)); for ($j = 0; $j < $b; ++$j) { @@ -642,7 +644,7 @@ final class Idn $n += intdiv($i, $outPlusOne); $i %= $outPlusOne; - array_splice($output, $i++, 0, array(mb_chr($n, 'utf-8'))); + array_splice($output, $i++, 0, [mb_chr($n, 'utf-8')]); } return implode('', $output); @@ -701,7 +703,9 @@ final class Idn foreach ($iter as $codePoint) { if ($codePoint < $n && 0 === ++$delta) { throw new Exception('Integer overflow'); - } elseif ($codePoint === $n) { + } + + if ($codePoint === $n) { $q = $delta; for ($k = self::BASE; /* no condition */; $k += self::BASE) { @@ -791,7 +795,7 @@ final class Idn $lowerBoundary = 0x80; $upperBoundary = 0xBF; $codePoint = 0; - $codePoints = array(); + $codePoints = []; $length = \strlen($input); for ($i = 0; $i < $length; ++$i) { @@ -885,19 +889,19 @@ final class Idn } if (isset(self::$mapped[$codePoint])) { - return array('status' => 'mapped', 'mapping' => self::$mapped[$codePoint]); + return ['status' => 'mapped', 'mapping' => self::$mapped[$codePoint]]; } if (isset(self::$ignored[$codePoint])) { - return array('status' => 'ignored'); + return ['status' => 'ignored']; } if (isset(self::$deviation[$codePoint])) { - return array('status' => 'deviation', 'mapping' => self::$deviation[$codePoint]); + return ['status' => 'deviation', 'mapping' => self::$deviation[$codePoint]]; } if (isset(self::$disallowed[$codePoint]) || DisallowedRanges::inRange($codePoint)) { - return array('status' => 'disallowed'); + return ['status' => 'disallowed']; } $isDisallowedMapped = isset(self::$disallowed_STD3_mapped[$codePoint]); @@ -910,12 +914,12 @@ final class Idn } if ($isDisallowedMapped) { - return array('status' => $status, 'mapping' => self::$disallowed_STD3_mapped[$codePoint]); + return ['status' => $status, 'mapping' => self::$disallowed_STD3_mapped[$codePoint]]; } - return array('status' => $status); + return ['status' => $status]; } - return array('status' => 'valid'); + return ['status' => 'valid']; } } diff --git a/vendor/symfony/polyfill-intl-idn/bootstrap.php b/vendor/symfony/polyfill-intl-idn/bootstrap.php index f02d5de..57c7835 100644 --- a/vendor/symfony/polyfill-intl-idn/bootstrap.php +++ b/vendor/symfony/polyfill-intl-idn/bootstrap.php @@ -15,6 +15,10 @@ if (extension_loaded('intl')) { return; } +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + if (!defined('U_IDNA_PROHIBITED_ERROR')) { define('U_IDNA_PROHIBITED_ERROR', 66560); } @@ -124,18 +128,18 @@ if (!defined('IDNA_ERROR_CONTEXTJ')) { define('IDNA_ERROR_CONTEXTJ', 4096); } -if (PHP_VERSION_ID < 70400) { +if (\PHP_VERSION_ID < 70400) { if (!function_exists('idn_to_ascii')) { - function idn_to_ascii($domain, $options = IDNA_DEFAULT, $variant = INTL_IDNA_VARIANT_2003, &$idna_info = array()) { return p\Idn::idn_to_ascii($domain, $options, $variant, $idna_info); } + function idn_to_ascii($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_2003, &$idna_info = null) { return p\Idn::idn_to_ascii($domain, $flags, $variant, $idna_info); } } if (!function_exists('idn_to_utf8')) { - function idn_to_utf8($domain, $options = IDNA_DEFAULT, $variant = INTL_IDNA_VARIANT_2003, &$idna_info = array()) { return p\Idn::idn_to_utf8($domain, $options, $variant, $idna_info); } + function idn_to_utf8($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_2003, &$idna_info = null) { return p\Idn::idn_to_utf8($domain, $flags, $variant, $idna_info); } } } else { if (!function_exists('idn_to_ascii')) { - function idn_to_ascii($domain, $options = IDNA_DEFAULT, $variant = INTL_IDNA_VARIANT_UTS46, &$idna_info = array()) { return p\Idn::idn_to_ascii($domain, $options, $variant, $idna_info); } + function idn_to_ascii($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_UTS46, &$idna_info = null) { return p\Idn::idn_to_ascii($domain, $flags, $variant, $idna_info); } } if (!function_exists('idn_to_utf8')) { - function idn_to_utf8($domain, $options = IDNA_DEFAULT, $variant = INTL_IDNA_VARIANT_UTS46, &$idna_info = array()) { return p\Idn::idn_to_utf8($domain, $options, $variant, $idna_info); } + function idn_to_utf8($domain, $flags = 0, $variant = \INTL_IDNA_VARIANT_UTS46, &$idna_info = null) { return p\Idn::idn_to_utf8($domain, $flags, $variant, $idna_info); } } } diff --git a/vendor/symfony/polyfill-intl-idn/composer.json b/vendor/symfony/polyfill-intl-idn/composer.json index af34193..c5a2a46 100644 --- a/vendor/symfony/polyfill-intl-idn/composer.json +++ b/vendor/symfony/polyfill-intl-idn/composer.json @@ -20,9 +20,8 @@ } ], "require": { - "php": ">=5.3.3", + "php": ">=7.1", "symfony/polyfill-intl-normalizer": "^1.10", - "symfony/polyfill-php70": "^1.10", "symfony/polyfill-php72": "^1.10" }, "autoload": { @@ -35,7 +34,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", diff --git a/vendor/symfony/polyfill-intl-normalizer/Normalizer.php b/vendor/symfony/polyfill-intl-normalizer/Normalizer.php index a60fae6..4443c23 100644 --- a/vendor/symfony/polyfill-intl-normalizer/Normalizer.php +++ b/vendor/symfony/polyfill-intl-normalizer/Normalizer.php @@ -23,28 +23,27 @@ namespace Symfony\Polyfill\Intl\Normalizer; */ class Normalizer { - const FORM_D = \Normalizer::FORM_D; - const FORM_KD = \Normalizer::FORM_KD; - const FORM_C = \Normalizer::FORM_C; - const FORM_KC = \Normalizer::FORM_KC; - const NFD = \Normalizer::NFD; - const NFKD = \Normalizer::NFKD; - const NFC = \Normalizer::NFC; - const NFKC = \Normalizer::NFKC; + public const FORM_D = \Normalizer::FORM_D; + public const FORM_KD = \Normalizer::FORM_KD; + public const FORM_C = \Normalizer::FORM_C; + public const FORM_KC = \Normalizer::FORM_KC; + public const NFD = \Normalizer::NFD; + public const NFKD = \Normalizer::NFKD; + public const NFC = \Normalizer::NFC; + public const NFKC = \Normalizer::NFKC; private static $C; private static $D; private static $KD; private static $cC; - private static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4); + private static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; private static $ASCII = "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; - public static function isNormalized($s, $form = self::NFC) + public static function isNormalized(string $s, int $form = self::FORM_C) { - if (!\in_array($form, array(self::NFD, self::NFKD, self::NFC, self::NFKC))) { + if (!\in_array($form, [self::NFD, self::NFKD, self::NFC, self::NFKC])) { return false; } - $s = (string) $s; if (!isset($s[strspn($s, self::$ASCII)])) { return true; } @@ -55,9 +54,8 @@ class Normalizer return self::normalize($s, $form) === $s; } - public static function normalize($s, $form = self::NFC) + public static function normalize(string $s, int $form = self::FORM_C) { - $s = (string) $s; if (!preg_match('//u', $s)) { return false; } @@ -72,7 +70,11 @@ class Normalizer return $s; } - return false; + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError('normalizer_normalize(): Argument #2 ($form) must be a a valid normalization form'); } if ('' === $s) { @@ -152,7 +154,7 @@ class Normalizer || $lastUcls) { // Table lookup and combining chars composition - $ucls = isset($combClass[$uchr]) ? $combClass[$uchr] : 0; + $ucls = $combClass[$uchr] ?? 0; if (isset($compMap[$lastUchr.$uchr]) && (!$lastUcls || $lastUcls < $ucls)) { $lastUchr = $compMap[$lastUchr.$uchr]; @@ -204,7 +206,7 @@ class Normalizer $compatMap = self::$KD; } - $c = array(); + $c = []; $i = 0; $len = \strlen($s); @@ -215,7 +217,7 @@ class Normalizer if ($c) { ksort($c); $result .= implode('', $c); - $c = array(); + $c = []; } $j = 1 + strspn($s, $ASCII, $i + 1); @@ -231,7 +233,7 @@ class Normalizer if ($uchr < "\xEA\xB0\x80" || "\xED\x9E\xA3" < $uchr) { // Table lookup - if ($uchr !== $j = isset($compatMap[$uchr]) ? $compatMap[$uchr] : (isset($decompMap[$uchr]) ? $decompMap[$uchr] : $uchr)) { + if ($uchr !== $j = $compatMap[$uchr] ?? ($decompMap[$uchr] ?? $uchr)) { $uchr = $j; $j = \strlen($uchr); @@ -283,7 +285,7 @@ class Normalizer if ($c) { ksort($c); $result .= implode('', $c); - $c = array(); + $c = []; } $result .= $uchr; diff --git a/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php b/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php index ca18eff..0fdfc89 100644 --- a/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php +++ b/vendor/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php @@ -5,13 +5,13 @@ class Normalizer extends Symfony\Polyfill\Intl\Normalizer\Normalizer /** * @deprecated since ICU 56 and removed in PHP 8 */ - const NONE = 1; - const FORM_D = 2; - const FORM_KD = 3; - const FORM_C = 4; - const FORM_KC = 5; - const NFD = 2; - const NFKD = 3; - const NFC = 4; - const NFKC = 5; + public const NONE = 2; + public const FORM_D = 4; + public const FORM_KD = 8; + public const FORM_C = 16; + public const FORM_KC = 32; + public const NFD = 4; + public const NFKD = 8; + public const NFC = 16; + public const NFKC = 32; } diff --git a/vendor/symfony/polyfill-intl-normalizer/bootstrap.php b/vendor/symfony/polyfill-intl-normalizer/bootstrap.php index ba62006..3608e5c 100644 --- a/vendor/symfony/polyfill-intl-normalizer/bootstrap.php +++ b/vendor/symfony/polyfill-intl-normalizer/bootstrap.php @@ -11,9 +11,13 @@ use Symfony\Polyfill\Intl\Normalizer as p; +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + if (!function_exists('normalizer_is_normalized')) { - function normalizer_is_normalized($s, $form = p\Normalizer::NFC) { return p\Normalizer::isNormalized($s, $form); } + function normalizer_is_normalized($string, $form = p\Normalizer::FORM_C) { return p\Normalizer::isNormalized($string, $form); } } if (!function_exists('normalizer_normalize')) { - function normalizer_normalize($s, $form = p\Normalizer::NFC) { return p\Normalizer::normalize($s, $form); } + function normalizer_normalize($string, $form = p\Normalizer::FORM_C) { return p\Normalizer::normalize($string, $form); } } diff --git a/vendor/symfony/polyfill-intl-normalizer/composer.json b/vendor/symfony/polyfill-intl-normalizer/composer.json index b0986a8..393edf7 100644 --- a/vendor/symfony/polyfill-intl-normalizer/composer.json +++ b/vendor/symfony/polyfill-intl-normalizer/composer.json @@ -16,7 +16,7 @@ } ], "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "autoload": { "psr-4": { "Symfony\\Polyfill\\Intl\\Normalizer\\": "" }, @@ -29,7 +29,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", diff --git a/vendor/symfony/polyfill-php70/LICENSE b/vendor/symfony/polyfill-php70/LICENSE deleted file mode 100644 index 4cd8bdd..0000000 --- a/vendor/symfony/polyfill-php70/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2015-2019 Fabien Potencier - -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/symfony/polyfill-php70/Php70.php b/vendor/symfony/polyfill-php70/Php70.php deleted file mode 100644 index 7f1ad08..0000000 --- a/vendor/symfony/polyfill-php70/Php70.php +++ /dev/null @@ -1,74 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Polyfill\Php70; - -/** - * @author Nicolas Grekas - * - * @internal - */ -final class Php70 -{ - public static function intdiv($dividend, $divisor) - { - $dividend = self::intArg($dividend, __FUNCTION__, 1); - $divisor = self::intArg($divisor, __FUNCTION__, 2); - - if (0 === $divisor) { - throw new \DivisionByZeroError('Division by zero'); - } - if (-1 === $divisor && ~PHP_INT_MAX === $dividend) { - throw new \ArithmeticError('Division of PHP_INT_MIN by -1 is not an integer'); - } - - return ($dividend - ($dividend % $divisor)) / $divisor; - } - - public static function preg_replace_callback_array(array $patterns, $subject, $limit = -1, &$count = 0) - { - $count = 0; - $result = (string) $subject; - if (0 === $limit = self::intArg($limit, __FUNCTION__, 3)) { - return $result; - } - - foreach ($patterns as $pattern => $callback) { - $result = preg_replace_callback($pattern, $callback, $result, $limit, $c); - $count += $c; - } - - return $result; - } - - public static function error_clear_last() - { - static $handler; - if (!$handler) { - $handler = function () { return false; }; - } - set_error_handler($handler); - @trigger_error(''); - restore_error_handler(); - } - - private static function intArg($value, $caller, $pos) - { - if (\is_int($value)) { - return $value; - } - if (!\is_numeric($value) || PHP_INT_MAX <= ($value += 0) || ~PHP_INT_MAX >= $value) { - throw new \TypeError(sprintf('%s() expects parameter %d to be integer, %s given', $caller, $pos, \gettype($value))); - } - - return (int) $value; - } -} diff --git a/vendor/symfony/polyfill-php70/README.md b/vendor/symfony/polyfill-php70/README.md deleted file mode 100644 index abd5488..0000000 --- a/vendor/symfony/polyfill-php70/README.md +++ /dev/null @@ -1,28 +0,0 @@ -Symfony Polyfill / Php70 -======================== - -This component provides features unavailable in releases prior to PHP 7.0: - -- [`intdiv`](https://php.net/intdiv) -- [`preg_replace_callback_array`](https://php.net/preg_replace_callback_array) -- [`error_clear_last`](https://php.net/error_clear_last) -- `random_bytes` and `random_int` (from [paragonie/random_compat](https://github.com/paragonie/random_compat)) -- [`*Error` throwable classes](https://php.net/Error) -- [`PHP_INT_MIN`](https://php.net/reserved.constants#constant.php-int-min) -- `SessionUpdateTimestampHandlerInterface` - -More information can be found in the -[main Polyfill README](https://github.com/symfony/polyfill/blob/master/README.md). - -Compatibility notes -=================== - -To write portable code between PHP5 and PHP7, some care must be taken: -- `\*Error` exceptions must be caught before `\Exception`; -- after calling `error_clear_last()`, the result of `$e = error_get_last()` must be - verified using `isset($e['message'][0])` instead of `null !== $e`. - -License -======= - -This library is released under the [MIT license](LICENSE). diff --git a/vendor/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php b/vendor/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php deleted file mode 100644 index 6819124..0000000 --- a/vendor/symfony/polyfill-php70/Resources/stubs/ArithmeticError.php +++ /dev/null @@ -1,5 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Symfony\Polyfill\Php70 as p; - -if (PHP_VERSION_ID >= 70000) { - return; -} - -if (!defined('PHP_INT_MIN')) { - define('PHP_INT_MIN', ~PHP_INT_MAX); -} - -if (!function_exists('intdiv')) { - function intdiv($dividend, $divisor) { return p\Php70::intdiv($dividend, $divisor); } -} -if (!function_exists('preg_replace_callback_array')) { - function preg_replace_callback_array(array $patterns, $subject, $limit = -1, &$count = 0) { return p\Php70::preg_replace_callback_array($patterns, $subject, $limit, $count); } -} -if (!function_exists('error_clear_last')) { - function error_clear_last() { return p\Php70::error_clear_last(); } -} diff --git a/vendor/symfony/polyfill-php70/composer.json b/vendor/symfony/polyfill-php70/composer.json deleted file mode 100644 index 771a6f6..0000000 --- a/vendor/symfony/polyfill-php70/composer.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "symfony/polyfill-php70", - "type": "library", - "description": "Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions", - "keywords": ["polyfill", "shim", "compatibility", "portable"], - "homepage": "https://symfony.com", - "license": "MIT", - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "require": { - "php": ">=5.3.3", - "paragonie/random_compat": "~1.0|~2.0|~9.99" - }, - "autoload": { - "psr-4": { "Symfony\\Polyfill\\Php70\\": "" }, - "files": [ "bootstrap.php" ], - "classmap": [ "Resources/stubs" ] - }, - "minimum-stability": "dev", - "extra": { - "branch-alias": { - "dev-master": "1.18-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - } -} diff --git a/vendor/symfony/polyfill-php72/Php72.php b/vendor/symfony/polyfill-php72/Php72.php index 9b3edc7..5e20d5b 100644 --- a/vendor/symfony/polyfill-php72/Php72.php +++ b/vendor/symfony/polyfill-php72/Php72.php @@ -73,7 +73,7 @@ final class Php72 return 'Windows'; } - $map = array( + $map = [ 'Darwin' => 'Darwin', 'DragonFly' => 'BSD', 'FreeBSD' => 'BSD', @@ -81,9 +81,9 @@ final class Php72 'OpenBSD' => 'BSD', 'Linux' => 'Linux', 'SunOS' => 'Solaris', - ); + ]; - return isset($map[PHP_OS]) ? $map[PHP_OS] : 'Unknown'; + return isset($map[\PHP_OS]) ? $map[\PHP_OS] : 'Unknown'; } public static function spl_object_id($object) @@ -102,7 +102,7 @@ final class Php72 public static function sapi_windows_vt100_support($stream, $enable = null) { if (!\is_resource($stream)) { - trigger_error('sapi_windows_vt100_support() expects parameter 1 to be resource, '.\gettype($stream).' given', E_USER_WARNING); + trigger_error('sapi_windows_vt100_support() expects parameter 1 to be resource, '.\gettype($stream).' given', \E_USER_WARNING); return false; } @@ -110,7 +110,7 @@ final class Php72 $meta = stream_get_meta_data($stream); if ('STDIO' !== $meta['stream_type']) { - trigger_error('sapi_windows_vt100_support() was not able to analyze the specified stream', E_USER_WARNING); + trigger_error('sapi_windows_vt100_support() was not able to analyze the specified stream', \E_USER_WARNING); return false; } @@ -134,7 +134,7 @@ final class Php72 public static function stream_isatty($stream) { if (!\is_resource($stream)) { - trigger_error('stream_isatty() expects parameter 1 to be resource, '.\gettype($stream).' given', E_USER_WARNING); + trigger_error('stream_isatty() expects parameter 1 to be resource, '.\gettype($stream).' given', \E_USER_WARNING); return false; } @@ -150,12 +150,12 @@ final class Php72 private static function initHashMask() { - $obj = (object) array(); + $obj = (object) []; self::$hashMask = -1; // check if we are nested in an output buffering handler to prevent a fatal error with ob_start() below - $obFuncs = array('ob_clean', 'ob_end_clean', 'ob_flush', 'ob_end_flush', 'ob_get_contents', 'ob_get_flush'); - foreach (debug_backtrace(\PHP_VERSION_ID >= 50400 ? DEBUG_BACKTRACE_IGNORE_ARGS : false) as $frame) { + $obFuncs = ['ob_clean', 'ob_end_clean', 'ob_flush', 'ob_end_flush', 'ob_get_contents', 'ob_get_flush']; + foreach (debug_backtrace(\PHP_VERSION_ID >= 50400 ? \DEBUG_BACKTRACE_IGNORE_ARGS : false) as $frame) { if (isset($frame['function'][0]) && !isset($frame['class']) && 'o' === $frame['function'][0] && \in_array($frame['function'], $obFuncs)) { $frame['line'] = 0; break; @@ -182,7 +182,7 @@ final class Php72 $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); } - if ('UTF-8' !== $encoding) { + if ('UTF-8' !== $encoding = $encoding ?? mb_internal_encoding()) { $s = mb_convert_encoding($s, $encoding, 'UTF-8'); } @@ -191,7 +191,7 @@ final class Php72 public static function mb_ord($s, $encoding = null) { - if (null == $encoding) { + if (null === $encoding) { $s = mb_convert_encoding($s, 'UTF-8'); } elseif ('UTF-8' !== $encoding) { $s = mb_convert_encoding($s, 'UTF-8', $encoding); diff --git a/vendor/symfony/polyfill-php72/bootstrap.php b/vendor/symfony/polyfill-php72/bootstrap.php index a27a900..b5c92d4 100644 --- a/vendor/symfony/polyfill-php72/bootstrap.php +++ b/vendor/symfony/polyfill-php72/bootstrap.php @@ -11,7 +11,7 @@ use Symfony\Polyfill\Php72 as p; -if (PHP_VERSION_ID >= 70200) { +if (\PHP_VERSION_ID >= 70200) { return; } @@ -31,27 +31,27 @@ if (!defined('PHP_OS_FAMILY')) { define('PHP_OS_FAMILY', p\Php72::php_os_family()); } -if ('\\' === DIRECTORY_SEPARATOR && !function_exists('sapi_windows_vt100_support')) { +if ('\\' === \DIRECTORY_SEPARATOR && !function_exists('sapi_windows_vt100_support')) { function sapi_windows_vt100_support($stream, $enable = null) { return p\Php72::sapi_windows_vt100_support($stream, $enable); } } if (!function_exists('stream_isatty')) { function stream_isatty($stream) { return p\Php72::stream_isatty($stream); } } if (!function_exists('utf8_encode')) { - function utf8_encode($s) { return p\Php72::utf8_encode($s); } + function utf8_encode($string) { return p\Php72::utf8_encode($string); } } if (!function_exists('utf8_decode')) { - function utf8_decode($s) { return p\Php72::utf8_decode($s); } + function utf8_decode($string) { return p\Php72::utf8_decode($string); } } if (!function_exists('spl_object_id')) { - function spl_object_id($s) { return p\Php72::spl_object_id($s); } + function spl_object_id($object) { return p\Php72::spl_object_id($object); } } if (!function_exists('mb_ord')) { - function mb_ord($s, $enc = null) { return p\Php72::mb_ord($s, $enc); } + function mb_ord($string, $encoding = null) { return p\Php72::mb_ord($string, $encoding); } } if (!function_exists('mb_chr')) { - function mb_chr($code, $enc = null) { return p\Php72::mb_chr($code, $enc); } + function mb_chr($codepoint, $encoding = null) { return p\Php72::mb_chr($codepoint, $encoding); } } if (!function_exists('mb_scrub')) { - function mb_scrub($s, $enc = null) { $enc = null === $enc ? mb_internal_encoding() : $enc; return mb_convert_encoding($s, $enc, $enc); } + function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); } } diff --git a/vendor/symfony/polyfill-php72/composer.json b/vendor/symfony/polyfill-php72/composer.json index e295cab..c96c844 100644 --- a/vendor/symfony/polyfill-php72/composer.json +++ b/vendor/symfony/polyfill-php72/composer.json @@ -16,7 +16,7 @@ } ], "require": { - "php": ">=5.3.3" + "php": ">=7.1" }, "autoload": { "psr-4": { "Symfony\\Polyfill\\Php72\\": "" }, @@ -25,7 +25,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "1.18-dev" + "dev-main": "1.23-dev" }, "thanks": { "name": "symfony/polyfill", 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.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/Executor/ExecutionContext.php b/vendor/webonyx/graphql-php/src/Executor/ExecutionContext.php index 3de1a2e..4a57f20 100644 --- a/vendor/webonyx/graphql-php/src/Executor/ExecutionContext.php +++ b/vendor/webonyx/graphql-php/src/Executor/ExecutionContext.php @@ -14,7 +14,7 @@ use GraphQL\Type\Schema; * Data that must be available at all points during query execution. * * Namely, schema of the type system that is currently executing, - * and the fragments defined in the query document + * and the fragments defined in the query document. * * @internal */ @@ -45,28 +45,28 @@ class ExecutionContext public $errors; /** @var PromiseAdapter */ - public $promises; + public $promiseAdapter; public function __construct( $schema, $fragments, - $root, + $rootValue, $contextValue, $operation, - $variables, + $variableValues, $errors, $fieldResolver, $promiseAdapter ) { $this->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/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/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/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/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/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/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/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/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/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/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/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/ValidationContext.php b/vendor/webonyx/graphql-php/src/Validator/ValidationContext.php index 7163371..549053e 100644 --- a/vendor/webonyx/graphql-php/src/Validator/ValidationContext.php +++ b/vendor/webonyx/graphql-php/src/Validator/ValidationContext.php @@ -4,24 +4,33 @@ declare(strict_types=1); namespace GraphQL\Validator; -use GraphQL\Error\Error; +use GraphQL\Error\InvariantViolation; use GraphQL\Language\AST\DocumentNode; +use GraphQL\Language\AST\FieldNode; use GraphQL\Language\AST\FragmentDefinitionNode; use GraphQL\Language\AST\FragmentSpreadNode; use GraphQL\Language\AST\HasSelectionSet; +use GraphQL\Language\AST\InlineFragmentNode; use GraphQL\Language\AST\NodeKind; use GraphQL\Language\AST\OperationDefinitionNode; use GraphQL\Language\AST\SelectionSetNode; use GraphQL\Language\AST\VariableNode; use GraphQL\Language\Visitor; +use GraphQL\Type\Definition\CompositeType; +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\OutputType; +use GraphQL\Type\Definition\ScalarType; use GraphQL\Type\Definition\Type; use GraphQL\Type\Schema; use GraphQL\Utils\TypeInfo; use SplObjectStorage; +use function array_merge; use function array_pop; -use function call_user_func_array; use function count; /** @@ -29,20 +38,11 @@ use function count; * allowing access to commonly useful contextual information from within a * validation rule. */ -class ValidationContext +class ValidationContext extends ASTValidationContext { - /** @var Schema */ - private $schema; - - /** @var DocumentNode */ - private $ast; - /** @var TypeInfo */ private $typeInfo; - /** @var Error[] */ - private $errors; - /** @var FragmentDefinitionNode[] */ private $fragments; @@ -60,37 +60,14 @@ class ValidationContext public function __construct(Schema $schema, DocumentNode $ast, TypeInfo $typeInfo) { - $this->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(); }