Passed
Pull Request — master (#28)
by Michel
17:22
created

Extension::process()   B

Complexity

Conditions 6
Paths 44

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6.0045

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 6
eloc 20
c 4
b 0
f 0
nc 44
nop 1
dl 0
loc 33
ccs 19
cts 20
cp 0.95
crap 6.0045
rs 8.9777
1
<?php
2
/**
3
 * Behat Code Coverage
4
 */
5
declare(strict_types=1);
6
7
namespace DVDoug\Behat\CodeCoverage;
8
9
use Behat\Testwork\Cli\Controller;
10
use Behat\Testwork\Cli\ServiceContainer\CliExtension;
11
use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension;
12
use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface;
13
use Behat\Testwork\ServiceContainer\ExtensionManager;
14
use DVDoug\Behat\CodeCoverage\Subscriber\EventSubscriber;
15
use SebastianBergmann\CodeCoverage\CodeCoverage;
16
use SebastianBergmann\CodeCoverage\Driver\Selector;
17
use SebastianBergmann\CodeCoverage\Driver\XdebugNotAvailableException;
18
use SebastianBergmann\CodeCoverage\Driver\XdebugNotEnabledException;
19
use SebastianBergmann\CodeCoverage\Filter;
20
use SebastianBergmann\CodeCoverage\NoCodeCoverageDriverAvailableException;
21
use SebastianBergmann\CodeCoverage\NoCodeCoverageDriverWithPathCoverageSupportAvailableException;
22
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;
23
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
24
use Symfony\Component\Config\FileLocator;
25
use Symfony\Component\Console\Input\InputInterface;
26
use Symfony\Component\Console\Output\ConsoleOutputInterface;
27
use Symfony\Component\Console\Output\OutputInterface;
28
use Symfony\Component\DependencyInjection\ContainerBuilder;
29
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
30
use Symfony\Component\DependencyInjection\Reference;
31
32
use function sprintf;
33
use function sys_get_temp_dir;
34
use function realpath;
35
36
class Extension implements ExtensionInterface
37
{
38 36
    public function initialize(ExtensionManager $extensionManager): void
39
    {
40 36
    }
41
42 36
    public function load(ContainerBuilder $container, array $config): void
43
    {
44 36
        $container->registerForAutoconfiguration(Controller::class)->addTag(CliExtension::CONTROLLER_TAG);
45 36
        $container->registerForAutoconfiguration(EventSubscriber::class)->addTag(EventDispatcherExtension::SUBSCRIBER_TAG);
46
47 36
        $loader = new PhpFileLoader($container, new FileLocator(__DIR__ . '/../config'));
48 36
        $loader->load('services.php');
49
50 36
        $container->setParameter('behat.code_coverage.config.filter', $config['filter']);
51 36
        $container->setParameter('behat.code_coverage.config.branchAndPathCoverage', $config['branchAndPathCoverage']);
52 36
        $container->setParameter('behat.code_coverage.config.reports', $config['reports'] ?? []);
53 36
        $container->setParameter('behat.code_coverage.config.cache', $config['cache']);
54
    }
55
56 72
    public function configure(ArrayNodeDefinition $builder): void
57
    {
58 72
        $builder
59 72
            ->children()
60 72
                ->scalarNode('cache')
61 72
                    ->defaultValue(sys_get_temp_dir() . '/behat-code-coverage-cache')
62 72
                ->end()
63 72
                ->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

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