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 (#237)
by Jérémiah
08:38
created

OverblogGraphQLTypesExtension::getAlias()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Overblog\GraphQLBundle\DependencyInjection;
4
5
use Overblog\GraphQLBundle\OverblogGraphQLBundle;
6
use Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException;
7
use Symfony\Component\Config\Resource\FileResource;
8
use Symfony\Component\DependencyInjection\ContainerBuilder;
9
use Symfony\Component\Finder\Finder;
10
use Symfony\Component\Finder\SplFileInfo;
11
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
12
13
class OverblogGraphQLTypesExtension extends Extension
14
{
15
    private static $configTypes = ['yaml', 'xml'];
16
17
    private static $typeExtensions = ['yaml' => '{yaml,yml}', 'xml' => 'xml'];
18
19
    private static $defaultDefaultConfig = [
20
        'definitions' => [
21
            'mappings' => [
22
                'auto_discover' => [
23
                    'root_dir' => true,
24
                    'bundles' => true,
25
                ],
26
                'types' => [],
27
            ],
28
        ],
29
    ];
30
31
    private $treatedFiles = [];
32
33
    const DEFAULT_TYPES_SUFFIX = '.types';
34
35 30
    public function load(array $configs, ContainerBuilder $container)
36
    {
37 30
        $this->checkTypesDuplication($configs);
38
        // flatten config is a requirement to support inheritance
39 29
        $flattenConfig = [call_user_func_array('array_merge', $configs)];
40 29
        $configuration = $this->getConfiguration($flattenConfig, $container);
41 29
        $config = $this->processConfiguration($configuration, $flattenConfig);
0 ignored issues
show
Bug introduced by
It seems like $configuration defined by $this->getConfiguration(...ttenConfig, $container) on line 40 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...
42
43 24
        $container->setParameter($this->getAlias().'.config', $config);
44 24
    }
45
46 25
    public function containerPrependExtensionConfig(array $config, ContainerBuilder $container)
47
    {
48 25
        $typesMappings = $this->mappingConfig($config, $container);
49
        // reset treated files
50 25
        $this->treatedFiles = [];
51
        // treats mappings
52 25
        foreach ($typesMappings as $params) {
53 25
            $this->prependExtensionConfigFromFiles($params['type'], $params['files'], $container);
54
        }
55 23
    }
56
57
    /**
58
     * @param $type
59
     * @param SplFileInfo[]    $files
60
     * @param ContainerBuilder $container
61
     */
62 25
    private function prependExtensionConfigFromFiles($type, $files, ContainerBuilder $container)
63
    {
64 25
        foreach ($files as $file) {
65 25
            $fileRealPath = $file->getRealPath();
66 25
            if (isset($this->treatedFiles[$fileRealPath])) {
67 1
                continue;
68
            }
69
70 25
            $parserClass = sprintf('Overblog\\GraphQLBundle\\Config\\Parser\\%sParser', ucfirst($type));
71
72 25
            $typeConfig = call_user_func($parserClass.'::parse', $file, $container);
73 23
            $container->prependExtensionConfig($this->getAlias(), $typeConfig);
74 23
            $this->treatedFiles[$file->getRealPath()] = true;
75
        }
76 23
    }
77
78 30
    private function checkTypesDuplication(array $typeConfigs)
79
    {
80 30
        $types = call_user_func_array('array_merge', array_map('array_keys', $typeConfigs));
81 30
        $duplications = array_keys(array_filter(array_count_values($types), function ($count) {
82 30
            return $count > 1;
83 30
        }));
84 30
        if (!empty($duplications)) {
85 1
            throw new ForbiddenOverwriteException(sprintf(
86 1
                'Types (%s) cannot be overwritten. See inheritance doc section for more details.',
87 1
                implode(', ', array_map('json_encode', $duplications))
88
            ));
89
        }
90 29
    }
91
92 25
    private function mappingConfig(array $config, ContainerBuilder $container)
93
    {
94
        // use default value if needed
95 25
        $config = array_replace_recursive(self::$defaultDefaultConfig, $config);
96
97 25
        $mappingConfig = $config['definitions']['mappings'];
98 25
        $typesMappings = $mappingConfig['types'];
99
100
        // app only config files (yml or xml)
101 25
        if ($mappingConfig['auto_discover']['root_dir'] && $container->hasParameter('kernel.root_dir')) {
102 1
            $typesMappings[] = ['dir' => $container->getParameter('kernel.root_dir').'/config/graphql', 'type' => null];
103
        }
104 25
        if ($mappingConfig['auto_discover']['bundles']) {
105 3
            $mappingFromBundles = $this->mappingFromBundles($container);
106 3
            $typesMappings = array_merge($typesMappings, $mappingFromBundles);
107
        } else {
108
            // enabled only for this bundle
109 22
            $typesMappings[] = [
110 22
                'dir' => $this->bundleDir(OverblogGraphQLBundle::class).'/Resources/config/graphql',
111 22
                'type' => 'yaml',
112
            ];
113
        }
114
115
        // from config
116 25
        $typesMappings = $this->detectFilesFromTypesMappings($typesMappings, $container);
117
118 25
        return $typesMappings;
119
    }
120
121 25
    private function detectFilesFromTypesMappings(array $typesMappings, ContainerBuilder $container)
122
    {
123 25
        return array_filter(array_map(
124 25
            function (array $typeMapping) use ($container) {
125 25
                $params = $this->detectFilesByType(
126 25
                    $container,
127 25
                    $typeMapping['dir'],
128 25
                    $typeMapping['type'],
129 25
                    isset($typeMapping['suffix']) ? $typeMapping['suffix'] : ''
130
                );
131
132 25
                return $params;
133 25
            },
134 25
            $typesMappings
135
        ));
136
    }
137
138 3
    private function mappingFromBundles(ContainerBuilder $container)
139
    {
140 3
        $typesMappings = [];
141 3
        $bundles = $container->getParameter('kernel.bundles');
142
143
        // auto detect from bundle
144 3
        foreach ($bundles as $name => $class) {
145 1
            $bundleDir = $this->bundleDir($class);
146
147
            // only config files (yml or xml)
148 1
            $typesMappings[] = ['dir' => $bundleDir.'/Resources/config/graphql', 'type' => null];
149
        }
150
151 3
        return $typesMappings;
152
    }
153
154 25
    private function detectFilesByType(ContainerBuilder $container, $path, $type, $suffix)
155
    {
156
        // add the closest existing directory as a resource
157 25
        $resource = $path;
158 25
        while (!is_dir($resource)) {
159 1
            $resource = dirname($resource);
160
        }
161 25
        $container->addResource(new FileResource($resource));
162
163 25
        $finder = new Finder();
164
165 25
        $types = null === $type ? self::$configTypes : [$type];
166
167 25
        foreach ($types as $type) {
168
            try {
169 25
                $finder->files()->in($path)->name('*'.$suffix.'.'.self::$typeExtensions[$type]);
170 1
            } catch (\InvalidArgumentException $e) {
171 1
                continue;
172
            }
173 25
            if ($finder->count() > 0) {
174
                return [
175 25
                    'type' => $type,
176 25
                    'files' => $finder,
177
                ];
178
            }
179
        }
180
181 1
        return;
182
    }
183
184 23
    private function bundleDir($bundleClass)
185
    {
186 23
        $bundle = new \ReflectionClass($bundleClass);
187 23
        $bundleDir = dirname($bundle->getFileName());
188
189 23
        return $bundleDir;
190
    }
191
192 24
    public function getAliasPrefix()
193
    {
194 24
        return 'overblog_graphql';
195
    }
196
197 24
    public function getAlias()
198
    {
199 24
        return $this->getAliasPrefix().'_types';
200
    }
201
202 29
    public function getConfiguration(array $config, ContainerBuilder $container)
203
    {
204 29
        return new TypesConfiguration();
205
    }
206
}
207