Completed
Pull Request — master (#54)
by Frank
02:04
created

CodeDumper::dumpClass()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 6
nop 3
dl 0
loc 29
ccs 17
cts 17
cp 1
crap 5
rs 9.3888
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing\CodeGeneration;
6
7
use LogicException;
8
use const null;
9
use function array_filter;
10
use function sprintf;
11
use function ucfirst;
12
use function var_export;
13
14
class CodeDumper
15
{
16
    /**
17
     * @var DefinitionGroup
18
     */
19
    private $definitionGroup;
20
21 12
    public function dump(DefinitionGroup $definitionGroup, bool $withHelpers = true, bool $withSerialization = true): string
22
    {
23 12
        $this->definitionGroup = $definitionGroup;
24 12
        $definitionCode = $this->dumpClass($definitionGroup->events(), $withHelpers, $withSerialization);
25 12
        $commandCode = $this->dumpClass($definitionGroup->commands(), $withHelpers, $withSerialization);
26 11
        $namespace = $definitionGroup->namespace();
27 11
        $allCode = implode("\n\n", array_filter([$definitionCode, $commandCode]));
28
29 11
        if ($withSerialization) {
30 11
            $namespace .= ";
31
32
use EventSauce\EventSourcing\Serialization\SerializablePayload";
33
        }
34
35
        return <<<EOF
36
<?php
37
38 11
namespace $namespace;
39
40 11
$allCode
41
42
EOF;
43
    }
44
45 12
    private function dumpClass(array $definitions, bool $withHelpers, bool $withSerialization): string
46
    {
47 12
        $code = [];
48
49 12
        if (empty($definitions)) {
50 9
            return '';
51
        }
52
53 12
        foreach ($definitions as $definition) {
54 12
            $name = $definition->name();
55 12
            $fields = $this->dumpFields($definition);
56 11
            $constructor = $this->dumpConstructor($definition);
57 11
            $methods = $this->dumpMethods($definition);
58 11
            $deserializer = $this->dumpSerializationMethods($definition);
59 11
            $testHelpers = $withHelpers ? $this->dumpTestHelpers($definition) : '';
60 11
            $implements = $withSerialization ? ' implements SerializablePayload' : '';
61
62 11
            $code[] = <<<EOF
63 11
final class $name$implements
64
{
65 11
$fields$constructor$methods$deserializer
66
67 11
$testHelpers}
68
69
70
EOF;
71
        }
72
73 11
        return rtrim(implode('', $code));
74
    }
75
76 12
    private function dumpFields(PayloadDefinition $definition): string
77
    {
78 12
        $fields = $this->fieldsFromDefinition($definition);
79 11
        $code = [];
80 11
        $code[] = <<<EOF
81
82
EOF;
83
84 11
        foreach ($fields as $field) {
85 10
            $name = $field['name'];
86 10
            $type = $this->definitionGroup->resolveTypeAlias($field['type']);
87
88 10
            $code[] = <<<EOF
89
    /**
90 10
     * @var $type
91
     */
92 10
    private \$$name;
93
94
95
EOF;
96
        }
97
98 11
        return implode('', $code);
99
    }
100
101 11
    private function dumpConstructor(PayloadDefinition $definition): string
102
    {
103 11
        $arguments = [];
104 11
        $assignments = [];
105 11
        $fields = $this->fieldsFromDefinition($definition);
106
107 11
        if (empty($fields)) {
108 1
            return '';
109
        }
110
111 10
        foreach ($fields as $field) {
112 10
            $resolvedType = $this->definitionGroup->resolveTypeAlias($field['type']);
113 10
            $arguments[] = sprintf('        %s $%s', $resolvedType, $field['name']);
114 10
            $assignments[] = sprintf('        $this->%s = $%s;', $field['name'], $field['name']);
115
        }
116
117 10
        $arguments = implode(",\n", $arguments);
118 10
        $assignments = implode("\n", $assignments);
119
120
        return <<<EOF
121
    public function __construct(
122 10
$arguments
123
    ) {
124 10
$assignments
125
    }
126
127
128
EOF;
129
    }
130
131 11
    private function dumpMethods(PayloadDefinition $command): string
132
    {
133 11
        $methods = [];
134
135 11
        foreach ($this->fieldsFromDefinition($command) as $field) {
136 10
            $methods[] = <<<EOF
137 10
    public function {$field['name']}(): {$this->definitionGroup->resolveTypeAlias($field['type'])}
138
    {
139 10
        return \$this->{$field['name']};
140
    }
141
142
143
EOF;
144
        }
145
146 11
        return empty($methods) ? '' : rtrim(implode('', $methods)) . "\n";
147
    }
148
149 11
    private function dumpSerializationMethods(PayloadDefinition $definition)
150
    {
151 11
        $name = $definition->name();
152 11
        $arguments = [];
153 11
        $serializers = [];
154
155 11
        foreach ($this->fieldsFromDefinition($definition) as $field) {
156 10
            $type = $this->definitionGroup->resolveTypeAlias($field['type']);
157 10
            $parameter = sprintf('$payload[\'%s\']', $field['name']);
158 10
            $template = $definition->deserializerForField($field['name'])
159 10
                ?: $definition->deserializerForType($field['type']);
160 10
            $arguments[] = trim(strtr($template, ['{type}' => $type, '{param}' => $parameter]));
161
162 10
            $property = sprintf('$this->%s', $field['name']);
163 10
            $template = $definition->serializerForField($field['name'])
164 10
                ?: $definition->serializerForType($field['type']);
165 10
            $template = sprintf("'%s' => %s", $field['name'], $template);
166 10
            $serializers[] = trim(strtr($template, ['{type}' => $type, '{param}' => $property]));
167
        }
168
169 11
        $arguments = preg_replace('/^.{2,}$/m', '            $0', implode(",\n", $arguments));
170
171 11
        if ( ! empty($arguments)) {
172 10
            $arguments = "\n$arguments\n        ";
173
        }
174
175 11
        $serializers = preg_replace('/^.{2,}$/m', '            $0', implode(",\n", $serializers));
176
177 11
        if ( ! empty($serializers)) {
178 10
            $serializers = "\n$serializers,\n        ";
179
        }
180
181
        return <<<EOF
182
    public static function fromPayload(array \$payload): SerializablePayload
183
    {
184 11
        return new $name($arguments);
185
    }
186
187
    public function toPayload(): array
188
    {
189 11
        return [$serializers];
190
    }
191
EOF;
192
    }
193
194 9
    private function dumpTestHelpers(PayloadDefinition $definition): string
195
    {
196 9
        $constructor = [];
197 9
        $constructorArguments = '';
198 9
        $constructorValues = [];
199 9
        $helpers = [];
200
201 9
        foreach ($this->fieldsFromDefinition($definition) as $field) {
202 8
            $resolvedType = $this->definitionGroup->resolveTypeAlias($field['type']);
203
204 8
            if (null === $field['example']) {
205 3
                $constructor[] = ucfirst($field['name']);
206
207 3
                if ('' !== $constructorArguments) {
208 1
                    $constructorArguments .= ', ';
209
                }
210
211 3
                $constructorArguments .= sprintf('%s $%s', $resolvedType, $field['name']);
212 3
                $constructorValues[] = sprintf('$%s', $field['name']);
213
            } else {
214 6
                $constructorValues[] = $this->dumpConstructorValue($field, $definition);
215 6
                $method = sprintf('with%s', ucfirst($field['name']));
216 6
                $helpers[] = <<<EOF
217
    /**
218
     * @codeCoverageIgnore
219
     */
220 6
    public function $method({$resolvedType} \${$field['name']}): {$definition->name()}
221
    {
222
        \$clone = clone \$this;
223 6
        \$clone->{$field['name']} = \${$field['name']};
224
225
        return \$clone;
226
    }
227
228
229
EOF;
230
            }
231
        }
232
233 9
        $constructor = sprintf('with%s', implode('And', $constructor));
234 9
        $constructorValues = implode(",\n            ", $constructorValues);
235
236 9
        if ('' !== $constructorValues) {
237 8
            $constructorValues = "\n            $constructorValues\n        ";
238
        }
239
240 9
        $helpers[] = <<<EOF
241
    /**
242
     * @codeCoverageIgnore
243
     */
244 9
    public static function $constructor($constructorArguments): {$definition->name()}
245
    {
246 9
        return new {$definition->name()}($constructorValues);
247
    }
248
249
250
EOF;
251
252 9
        return rtrim(implode('', $helpers)) . "\n";
253
    }
254
255 6
    private function dumpConstructorValue(array $field, PayloadDefinition $definition): string
256
    {
257 6
        $parameter = rtrim($field['example']);
258 6
        $resolvedType = $this->definitionGroup->resolveTypeAlias($field['type']);
259
260 6
        if (gettype($parameter) === $resolvedType) {
261 5
            $parameter = var_export($parameter, true);
262
        }
263
264 6
        $template = $definition->deserializerForField($field['name'])
265 6
            ?: $definition->deserializerForType($field['type']);
266
267 6
        return rtrim(strtr($template, ['{type}' => $resolvedType, '{param}' => $parameter]));
268
    }
269
270
    /**
271
     * @param PayloadDefinition $definition
272
     *
273
     * @return array
274
     */
275 12
    private function fieldsFromDefinition(PayloadDefinition $definition): array
276
    {
277 12
        $fields = $this->fieldsFrom($definition->fieldsFrom());
278
279 11
        foreach ($definition->fields() as $field) {
280 10
            array_push($fields, $field);
281
        }
282
283 11
        return $fields;
284
    }
285
286 12
    private function fieldsFrom(string $fieldsFrom): array
287
    {
288 12
        if (empty($fieldsFrom)) {
289 11
            return [];
290
        }
291
292 2
        foreach ($this->definitionGroup->events() as $definition) {
293 1
            if ($definition->name() === $fieldsFrom) {
294 1
                return $definition->fields();
295
            }
296
        }
297
298 2
        foreach ($this->definitionGroup->commands() as $command) {
299 2
            if ($command->name() === $fieldsFrom) {
300 1
                return $command->fields();
301
            }
302
        }
303
304 1
        throw new LogicException("Could not inherit fields from {$fieldsFrom}.");
305
    }
306
}
307