YnloGraphQLExtension   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 146
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 16
eloc 84
c 3
b 1
f 0
dl 0
loc 146
ccs 0
cts 102
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getAlias() 0 3 1
A setBackwardCompatibilitySettings() 0 10 5
C load() 0 109 10
1
<?php
2
3
/*******************************************************************************
4
 *  This file is part of the GraphQL Bundle package.
5
 *
6
 *  (c) YnloUltratech <[email protected]>
7
 *
8
 *  For the full copyright and license information, please view the LICENSE
9
 *  file that was distributed with this source code.
10
 ******************************************************************************/
11
12
namespace Ynlo\GraphQLBundle\DependencyInjection;
13
14
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
15
use Symfony\Component\Config\FileLocator;
16
use Symfony\Component\DependencyInjection\ContainerBuilder;
17
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
18
use Symfony\Component\DependencyInjection\Parameter;
19
use Symfony\Component\DependencyInjection\Reference;
20
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
21
use Ynlo\GraphQLBundle\Cache\DefinitionCacheWarmer;
22
use Ynlo\GraphQLBundle\Command\MercureHubCommand;
23
use Ynlo\GraphQLBundle\Command\SubscriptionConsumerCommand;
24
use Ynlo\GraphQLBundle\Controller\GraphQLEndpointController;
25
use Ynlo\GraphQLBundle\Controller\SubscriptionsController;
0 ignored issues
show
Bug introduced by
The type Ynlo\GraphQLBundle\Contr...SubscriptionsController was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use Ynlo\GraphQLBundle\Controller\SubscriptionsHeartbeatController;
0 ignored issues
show
Bug introduced by
The type Ynlo\GraphQLBundle\Contr...ionsHeartbeatController was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use Ynlo\GraphQLBundle\Encoder\IDEncoderManager;
28
use Ynlo\GraphQLBundle\GraphiQL\JWTGraphiQLAuthentication;
29
use Ynlo\GraphQLBundle\GraphiQL\LexikJWTGraphiQLAuthenticator;
30
use Ynlo\GraphQLBundle\Request\SubscriptionsRequestMiddleware;
31
use Ynlo\GraphQLBundle\Subscription\Publisher;
32
use Ynlo\GraphQLBundle\Subscription\PubSub\RedisPubSubHandler;
33
use Ynlo\GraphQLBundle\Subscription\Subscriber;
34
use Ynlo\GraphQLBundle\Subscription\SubscriptionAwareInterface;
35
use Ynlo\GraphQLBundle\Subscription\SubscriptionManager;
36
37
/**
38
 * Class YnloGraphQLExtension
39
 */
40
class YnloGraphQLExtension extends Extension
41
{
42
    protected $subscriptionsDependenciesInstalled = true;
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function load(array $configs, ContainerBuilder $container)
48
    {
49
        $configuration = new Configuration();
50
        $config = $this->processConfiguration($configuration, $configs);
51
52
        if (!isset($config['namespaces']['bundles']['aliases']['GraphQLBundle'])) {
53
            $config['namespaces']['bundles']['aliases']['GraphQLBundle'] = 'AppBundle';
54
        }
55
56
        $container->setParameter('graphql.config', $config);
57
        $container->setParameter('graphql.pagination', $config['pagination'] ?? []);
58
        $container->setParameter('graphql.error_handling', $config['error_handling'] ?? []);
59
        $container->setParameter('graphql.error_handling.controlled_errors', $config['error_handling']['controlled_errors'] ?? []);
60
        $container->setParameter('graphql.error_handling.jwt_auth_failure_compatibility', $config['error_handling']['jwt_auth_failure_compatibility'] ?? false);
61
        $container->setParameter('graphql.namespaces', $config['namespaces'] ?? []);
62
        $container->setParameter('graphql.cors_config', $config['cors'] ?? []);
63
        $container->setParameter('graphql.graphiql', $config['graphiql'] ?? []);
64
        $container->setParameter('graphql.graphiql_auth_jwt', $config['graphiql']['authentication']['provider']['jwt'] ?? []);//DEPRECATED
65
        $container->setParameter('graphql.graphiql_auth_lexik_jwt', $config['graphiql']['authentication']['provider']['lexik_jwt'] ?? []);
66
        $container->setParameter('graphql.security.validation_rules', $config['security']['validation_rules'] ?? []);
67
        $container->setParameter('graphql.subscriptions.redis', $config['subscriptions']['redis'] ?? []);
68
        $container->setParameter('graphql.subscriptions.ttl', $config['subscriptions']['ttl'] ?? []);
69
70
        $endpointsConfig = [];
71
        $endpointsConfig['endpoints'] = $config['endpoints'] ?? [];
72
        $endpointsConfig['default'] = $config['endpoint_default'] ?? null;
73
        $endpointsConfig['alias'] = $config['endpoint_alias'] ?? [];
74
75
        $container->setParameter('graphql.endpoints', $endpointsConfig);
76
        $container->setParameter('graphql.endpoints_list', array_keys($endpointsConfig['endpoints']));
77
78
        $graphiQLAuthProvider = null;
79
80
        //DEPRECATED since v1.1
81
        if ($config['graphiql']['authentication']['provider']['jwt']['enabled'] ?? false) {
82
            $graphiQLAuthProvider = JWTGraphiQLAuthentication::class;
83
            @trigger_error('The option `graphql.graphiql.authentication.provider.jwt` has been deprecated use `graphql.graphiql.authentication.provider.lexik_jwt` instead');
84
        }
85
86
        if ($config['graphiql']['authentication']['provider']['lexik_jwt']['enabled'] ?? false) {
87
            $graphiQLAuthProvider = LexikJWTGraphiQLAuthenticator::class;
88
            if (!interface_exists(JWTTokenManagerInterface::class)) {
89
                throw new \InvalidArgumentException('In order to use `lexik_jwt` authentication in GraphiQL Explorer must install LexikJWTAuthenticationBundle.');
90
            }
91
        }
92
93
        if ($config['graphiql']['authentication']['provider']['custom'] ?? false) {
94
            $graphiQLAuthProvider = $config['graphiql']['authentication']['provider']['custom'];
95
        }
96
        $container->setParameter('graphql.graphiql_auth_provider', $graphiQLAuthProvider);
97
98
        $configDir = __DIR__.'/../Resources/config';
99
        $loader = new YamlFileLoader($container, new FileLocator($configDir));
100
        $loader->load('services.yml');
101
102
        if ($container->getParameter('kernel.environment') !== 'dev') {
103
            $container->getDefinition(DefinitionCacheWarmer::class)->clearTag('kernel.event_subscriber');
104
        }
105
106
        //configure LexikJWTGraphiQLAuthenticator definition
107
        if ($config['graphiql']['authentication']['provider']['lexik_jwt']['enabled'] ?? false) {
108
            $providerName = sprintf('security.user.provider.concrete.%s', $config['graphiql']['authentication']['provider']['lexik_jwt']['user_provider']);
109
            $container->getDefinition(LexikJWTGraphiQLAuthenticator::class)
110
                      ->setArgument(1, new Reference($providerName));
111
        } else {
112
            $container->removeDefinition(LexikJWTGraphiQLAuthenticator::class);
113
        }
114
115
        $this->setBackwardCompatibilitySettings($container, $config['bc'] ?? []);
116
117
        //build the ID encoder manager with configured encoder
118
        $container->getDefinition(IDEncoderManager::class)
119
                  ->setPublic(true)
120
                  ->replaceArgument(0, new Reference($config['id_encoder']));
121
122
123
        //endpoint definition
124
        $container->getDefinition(GraphQLEndpointController::class)
125
                  ->addMethodCall('setErrorFormatter', [new Reference($config['error_handling']['formatter'])])
126
                  ->addMethodCall('setErrorHandler', [new Reference($config['error_handling']['handler'])]);
127
128
        $bundles = $container->getParameter('kernel.bundles');
129
        if (isset($bundles['MercureBundle']) && $config['subscriptions']['enabled']) {
130
            $mercureHub = $config['subscriptions']['mercure_hub'];
131
132
            $mercurePublisherReference = new Reference(sprintf('mercure.hub.%s.publisher', $mercureHub));
133
134
            $container->getDefinition(SubscriptionManager::class)
135
                      ->addArgument(new Reference($config['subscriptions']['pubsub_handler']))
136
                      ->addArgument(new Parameter('kernel.secret'));
137
138
            $container->getDefinition(Subscriber::class)
139
                      ->addMethodCall('setMercureHubUrl', [new Parameter('mercure.hubs'), $mercureHub]);
140
141
            $container->getDefinition(SubscriptionConsumerCommand::class)
142
                      ->addArgument($mercurePublisherReference);
143
144
            $container->getDefinition(GraphQLEndpointController::class)->addMethodCall('setPublisher', [$mercurePublisherReference]);
145
146
            $container->registerForAutoconfiguration(SubscriptionAwareInterface::class)
147
                      ->addMethodCall('setPublisher', [new Reference(Publisher::class)]);
148
        } else {
149
            $container->removeDefinition(SubscriptionManager::class);
150
            $container->removeDefinition(MercureHubCommand::class);
151
            $container->removeDefinition(SubscriptionConsumerCommand::class);
152
            $container->removeDefinition(SubscriptionsRequestMiddleware::class);
153
            $container->removeDefinition(Subscriber::class);
154
            $container->removeDefinition(Publisher::class);
155
            $container->removeDefinition(RedisPubSubHandler::class);
156
        }
157
    }
158
159
    /**
160
     * @param ContainerBuilder $container
161
     * @param array            $config
162
     *
163
     * @throws \ReflectionException
164
     */
165
    public function setBackwardCompatibilitySettings(ContainerBuilder $container, array $config): void
166
    {
167
        foreach ($container->getDefinitions() as $class => $definition) {
168
            if ($definition->getClass()) {
169
                $class = $definition->getClass();
170
            }
171
            if (class_exists($class)) {
172
                $ref = new \ReflectionClass($class);
173
                if ($ref->implementsInterface(BackwardCompatibilityAwareInterface::class)) {
174
                    $definition->addMethodCall('setBCConfig', [$config]);
175
                }
176
            }
177
        }
178
    }
179
180
    /**
181
     * {@inheritDoc}
182
     */
183
    public function getAlias()
184
    {
185
        return 'graphql';
186
    }
187
}
188