-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathComposerJsonFileProcessor.php
More file actions
72 lines (59 loc) · 2.15 KB
/
Copy pathComposerJsonFileProcessor.php
File metadata and controls
72 lines (59 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace a9f\FractorComposerJson;
use a9f\Fractor\Application\Contract\FileProcessor;
use a9f\Fractor\Application\ValueObject\AppliedRule;
use a9f\Fractor\Application\ValueObject\File;
use a9f\Fractor\Caching\Detector\ChangedFilesDetector;
use a9f\Fractor\ValueObject\Indent;
use a9f\FractorComposerJson\Contract\ComposerJsonFractorRule;
use a9f\FractorComposerJson\Contract\ComposerJsonPrinter;
/**
* @implements FileProcessor<ComposerJsonFractorRule>
*/
final readonly class ComposerJsonFileProcessor implements FileProcessor
{
/**
* @param iterable<ComposerJsonFractorRule> $rules
*/
public function __construct(
private iterable $rules,
private Indent $indent,
private ComposerJsonPrinter $composerJsonPrinter,
private ComposerJsonFactory $composerJsonFactory,
private ChangedFilesDetector $changedFilesDetector
) {
}
public function canHandle(File $file): bool
{
return $file->getFileName() === 'composer.json';
}
public function handle(File $file, iterable $appliedRules): void
{
$rawContent = $file->getContent();
$composerJson = $this->composerJsonFactory->createFromFile($file);
foreach ($appliedRules as $rule) {
$beforeArray = $composerJson->getJsonArray();
$rule->refactor($composerJson);
if ($beforeArray !== $composerJson->getJsonArray()) {
$file->addAppliedRule(AppliedRule::fromRule($rule));
}
}
// Always re-print: a formatting-only change (indentation) is then
// attributed to CodeFormatRule by the runner rather than applied silently.
$newContent = rtrim($this->composerJsonPrinter->printToString($this->indent, $composerJson)) . "\n";
if ($newContent === $rawContent) {
$this->changedFilesDetector->addCachableFile($file->getFilePath());
return;
}
$file->changeFileContent($newContent);
}
public function allowedFileExtensions(): array
{
return ['json'];
}
public function getAllRules(): iterable
{
return $this->rules;
}
}