Map to different property name #19
-
First of all, what a useful library! How to map properties different from JSON keys? For example: class Thread {
public readonly int $id;
public readonly string $content;
public readonly DateTimeImmutable $creationDate;
} and {
"id": 1337,
"content": "Do you like potatoes?",
"creation_date": "1957-07-23 13:37:42"
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
🤗
I've already thought about this case, though I did not try a solution nor documented anything related to it. I just tried something locally, but I spotted a bug that needs to be fixed in order for the code below to work (I'll work on it ASAP). final class KeyReplacementSource implements IteratorAggregate
{
/** @var mixed[] */
private array $source;
/**
* @param iterable<mixed> $source
* @param array<string, string> $keyReplacements
*/
public function __construct(iterable $source, array $keyReplacements)
{
$this->source = $this->replace($source, $keyReplacements);
}
/**
* @param iterable<mixed> $source
* @param array<string, string> $keyReplacements
*/
private function replace(iterable $source, array $keyReplacements): array
{
$array = [];
foreach ($source as $key => $value) {
if (is_iterable($value)) {
$value = $this->replace($value, $keyReplacements);
}
$array[$keyReplacements[$key] ?? $key] = $value;
}
return $array;
}
/**
* @return Iterator<mixed>
*/
public function getIterator(): Traversable
{
yield from $this->source;
}
}
// and use it like this…
$this->mapperBuilder
->mapper()
->map(Thread::class, new KeyReplacementSource(
[
// …
'creation_date' => '1957-07-23 13:37:42',
],
[
'creation_date' => 'creationDate',
]
)); We could even have this kind of services for automatic snake-case to camel-case keys conversions, I'll think about it. |
Beta Was this translation helpful? Give feedback.
-
In the meantime since this thread was created, has any solution emerged within the library itself for this case, or do I still need to implement the KeyReplacementSource? Thank you! |
Beta Was this translation helpful? Give feedback.
🤗
I've already thought about this case, though I did not try a solution nor documented anything related to it.
I just tried something locally, but I spotted a bug that needs to be fixed in order for the code below to work (I'll work on it ASAP).