Skip to content

Commit 1f9e54d

Browse files
authored
Merge pull request #22 from square/custom-exception
Throw custom exception on missing required prop
2 parents f990d5a + 1afe844 commit 1f9e54d

File tree

3 files changed

+19
-4
lines changed

3 files changed

+19
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Square\Pjson\Exceptions;
4+
5+
use Exception;
6+
7+
class MissingRequiredPropertyException extends Exception
8+
{
9+
public function __construct(array $path, string $json)
10+
{
11+
parent::__construct(sprintf("missing property %s in %s", json_encode($path), $json));
12+
}
13+
}

src/Json.php

+4-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use Attribute;
55
use ReflectionNamedType;
66
use ReflectionProperty;
7+
use Square\Pjson\Exceptions\MissingRequiredPropertyException;
78
use Square\Pjson\Internal\RClass;
89
use Traversable;
910

@@ -64,7 +65,7 @@ public function retrieveValue(array $data, ?ReflectionNamedType $type = null)
6465
{
6566
foreach ($this->path as $pathBit) {
6667
if (!array_key_exists($pathBit, $data)) {
67-
return $this->handleMissingValue();
68+
return $this->handleMissingValue($data);
6869
}
6970
$data = $data[$pathBit];
7071
}
@@ -119,10 +120,10 @@ public function retrieveValue(array $data, ?ReflectionNamedType $type = null)
119120
/**
120121
* What happens when deserializing a property that isn't set.
121122
*/
122-
protected function handleMissingValue()
123+
protected function handleMissingValue($data)
123124
{
124125
if ($this->required) {
125-
throw new \Exception('missing required value: '.json_encode($this->path));
126+
throw new MissingRequiredPropertyException($this->path, json_encode($data));
126127
}
127128
return null;
128129
}

tests/DeSerializationTest.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
use PHPUnit\Framework\TestCase;
55
use ReflectionClass;
6+
use Square\Pjson\Exceptions\MissingRequiredPropertyException;
67
use Square\Pjson\Tests\Definitions\BigCat;
78
use Square\Pjson\Tests\Definitions\BigInt;
89
use Square\Pjson\Tests\Definitions\CatalogCategory;
@@ -562,7 +563,7 @@ public function testRequiredPropertyMissing()
562563
{
563564
$json = '{}';
564565

565-
$this->expectException(\Exception::class);
566+
$this->expectException(MissingRequiredPropertyException::class);
566567

567568
Token::fromJsonString($json);
568569
}

0 commit comments

Comments
 (0)