From 3ba3a3ccbd99d4c1f96305292604d48e38e9ae66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabian=20Ba=CC=86doi?= Date: Thu, 5 Apr 2018 15:44:18 +0300 Subject: [PATCH 1/2] Add else and elseif statements to the cyclomatic complexity test --- .../Complexity/CyclomaticComplexityVisitorTest.php | 4 ++-- tests/Metric/examples/cyclomatic1.php | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/Metric/Class_/Complexity/CyclomaticComplexityVisitorTest.php b/tests/Metric/Class_/Complexity/CyclomaticComplexityVisitorTest.php index 74c2204f..9c130b08 100644 --- a/tests/Metric/Class_/Complexity/CyclomaticComplexityVisitorTest.php +++ b/tests/Metric/Class_/Complexity/CyclomaticComplexityVisitorTest.php @@ -53,7 +53,7 @@ public function testCyclomaticComplexityOfMethodsIsWellCalculated($example, $cla public function provideExamplesForClasses() { return [ - [ __DIR__.'/../../examples/cyclomatic1.php', 'A', 4], + [ __DIR__.'/../../examples/cyclomatic1.php', 'A', 8], [ __DIR__.'/../../examples/cyclomatic1.php', 'B', 5], [ __DIR__.'/../../examples/cyclomatic_anon.php', 'Foo\C', 1], ]; @@ -62,7 +62,7 @@ public function provideExamplesForClasses() public function provideExamplesForMethods() { return [ - [ __DIR__.'/../../examples/cyclomatic1.php', 'A', 3], + [ __DIR__.'/../../examples/cyclomatic1.php', 'A', 6], [ __DIR__.'/../../examples/cyclomatic1.php', 'B', 5], ]; } diff --git a/tests/Metric/examples/cyclomatic1.php b/tests/Metric/examples/cyclomatic1.php index b7ed03bf..50a003f5 100644 --- a/tests/Metric/examples/cyclomatic1.php +++ b/tests/Metric/examples/cyclomatic1.php @@ -13,6 +13,16 @@ public function foo2() { if(true) { + } else { + if (true) { + + } else if (true) { + + } elseif (true) { + + } elseif (true) { + + } } } From 6303cb806e91e31126818adef3dc42a99ecf07c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabian=20Ba=CC=86doi?= Date: Thu, 5 Apr 2018 15:45:41 +0300 Subject: [PATCH 2/2] Fix bug that caused cyclomatic complexity to be underreported --- .../Class_/Complexity/CyclomaticComplexityVisitor.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Hal/Metric/Class_/Complexity/CyclomaticComplexityVisitor.php b/src/Hal/Metric/Class_/Complexity/CyclomaticComplexityVisitor.php index 1fc67cf5..862d7186 100644 --- a/src/Hal/Metric/Class_/Complexity/CyclomaticComplexityVisitor.php +++ b/src/Hal/Metric/Class_/Complexity/CyclomaticComplexityVisitor.php @@ -60,9 +60,12 @@ public function leaveNode(Node $node) // iterate over children, recursively $cb = function ($node) use (&$cb) { $ccn = 0; - if (isset($node->stmts) && $node->stmts) { - foreach ($node->stmts as $child) { - $ccn += $cb($child); + + foreach (get_object_vars($node) as $name => $member) { + foreach (is_array($member) ? $member : [$member] as $member_item) { + if ($member_item instanceof Node) { + $ccn += $cb($member_item); + } } }