Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of sebastian/complexity.
4
 *
5
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace SebastianBergmann\Complexity;
11
 
12
use PhpParser\Error;
13
use PhpParser\Lexer;
14
use PhpParser\Node;
15
use PhpParser\NodeTraverser;
16
use PhpParser\NodeVisitor\NameResolver;
17
use PhpParser\NodeVisitor\ParentConnectingVisitor;
18
use PhpParser\Parser;
19
use PhpParser\ParserFactory;
20
 
21
final class Calculator
22
{
23
    /**
24
     * @throws RuntimeException
25
     */
26
    public function calculateForSourceFile(string $sourceFile): ComplexityCollection
27
    {
28
        return $this->calculateForSourceString(file_get_contents($sourceFile));
29
    }
30
 
31
    /**
32
     * @throws RuntimeException
33
     */
34
    public function calculateForSourceString(string $source): ComplexityCollection
35
    {
36
        try {
37
            $nodes = $this->parser()->parse($source);
38
 
39
            assert($nodes !== null);
40
 
41
            return $this->calculateForAbstractSyntaxTree($nodes);
42
 
43
            // @codeCoverageIgnoreStart
44
        } catch (Error $error) {
45
            throw new RuntimeException(
46
                $error->getMessage(),
47
                (int) $error->getCode(),
48
                $error
49
            );
50
        }
51
        // @codeCoverageIgnoreEnd
52
    }
53
 
54
    /**
55
     * @param Node[] $nodes
56
     *
57
     * @throws RuntimeException
58
     */
59
    public function calculateForAbstractSyntaxTree(array $nodes): ComplexityCollection
60
    {
61
        $traverser                    = new NodeTraverser;
62
        $complexityCalculatingVisitor = new ComplexityCalculatingVisitor(true);
63
 
64
        $traverser->addVisitor(new NameResolver);
65
        $traverser->addVisitor(new ParentConnectingVisitor);
66
        $traverser->addVisitor($complexityCalculatingVisitor);
67
 
68
        try {
69
            /* @noinspection UnusedFunctionResultInspection */
70
            $traverser->traverse($nodes);
71
            // @codeCoverageIgnoreStart
72
        } catch (Error $error) {
73
            throw new RuntimeException(
74
                $error->getMessage(),
75
                (int) $error->getCode(),
76
                $error
77
            );
78
        }
79
        // @codeCoverageIgnoreEnd
80
 
81
        return $complexityCalculatingVisitor->result();
82
    }
83
 
84
    private function parser(): Parser
85
    {
86
        return (new ParserFactory)->create(ParserFactory::PREFER_PHP7, new Lexer);
87
    }
88
}