Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/Business/Cognitive/CognitiveMetrics.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,20 @@ private function setRequiredMetricProperties(array $metrics): void
{
$missingKeys = array_diff_key($this->metrics, $metrics);
if (!empty($missingKeys)) {
throw new InvalidArgumentException('Missing required keys: ' . implode(', ', $missingKeys));
$class = $metrics['class'] ?? 'Unknown';
$method = $metrics['method'] ?? 'Unknown';
$file = $metrics['file'] ?? 'Unknown';

$errorMessage = sprintf(
'Missing required keys for %s::%s in file %s: %s. Available keys: %s',
$class,
$method,
$file,
implode(', ', $missingKeys),
implode(', ', array_keys($metrics))
);

throw new InvalidArgumentException($errorMessage);
}

// Not pretty to set each but more efficient than using a loop and $this->metrics
Expand Down
2 changes: 2 additions & 0 deletions src/Business/Cognitive/CognitiveMetricsCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,10 @@ private function processMethodMetrics(
continue;
}


[$class, $method] = explode('::', $classAndMethod);


$metricsArray = array_merge($metrics, [
'class' => $class,
'method' => $method,
Expand Down
10 changes: 8 additions & 2 deletions src/Business/Cognitive/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,10 @@ private function getHalsteadMetricsVisitor(array $methodMetrics): array
if (str_ends_with($method, '::')) {
continue;
}
$methodMetrics[$method]['halstead'] = $metrics;
// Only add Halstead metrics to methods that were processed by CognitiveMetricsVisitor
if (isset($methodMetrics[$method])) {
$methodMetrics[$method]['halstead'] = $metrics;
}
}

return $methodMetrics;
Expand All @@ -150,7 +153,10 @@ private function getCyclomaticComplexityVisitor(array $methodMetrics): array
if (str_ends_with($method, '::')) {
continue;
}
$methodMetrics[$method]['cyclomatic_complexity'] = $complexity;
// Only add cyclomatic complexity to methods that were processed by CognitiveMetricsVisitor
if (isset($methodMetrics[$method])) {
$methodMetrics[$method]['cyclomatic_complexity'] = $complexity;
}
}

return $methodMetrics;
Expand Down
15 changes: 13 additions & 2 deletions src/PhpParser/CognitiveMetricsVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace Phauthentic\CognitiveCodeAnalysis\PhpParser;

use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor;
use PhpParser\NodeVisitorAbstract;

/**
Expand Down Expand Up @@ -217,6 +219,7 @@ private function setCurrentClassOnEnterNode(Node $node): bool
}

if ($node->name === null) {
// Skip anonymous classes - they don't have a proper class name
return false;
}

Expand All @@ -240,18 +243,21 @@ private function normalizeFqcn(string $fqcn): string
return str_starts_with($fqcn, '\\') ? $fqcn : '\\' . $fqcn;
}

public function enterNode(Node $node): void
public function enterNode(Node $node): int|Node|null
{
$this->setCurrentNamespaceOnEnterNode($node);
if (!$this->setCurrentClassOnEnterNode($node)) {
return;
// Skip the entire subtree for anonymous classes or ignored classes
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
}

$this->classMethodOnEnterNode($node);

if ($this->currentMethod) {
$this->gatherMetrics($node);
}

return null;
}

private function gatherMetrics(Node $node): void
Expand Down Expand Up @@ -389,6 +395,11 @@ private function checkNameSpaceOnLeaveNode(Node $node): void
private function checkClassOnLeaveNode(Node $node): void
{
if ($this->isClassOrTraitNode($node)) {
if (!empty($this->currentMethod)) {
// Don't clear the class context if we're still processing a method
return;
}

$this->currentClassName = '';
}
}
Expand Down
14 changes: 12 additions & 2 deletions src/PhpParser/HalsteadMetricsVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,11 @@ public function enterNode(Node $node)
$this->setCurrentClassName($node);

// Check if this class should be ignored
if ($this->annotationVisitor !== null && $this->annotationVisitor->isClassIgnored($this->currentClassName)) {
if (
$this->currentClassName !== null
&& $this->annotationVisitor !== null
&& $this->annotationVisitor->isClassIgnored($this->currentClassName)
) {
$this->currentClassName = null; // Clear the class name if ignored
}
},
Expand Down Expand Up @@ -113,7 +117,13 @@ private function setCurrentNamespace(Namespace_ $node): void

private function setCurrentClassName(Node $node): void
{
$className = $node->name ? $node->name->toString() : '';
// Skip anonymous classes - they don't have a proper class name
if ($node->name === null) {
$this->currentClassName = null;
return;
}

$className = $node->name->toString();
// Always build FQCN as "namespace\class" (even if namespace is empty)
$fqcn = ($this->currentNamespace !== '' ? $this->currentNamespace . '\\' : '') . $className;
$this->currentClassName = $this->normalizeFqcn($fqcn);
Expand Down
181 changes: 181 additions & 0 deletions tests/Unit/Business/Cognitive/CognitiveMetricsCollectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,185 @@ public function testCollectedMetrics(): void
$this->assertSame(3, $metrics->getVariableCount());
$this->assertSame(2, $metrics->getPropertyCallCount());
}

/**
* Test that the collector handles files with anonymous classes without errors.
* This test ensures that the full pipeline (Parser -> Collector -> CognitiveMetrics)
* works correctly with anonymous classes and doesn't cause "Missing required keys" errors.
*/
#[Test]
public function testCollectWithAnonymousClasses(): void
{
// Create a temporary test file with anonymous classes
$testFile = sys_get_temp_dir() . '/test_anonymous_classes.php';
$testCode = <<<'CODE'
<?php

namespace TestNamespace;

class TestClass {
public function methodWithAnonymousClass() {
$subscriber = new class(123) extends BaseClass {
public function __construct(private int $value) {
$this->value = $value;
}

public function process() {
if ($this->value > 0) {
return $this->value;
}
return 0;
}
};

$anotherSubscriber = new class(456) extends AnotherBaseClass {
public function __construct(private int $value) {
$this->value = $value;
}

public function handle() {
return $this->value * 2;
}
};

return $subscriber->process();
}

public function normalMethod() {
$var = 1;
return $var;
}
}
CODE;

file_put_contents($testFile, $testCode);

try {
// This should not throw any exceptions
$metricsCollection = $this->metricsCollector->collect($testFile, $this->configService->getConfig());

$this->assertInstanceOf(CognitiveMetricsCollection::class, $metricsCollection);
$this->assertCount(2, $metricsCollection);

// Verify that we can get the metrics for both methods
$methodWithAnonymous = $metricsCollection->getClassWithMethod('\\TestNamespace\\TestClass', 'methodWithAnonymousClass');
$normalMethod = $metricsCollection->getClassWithMethod('\\TestNamespace\\TestClass', 'normalMethod');

$this->assertNotNull($methodWithAnonymous);
$this->assertNotNull($normalMethod);

// Verify that the metrics have all required properties
$this->assertGreaterThan(0, $methodWithAnonymous->getLineCount());
$this->assertEquals(0, $methodWithAnonymous->getArgCount());
$this->assertGreaterThan(0, $methodWithAnonymous->getReturnCount());

$this->assertGreaterThan(0, $normalMethod->getLineCount());
$this->assertEquals(0, $normalMethod->getArgCount());
$this->assertEquals(1, $normalMethod->getReturnCount());
$this->assertEquals(1, $normalMethod->getVariableCount());
} finally {
// Clean up the temporary file
if (file_exists($testFile)) {
unlink($testFile);
}
}
}

/**
* Test that the collector handles complex anonymous class scenarios.
* This test ensures that the fix works in various anonymous class scenarios.
*/
#[Test]
public function testCollectWithComplexAnonymousClassScenarios(): void
{
// Create a temporary test file with complex anonymous class scenarios
$testFile = sys_get_temp_dir() . '/test_complex_anonymous_classes.php';
$testCode = <<<'CODE'
<?php

namespace TestNamespace;

class MainClass {
public function createAnonymousObjects() {
// Anonymous class with constructor
$obj1 = new class(42) {
public function __construct(private int $value) {
$this->value = $value;
}

public function getValue() {
return $this->value;
}
};

// Anonymous class extending another class
$obj2 = new class extends BaseClass {
public function __construct() {
parent::__construct();
}

public function process() {
if (true) {
return 'processed';
}
return 'not processed';
}
};

// Anonymous class implementing interface
$obj3 = new class implements SomeInterface {
public function __construct() {
$this->initialize();
}

public function initialize() {
$var = 1;
return $var;
}

public function execute() {
return 'executed';
}
};

return $obj1->getValue();
}

public function simpleMethod() {
return 'simple';
}
}
CODE;

file_put_contents($testFile, $testCode);

try {
// This should not throw any exceptions
$metricsCollection = $this->metricsCollector->collect($testFile, $this->configService->getConfig());

$this->assertInstanceOf(CognitiveMetricsCollection::class, $metricsCollection);
$this->assertCount(2, $metricsCollection);

// Verify that we can get the metrics for both methods
$createAnonymousObjects = $metricsCollection->getClassWithMethod('\\TestNamespace\\MainClass', 'createAnonymousObjects');
$simpleMethod = $metricsCollection->getClassWithMethod('\\TestNamespace\\MainClass', 'simpleMethod');

$this->assertNotNull($createAnonymousObjects);
$this->assertNotNull($simpleMethod);

// Verify that the metrics have all required properties
$this->assertGreaterThan(0, $createAnonymousObjects->getLineCount());
$this->assertEquals(0, $createAnonymousObjects->getArgCount());
$this->assertGreaterThan(0, $createAnonymousObjects->getReturnCount());

$this->assertGreaterThan(0, $simpleMethod->getLineCount());
$this->assertEquals(0, $simpleMethod->getArgCount());
$this->assertEquals(1, $simpleMethod->getReturnCount());
} finally {
// Clean up the temporary file
if (file_exists($testFile)) {
unlink($testFile);
}
}
}
}
Loading