Runner::run()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 2

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 12
c 1
b 1
f 0
nc 2
nop 0
dl 0
loc 20
ccs 16
cts 16
cp 1
crap 2
rs 9.8666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpNsFixer\Runner;
6
7
use PhpNsFixer\Event\FileProcessedEvent;
8
use PhpNsFixer\Fixer\Evaluator;
9
use PhpNsFixer\Fixer\Fixer;
10
use PhpNsFixer\Fixer\Result;
11
use Symfony\Component\EventDispatcher\EventDispatcher;
12
use Symfony\Component\Finder\SplFileInfo;
13
use Tightenco\Collect\Support\Collection;
14
15
final class Runner
16
{
17
    /**
18
     * @var EventDispatcher|null
19
     */
20
    protected $dispatcher;
21
22
    /**
23
     * @var Evaluator
24
     */
25
    protected $evaluator;
26
27
    /**
28
     * @var Fixer
29
     */
30
    protected $fixer;
31
32
    /**
33
     * @var RunnerOptions
34
     */
35
    protected $options;
36
37
    /**
38
     * @param RunnerOptions $options
39
     * @param EventDispatcher $dispatcher
40
     */
41 9
    public function __construct(RunnerOptions $options, EventDispatcher $dispatcher = null)
42
    {
43 9
        $this->options = $options;
44 9
        $this->dispatcher = $dispatcher;
45 9
        $this->evaluator = new Evaluator();
46 9
        $this->fixer = new Fixer();
47 9
    }
48
49
    /**
50
     * @return Collection
51
     */
52 9
    public function run(): Collection
53
    {
54 9
        $files = $this->options
55 9
            ->getFiles()
56 9
            ->map(function (SplFileInfo $file) {
57 9
                $this->fireFileProcessedEvent($file);
58 9
                return $this->evaluator->check($file, $this->options->getPrefix(), $this->options->isSkipEmpty());
59 9
            })
60 9
            ->reject(function (Result $result) {
61 9
                return $result->isValid();
62 9
            })
63 9
            ->values();
64
65 9
        if (!$this->options->isDryRun()) {
66 5
            $files->each(function ($file) {
67 2
                $this->fixer->fix($file);
68 5
            });
69
        }
70
71 9
        return $files;
72
    }
73
74
    /**
75
     * Dispatch event, if dispatcher is available.
76
     *
77
     * @param SplFileInfo $file
78
     * @return void
79
     */
80 9
    private function fireFileProcessedEvent(SplFileInfo $file): void
81
    {
82 9
        if ($this->dispatcher === null) {
83 3
            return;
84
        }
85
86 6
        $this->dispatcher->dispatch(new FileProcessedEvent($file), FileProcessedEvent::class);
87 6
    }
88
}
89