Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@

# 3.0.0 (unreleased)

* Update to liip/metadata-parser 2.x
* The `LiipMetadataAnnotationParser` got renamed to `LiipMetadataAttributeParser` which means the `@Preferred`
annotation is no longer allowed and has to be replaced by the `#[Preferred]` attribute.
* Setting a (different) naming strategy via the `PropertyCollection::useIdenticalNamingStrategy` is no longer
possible, instead the naming strategy now has to be passed as the second argument when creating a new instance
of the `Parser` class
* For further changes in this library, take a look at the
[changelog from metadata-parser](https://github.com/liip/metadata-parser/blob/2.x/CHANGELOG.md)
* Add discriminator support

# 2.x

# 2.6.2
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use Liip\MetadataParser\Builder;
use Liip\MetadataParser\Parser;
use Liip\MetadataParser\RecursionChecker;
use Liip\MetadataParser\ModelParser\JMSParser;
use Liip\MetadataParser\ModelParser\LiipMetadataAnnotationParser;
use Liip\MetadataParser\ModelParser\LiipMetadataAttributeParser;
use Liip\MetadataParser\ModelParser\PhpDocParser;
use Liip\MetadataParser\ModelParser\ReflectionParser;
use Liip\Serializer\DeserializerGenerator;
Expand Down Expand Up @@ -75,7 +75,7 @@ $parsers = [
new ReflectionParser(),
new PhpDocParser(),
new JMSParser(new AnnotationReader()),
new LiipMetadataAnnotationParser(new AnnotationReader()),
new LiipMetadataAttributeParser(),
];
$builder = new Builder(new Parser($parsers), new RecursionChecker(null, []));

Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"require": {
"php": "^8.0",
"ext-json": "*",
"liip/metadata-parser": "^1.2",
"liip/metadata-parser": "^2.0",
"pnz/json-exception": "^1.0",
"symfony/filesystem": "^4.4 || ^5.0 || ^6.0 || ^7.0 || ^8.0",
"symfony/finder": "^4.4 || ^5.0 || ^6.0 || ^7.0 || ^8.0",
Expand All @@ -25,7 +25,7 @@
},
"require-dev": {
"doctrine/collections": "^1.6",
"friendsofphp/php-cs-fixer": "^3.23",
"friendsofphp/php-cs-fixer": "^3.90.0",
"jms/serializer": "^1.13 || ^2 || ^3",
"phpstan/phpstan": "^1.0",
"phpstan/phpstan-phpunit": "^1.3",
Expand Down
98 changes: 93 additions & 5 deletions src/DeserializerGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
use Liip\MetadataParser\Builder;
use Liip\MetadataParser\Metadata\ClassMetadata;
use Liip\MetadataParser\Metadata\PropertyMetadata;
use Liip\MetadataParser\Metadata\PropertyTypeArray;
use Liip\MetadataParser\Metadata\PropertyType;
use Liip\MetadataParser\Metadata\PropertyTypeClass;
use Liip\MetadataParser\Metadata\PropertyTypeDateTime;
use Liip\MetadataParser\Metadata\PropertyTypeIterable;
use Liip\MetadataParser\Metadata\PropertyTypePrimitive;
use Liip\MetadataParser\Metadata\PropertyTypeUnion;
use Liip\MetadataParser\Metadata\PropertyTypeUnknown;
use Liip\MetadataParser\Reducer\TakeBestReducer;
use Liip\Serializer\Configuration\ClassToGenerate;
Expand Down Expand Up @@ -89,6 +91,11 @@ private function generateCodeForClass(
ModelPath $modelPath,
array $stack = [],
): string {
$discriminatorMetadata = $classMetadata->getDiscriminatorMetadata();
if (null !== $discriminatorMetadata && $discriminatorMetadata->baseClass == $classMetadata->getClassName()) {
return $this->generateCodeForDiscriminatorClass($classMetadata, $arrayPath, $modelPath, $stack);
}

$stack[$classMetadata->getClassName()] = ($stack[$classMetadata->getClassName()] ?? 0) + 1;

$constructorArgumentNames = [];
Expand Down Expand Up @@ -143,6 +150,29 @@ private function generateCodeForClass(
return $this->templating->renderClass((string) $modelPath, $classMetadata->getClassName(), $constructorArguments, $code, $initCode);
}

/**
* @param array<string, positive-int> $stack
*/
private function generateCodeForDiscriminatorClass(
ClassMetadata $classMetadata,
ArrayPath $arrayPath,
ModelPath $modelPath,
array $stack = [],
): string {
$code = '';
$discriminatorMetadata = $classMetadata->getDiscriminatorMetadata();
$discriminatorFieldPath = $arrayPath->withFieldName($discriminatorMetadata->propertyName);
foreach ($discriminatorMetadata->classMap as $typeValue => $class) {
$code .= $this->templating->renderDiscriminatorConditional(
(string) $discriminatorFieldPath,
$typeValue,
$this->generateCodeForClass($discriminatorMetadata->getMetadataForClass($class), $arrayPath, $modelPath, $stack)
);
}

return $code;
}

/**
* @param array<string, positive-int> $stack
*/
Expand Down Expand Up @@ -204,7 +234,7 @@ private function generateInnerCodeForFieldType(
$type = $propertyMetadata->getType();

switch ($type) {
case $type instanceof PropertyTypeArray:
case $type instanceof PropertyTypeIterable:
if ($type->isTraversable()) {
return $this->generateCodeForArrayCollection($propertyMetadata, $type, $arrayPath, $modelPropertyPath, $stack);
}
Expand All @@ -229,16 +259,74 @@ private function generateInnerCodeForFieldType(
case $type instanceof PropertyTypeClass:
return $this->generateCodeForClass($type->getClassMetadata(), $arrayPath, $modelPropertyPath, $stack);

case $type instanceof PropertyTypeUnion:
return $this->generateCodeForUnion($type, $arrayPath, $modelPropertyPath, $stack);

default:
throw new \Exception('Unexpected type '.$type::class.' at '.$modelPropertyPath);
}
}

/**
* @param array<string, positive-int> $stack
*/
private function generateCodeForUnion(
PropertyTypeUnion $type,
ArrayPath $arrayPath,
ModelPath $modelPath,
array $stack,
): string {
$code = '';

$types = $type->getTypes();
$typesWithoutPrimitives = array_filter($types, static function (PropertyType $subType): bool {
return !($subType instanceof PropertyTypePrimitive || $subType instanceof PropertyTypeIterable);
});

$fieldName = $type->getFieldName();
if (null !== $fieldName) {
$discriminatorFieldPath = $arrayPath->withFieldName($fieldName);

foreach ($type->getTypeMap() as $typeValue => $class) {
$classType = $type->getTypeByClassName($class);
$code .= $this->templating->renderDiscriminatorConditional(
(string) $discriminatorFieldPath,
$typeValue,
$this->generateCodeForClass($classType->getClassMetadata(), $arrayPath, $modelPath, $stack)
);
}

return $code;
}

if (0 !== \count($typesWithoutPrimitives)) {
throw new \Exception('Found union type that contains primitives and non primitives, which is currently not supported.');
}

$amountOfTypes = \count($types);
foreach ($types as $key => $subType) {
$phpType = 'array';
if ($subType instanceof PropertyTypePrimitive) {
$phpType = $subType->getTypeName();
}

$withElseBlock = $key !== ($amountOfTypes - 1);
$code .= $this->templating->renderPrimitiveConditional(
$phpType,
(string) $arrayPath,
$this->templating->renderAssignJsonDataToFieldWithCast($phpType, (string) $modelPath, (string) $arrayPath),
$withElseBlock
);
}

return $code;
}

/**
* @param array<string, positive-int> $stack
*/
private function generateCodeForArray(
PropertyTypeArray $type,
PropertyTypeIterable $type,
ArrayPath $arrayPath,
ModelPath $modelPath,
array $stack,
Expand All @@ -254,7 +342,7 @@ private function generateCodeForArray(
$subType = $type->getSubType();

switch ($subType) {
case $subType instanceof PropertyTypeArray:
case $subType instanceof PropertyTypeIterable:
$innerCode = $this->generateCodeForArray($subType, $arrayPropertyPath, $modelPropertyPath, $stack);
break;

Expand Down Expand Up @@ -284,7 +372,7 @@ private function generateCodeForArray(
*/
private function generateCodeForArrayCollection(
PropertyMetadata $propertyMetadata,
PropertyTypeArray $type,
PropertyTypeIterable $type,
ArrayPath $arrayPath,
ModelPath $modelPath,
array $stack,
Expand Down
4 changes: 2 additions & 2 deletions src/Recursion.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace Liip\Serializer;

use Liip\MetadataParser\Metadata\PropertyMetadata;
use Liip\MetadataParser\Metadata\PropertyTypeArray;
use Liip\MetadataParser\Metadata\PropertyTypeClass;
use Liip\MetadataParser\Metadata\PropertyTypeIterable;

abstract class Recursion
{
Expand Down Expand Up @@ -44,7 +44,7 @@ public static function hasMaxDepthReached(PropertyMetadata $propertyMetadata, ar
private static function getClassNameFromProperty(PropertyMetadata $propertyMetadata): ?string
{
$type = $propertyMetadata->getType();
if ($type instanceof PropertyTypeArray) {
if ($type instanceof PropertyTypeIterable) {
$type = $type->getLeafType();
}

Expand Down
101 changes: 94 additions & 7 deletions src/SerializerGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
use Liip\MetadataParser\Metadata\ClassMetadata;
use Liip\MetadataParser\Metadata\PropertyMetadata;
use Liip\MetadataParser\Metadata\PropertyType;
use Liip\MetadataParser\Metadata\PropertyTypeArray;
use Liip\MetadataParser\Metadata\PropertyTypeClass;
use Liip\MetadataParser\Metadata\PropertyTypeDateTime;
use Liip\MetadataParser\Metadata\PropertyTypeIterable;
use Liip\MetadataParser\Metadata\PropertyTypePrimitive;
use Liip\MetadataParser\Metadata\PropertyTypeUnion;
use Liip\MetadataParser\Metadata\PropertyTypeUnknown;
use Liip\MetadataParser\Reducer\GroupReducer;
use Liip\MetadataParser\Reducer\PreferredReducer;
Expand Down Expand Up @@ -120,16 +121,51 @@ private function generateCodeForClass(
string $modelPath,
array $stack = [],
): string {
$discriminatorMetadata = $classMetadata->getDiscriminatorMetadata();
if (null !== $discriminatorMetadata && $discriminatorMetadata->baseClass == $classMetadata->getClassName()) {
return $this->generateCodeForDiscriminatorClass($classMetadata, $apiVersion, $serializerGroups, $arrayPath, $modelPath, $stack);
}

$stack[$classMetadata->getClassName()] = ($stack[$classMetadata->getClassName()] ?? 0) + 1;

$code = '';
foreach ($classMetadata->getProperties() as $propertyMetadata) {
$code .= $this->generateCodeForField($propertyMetadata, $apiVersion, $serializerGroups, $arrayPath, $modelPath, $stack);
}

if (null !== $discriminatorMetadata) {
$discriminatorFieldPath = $arrayPath.'["'.$discriminatorMetadata->propertyName.'"]';
$code .= $this->templating->renderAssign($discriminatorFieldPath, \sprintf("'%s'", $discriminatorMetadata->value));
}

return $this->templating->renderClass($arrayPath, $code);
}

/**
* @param list<string> $serializerGroups
* @param array<string, positive-int> $stack
*/
private function generateCodeForDiscriminatorClass(
ClassMetadata $classMetadata,
?string $apiVersion,
array $serializerGroups,
string $arrayPath,
string $modelPath,
array $stack = [],
): string {
$code = '';
$discriminatorMetadata = $classMetadata->getDiscriminatorMetadata();
foreach ($discriminatorMetadata->classMap as $class) {
$code .= $this->templating->renderInstanceOfConditional(
$modelPath,
$class,
$this->generateCodeForClass($discriminatorMetadata->getMetadataForClass($class), $apiVersion, $serializerGroups, $arrayPath, $modelPath, $stack)
);
}

return $code;
}

/**
* @param list<string> $serializerGroups
* @param array<string, positive-int> $stack
Expand Down Expand Up @@ -196,9 +232,12 @@ private function generateCodeForFieldType(
case $type instanceof PropertyTypeClass:
return $this->generateCodeForClass($type->getClassMetadata(), $apiVersion, $serializerGroups, $fieldPath, $modelPropertyPath, $stack);

case $type instanceof PropertyTypeArray:
case $type instanceof PropertyTypeIterable:
return $this->generateCodeForArray($type, $apiVersion, $serializerGroups, $fieldPath, $modelPropertyPath, $stack);

case $type instanceof PropertyTypeUnion:
return $this->generateCodeForUnion($type, $apiVersion, $serializerGroups, $fieldPath, $modelPropertyPath, $stack);

default:
throw new \Exception('Unexpected type '.$type::class.' at '.$modelPropertyPath);
}
Expand All @@ -209,7 +248,7 @@ private function generateCodeForFieldType(
* @param array<string, positive-int> $stack
*/
private function generateCodeForArray(
PropertyTypeArray $type,
PropertyTypeIterable $type,
?string $apiVersion,
array $serializerGroups,
string $arrayPath,
Expand All @@ -221,11 +260,11 @@ private function generateCodeForArray(

switch ($subType) {
case $subType instanceof PropertyTypePrimitive:
case $subType instanceof PropertyTypeArray && self::isArrayForPrimitive($subType):
case $subType instanceof PropertyTypeIterable && self::isArrayForPrimitive($subType):
case $subType instanceof PropertyTypeUnknown && $this->configuration->shouldAllowGenericArrays():
return $this->templating->renderArrayAssign($arrayPath, $modelPath);

case $subType instanceof PropertyTypeArray:
case $subType instanceof PropertyTypeIterable:
$innerCode = $this->generateCodeForArray($subType, $apiVersion, $serializerGroups, $arrayPath.'['.$index.']', $modelPath.'['.$index.']', $stack);
break;

Expand All @@ -252,14 +291,62 @@ private function generateCodeForArray(
return $this->templating->renderLoopArray($arrayPath, $modelPath, $index, $innerCode);
}

private static function isArrayForPrimitive(PropertyTypeArray $type): bool
/**
* @param list<string> $serializerGroups
* @param array<string, positive-int> $stack
*/
private function generateCodeForUnion(
PropertyTypeUnion $subType,
?string $apiVersion,
array $serializerGroups,
string $arrayPath,
string $modelPath,
array $stack,
): string {
$code = '';

$types = $subType->getTypes();
$typesWithoutPrimitives = array_filter($types, static function (PropertyType $subType): bool {
return !($subType instanceof PropertyTypePrimitive || $subType instanceof PropertyTypeUnknown);
});

$hasPrimitives = \count($types) !== \count($typesWithoutPrimitives);
if ($hasPrimitives) {
$code .= $this->templating->renderPrimitiveConditional(
$modelPath,
$this->templating->renderAssign($arrayPath, $modelPath)
);
}

foreach ($typesWithoutPrimitives as $subType) {
switch ($subType::class) {
case PropertyTypeClass::class:
$code .= $this->templating->renderInstanceOfConditional(
$modelPath,
$subType->getClassName(),
$this->generateCodeForFieldType($subType, $apiVersion, $serializerGroups, $arrayPath, $modelPath, $stack)
);
break;
case PropertyTypeIterable::class:
$code .= $this->templating->renderArrayConditional(
$modelPath,
$this->generateCodeForArray($subType, $apiVersion, $serializerGroups, $arrayPath, $modelPath, $stack)
);
break;
}
}

return $code;
}

private static function isArrayForPrimitive(PropertyTypeIterable $type): bool
{
do {
$type = $type->getSubType();
if ($type instanceof PropertyTypePrimitive) {
return true;
}
} while ($type instanceof PropertyTypeArray);
} while ($type instanceof PropertyTypeIterable);

return false;
}
Expand Down
Loading