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