Skip to content

Commit

Permalink
Refactoring the config
Browse files Browse the repository at this point in the history
  • Loading branch information
floriankraemer committed Oct 1, 2024
1 parent 33542c9 commit a808f43
Show file tree
Hide file tree
Showing 16 changed files with 210 additions and 113 deletions.
8 changes: 8 additions & 0 deletions config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,32 @@ cognitive:
lineCount:
threshold: 60
scale: 25.0
enabled: true
argCount:
threshold: 4
scale: 1.0
enabled: true
returnCount:
threshold: 2
scale: 5.0
enabled: true
variableCount:
threshold: 2
scale: 5.0
enabled: true
propertyCallCount:
threshold: 2
scale: 15.0
enabled: true
ifCount:
threshold: 3
scale: 1.0
enabled: true
ifNestingLevel:
threshold: 1
scale: 1.0
enabled: true
elseCount:
threshold: 1
scale: 1.0
enabled: true
3 changes: 3 additions & 0 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ private function registerServices(): void
->setPublic(true);

$this->containerBuilder->register(CognitiveMetricTextRenderer::class, CognitiveMetricTextRenderer::class)
->setArguments([
new Reference(OutputInterface::class)
])
->setPublic(true);

$this->containerBuilder->register(BaselineService::class, BaselineService::class)
Expand Down
41 changes: 19 additions & 22 deletions src/Business/Cognitive/CognitiveMetricsCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Phauthentic\CognitiveCodeAnalysis\Business\DirectoryScanner;
use Phauthentic\CognitiveCodeAnalysis\CognitiveAnalysisException;
use Phauthentic\CognitiveCodeAnalysis\Config\CognitiveConfig;
use Phauthentic\CognitiveCodeAnalysis\Config\ConfigService;
use Phauthentic\CognitiveCodeAnalysis\PhpParser\CognitiveMetricsVisitor;
use PhpParser\Error;
Expand Down Expand Up @@ -34,38 +35,38 @@ public function __construct(
$this->parser = $parserFactory->createForHostVersion();
}

/**
* @param array<string, mixed> $config
* @return array<int, string>
*/
private function getExcludePatternsFromConfig(array $config): array
{
if (isset($config['excludePatterns'])) {
return $config['excludePatterns'];
}

return [];
}

/**
* Collect cognitive metrics from the given path
*
* @param string $path
* @param array<string, mixed> $config
* @param CognitiveConfig $config
* @return CognitiveMetricsCollection
* @throws CognitiveAnalysisException
*/
public function collect(string $path, array $config = []): CognitiveMetricsCollection
public function collect(string $path, CognitiveConfig $config): CognitiveMetricsCollection
{
$files = $this->findSourceFiles($path, $this->getExcludePatternsFromConfig($config));
$files = $this->findSourceFiles($path, $config->excludeFilePatterns);

return $this->findMetrics($files);
}

private function getCodeFromFile(SplFileInfo $file): string
{
$code = file_get_contents($file->getRealPath());

if ($code === false) {
throw new CognitiveAnalysisException("Could not read file: {$file->getRealPath()}");
}

return $code;
}

/**
* Collect metrics from the found source files
*
* @param iterable<SplFileInfo> $files
* @return CognitiveMetricsCollection
* @throws CognitiveAnalysisException
*/
private function findMetrics(iterable $files): CognitiveMetricsCollection
{
Expand All @@ -81,11 +82,7 @@ private function findMetrics(iterable $files): CognitiveMetricsCollection
$plugin->beforeFindMetrics($file);
}

$code = file_get_contents($file->getRealPath());

if ($code === false) {
throw new CognitiveAnalysisException("Could not read file: {$file->getRealPath()}");
}
$code = $this->getCodeFromFile($file);

$this->traverser->addVisitor($visitor);
$this->traverseAbstractSyntaxTree($code);
Expand Down Expand Up @@ -139,7 +136,7 @@ private function processMethodMetrics(

private function isExcluded(string $classAndMethod): bool
{
$regexes = $this->configService->getConfig()['cognitive']['excludePatterns'];
$regexes = $this->configService->getConfig()->excludePatterns;

foreach ($regexes as $regex) {
if (preg_match('/' . $regex . '/', $classAndMethod, $matches)) {
Expand Down
20 changes: 11 additions & 9 deletions src/Business/Cognitive/ScoreCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Phauthentic\CognitiveCodeAnalysis\Business\Cognitive;

use Phauthentic\CognitiveCodeAnalysis\Config\CognitiveConfig;

/**
*
*/
Expand All @@ -25,13 +27,11 @@ class ScoreCalculator

/**
* @param CognitiveMetrics $metrics
* @param array<string, mixed> $metricConfiguration
* @param CognitiveConfig $config
* @return void
*/
public function calculate(CognitiveMetrics $metrics, array $metricConfiguration = []): void
public function calculate(CognitiveMetrics $metrics, CognitiveConfig $config): void
{
$metricConfiguration = $metricConfiguration['metrics'];

// List of metric types to process
$metricTypes = [
'LineCount' => 'lineCount',
Expand All @@ -45,7 +45,7 @@ public function calculate(CognitiveMetrics $metrics, array $metricConfiguration
];

// Calculate and set weights for each metric type
$this->calculateMetricWeights($metricTypes, $metrics, $metricConfiguration);
$this->calculateMetricWeights($metricTypes, $metrics, $config);

// Calculate the overall score
$this->calculateScore($metrics);
Expand All @@ -65,20 +65,22 @@ private function calculateScore(CognitiveMetrics $metrics): void
/**
* @param array<string, string> $metricTypes
* @param CognitiveMetrics $metrics
* @param array<string, mixed> $config
* @param CognitiveConfig $config
* @return void
*/
private function calculateMetricWeights(array $metricTypes, CognitiveMetrics $metrics, array $config): void
private function calculateMetricWeights(array $metricTypes, CognitiveMetrics $metrics, CognitiveConfig $config): void
{
$metricConfigs = $config->metrics;

foreach ($metricTypes as $methodSuffix => $configKey) {
$getMethod = 'get' . $methodSuffix;
$setMethod = 'set' . $methodSuffix . 'Weight';

$metrics->{$setMethod}(
$this->calculateLogWeight(
$metrics->{$getMethod}(),
$config[$configKey]['threshold'],
$config[$configKey]['scale']
$metricConfigs[$configKey]->threshold,
$metricConfigs[$configKey]->scale,
)
);
}
Expand Down
10 changes: 8 additions & 2 deletions src/Business/MetricsFacade.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Phauthentic\CognitiveCodeAnalysis\Business\Cognitive\Exporter\HtmlExporter;
use Phauthentic\CognitiveCodeAnalysis\Business\Cognitive\Exporter\JsonExporter;
use Phauthentic\CognitiveCodeAnalysis\Business\Cognitive\ScoreCalculator;
use Phauthentic\CognitiveCodeAnalysis\Config\CognitiveConfig;
use Phauthentic\CognitiveCodeAnalysis\Config\ConfigService;

/**
Expand All @@ -36,10 +37,10 @@ public function __construct(
*/
public function getCognitiveMetrics(string $path): CognitiveMetricsCollection
{
$metricsCollection = $this->cognitiveMetricsCollector->collect($path, $this->configService->getConfig()['cognitive']);
$metricsCollection = $this->cognitiveMetricsCollector->collect($path, $this->configService->getConfig());

foreach ($metricsCollection as $metric) {
$this->scoreCalculator->calculate($metric, $this->configService->getConfig()['cognitive']);
$this->scoreCalculator->calculate($metric, $this->configService->getConfig());
}

return $metricsCollection;
Expand All @@ -56,6 +57,11 @@ public function loadConfig(string $configFilePath): void
$this->configService->loadConfig($configFilePath);
}

public function getConfig(): CognitiveConfig
{
return $this->configService->getConfig();
}

public function metricsCollectionToCsv(CognitiveMetricsCollection $metricsCollection, string $filename): void
{
(new CsvExporter())->export($metricsCollection, $filename);
Expand Down
2 changes: 1 addition & 1 deletion src/Command/CognitiveMetricsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}

// Render the metrics to the console.
$this->metricTextRenderer->render($metricsCollection, $output);
$this->metricTextRenderer->render($metricsCollection, $this->metricsFacade->getConfig());

return Command::SUCCESS;
}
Expand Down
45 changes: 34 additions & 11 deletions src/Command/Presentation/CognitiveMetricTextRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Phauthentic\CognitiveCodeAnalysis\Business\Cognitive\CognitiveMetrics;
use Phauthentic\CognitiveCodeAnalysis\Business\Cognitive\CognitiveMetricsCollection;
use Phauthentic\CognitiveCodeAnalysis\Config\CognitiveConfig;
use RuntimeException;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Output\OutputInterface;
Expand All @@ -15,33 +16,55 @@
*/
class CognitiveMetricTextRenderer
{
public function __construct(
private readonly OutputInterface $output
) {
}

/**
* @param CognitiveMetricsCollection $metricsCollection
* @param OutputInterface $output
*/
public function render(CognitiveMetricsCollection $metricsCollection, OutputInterface $output): void
public function render(CognitiveMetricsCollection $metricsCollection, CognitiveConfig $config): void
{
$groupedByClass = $metricsCollection->groupBy('class');

foreach ($groupedByClass as $className => $metrics) {
$output->writeln("<info>Class: $className</info>");

$table = new Table($output);
$table->setStyle('box');
$table->setHeaders($this->getTableHeaders());

$rows = [];
foreach ($metrics as $metric) {
if (
$config->showOnlyMethodsExceedingThreshold &&
$metric->getScore() <= $config->scoreThreshold
) {
continue;
}

$row = $this->prepareTableRow($metric);
$rows[] = $row;
}

$table->setRows($rows);
$table->render();
$output->writeln("");
if (empty($rows)) {
continue;
}

$this->renderTable((string)$className, $rows);
}
}

/**
* @param string $className
* @param array<int, mixed> $rows
*/
private function renderTable(string $className, array $rows): void
{
$table = new Table($this->output);
$table->setStyle('box');
$table->setHeaders($this->getTableHeaders());
$this->output->writeln("<info>Class: $className</info>");
$table->setRows($rows);
$table->render();
$this->output->writeln("");
}

/**
* @return string[]
*/
Expand Down
6 changes: 5 additions & 1 deletion src/Config/CognitiveConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Phauthentic\CognitiveCodeAnalysis\Config;

use InvalidArgumentException;

/**
*
*/
Expand All @@ -17,7 +19,9 @@ class CognitiveConfig
public function __construct(
public readonly array $excludeFilePatterns,
public readonly array $excludePatterns,
public readonly array $metrics
public readonly array $metrics,
public readonly bool $showOnlyMethodsExceedingThreshold,
public readonly float $scoreThreshold
) {
}
}
18 changes: 0 additions & 18 deletions src/Config/Config.php

This file was deleted.

12 changes: 6 additions & 6 deletions src/Config/ConfigFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ class ConfigFactory
{
/**
* @param array<string, mixed> $config
* @return Config
* @return CognitiveConfig
*/
public function fromArray(array $config): Config
public function fromArray(array $config): CognitiveConfig
{
$metrics = [];
foreach ($config['cognitive']['metrics'] as $name => $metric) {
Expand All @@ -24,12 +24,12 @@ public function fromArray(array $config): Config
);
}

$cognitive = new CognitiveConfig(
return new CognitiveConfig(
$config['cognitive']['excludeFilePatterns'],
$config['cognitive']['excludePatterns'],
$metrics
$metrics,
$config['cognitive']['showOnlyMethodsExceedingThreshold'],
$config['cognitive']['scoreThreshold']
);

return new Config($cognitive);
}
}
7 changes: 2 additions & 5 deletions src/Config/ConfigService.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,8 @@ public function loadConfig(string $configFilePath): void
]);
}

/**
* @return array<string, mixed>
*/
public function getConfig(): array
public function getConfig(): CognitiveConfig
{
return $this->config;
return (new ConfigFactory())->fromArray($this->config);
}
}
Loading

0 comments on commit a808f43

Please sign in to comment.