Skip to content

Fix nullable transformable properties handling #13

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ievgenii-syrotenko
Copy link

@ievgenii-syrotenko ievgenii-syrotenko commented Jul 8, 2025

Fix the issue #14

Issue Description

There was an issue with transforming nullable transformable properties (like DTO objects) when null values were provided. Instead of preserving the null value, the system was incorrectly creating an empty instance of the class.

How to reproduce

class ProductDTO
{
    public int $id;
    public string $name;
}

class DiscountDTO
{
    public string $code;
    public int $value;
}

class PurchaseDTO
{
    public ProductDTO $product;
    public ?DiscountDTO $discount;
    public float $cost;
}

$data = [
    'product' => ['id' => 1, 'name' => 'phone'],
    'discount' => null,
    'cost' => 10012.23,
];

$purchaseDTO = ClassTransformer\Hydrator::init()->create(PurchaseDTO::class, $data);
var_dump($purchaseDTO->discount);

Expected behavior

The $purchaseDTO->discount property should be null since we provided null in the input data and the property is nullable (?DiscountDTO).

Actual behavior

The system was creating an empty DiscountDTO object:

object(DiscountDTO)#34 (0) {
  ["code"]=>
  uninitialized(string)
  ["value"]=>
  uninitialized(int)
}

Fix

The issue was in the PropertyTypeFactory::create() method, where the wrong parameter was being passed to the
TransformableType constructor. The method was passing the $isScalar flag instead of the $isNullable flag, causing the nullable information to be lost during transformation.

This PR fixes the issue by passing the correct $isNullable parameter to ensure that nullable properties remain null when null values are provided.

Tests

Added a test condition to ValueCastingTest and new test cases to ClassTransformerFromArrayTest that verify:

  1. Nullable properties correctly remain null when null is provided
  2. Nullable properties are correctly transformed when valid data is provided

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants