Skip to content

Commit 08c7f15

Browse files
Refactoring
1 parent ee822d3 commit 08c7f15

File tree

2 files changed

+80
-44
lines changed

2 files changed

+80
-44
lines changed

src/Business/Cognitive/CognitiveMetricsCollector.php

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use Phauthentic\CognitiveCodeAnalysis\CognitiveAnalysisException;
1212
use Phauthentic\CognitiveCodeAnalysis\Config\CognitiveConfig;
1313
use Phauthentic\CognitiveCodeAnalysis\Config\ConfigService;
14+
use Psr\Cache\InvalidArgumentException;
1415
use SplFileInfo;
1516
use Symfony\Component\Messenger\Exception\ExceptionInterface;
1617
use Symfony\Component\Messenger\MessageBusInterface;
@@ -43,7 +44,7 @@ public function __construct(
4344
* @param string $path
4445
* @param CognitiveConfig $config
4546
* @return CognitiveMetricsCollection
46-
* @throws CognitiveAnalysisException
47+
* @throws CognitiveAnalysisException|ExceptionInterface
4748
*/
4849
public function collect(string $path, CognitiveConfig $config): CognitiveMetricsCollection
4950
{
@@ -56,7 +57,7 @@ public function collect(string $path, CognitiveConfig $config): CognitiveMetrics
5657
* @param array<string> $paths Array of paths to process
5758
* @param CognitiveConfig $config
5859
* @return CognitiveMetricsCollection Merged collection of metrics from all paths
59-
* @throws CognitiveAnalysisException
60+
* @throws CognitiveAnalysisException|ExceptionInterface
6061
*/
6162
public function collectFromPaths(array $paths, CognitiveConfig $config): CognitiveMetricsCollection
6263
{
@@ -91,7 +92,6 @@ private function getCodeFromFile(SplFileInfo $file): string
9192
*
9293
* @param iterable<SplFileInfo> $files
9394
* @return CognitiveMetricsCollection
94-
* @throws ExceptionInterface
9595
*/
9696
private function findMetrics(iterable $files): CognitiveMetricsCollection
9797
{
@@ -115,12 +115,10 @@ private function findMetrics(iterable $files): CognitiveMetricsCollection
115115
}
116116
}
117117

118-
$filename = $this->normalizeFilename($file);
119-
120118
$metricsCollection = $this->processMethodMetrics(
121119
$metrics,
122120
$metricsCollection,
123-
$filename
121+
$this->normalizeFilename($file)
124122
);
125123
}
126124

@@ -182,6 +180,7 @@ private function isExcluded(string $classAndMethod): bool
182180
* @param string $path Path to the directory or file to scan
183181
* @param array<int, string> $exclude List of regx to exclude
184182
* @return iterable<mixed, SplFileInfo> An iterable of SplFileInfo objects
183+
* @throws CognitiveAnalysisException
185184
*/
186185
private function findSourceFiles(string $path, array $exclude = []): iterable
187186
{
@@ -194,11 +193,12 @@ private function findSourceFiles(string $path, array $exclude = []): iterable
194193
/**
195194
* Get the project root directory path.
196195
*
196+
* Start from the current file's directory and traverse up to find composer.json
197+
*
197198
* @return string|null The project root path or null if not found
198199
*/
199200
private function getProjectRoot(): ?string
200201
{
201-
// Start from the current file's directory and traverse up to find composer.json
202202
$currentDir = __DIR__;
203203

204204
while ($currentDir !== dirname($currentDir)) {
@@ -212,7 +212,7 @@ private function getProjectRoot(): ?string
212212
}
213213

214214
/**
215-
* Generate cache key for a file based on path, modification time, and config hash
215+
* Generate a cache key for a file based on path, modification time, and config hash
216216
*/
217217
private function generateCacheKey(SplFileInfo $file, string $configHash): string
218218
{
@@ -262,17 +262,21 @@ public function clearCache(): void
262262
}
263263

264264
/**
265-
* Normalize filename for test environment
265+
* Normalize filename for the test environment
266+
*
267+
* This is to ensure consistent file paths in test outputs
266268
*/
267269
private function normalizeFilename(SplFileInfo $file): string
268270
{
269271
$filename = $file->getRealPath();
270272

271-
if (getenv('APP_ENV') === 'test') {
272-
$projectRoot = $this->getProjectRoot();
273-
if ($projectRoot && str_starts_with($filename, $projectRoot)) {
274-
$filename = substr($filename, strlen($projectRoot) + 1);
275-
}
273+
if (getenv('APP_ENV') !== 'test') {
274+
return $filename;
275+
}
276+
277+
$projectRoot = $this->getProjectRoot();
278+
if ($projectRoot && str_starts_with($filename, $projectRoot)) {
279+
$filename = substr($filename, strlen($projectRoot) + 1);
276280
}
277281

278282
return $filename;
@@ -282,6 +286,7 @@ private function normalizeFilename(SplFileInfo $file): string
282286
* Try to get cached metrics for a file
283287
*
284288
* @return array{metrics: array<string, mixed>|null, cacheItem: CacheItemInterface|null}
289+
* @throws InvalidArgumentException|ExceptionInterface
285290
*/
286291
private function getCachedMetrics(SplFileInfo $file, string $configHash, bool $useCache): array
287292
{
@@ -341,6 +346,7 @@ private function processFile(
341346
$file,
342347
$exception
343348
));
349+
344350
return null;
345351
}
346352
}

src/Cache/FileCache.php

Lines changed: 60 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,24 @@
1414
class FileCache implements CacheItemPoolInterface
1515
{
1616
private string $cacheDirectory;
17-
/** @var array<CacheItemInterface> */
17+
18+
/**
19+
* @var array<CacheItemInterface>
20+
*/
1821
private array $deferred = [];
1922

23+
/**
24+
* @throws CacheException
25+
*/
2026
public function __construct(string $cacheDirectory = './.phpcca.cache')
2127
{
2228
$this->cacheDirectory = rtrim($cacheDirectory, '/');
2329
$this->ensureCacheDirectory();
2430
}
2531

32+
/**
33+
* @throws CacheException
34+
*/
2635
public function getItem(string $key): CacheItemInterface
2736
{
2837
$filePath = $this->getCacheFilePath($key);
@@ -39,19 +48,27 @@ public function getItem(string $key): CacheItemInterface
3948
return new CacheItem($key, $data, true);
4049
}
4150

42-
/** @return array<string, CacheItemInterface> */
51+
/**
52+
* @return array<string, CacheItemInterface>
53+
* @throws CacheException
54+
*/
4355
public function getItems(array $keys = []): iterable
4456
{
4557
$items = [];
4658
foreach ($keys as $key) {
4759
$items[$key] = $this->getItem($key);
4860
}
61+
4962
return $items;
5063
}
5164

65+
/**
66+
* @throws CacheException
67+
*/
5268
public function hasItem(string $key): bool
5369
{
5470
$filePath = $this->getCacheFilePath($key);
71+
5572
return file_exists($filePath) && $this->loadCacheData($filePath) !== null;
5673
}
5774

@@ -66,6 +83,9 @@ public function clear(): bool
6683
}
6784
}
6885

86+
/**
87+
* @throws CacheException
88+
*/
6989
public function deleteItem(string $key): bool
7090
{
7191
$filePath = $this->getCacheFilePath($key);
@@ -77,6 +97,9 @@ public function deleteItem(string $key): bool
7797
return true;
7898
}
7999

100+
/**
101+
* @throws CacheException
102+
*/
80103
public function deleteItems(array $keys): bool
81104
{
82105
$success = true;
@@ -88,12 +111,11 @@ public function deleteItems(array $keys): bool
88111
return $success;
89112
}
90113

114+
/**
115+
* @throws CacheException
116+
*/
91117
public function save(CacheItemInterface $item): bool
92118
{
93-
if (!$item instanceof CacheItem) {
94-
return false;
95-
}
96-
97119
$filePath = $this->getCacheFilePath($item->getKey());
98120
$data = $item->get();
99121

@@ -106,11 +128,8 @@ public function save(CacheItemInterface $item): bool
106128

107129
public function saveDeferred(CacheItemInterface $item): bool
108130
{
109-
if (!$item instanceof CacheItem) {
110-
return false;
111-
}
112-
113131
$this->deferred[] = $item;
132+
114133
return true;
115134
}
116135

@@ -126,26 +145,35 @@ public function commit(): bool
126145
return $success;
127146
}
128147

148+
/**
149+
* @throws CacheException
150+
*/
129151
private function ensureCacheDirectory(): void
130152
{
131-
if (!is_dir($this->cacheDirectory)) {
132-
if (!mkdir($this->cacheDirectory, 0755, true)) {
133-
throw new CacheException("Failed to create cache directory: {$this->cacheDirectory}");
134-
}
153+
if (
154+
!is_dir($this->cacheDirectory)
155+
&& !mkdir($this->cacheDirectory, 0755, true)
156+
) {
157+
throw new CacheException("Failed to create cache directory: {$this->cacheDirectory}");
135158
}
136159
}
137160

161+
/**
162+
* Create subdirectories to avoid too many files in one directory
163+
*
164+
* @throws CacheException
165+
*/
138166
private function getCacheFilePath(string $key): string
139167
{
140-
// Create subdirectories to avoid too many files in one directory
141168
$hash = md5($key);
142169
$subDir = substr($hash, 0, 2);
143170
$dir = $this->cacheDirectory . '/' . $subDir;
144171

145-
if (!is_dir($dir)) {
146-
if (!mkdir($dir, 0755, true)) {
147-
throw new CacheException("Failed to create cache subdirectory: {$dir}");
148-
}
172+
if (
173+
!is_dir($dir)
174+
&& !mkdir($dir, 0755, true)
175+
) {
176+
throw new CacheException("Failed to create cache subdirectory: {$dir}");
149177
}
150178

151179
return $dir . '/' . $hash . '.cache';
@@ -164,18 +192,18 @@ private function loadCacheData(string $filePath): ?array
164192
return null;
165193
}
166194

167-
// Data is stored without compression for now
168-
169195
return $data;
170196
}
171197

172-
/** @param array<string, mixed> $data */
198+
/**
199+
* Store data
200+
*
201+
* Sanitize data to ensure valid UTF-8 encoding
202+
*
203+
* @param array<string, mixed> $data
204+
*/
173205
private function saveCacheData(string $filePath, array $data): bool
174206
{
175-
// Store data without compression for now (compression can be added later)
176-
// This ensures cache works reliably
177-
178-
// Sanitize data to ensure valid UTF-8 encoding
179207
$data = $this->sanitizeUtf8($data);
180208

181209
$json = json_encode($data, JSON_PRETTY_PRINT);
@@ -184,13 +212,15 @@ private function saveCacheData(string $filePath, array $data): bool
184212
}
185213

186214
$dir = dirname($filePath);
187-
if (!is_dir($dir)) {
188-
if (!mkdir($dir, 0755, true)) {
189-
return false;
190-
}
215+
if (
216+
!is_dir($dir)
217+
&& !mkdir($dir, 0755, true)
218+
) {
219+
return false;
191220
}
192221

193222
$result = file_put_contents($filePath, $json);
223+
194224
return $result !== false;
195225
}
196226

0 commit comments

Comments
 (0)