Passed
Push — main ( 4736ca...948518 )
by mikhail
03:04
created

UncaughtExceptionVisitor::enterNode()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6.0702

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 7
c 1
b 0
f 0
nc 12
nop 1
dl 0
loc 13
ccs 7
cts 8
cp 0.875
crap 6.0702
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SavinMikhail\CommentsDensity\MissingDocblock;
6
7
use PhpParser\Node;
8
use PhpParser\Node\Expr\Throw_;
9
use PhpParser\Node\Stmt\Catch_;
10
use PhpParser\Node\Stmt\TryCatch;
11
use PhpParser\NodeVisitorAbstract;
12
13
final class UncaughtExceptionVisitor extends NodeVisitorAbstract
14
{
15
    public bool $throwsUncaughtExceptions = false;
16
    private array $tryCatchStack = [];
17
    private array $catchStack = [];
18
19 2
    public function enterNode(Node $node): void
20
    {
21 2
        if ($node instanceof TryCatch) {
22 1
            $this->tryCatchStack[] = $node;
23
        }
24
25 2
        if ($node instanceof Catch_) {
26 1
            $this->catchStack[] = $node;
27
        }
28
29 2
        if ($node instanceof Throw_) {
30 1
            if (!$this->isInCatchBlock($node) && !$this->isInTryBlock($node)) {
31
                $this->throwsUncaughtExceptions = true;
32
            }
33
        }
34
    }
35
36 2
    public function leaveNode(Node $node): void
37
    {
38 2
        if ($node instanceof TryCatch) {
39 1
            array_pop($this->tryCatchStack);
40
        }
41
42 2
        if ($node instanceof Catch_) {
43 1
            array_pop($this->catchStack);
44
        }
45
    }
46
47 1
    private function isInCatchBlock(Node $node): bool
48
    {
49 1
        foreach ($this->catchStack as $catch) {
50
            if ($this->nodeIsWithin($node, $catch)) {
51
                return true;
52
            }
53
        }
54 1
        return false;
55
    }
56
57 1
    private function isInTryBlock(Node $node): bool
58
    {
59 1
        foreach ($this->tryCatchStack as $tryCatch) {
60 1
            foreach ($tryCatch->stmts as $stmt) {
61 1
                if ($this->nodeIsWithin($node, $stmt)) {
62 1
                    return true;
63
                }
64
            }
65
        }
66
        return false;
67
    }
68
69 1
    private function nodeIsWithin(Node $node, Node $container): bool
70
    {
71 1
        return $node->getStartFilePos() >= $container->getStartFilePos() &&
72 1
            $node->getEndFilePos() <= $container->getEndFilePos();
73
    }
74
}
75