Skip to content

Commit de4cf6c

Browse files
authored
Normalize object arguments in factory context (#270)
1 parent d429d83 commit de4cf6c

39 files changed

Lines changed: 207 additions & 181 deletions

‎src/Domain/Command/Handler/DeleteProjectionDocumentHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,6 @@ public function __invoke(DeleteProjectionDocumentCommand $command): void
3333
}
3434

3535
$this->repository->delete($document->getType(), $document->getId());
36-
$this->dispatch(ProjectionDocumentDeletedEvent::class, [$document]);
36+
$this->dispatch(ProjectionDocumentDeletedEvent::class, compact('document'));
3737
}
3838
}

‎src/Domain/Command/Handler/SaveProjectionDocumentHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,6 @@ public function __invoke(SaveProjectionDocumentCommand $command): void
3131
$document = new ProjectionDocument($command->type, $command->id, $command->body);
3232

3333
$this->repository->save($document);
34-
$this->dispatch(ProjectionDocumentSavedEvent::class, [$document]);
34+
$this->dispatch(ProjectionDocumentSavedEvent::class, compact('document'));
3535
}
3636
}

‎src/Domain/Factory/ClassMethodResolver.php‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
/**
1010
* @author Roland Franssen <franssen.roland@gmail.com>
11+
*
12+
* @internal
1113
*/
1214
final class ClassMethodResolver
1315
{
@@ -26,11 +28,11 @@ public static function resolve(string $class, string $method): array
2628
throw InvalidClassException::createForMethod($class, $method);
2729
}
2830

29-
if (null === $reflection) {
31+
if (null === $reflection || !$reflection->getNumberOfParameters()) {
3032
return self::$cache[$key] = [];
3133
}
3234

33-
return self::$cache[$key] = array_map(function (\ReflectionParameter $param): array {
35+
foreach ($reflection->getParameters() as $i => $param) {
3436
$type = $param->getType();
3537

3638
if (null !== $type) {
@@ -61,13 +63,14 @@ public static function resolve(string $class, string $method): array
6163
$required = true;
6264
}
6365

64-
return [
65-
'name' => $name = $param->getName(),
66-
'key' => strtolower((string) preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], $name)),
66+
self::$cache[$key][$param->getName()] = [
67+
'index' => $i,
6768
'required' => $required,
6869
'default' => $default,
6970
'type' => $type,
7071
];
71-
}, $reflection->getParameters());
72+
}
73+
74+
return self::$cache[$key];
7275
}
7376
}

‎src/Domain/Factory/DomainObjectFactory.php‎

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -49,28 +49,21 @@ private function resolveArguments(string $class, string $method, array $context)
4949
{
5050
$arguments = [];
5151

52-
foreach (ClassMethodResolver::resolve($class, $method) as $i => $argument) {
53-
$given = true;
54-
if (array_key_exists($name = $argument['name'], $context)) {
55-
$value = $context[$name];
56-
} elseif (array_key_exists($key = $argument['key'], $context)) {
57-
$value = $context[$key];
58-
} elseif (array_key_exists($i, $context)) {
59-
$value = $context[$i];
60-
} elseif (!$argument['required']) {
61-
$value = $argument['default'];
52+
foreach (ClassMethodResolver::resolve($class, $method) as $argument => $metadata) {
53+
if (array_key_exists($argument, $context)) {
54+
$given = true;
55+
$value = $context[$argument];
56+
} elseif (!$metadata['required']) {
6257
$given = false;
58+
$value = $metadata['default'];
6359
} else {
64-
throw new \LogicException(sprintf('No value available for argument $%s in class method "%s::%s()".', $name, $class, $method));
60+
throw new \LogicException(sprintf('No value available for argument $%s in class method "%s::%s()".', $argument, $class, $method));
6561
}
6662

67-
if ($given && isset($argument['type']) && (class_exists($argument['type']) || interface_exists($argument['type'], false)) && !\is_object($value)) {
68-
try {
69-
$arguments[] = ($this->factory ?? $this)->create($argument['type'], (array) $value);
70-
71-
continue;
72-
} catch (InvalidClassException $e) {
73-
}
63+
$type = $metadata['type'];
64+
if ($given && null !== $type && !\is_object($value) && (class_exists($type) || interface_exists($type, false))) {
65+
$arguments[] = ($this->factory ?? $this)->create($metadata['type'], (array) $value);
66+
continue;
7467
}
7568

7669
$arguments[] = $value;

‎src/Domain/Infra/Console/Context/ClassContextFactory.php‎

Lines changed: 79 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ final class ClassContextFactory implements ContextFactoryInterface
3030
private $fieldMapping = [];
3131
private $generatedValues = [];
3232

33+
public static function getFieldName(string $argument, bool $isOption = true): string
34+
{
35+
$field = strtolower((string) preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], $argument));
36+
37+
return $isOption ? str_replace('_', '-', $field) : $field;
38+
}
39+
3340
public static function getUniqueFieldName(InputDefinition $definition, string $field, bool $isOption = true): string
3441
{
3542
$known = $isOption ? $definition->getOptions() : $definition->getArguments();
@@ -62,33 +69,35 @@ public function configure(InputDefinition $definition): void
6269
$origOptions = $origArgs = [];
6370
}
6471

65-
foreach ($this->resolve() as $argument) {
72+
foreach ($this->resolve() as $argument => $metadata) {
6673
$isOption = true;
67-
if ('bool' === $argument['type']) {
74+
if ('bool' === $metadata['type']) {
6875
$mode = InputOption::VALUE_NONE;
69-
} elseif (self::isComplex($argument['type'])) {
76+
} elseif (self::isComplex($metadata['type'])) {
7077
$mode = InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY;
71-
} elseif (!$argument['required'] || ($this->flags & self::ALWAYS_OPTIONAL)) {
78+
} elseif (!$metadata['required'] || ($this->flags & self::ALWAYS_OPTIONAL)) {
7279
$mode = InputOption::VALUE_OPTIONAL;
7380
} else {
7481
$mode = InputArgument::OPTIONAL;
7582
$isOption = false;
7683
}
7784

78-
$field = $isOption ? str_replace('_', '-', $argument['key']) : $argument['key'];
85+
$field = self::getFieldName($argument, $isOption);
7986
if (!isset($origOptions[$field]) && !isset($origArgs[$field])) {
8087
$field = self::getUniqueFieldName($definition, $field, $isOption);
88+
/** @var ContextElement $element */
89+
$element = $metadata['element'];
8190

8291
if ($isOption) {
83-
$definition->addOption(new InputOption($field, null, $mode, $argument['element']->description));
92+
$definition->addOption(new InputOption($field, null, $mode, $element->description));
8493
} else {
85-
$definition->addArgument(new InputArgument($field, $mode, $argument['element']->description));
94+
$definition->addArgument(new InputArgument($field, $mode, $element->description));
8695
}
8796
} else {
8897
$isOption = isset($origOptions[$field]);
8998
}
9099

91-
$this->fieldMapping[$argument['name']] = [$field, $isOption];
100+
$this->fieldMapping[$argument] = [$field, $isOption];
92101
}
93102
}
94103

@@ -97,51 +106,34 @@ public function getContext(InputInterface $input, StyleInterface $io, array $val
97106
$context = $normalizers = [];
98107
$interactive = $input->isInteractive();
99108

100-
foreach ($resolved ?? $this->resolve() as $argument) {
101-
$key = $argument['name'];
109+
foreach ($resolved ?? $this->resolve() as $argument => $metadata) {
102110
if (null === $resolved) {
103-
[$field, $isOption] = $this->fieldMapping[$key];
111+
[$field, $isOption] = $this->fieldMapping[$argument];
104112
$value = $isOption ? $input->getOption($field) : $input->getArgument($field);
105113
} else {
106-
$field = $key;
107-
$value = $argument['value'] ?? null;
114+
$field = $argument;
115+
$value = $metadata['value'] ?? null;
108116
}
109117

110-
if (array_key_exists($key, $values)) {
111-
$context[$key] = $values[$key];
118+
if (array_key_exists($argument, $values)) {
119+
$context[$argument] = $values[$argument];
112120
continue;
113121
}
114122

115123
$isEmpty = null === $value || false === $value || [] === $value;
116124
$given = !$isEmpty || $input->hasParameterOption('--'.$field);
117-
125+
$required = $metadata['required'] && !($this->flags & self::ALWAYS_OPTIONAL);
126+
$type = $metadata['type'];
118127
/** @var ContextElement $element */
119-
$element = $argument['element'];
120-
$required = $argument['required'] && !($this->flags & self::ALWAYS_OPTIONAL);
121-
122-
if (\is_array($value) && self::isObject($type = $argument['type']) && ($required || $given)) {
123-
$method = is_subclass_of($type, DomainCollectionInterface::class) || is_subclass_of($type, DomainIdInterface::class) ? 'fromValue' : '__construct';
124-
$context[$key] = $this->getContext($input, $io, [], array_map(function (array $argument, int $i) use ($type, $method, $value, $element): array {
125-
if (array_key_exists($argument['name'], $value)) {
126-
$argument['value'] = $value[$argument['name']];
127-
} elseif (array_key_exists($i, $value)) {
128-
$argument['value'] = $value[$i];
129-
} elseif ('bool' === $argument['type']) {
130-
$argument['value'] = false;
131-
} elseif (self::isComplex($argument['type'])) {
132-
$argument['value'] = [];
133-
}
134-
135-
$child = $this->elementFactory->getElement($type, $method, $argument['name']);
136-
$child->label = $element->label.' > '.$child->label;
137-
138-
return ['element' => $child] + $argument;
139-
}, $objectResolved = ClassMethodResolver::resolve($type, $method), array_keys($objectResolved)));
128+
$element = $metadata['element'];
129+
130+
if (\is_array($value) && self::isObject($type) && ($required || $given)) {
131+
$context[$argument] = $this->getContext($input, $io, [], $this->resolveNested($type, $value, $element));
140132
continue;
141133
}
142134

143135
if (!$isEmpty) {
144-
$context[$key] = $element->normalize($value);
136+
$context[$argument] = $element->normalize($value);
145137
continue;
146138
}
147139

@@ -152,9 +144,9 @@ public function getContext(InputInterface $input, StyleInterface $io, array $val
152144

153145
if ($element->generate($io, $generated)) {
154146
$this->generatedValues[] = [$element->label, json_encode($generated)];
155-
$context[$key] = $element->normalize($generated);
147+
$context[$argument] = $element->normalize($generated);
156148
} else {
157-
$context[$key] = $this->askRequiredValue($io, $element, $value);
149+
$context[$argument] = self::askRequiredValue($io, $element, $value);
158150
}
159151
continue;
160152
}
@@ -163,7 +155,7 @@ public function getContext(InputInterface $input, StyleInterface $io, array $val
163155
continue;
164156
}
165157

166-
$context[$key] = $element->normalize($argument['default']);
158+
$context[$argument] = $element->normalize($metadata['default']);
167159
}
168160

169161
if ($this->generatedValues) {
@@ -185,6 +177,23 @@ private static function isObject(?string $type): bool
185177
return null !== $type && (class_exists($type) || interface_exists($type, false));
186178
}
187179

180+
private static function askRequiredValue(StyleInterface $io, ContextElement $element, $emptyValue)
181+
{
182+
if (null === $emptyValue) {
183+
return $element->askString($io);
184+
}
185+
186+
if (false === $emptyValue) {
187+
return $element->askBool($io);
188+
}
189+
190+
if ([] === $emptyValue) {
191+
return $element->askIterable($io);
192+
}
193+
194+
return $emptyValue;
195+
}
196+
188197
private function resolve(): iterable
189198
{
190199
if (null !== $this->resolved) {
@@ -193,30 +202,44 @@ private function resolve(): iterable
193202

194203
$this->resolved = [];
195204

196-
foreach (ClassMethodResolver::resolve($this->class, $this->method) as $argument) {
197-
$this->resolved[] = [
198-
'element' => $this->elementFactory->getElement($this->class, $this->method, $argument['name']),
199-
'type' => isset($argument['type']) ? ($this->classMapping[$argument['type']] ?? $argument['type']) : null,
200-
] + $argument;
205+
foreach (ClassMethodResolver::resolve($this->class, $this->method) as $argument => $metadata) {
206+
$this->resolved[$argument] = [
207+
'element' => $this->elementFactory->getElement($this->class, $this->method, $argument),
208+
'type' => isset($metadata['type']) ? ($this->classMapping[$metadata['type']] ?? $metadata['type']) : null,
209+
] + $metadata;
201210
}
202211

203212
return $this->resolved;
204213
}
205214

206-
private function askRequiredValue(StyleInterface $io, ContextElement $element, $emptyValue)
215+
private function resolveNested(string $type, array $parentValue, ContextElement $parentElement): iterable
207216
{
208-
if (null === $emptyValue) {
209-
return $element->askString($io);
210-
}
217+
$method = is_subclass_of($type, DomainCollectionInterface::class) || is_subclass_of($type, DomainIdInterface::class) ? 'fromValue' : '__construct';
218+
$resolved = [];
219+
220+
foreach (ClassMethodResolver::resolve($type, $method) as $argument => $metadata) {
221+
if (array_key_exists($argument, $parentValue)) {
222+
$value = $parentValue[$argument];
223+
} elseif (array_key_exists($metadata['index'], $parentValue)) {
224+
$value = $parentValue[$metadata['index']];
225+
} elseif ('bool' === $metadata['type']) {
226+
$value = false;
227+
} elseif (self::isComplex($metadata['type'])) {
228+
$value = [];
229+
} else {
230+
$value = null;
231+
}
211232

212-
if (false === $emptyValue) {
213-
return $element->askBool($io);
214-
}
233+
$element = $this->elementFactory->getElement($type, $method, $argument);
234+
$element->label = $parentElement->label.' > '.$element->label;
215235

216-
if ([] === $emptyValue) {
217-
return $element->askIterable($io);
236+
$resolved[$argument] = [
237+
'element' => $element,
238+
'type' => isset($metadata['type']) ? ($this->classMapping[$metadata['type']] ?? $metadata['type']) : null,
239+
'value' => $value,
240+
] + $metadata;
218241
}
219242

220-
return $emptyValue;
243+
return $resolved;
221244
}
222245
}

‎src/Domain/Tests/Factory/ClassMethodResolverTest.php‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@ public function testResolve(): void
1515
$arguments = ClassMethodResolver::resolve(TestClass::class, '__construct');
1616

1717
self::assertSame([
18-
['name' => 'fooBar', 'key' => 'foo_bar', 'required' => true, 'default' => null, 'type' => 'string'],
19-
['name' => 'foo_bar', 'key' => 'foo_bar', 'required' => false, 'default' => null, 'type' => WrongCase::class],
20-
['name' => 'fooBar_Baz', 'key' => 'foo_bar_baz', 'required' => false, 'default' => null, 'type' => null],
21-
['name' => 'it', 'key' => 'it', 'required' => true, 'default' => [], 'type' => 'iterable'],
22-
['name' => '_stdClass', 'key' => '_std_class', 'required' => true, 'default' => null, 'type' => \stdClass::class],
23-
['name' => 'foo', 'key' => 'foo', 'required' => false, 'default' => 1, 'type' => 'int'],
24-
['name' => 'bar', 'key' => 'bar', 'required' => false, 'default' => null, 'type' => TestClass::class],
25-
['name' => 'baz', 'key' => 'baz', 'required' => false, 'default' => [1], 'type' => 'array'],
18+
'fooBar' => ['index' => 0, 'required' => true, 'default' => null, 'type' => 'string'],
19+
'foo_bar' => ['index' => 1, 'required' => false, 'default' => null, 'type' => WrongCase::class],
20+
'fooBar_Baz' => ['index' => 2, 'required' => false, 'default' => null, 'type' => null],
21+
'it' => ['index' => 3, 'required' => true, 'default' => [], 'type' => 'iterable'],
22+
'_stdClass' => ['index' => 4, 'required' => true, 'default' => null, 'type' => \stdClass::class],
23+
'foo' => ['index' => 5, 'required' => false, 'default' => 1, 'type' => 'int'],
24+
'bar' => ['index' => 6, 'required' => false, 'default' => null, 'type' => TestClass::class],
25+
'baz' => ['index' => 7, 'required' => false, 'default' => [1], 'type' => 'array'],
2626
], $arguments);
2727
}
2828

@@ -39,17 +39,14 @@ public function testResolveWithUnknownClass(): void
3939
{
4040
$this->expectException(InvalidClassException::class);
4141

42-
ClassMethodResolver::resolve('foo', 'bar');
42+
ClassMethodResolver::resolve(UnknownTestObject::class, 'bar');
4343
}
4444

4545
public function testResolveWithUnknownMethod(): void
4646
{
47-
$object = new class() {
48-
};
49-
5047
$this->expectException(InvalidClassException::class);
5148

52-
ClassMethodResolver::resolve(\get_class($object), 'bar');
49+
ClassMethodResolver::resolve(\stdClass::class, 'bar');
5350
}
5451
}
5552

0 commit comments

Comments
 (0)