@@ -24,18 +24,25 @@ class ArrayBinding implements Binding
2424 */
2525 private $ type ;
2626
27+ /**
28+ * @var bool
29+ */
30+ private $ isRequired ;
31+
2732 /**
2833 * ArrayBinding constructor.
2934 *
30- * @param string $property the property to bind to
31- * @param string $jsonField the json field
32- * @param string $type the desired type of the property
35+ * @param string $property the property to bind to
36+ * @param string $jsonField the json field
37+ * @param string $type the desired type of the property
38+ * @param bool $isRequired defines if the field value is required during decoding
3339 */
34- public function __construct ($ property , $ jsonField , $ type )
40+ public function __construct ($ property , $ jsonField , $ type, $ isRequired = false )
3541 {
3642 $ this ->property = $ property ;
3743 $ this ->jsonField = $ jsonField ;
3844 $ this ->type = $ type ;
45+ $ this ->isRequired = $ isRequired ;
3946 }
4047
4148 /**
@@ -51,21 +58,23 @@ public function __construct($property, $jsonField, $type)
5158 */
5259 public function bind ($ jsonDecoder , $ jsonData , $ propertyAccessor )
5360 {
54- if (!array_key_exists ($ this ->jsonField , $ jsonData )) {
55- throw new JsonValueException (
56- sprintf ('the value "%s" for property "%s" does not exist ' , $ this ->jsonField , $ this ->property )
57- );
58- }
61+ if (array_key_exists ($ this ->jsonField , $ jsonData )) {
62+ $ data = $ jsonData [$ this ->jsonField ];
63+ $ values = [];
5964
60- $ data = $ jsonData [$ this ->jsonField ];
61- $ values = [];
65+ if (is_array ($ data )) {
66+ foreach ($ data as $ item ) {
67+ $ values [] = $ jsonDecoder ->decodeArray ($ item , $ this ->type );
68+ }
6269
63- if (is_array ($ data )) {
64- foreach ($ data as $ item ) {
65- $ values [] = $ jsonDecoder ->decodeArray ($ item , $ this ->type );
70+ $ propertyAccessor ->set ($ values );
6671 }
72+ }
6773
68- $ propertyAccessor ->set ($ values );
74+ if ($ this ->isRequired ) {
75+ throw new JsonValueException (
76+ sprintf ('the value "%s" for property "%s" does not exist ' , $ this ->jsonField , $ this ->property )
77+ );
6978 }
7079 }
7180
0 commit comments