-
Notifications
You must be signed in to change notification settings - Fork 3
/
Printer.php
113 lines (92 loc) · 3.1 KB
/
Printer.php
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace Jane\Component\JsonSchema;
use Jane\Component\JsonSchema\Registry\Registry;
use PhpCsFixer\Console\Command\FixCommand;
use PhpCsFixer\ToolInfo;
use PhpParser\PrettyPrinterAbstract;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Filesystem\Filesystem;
class Printer
{
private $prettyPrinter;
private $fixerConfig;
private $useFixer = false;
private $cleanGenerated = true;
public function __construct(PrettyPrinterAbstract $prettyPrinter, string $fixerConfig = '')
{
$this->prettyPrinter = $prettyPrinter;
$this->fixerConfig = $fixerConfig;
}
public function setUseFixer(bool $useFixer): void
{
$this->useFixer = $useFixer;
}
public function setCleanGenerated(bool $cleanGenerated): void
{
$this->cleanGenerated = $cleanGenerated;
}
public function output(Registry $registry): void
{
if ($this->cleanGenerated) {
$fs = new Filesystem();
foreach ($registry->getOutputDirectories() as $directory) {
$fs->remove($directory);
$fs->mkdir($directory);
}
}
foreach ($registry->getSchemas() as $schema) {
foreach ($schema->getFiles() as $file) {
if (!file_exists(\dirname($file->getFilename()))) {
mkdir(\dirname($file->getFilename()), 0755, true);
}
file_put_contents($file->getFilename(), $this->prettyPrinter->prettyPrintFile([$file->getNode()]));
}
}
if ($this->useFixer) {
foreach ($registry->getOutputDirectories() as $directory) {
$this->fix($directory);
}
}
}
protected function getDefaultRules(): string
{
$rules = [
'@Symfony' => true,
'self_accessor' => true,
'array_syntax' => ['syntax' => 'short'],
'concat_space' => ['spacing' => 'one'],
'declare_strict_types' => true,
'header_comment' => [
'header' => <<<EOH
This file has been auto generated by Jane,
Do no edit it directly.
EOH
,
],
];
if (version_compare(\PhpCsFixer\Console\Application::VERSION, '3.0.0', '>=')) {
$rules['yoda_style'] = false;
} elseif (version_compare(\PhpCsFixer\Console\Application::VERSION, '2.6.0', '>=')) {
$rules['yoda_style'] = null;
}
return json_encode($rules);
}
protected function fix(string $path): void
{
if (!class_exists(FixCommand::class)) {
return;
}
$command = new FixCommand(new ToolInfo());
$config = [
'path' => [$path],
];
if (!empty($this->fixerConfig)) {
$config['--config'] = $this->fixerConfig;
} else {
$config['--allow-risky'] = 'yes';
$config['--rules'] = $this->getDefaultRules();
}
$command->run(new ArrayInput($config, $command->getDefinition()), new NullOutput());
}
}