Passed
Push — master ( 24d3ea...342023 )
by Doug
02:11
created

Extension::initCodeCoverage()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 52
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 7.0368

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
eloc 32
c 3
b 0
f 0
nc 24
nop 5
dl 0
loc 52
ccs 30
cts 33
cp 0.9091
crap 7.0368
rs 8.4746

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Behat Code Coverage
4
 */
5
declare(strict_types=1);
6
7
namespace DVDoug\Behat\CodeCoverage;
8
9
use function array_walk;
10
11
use Behat\Testwork\Cli\ServiceContainer\CliExtension;
12
use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface;
13
use Behat\Testwork\ServiceContainer\ExtensionManager;
14
use Composer\InstalledVersions;
15
use Composer\Semver\VersionParser;
16
use DVDoug\Behat\CodeCoverage\Subscriber\EventSubscriber;
17
use SebastianBergmann\CodeCoverage\CodeCoverage;
18
use SebastianBergmann\CodeCoverage\Driver\Driver;
19
use SebastianBergmann\CodeCoverage\Driver\Selector;
20
use SebastianBergmann\CodeCoverage\Driver\Xdebug2NotEnabledException;
21
use SebastianBergmann\CodeCoverage\Driver\Xdebug3NotEnabledException;
22
use SebastianBergmann\CodeCoverage\Driver\XdebugNotAvailableException;
23
use SebastianBergmann\CodeCoverage\Driver\XdebugNotEnabledException;
0 ignored issues
show
Bug introduced by
The type SebastianBergmann\CodeCo...ebugNotEnabledException 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...
24
use SebastianBergmann\CodeCoverage\Filter;
25
use SebastianBergmann\CodeCoverage\NoCodeCoverageDriverAvailableException;
26
use SebastianBergmann\CodeCoverage\NoCodeCoverageDriverWithPathCoverageSupportAvailableException;
27
28
use function sprintf;
29
30
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
31
use Symfony\Component\Config\FileLocator;
32
use Symfony\Component\Console\Input\InputInterface;
33
use Symfony\Component\Console\Output\OutputInterface;
34
use Symfony\Component\DependencyInjection\ContainerBuilder;
35
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
36
use Symfony\Component\DependencyInjection\Reference;
37
38
use function sys_get_temp_dir;
39
40
class Extension implements ExtensionInterface
41
{
42
    /**
43
     * {@inheritdoc}
44
     */
45 1
    public function initialize(ExtensionManager $extensionManager): void
46
    {
47 1
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 4
    public function load(ContainerBuilder $container, array $config): void
53
    {
54 4
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/Resources/config'));
55
56 4
        $servicesFile = 'services.xml';
57 4
        $loader->load($servicesFile);
58
59 4
        $container->setParameter('behat.code_coverage.config.filter', $config['filter']);
60 4
        $container->setParameter('behat.code_coverage.config.branchAndPathCoverage', $config['branchAndPathCoverage']);
61 4
        $container->setParameter('behat.code_coverage.config.reports', $config['reports'] ?? []);
62 4
        $container->setParameter('behat.code_coverage.config.cache', $config['cache']);
63 1
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 8
    public function configure(ArrayNodeDefinition $builder): void
69
    {
70
        $builder
71 8
            ->children()
72 8
                ->scalarNode('cache')
73 8
                    ->defaultValue(sys_get_temp_dir() . '/behat-code-coverage-cache')
74 8
                ->end()
75 8
                ->booleanNode('branchAndPathCoverage')
0 ignored issues
show
Bug introduced by
The method booleanNode() does not exist on Symfony\Component\Config...der\NodeParentInterface. It seems like you code against a sub-type of Symfony\Component\Config...der\NodeParentInterface such as Symfony\Component\Config...ion\Builder\NodeBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

75
                ->/** @scrutinizer ignore-call */ booleanNode('branchAndPathCoverage')
Loading history...
76 8
                  ->defaultNull() // use null to mean auto
77 8
                ->end()
78 8
                ->arrayNode('filter')
79 8
                    ->addDefaultsIfNotSet()
80 8
                    ->children()
81 8
                        ->scalarNode('includeUncoveredFiles')
82 8
                            ->defaultTrue()
83 8
                        ->end()
84 8
                        ->scalarNode('processUncoveredFiles')
85 8
                            ->defaultFalse()
86 8
                            ->setDeprecated('dvdoug/behat-code-coverage', '5.3', 'the processUncoveredFiles setting is deprecated, it has been removed from php-code-coverage v10')
87 8
                        ->end()
88 8
                        ->arrayNode('include')
89 8
                            ->addDefaultsIfNotSet()
90 8
                            ->children()
91 8
                                ->arrayNode('directories')
92 8
                                   ->useAttributeAsKey('name')
93 8
                                   ->normalizeKeys(false)
94 8
                                   ->prototype('array')
95 8
                                       ->children()
96 8
                                           ->scalarNode('prefix')->defaultValue('')->end()
97 8
                                           ->scalarNode('suffix')->defaultValue('.php')->end()
98 8
                                       ->end()
99 8
                                   ->end()
100 8
                                ->end()
101 8
                                ->arrayNode('files')
102 8
                                   ->prototype('scalar')->end()
103 8
                                ->end()
104 8
                            ->end()
105 8
                        ->end()
106 8
                        ->arrayNode('exclude')
107 8
                            ->addDefaultsIfNotSet()
108 8
                            ->children()
109 8
                                ->arrayNode('directories')
110 8
                                   ->useAttributeAsKey('name')
111 8
                                   ->normalizeKeys(false)
112 8
                                   ->prototype('array')
113 8
                                       ->children()
114 8
                                           ->scalarNode('prefix')->defaultValue('')->end()
115 8
                                           ->scalarNode('suffix')->defaultValue('.php')->end()
116 8
                                       ->end()
117 8
                                   ->end()
118 8
                                ->end()
119 8
                                ->arrayNode('files')
120 8
                                   ->prototype('scalar')->end()
121 8
                                ->end()
122 8
                            ->end()
123 8
                        ->end()
124 8
                    ->end()
125 8
                ->end()
126 8
                ->arrayNode('reports')
127 8
                    ->children()
128 8
                        ->arrayNode('cobertura')
129 8
                            ->children()
130 8
                                ->scalarNode('name')->defaultNull()->end()
131 8
                                ->scalarNode('target')->isRequired()->cannotBeEmpty()->end()
132 8
                            ->end()
133 8
                        ->end()
134 8
                        ->arrayNode('clover')
135 8
                            ->children()
136 8
                                ->scalarNode('name')->defaultNull()->end()
137 8
                                ->scalarNode('target')->isRequired()->cannotBeEmpty()->end()
138 8
                            ->end()
139 8
                        ->end()
140 8
                        ->arrayNode('crap4j')
141 8
                            ->children()
142 8
                                ->scalarNode('name')->defaultNull()->end()
143 8
                                ->scalarNode('target')->isRequired()->cannotBeEmpty()->end()
144 8
                            ->end()
145 8
                        ->end()
146 8
                        ->arrayNode('html')
147 8
                            ->children()
148 8
                                ->scalarNode('target')->isRequired()->cannotBeEmpty()->end()
149 8
                                ->scalarNode('lowUpperBound')->defaultValue(50)->end()
150 8
                                ->scalarNode('highLowerBound')->defaultValue(90)->end()
151 8
                                ->arrayNode('colors')
152 8
                                    ->addDefaultsIfNotSet()
153 8
                                    ->children()
154 8
                                        ->scalarNode('successLow')->defaultValue('#dff0d8')->end()
155 8
                                        ->scalarNode('successMedium')->defaultValue('#c3e3b5')->end()
156 8
                                        ->scalarNode('successHigh')->defaultValue('#99cb84')->end()
157 8
                                        ->scalarNode('warning')->defaultValue('#fcf8e3')->end()
158 8
                                        ->scalarNode('danger')->defaultValue('#f2dede')->end()
159 8
                                    ->end()
160 8
                                ->end()
161 8
                                ->scalarNode('customCSSFile')->defaultNull()->end()
162 8
                            ->end()
163 8
                        ->end()
164 8
                        ->arrayNode('php')
165 8
                            ->children()
166 8
                                ->scalarNode('target')->isRequired()->cannotBeEmpty()->end()
167 8
                            ->end()
168 8
                        ->end()
169 8
                        ->arrayNode('text')
170 8
                            ->children()
171 8
                                ->booleanNode('showColors')->defaultValue(false)->end()
172 8
                                ->scalarNode('lowUpperBound')->defaultValue(50)->end()
173 8
                                ->scalarNode('highLowerBound')->defaultValue(90)->end()
174 8
                                ->booleanNode('showOnlySummary')->defaultValue(false)->end()
175 8
                                ->booleanNode('showUncoveredFiles')->defaultValue(false)->end()
176 8
                            ->end()
177 8
                        ->end()
178 8
                        ->arrayNode('xml')
179 8
                            ->children()
180 8
                                ->scalarNode('target')->isRequired()->cannotBeEmpty()->end()
181 8
                            ->end()
182 8
                        ->end()
183 8
                    ->end()
184 8
                ->end()
185 8
            ->end()
186 8
        ->end();
187 2
    }
188
189
    /**
190
     * {@inheritdoc}
191
     */
192 8
    public function getConfigKey()
193
    {
194 8
        return 'code_coverage';
195
    }
196
197
    /**
198
     * {@inheritdoc}
199
     */
200 16
    public function process(ContainerBuilder $container): void
201
    {
202
        /** @var InputInterface $input */
203 16
        $input = $container->get(CliExtension::INPUT_ID);
204
205
        /** @var OutputInterface $output */
206 16
        $output = $container->get(CliExtension::OUTPUT_ID);
207
208 16
        $filterConfig = $container->getParameter('behat.code_coverage.config.filter');
209 16
        $branchPathConfig = $container->getParameter('behat.code_coverage.config.branchAndPathCoverage');
210 16
        $cacheDir = $container->getParameter('behat.code_coverage.config.cache');
211
212 16
        $canCollectCodeCoverage = true;
213
        try {
214 16
            $this->initCodeCoverage(new Filter(), $filterConfig, null, $cacheDir, $output);
215
216 12
            $codeCoverageDefinition = $container->getDefinition(CodeCoverage::class);
217 12
            $filterDefinition = $container->getDefinition(Filter::class);
218 12
            $codeCoverageDefinition->setFactory([new Reference(self::class), 'initCodeCoverage']);
219 12
            $codeCoverageDefinition->setArguments([$filterDefinition, $filterConfig, $branchPathConfig, $cacheDir, $output]);
220 4
        } catch (NoCodeCoverageDriverAvailableException|Xdebug2NotEnabledException|Xdebug3NotEnabledException|XdebugNotEnabledException|XdebugNotAvailableException $e) {
221 4
            $output->writeln("<comment>No code coverage driver is available. {$e->getMessage()}</comment>");
222 4
            $canCollectCodeCoverage = false;
223
        }
224
225 16
        if (!$canCollectCodeCoverage || $input->hasParameterOption('--no-coverage')) {
226 8
            $container->getDefinition(EventSubscriber::class)->setArgument('$coverage', null);
227
        }
228 4
    }
229
230 12
    public function initCodeCoverage(Filter $filter, array $filterConfig, ?bool $branchPathConfig, string $cacheDir, OutputInterface $output): CodeCoverage
231
    {
232
        // set up filter
233 12
        array_walk($filterConfig['include']['directories'], static function (array $dir, string $path, Filter $filter): void {
234 12
            $filter->includeDirectory($path, $dir['suffix'], $dir['prefix']);
235 3
        }, $filter);
236
237 12
        array_walk($filterConfig['include']['files'], static function (string $file, string $key, Filter $filter): void {
238 12
            $filter->includeFile($file);
239 3
        }, $filter);
240
241 12
        array_walk($filterConfig['exclude']['directories'], static function (array $dir, string $path, Filter $filter): void {
242 12
            $filter->excludeDirectory($path, $dir['suffix'], $dir['prefix']);
243 3
        }, $filter);
244
245 12
        array_walk($filterConfig['exclude']['files'], static function (string $file, string $key, Filter $filter): void {
246 12
            $filter->excludeFile($file);
247 3
        }, $filter);
248
249
        // see if we can get a driver
250 12
        $selector = new Selector();
251 12
        $driver = $selector->forLineCoverage($filter);
252 12
        if ($branchPathConfig !== false) {
253
            try {
254 12
                $driver = $selector->forLineAndPathCoverage($filter);
255 6
            } catch (NoCodeCoverageDriverWithPathCoverageSupportAvailableException $e) {
256
                // fallback driver is already set
257 6
                if ($branchPathConfig === true) { // only warn if explicitly enabled
0 ignored issues
show
introduced by
The condition $branchPathConfig === true is always true.
Loading history...
258 2
                    $output->writeln(sprintf('<info>%s does not support collecting branch and path data</info>', $driver->nameAndVersion()));
259
                }
260
            }
261
        }
262
263
        // and init coverage
264 12
        $codeCoverage = new CodeCoverage($driver, $filter);
265 12
        $codeCoverage->cacheStaticAnalysis($cacheDir);
266
267 12
        if ($filterConfig['includeUncoveredFiles']) {
268 4
            $codeCoverage->includeUncoveredFiles();
269
        } else {
270 8
            $codeCoverage->excludeUncoveredFiles();
271
        }
272
273 12
        if (InstalledVersions::satisfies(new VersionParser(), 'phpunit/php-code-coverage', '^9.0')) {
274 12
            if ($filterConfig['processUncoveredFiles']) {
275 4
                $codeCoverage->processUncoveredFiles();
276
            } else {
277 8
                $codeCoverage->doNotProcessUncoveredFiles();
278
            }
279
        }
280
281 12
        return $codeCoverage;
282
    }
283
}
284