forked from laminas/laminas-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnumGenerator.php
95 lines (81 loc) · 2.36 KB
/
EnumGenerator.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
<?php
namespace Laminas\Code\Generator\EnumGenerator;
use Laminas\Code\Generator\EnumGenerator\Cases\BackedCases;
use Laminas\Code\Generator\EnumGenerator\Cases\CaseFactory;
use Laminas\Code\Generator\EnumGenerator\Cases\PureCases;
use ReflectionEnum;
use function array_map;
use function implode;
/** @psalm-immutable */
final class EnumGenerator
{
/**
* Line feed to use in place of EOL
*/
private const LINE_FEED = "\n";
/**
* spaces of indentation by default
*/
private const INDENTATION = ' ';
/**
* @param BackedCases|PureCases $cases
*/
private function __construct(private readonly Name $name, private $cases)
{
}
public function generate(): string
{
$output = '';
if (null !== $this->name->getNamespace()) {
$output .= 'namespace ' . $this->name->getNamespace() . ';' . self::LINE_FEED . self::LINE_FEED;
}
return $output . 'enum ' . $this->name->getName() . $this->retrieveType() . ' {'
. self::LINE_FEED
. $this->retrieveCases()
. '}'
. self::LINE_FEED;
}
private function retrieveType(): string
{
if ($this->cases instanceof BackedCases) {
return ': ' . $this->cases->type;
}
return '';
}
private function retrieveCases(): string
{
return implode(
'',
array_map(
fn (string $case): string => self::INDENTATION . 'case ' . $case . ';' . self::LINE_FEED,
$this->cases->cases
)
);
}
/**
* @psalm-param array{
* name: non-empty-string,
* pureCases: list<non-empty-string>,
* }|array{
* name: non-empty-string,
* backedCases: array{
* type: 'int'|'string',
* cases: array<non-empty-string, int|string>,
* },
* } $options
*/
public static function withConfig(array $options): self
{
return new self(
Name::fromFullyQualifiedClassName($options['name']),
CaseFactory::fromOptions($options),
);
}
public static function fromReflection(ReflectionEnum $enum): self
{
return new self(
Name::fromFullyQualifiedClassName($enum->getName()),
CaseFactory::fromReflectionCases($enum),
);
}
}