Passed
Pull Request — master (#54)
by Frank
02:54 queued 34s
created

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