Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for mapping oneOf via #[Discriminator] attribute #68

Merged
merged 16 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
21 changes: 21 additions & 0 deletions src/Compiler/Mapper/Object/Discriminator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php declare(strict_types = 1);

namespace ShipMonk\InputMapper\Compiler\Mapper\Object;

use Attribute;

#[Attribute(Attribute::TARGET_CLASS)]
class Discriminator
{

public function __construct(
public readonly string $key,
/**
* @var array<string, class-string>
*/
public readonly array $mapping
)
{
olsavmic marked this conversation as resolved.
Show resolved Hide resolved
}

}
160 changes: 160 additions & 0 deletions src/Compiler/Mapper/Object/MapDiscriminatedObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php declare(strict_types = 1);

namespace ShipMonk\InputMapper\Compiler\Mapper\Object;

use Attribute;
use LogicException;
use Nette\Utils\Arrays;
use PhpParser\Node\Expr;
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use ShipMonk\InputMapper\Compiler\CompiledExpr;
use ShipMonk\InputMapper\Compiler\Mapper\GenericMapperCompiler;
use ShipMonk\InputMapper\Compiler\Mapper\Scalar\MapString;
use ShipMonk\InputMapper\Compiler\Php\PhpCodeBuilder;
use ShipMonk\InputMapper\Compiler\Type\GenericTypeParameter;
use ShipMonk\InputMapper\Runtime\Exception\MappingFailedException;
use function array_keys;
use function count;
use function ucfirst;

/**
* @template T of object
*/
#[Attribute(Attribute::TARGET_PARAMETER | Attribute::TARGET_PROPERTY)]
class MapDiscriminatedObject implements GenericMapperCompiler
{

/**
* @param class-string<T> $className
* @param array<string, class-string> $subtypeMapping
* @param list<GenericTypeParameter> $genericParameters
*/
public function __construct(
public readonly string $className,
public readonly string $discriminatorFieldName,
public readonly array $subtypeMapping,
public readonly array $genericParameters = [],
)
{
}

public function compile(Expr $value, Expr $path, PhpCodeBuilder $builder): CompiledExpr
{
$provider = $builder->propertyFetch($builder->var('this'), 'provider');
olsavmic marked this conversation as resolved.
Show resolved Hide resolved

$statements = [
$builder->if($builder->not($builder->funcCall($builder->importFunction('is_array'), [$value])), [
$builder->throw(
$builder->staticCall(
$builder->importClass(MappingFailedException::class),
'incorrectType',
[$value, $path, $builder->val('array')],
),
),
]),
];

$isDiscriminatorPresent = $builder->funcCall($builder->importFunction('array_key_exists'), [$builder->val($this->discriminatorFieldName), $value]);
$isDiscriminatorMissing = $builder->not($isDiscriminatorPresent);

$statements[] = $builder->if($isDiscriminatorMissing, [
$builder->throw(
$builder->staticCall(
$builder->importClass(MappingFailedException::class),
'missingKey',
[$path, $this->discriminatorFieldName],
),
),
]);

$discriminatorRawValue = $builder->arrayDimFetch($value, $builder->val($this->discriminatorFieldName));
$discriminatorPath = $builder->arrayImmutableAppend($path, $builder->val($this->discriminatorFieldName));
$discriminatorMapperMethodName = $builder->uniqMethodName('map' . ucfirst($this->discriminatorFieldName));
$discriminatorMapperMethod = $builder->mapperMethod($discriminatorMapperMethodName, new MapString())->makePrivate()->getNode();
$discriminatorMapperCall = $builder->methodCall($builder->var('this'), $discriminatorMapperMethodName, [$discriminatorRawValue, $discriminatorPath]);
$builder->addMethod($discriminatorMapperMethod);

$validMappingKeys = array_keys($this->subtypeMapping);
$isDiscriminatorValid = $builder->funcCall($builder->importFunction('in_array'), [$discriminatorRawValue, $builder->val($validMappingKeys), $builder->val(true)]);

$expectedDescription = $builder->concat(
'one of ',
$builder->funcCall($builder->importFunction('implode'), [
', ',
$builder->val($validMappingKeys),
]),
);

$statements[] = $builder->if($builder->not($isDiscriminatorValid), [
$builder->throw(
$builder->staticCall(
$builder->importClass(MappingFailedException::class),
'incorrectValue',
[$discriminatorRawValue, $discriminatorPath, $expectedDescription],
),
),
]);

$subtypeMatchArms = [];

foreach ($this->subtypeMapping as $key => $subtype) {
$mapperProviderMethodCall = $builder->methodCall($provider, 'get', [
$builder->classConstFetch($builder->importClass($subtype), 'class'),
olsavmic marked this conversation as resolved.
Show resolved Hide resolved
]);

$subtypeMatchArms[] = $builder->matchArm(
$builder->val($key),
$builder->methodCall($mapperProviderMethodCall, 'map', [$value, $path]),
);
}

$subtypeMatchArms[] = $builder->matchArm(
null,
$builder->throwExpr(
$builder->new(
$builder->importClass(LogicException::class),
JanTvrdik marked this conversation as resolved.
Show resolved Hide resolved
['Impossible case detected. Please report this as a bug.'],
),
),
);

$matchedSubtype = $builder->match($discriminatorMapperCall, $subtypeMatchArms);

return new CompiledExpr(
$matchedSubtype,
$statements,
);
}

public function getInputType(): TypeNode
{
return new IdentifierTypeNode('mixed');
}

public function getOutputType(): TypeNode
{
$outputType = new IdentifierTypeNode($this->className);

if (count($this->genericParameters) === 0) {
return $outputType;
}

return new GenericTypeNode(
$outputType,
Arrays::map($this->genericParameters, static function (GenericTypeParameter $parameter): TypeNode {
return new IdentifierTypeNode($parameter->name);
}),
);
}

/**
* @return list<GenericTypeParameter>
*/
public function getGenericParameters(): array
{
return $this->genericParameters;
}

}
27 changes: 27 additions & 0 deletions src/Compiler/MapperFactory/DefaultMapperCompilerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@
use ShipMonk\InputMapper\Compiler\Mapper\Mixed\MapMixed;
use ShipMonk\InputMapper\Compiler\Mapper\Object\AllowExtraKeys;
use ShipMonk\InputMapper\Compiler\Mapper\Object\DelegateMapperCompiler;
use ShipMonk\InputMapper\Compiler\Mapper\Object\Discriminator;
use ShipMonk\InputMapper\Compiler\Mapper\Object\MapDateTimeImmutable;
use ShipMonk\InputMapper\Compiler\Mapper\Object\MapDiscriminatedObject;
use ShipMonk\InputMapper\Compiler\Mapper\Object\MapEnum;
use ShipMonk\InputMapper\Compiler\Mapper\Object\MapObject;
use ShipMonk\InputMapper\Compiler\Mapper\Object\SourceKey;
Expand Down Expand Up @@ -281,6 +283,12 @@ protected function createObjectMapperCompiler(string $inputClassName, array $opt
}
}

$classReflection = new ReflectionClass($inputClassName);

foreach ($classReflection->getAttributes(Discriminator::class) as $discriminatorAttribute) {
return $this->createDiscriminatorObjectMapping($inputClassName, $discriminatorAttribute->newInstance());
}

return $this->createObjectMappingByConstructorInvocation($inputClassName, $options);
}

Expand Down Expand Up @@ -327,6 +335,25 @@ protected function createObjectMappingByConstructorInvocation(
return new MapObject($classReflection->getName(), $constructorParameterMapperCompilers, $allowExtraKeys, $genericParameters);
}

/**
* @param class-string $inputClassName
*/
public function createDiscriminatorObjectMapping(
string $inputClassName,
Discriminator $discriminatorAttribute,
): MapperCompiler
{
$inputType = new IdentifierTypeNode($inputClassName);
$genericParameters = PhpDocTypeUtils::getGenericTypeDefinition($inputType)->parameters;

return new MapDiscriminatedObject(
$inputClassName,
$discriminatorAttribute->key,
$discriminatorAttribute->mapping,
$genericParameters,
);
}

/**
* @param list<string> $genericParameterNames
* @return array<string, TypeNode>
Expand Down
24 changes: 24 additions & 0 deletions src/Compiler/Php/PhpCodeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@
use PhpParser\Node\Expr\BinaryOp\SmallerOrEqual;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\Instanceof_;
use PhpParser\Node\Expr\Match_;
use PhpParser\Node\Expr\PreInc;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Throw_ as ThrowExpr_;
use PhpParser\Node\MatchArm;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_ as ClassNode;
Expand Down Expand Up @@ -216,6 +219,22 @@ public function if(Expr $if, array $then, ?array $else = null): If_
return new If_($if, ['stmts' => $then, 'elseifs' => $elseIfClauses, 'else' => $elseClause]);
}

/**
* @param list<MatchArm> $arms
*/
public function match(Expr $cond, array $arms = []): Match_
{
return new Match_($cond, $arms);
}

public function matchArm(?Expr $cond, Expr $body): MatchArm
{
return new MatchArm(
$cond !== null ? [$cond] : null,
$body,
);
}

/**
* @param list<Stmt> $statements
*/
Expand Down Expand Up @@ -260,6 +279,11 @@ public function throw(Expr $expr): Throw_
return new Throw_($expr);
}

public function throwExpr(Expr $expr): ThrowExpr_
{
return new ThrowExpr_($expr);
}

public function assign(Expr $var, Expr $expr): Expression
{
return new Expression(new Assign($var, $expr));
Expand Down
24 changes: 24 additions & 0 deletions tests/Compiler/Mapper/Object/Data/HierarchicalChildOneInput.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php declare(strict_types = 1);

namespace ShipMonkTests\InputMapper\Compiler\Mapper\Object\Data;

use ShipMonk\InputMapper\Runtime\Optional;

class HierarchicalChildOneInput extends HierarchicalParentInput
{

/**
* @param Optional<int> $age
*/
public function __construct(
int $id,
string $name,
Optional $age,
string $type,
public readonly string $childOneField,
)
{
parent::__construct($id, $name, $age, $type);
}

}
24 changes: 24 additions & 0 deletions tests/Compiler/Mapper/Object/Data/HierarchicalChildTwoInput.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php declare(strict_types = 1);

namespace ShipMonkTests\InputMapper\Compiler\Mapper\Object\Data;

use ShipMonk\InputMapper\Runtime\Optional;

class HierarchicalChildTwoInput extends HierarchicalParentInput
{

/**
* @param Optional<int> $age
*/
public function __construct(
int $id,
string $name,
Optional $age,
string $type,
public readonly int $childTwoField,
)
{
parent::__construct($id, $name, $age, $type);
}

}
30 changes: 30 additions & 0 deletions tests/Compiler/Mapper/Object/Data/HierarchicalParentInput.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php declare(strict_types=1);

namespace ShipMonkTests\InputMapper\Compiler\Mapper\Object\Data;

use ShipMonk\InputMapper\Compiler\Mapper\Object\Discriminator;
use ShipMonk\InputMapper\Runtime\Optional;

#[Discriminator(
'type',
mapping: [
'childOne' => HierarchicalChildOneInput::class,
'childTwo' => HierarchicalChildTwoInput::class,
],
)]
abstract class HierarchicalParentInput
{

/**
* @param Optional<int> $age
*/
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly Optional $age,
public readonly string $type,
)
{
}

}
Loading
Loading