Skip to content
Merged
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
12 changes: 12 additions & 0 deletions src/Formatter/ArrayBasedDeformatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public function deserializeInt(mixed $decoded, Field $field): int|DeformatterRes
}

// Weak mode.
if ($field->nullable && is_null($value)) {
return null;
}
return (int)($decoded[$field->serializedName]);
}

Expand All @@ -60,6 +63,9 @@ public function deserializeFloat(mixed $decoded, Field $field): float|Deformatte
}

// Weak mode.
if ($field->nullable && is_null($value)) {
return null;
}
return (float)($decoded[$field->serializedName]);
}

Expand All @@ -79,6 +85,9 @@ public function deserializeBool(mixed $decoded, Field $field): bool|DeformatterR
}

// Weak mode.
if ($field->nullable && is_null($value)) {
return null;
}
return (bool)($decoded[$field->serializedName]);
}

Expand All @@ -98,6 +107,9 @@ public function deserializeString(mixed $decoded, Field $field): string|Deformat
}

// Weak mode.
if ($field->nullable && is_null($value)) {
return null;
}
return (string)($value);
}

Expand Down
22 changes: 22 additions & 0 deletions tests/NonStrict/NonStrictNullableProperties.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Crell\Serde\NonStrict;

use Crell\Serde\Attributes\Field;

class NonStrictNullableProperties
{
public function __construct(
#[Field(strict: false)]
public readonly ?int $int = null,
#[Field(strict: false)]
public readonly ?float $float = null,
#[Field(strict: false)]
public readonly ?string $string = null,
#[Field(strict: false)]
public readonly ?bool $bool = null,
) {
}
}
4 changes: 4 additions & 0 deletions tests/SerdeTestCases.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Crell\Serde\Attributes\StaticTypeMap;
use Crell\Serde\Attributes\TransitiveTypeField;
use Crell\Serde\Formatter\SupportsCollecting;
use Crell\Serde\NonStrict\NonStrictNullableProperties;
use Crell\Serde\PropertyHandler\Exporter;
use Crell\Serde\PropertyHandler\ObjectExporter;
use Crell\Serde\PropertyHandler\ObjectImporter;
Expand Down Expand Up @@ -316,6 +317,9 @@ public static function round_trip_examples(): iterable
yield 'empty_values' => [
'data' => new EmptyData('beep', null),
];
yield 'non_strict_null_stays_null' => [
'data' => new NonStrictNullableProperties(),
];
yield 'native_object_serialization' => [
'data' => new NativeSerUn(
1,
Expand Down
Loading