Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Pull Request — master (#264)
by Jérémiah
12:13
created

setErrorHandlerArguments()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 8.7972
cc 4
eloc 13
nc 8
nop 2
crap 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A OverblogGraphQLExtension::setSecurity() 0 6 2
1
<?php
2
3
namespace Overblog\GraphQLBundle\DependencyInjection;
4
5
use GraphQL\Error\UserError;
6
use GraphQL\Type\Schema;
7
use Overblog\GraphQLBundle\CacheWarmer\CompileCacheWarmer;
8
use Overblog\GraphQLBundle\Config\Processor\BuilderProcessor;
9
use Overblog\GraphQLBundle\Error\ErrorHandler;
10
use Overblog\GraphQLBundle\Error\UserWarning;
11
use Overblog\GraphQLBundle\Event\Events;
12
use Overblog\GraphQLBundle\EventListener\ClassLoaderListener;
13
use Overblog\GraphQLBundle\EventListener\DebugListener;
14
use Overblog\GraphQLBundle\EventListener\ErrorHandlerListener;
15
use Overblog\GraphQLBundle\EventListener\ErrorLoggerListener;
16
use Symfony\Component\Cache\Adapter\ArrayAdapter;
17
use Symfony\Component\Config\FileLocator;
18
use Symfony\Component\DependencyInjection\ContainerBuilder;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20
use Symfony\Component\DependencyInjection\Definition;
21
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
22
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
23
use Symfony\Component\DependencyInjection\Reference;
24
use Symfony\Component\ExpressionLanguage\ParserCache\ArrayParserCache;
25
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
26
use Symfony\Component\HttpKernel\Kernel;
27
28
class OverblogGraphQLExtension extends Extension implements PrependExtensionInterface
29
{
30 27
    public function load(array $configs, ContainerBuilder $container)
31
    {
32 27
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
33 27
        $loader->load('services.yml');
34 27
        $loader->load('graphql_types.yml');
35
36 27
        $config = $this->treatConfigs($configs, $container);
37
38 27
        $this->setBatchingMethod($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...on::setBatchingMethod() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
39 27
        $this->setExpressionLanguageDefaultParser($container);
40 27
        $this->setServicesAliases($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...n::setServicesAliases() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
41 27
        $this->setSchemaBuilderArguments($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...chemaBuilderArguments() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
42 27
        $this->setSchemaArguments($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...n::setSchemaArguments() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
43 27
        $this->setErrorHandler($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...sion::setErrorHandler() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
44 27
        $this->setSecurity($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...xtension::setSecurity() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
45 27
        $this->setConfigBuilders($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...on::setConfigBuilders() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
46 27
        $this->setDebugListener($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...ion::setDebugListener() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
47 27
        $this->setDefinitionParameters($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...tDefinitionParameters() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
48 27
        $this->setClassLoaderListener($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...etClassLoaderListener() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
49 27
        $this->setCompilerCacheWarmer($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container) on line 36 can also be of type null; however, Overblog\GraphQLBundle\D...etCompilerCacheWarmer() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
50
51 27
        $container->setParameter($this->getAlias().'.resources_dir', realpath(__DIR__.'/../Resources'));
52 27
    }
53
54 25
    public function prepend(ContainerBuilder $container)
55
    {
56 25
        $configs = $container->getExtensionConfig($this->getAlias());
57 25
        $configs = $container->getParameterBag()->resolveValue($configs);
58 25
        $config = $this->treatConfigs($configs, $container, true);
59
60
        /** @var OverblogGraphQLTypesExtension $typesExtension */
61 25
        $typesExtension = $container->getExtension($this->getAlias().'_types');
62 25
        $typesExtension->containerPrependExtensionConfig($config, $container);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->treatConfigs($configs, $container, true) on line 58 can also be of type null; however, Overblog\GraphQLBundle\D...rependExtensionConfig() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
63 25
    }
64
65 27
    public function getAlias()
66
    {
67 27
        return Configuration::NAME;
68
    }
69
70 27
    public function getConfiguration(array $config, ContainerBuilder $container)
71
    {
72 27
        return new Configuration(
73 27
            $container->getParameter('kernel.debug'),
74 27
            $container->hasParameter('kernel.cache_dir') ? $container->getParameter('kernel.cache_dir') : null
75
        );
76
    }
77
78 27
    private function setCompilerCacheWarmer(array $config, ContainerBuilder $container)
79
    {
80 27
        if ($config['definitions']['auto_compile']) {
81 26
            $definition = $container->setDefinition(
82 26
                CompileCacheWarmer::class,
83 26
                new Definition(CompileCacheWarmer::class)
84
            );
85 26
            $definition->setArguments([new Reference($this->getAlias().'.cache_compiler')]);
86 26
            $definition->addTag('kernel.cache_warmer', ['priority' => 50]);
87
        }
88 27
    }
89
90 27
    private function setClassLoaderListener(array $config, ContainerBuilder $container)
91
    {
92 27
        $container->setParameter($this->getAlias().'.use_classloader_listener', $config['definitions']['use_classloader_listener']);
93 27
        if ($config['definitions']['use_classloader_listener']) {
94 26
            $definition = $container->setDefinition(
95 26
                $this->getAlias().'.event_listener.classloader_listener',
96 26
                new Definition(ClassLoaderListener::class)
97
            );
98 26
            $definition->setPublic(true);
99 26
            $definition->setArguments([new Reference($this->getAlias().'.cache_compiler')]);
100 26
            $definition->addTag('kernel.event_listener', ['event' => 'kernel.request', 'method' => 'load', 'priority' => 255]);
101 26
            $definition->addTag('kernel.event_listener', ['event' => 'console.command', 'method' => 'load', 'priority' => 255]);
102
        }
103 27
    }
104
105 27
    private function setDefinitionParameters(array $config, ContainerBuilder $container)
106
    {
107
        // auto mapping
108 27
        $container->setParameter($this->getAlias().'.auto_mapping.enabled', $config['definitions']['auto_mapping']['enabled']);
109 27
        $container->setParameter($this->getAlias().'.auto_mapping.directories', $config['definitions']['auto_mapping']['directories']);
110
        // generator and config
111 27
        $container->setParameter($this->getAlias().'.default_resolver', $config['definitions']['default_resolver']);
112 27
        $container->setParameter($this->getAlias().'.class_namespace', $config['definitions']['class_namespace']);
113 27
        $container->setParameter($this->getAlias().'.cache_dir', $config['definitions']['cache_dir']);
114 27
    }
115
116 27
    private function setBatchingMethod(array $config, ContainerBuilder $container)
117
    {
118 27
        $container->setParameter($this->getAlias().'.batching_method', $config['batching_method']);
119 27
    }
120
121 27
    private function setExpressionLanguageDefaultParser(ContainerBuilder $container)
122
    {
123 27
        $class = version_compare(Kernel::VERSION, '3.2.0', '>=') ? ArrayAdapter::class : ArrayParserCache::class;
124 27
        $definition = new Definition($class);
125 27
        $definition->setPublic(false);
126 27
        $container->setDefinition($this->getAlias().'.cache_expression_language_parser.default', $definition);
127 27
    }
128
129 27
    private function setDebugListener(array $config, ContainerBuilder $container)
130
    {
131 27
        if ($config['definitions']['show_debug_info']) {
132 1
            $definition = $container->setDefinition(
133 1
                DebugListener::class,
134 1
                new Definition(DebugListener::class)
135
            );
136 1
            $definition->addTag('kernel.event_listener', ['event' => Events::PRE_EXECUTOR, 'method' => 'onPreExecutor']);
137 1
            $definition->addTag('kernel.event_listener', ['event' => Events::POST_EXECUTOR, 'method' => 'onPostExecutor']);
138
        }
139 27
    }
140
141 27
    private function setConfigBuilders(array $config, ContainerBuilder $container)
142
    {
143 27
        $useObjectToAddResource = method_exists($container, 'addObjectResource');
144 27
        $objectToAddResourceMethod = $useObjectToAddResource ? 'addObjectResource' : 'addClassResource';
145
146 27
        foreach (BuilderProcessor::BUILDER_TYPES as $type) {
147 27
            if (!empty($config['definitions']['builders'][$type])) {
148 1
                foreach ($config['definitions']['builders'][$type] as $params) {
149 1
                    $object = $useObjectToAddResource ? $params['class'] : new \ReflectionClass($params['class']);
150 1
                    $container->$objectToAddResourceMethod($object);
151 27
                    BuilderProcessor::addBuilderClass($params['alias'], $type, $params['class']);
152
                }
153
            }
154
        }
155 27
    }
156
157 27
    private function treatConfigs(array $configs, ContainerBuilder $container, $forceReload = false)
158
    {
159 27
        static $config = null;
160
161 27
        if ($forceReload || null === $config) {
162 27
            $configuration = $this->getConfiguration($configs, $container);
163 27
            $config = $this->processConfiguration($configuration, $configs);
0 ignored issues
show
Bug introduced by
It seems like $configuration defined by $this->getConfiguration($configs, $container) on line 162 can be null; however, Symfony\Component\Depend...:processConfiguration() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
164
        }
165
166 27
        return $config;
167
    }
168
169 27
    private function setSecurity(array $config, ContainerBuilder $container)
170
    {
171 27
        foreach ($config['security'] as $key => $value) {
172 27
            $container->setParameter(sprintf('%s.%s', $this->getAlias(), $key), $value);
173
        }
174 27
    }
175
176 27
    private function setErrorHandler(array $config, ContainerBuilder $container)
177
    {
178 27
        if ($config['errors_handler']['enabled']) {
179 27
            $id = $this->getAlias().'.error_handler';
180 27
            $errorHandlerDefinition = $container->setDefinition($id, new Definition(ErrorHandler::class));
181 27
            $errorHandlerDefinition->setPublic(false)
182 27
                ->setArguments(
183
                    [
184 27
                        new Reference('event_dispatcher'),
185 27
                        $config['errors_handler']['internal_error_message'],
186 27
                        $this->buildExceptionMap($config['errors_handler']['exceptions']),
187 27
                        $config['errors_handler']['map_exceptions_to_parent'],
188
                    ]
189
                )
190
            ;
191
192 27
            $errorHandlerListenerDefinition = $container->setDefinition(ErrorHandlerListener::class, new Definition(ErrorHandlerListener::class));
193 27
            $errorHandlerListenerDefinition->setPublic(true)
194 27
                ->setArguments([new Reference($id), $config['errors_handler']['rethrow_internal_exceptions'], $config['errors_handler']['debug']])
195 27
                ->addTag('kernel.event_listener', ['event' => Events::POST_EXECUTOR, 'method' => 'onPostExecutor'])
196
            ;
197
198 27
            if ($config['errors_handler']['log']) {
199 27
                $loggerServiceId = $config['errors_handler']['logger_service'];
200 27
                $invalidBehavior = ErrorLoggerListener::DEFAULT_LOGGER_SERVICE === $loggerServiceId ? ContainerInterface::NULL_ON_INVALID_REFERENCE : ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
201 27
                $errorHandlerListenerDefinition = $container->setDefinition(ErrorLoggerListener::class, new Definition(ErrorLoggerListener::class));
202 27
                $errorHandlerListenerDefinition->setPublic(true)
203 27
                    ->setArguments([new Reference($loggerServiceId, $invalidBehavior)])
204 27
                    ->addTag('kernel.event_listener', ['event' => Events::ERROR_FORMATTING, 'method' => 'onErrorFormatting'])
205
                ;
206
            }
207
        }
208 27
    }
209
210 27
    private function setSchemaBuilderArguments(array $config, ContainerBuilder $container)
211
    {
212 27
        $container->getDefinition($this->getAlias().'.schema_builder')
213 27
            ->replaceArgument(1, $config['definitions']['config_validation']);
214 27
    }
215
216 27
    private function setSchemaArguments(array $config, ContainerBuilder $container)
217
    {
218 27
        if (isset($config['definitions']['schema'])) {
219 27
            $executorDefinition = $container->getDefinition($this->getAlias().'.request_executor');
220
221 27
            foreach ($config['definitions']['schema'] as $schemaName => $schemaConfig) {
222 23
                $schemaID = sprintf('%s.schema_%s', $this->getAlias(), $schemaName);
223 23
                $definition = new Definition(Schema::class);
224 23
                $definition->setFactory([new Reference('overblog_graphql.schema_builder'), 'create']);
225 23
                $definition->setArguments([$schemaConfig['query'], $schemaConfig['mutation'], $schemaConfig['subscription']]);
226 23
                $definition->setPublic(false);
227 23
                $container->setDefinition($schemaID, $definition);
228
229 23
                $executorDefinition->addMethodCall('addSchema', [$schemaName, new Reference($schemaID)]);
230
            }
231
        }
232 27
    }
233
234 27
    private function setServicesAliases(array $config, ContainerBuilder $container)
235
    {
236 27
        if (isset($config['services'])) {
237 27
            foreach ($config['services'] as $name => $id) {
238 27
                $alias = sprintf('%s.%s', $this->getAlias(), $name);
239 27
                $container->setAlias($alias, $id);
240
            }
241
        }
242 27
    }
243
244
    /**
245
     * Returns a list of custom exceptions mapped to error/warning classes.
246
     *
247
     * @param array $exceptionConfig
248
     *
249
     * @return array Custom exception map, [exception => UserError/UserWarning]
250
     */
251 27
    private function buildExceptionMap(array $exceptionConfig)
252
    {
253 27
        $exceptionMap = [];
254
        $errorsMapping = [
255 27
            'errors' => UserError::class,
256
            'warnings' => UserWarning::class,
257
        ];
258
259 27
        foreach ($exceptionConfig as $type => $exceptionList) {
260 27
            foreach ($exceptionList as $exception) {
261 27
                $exceptionMap[$exception] = $errorsMapping[$type];
262
            }
263
        }
264
265 27
        return $exceptionMap;
266
    }
267
}
268