Skip to content

Commit 1d785bc

Browse files
committed
Merge pull request #277 from dunglas/fix_date_serializer
Better DateTime invalid format handling.
2 parents d73fa0c + d2c9792 commit 1d785bc

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

JsonLd/Serializer/DateTimeNormalizer.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
namespace Dunglas\ApiBundle\JsonLd\Serializer;
1313

14+
use Dunglas\ApiBundle\Exception\DeserializationException;
1415
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
1516
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
1617

@@ -53,6 +54,10 @@ public function normalize($object, $format = null, array $context = [])
5354
*/
5455
public function denormalize($data, $class, $format = null, array $context = [])
5556
{
56-
return new \DateTime($data);
57+
try {
58+
return new \DateTime($data);
59+
} catch (\Exception $exception) {
60+
throw new DeserializationException($exception->getMessage(), $exception->getCode(), $exception);
61+
}
5762
}
5863
}

Tests/Behat/TestBundle/Entity/Dummy.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ public function setFoo(array $foo = null)
129129
{
130130
}
131131

132-
public function setDummyDate(\DateTime $dummyDate)
132+
public function setDummyDate(\DateTime $dummyDate = null)
133133
{
134134
$this->dummyDate = $dummyDate;
135135
}

features/invalid_data.feature

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ Feature: Handle properly invalid data submitted to the API
3232
}
3333
"""
3434

35+
Scenario: Ignore invalid dates
36+
When I send a "POST" request to "/dummies" with body:
37+
"""
38+
{
39+
"name": "Invalid date",
40+
"dummyDate": "Invalid"
41+
}
42+
"""
43+
Then the response status code should be 400
44+
And the response should be in JSON
45+
And the header "Content-Type" should be equal to "application/ld+json"
46+
3547
@dropSchema
3648
Scenario: Send non-array data when an array is expected
3749
When I send a "POST" request to "/dummies" with body:

0 commit comments

Comments
 (0)