Skip to content

Commit de65d1e

Browse files
committed
Construct from text array
1 parent a399bbc commit de65d1e

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

Tests/DefinitionTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,4 +270,27 @@ public function testMinLength() : void
270270
$this->expectException(\PHPFUI\ConstantContact\Exception\InvalidLength::class);
271271
$fixture->string = 'fred';
272272
}
273+
274+
public function testDefaultObjects() : void
275+
{
276+
$address = [];
277+
$address['created_at'] = (string)new \PHPFUI\ConstantContact\DateTime();
278+
$address['permission_to_send'] = 'explicit';
279+
280+
$email_address = new \PHPFUI\ConstantContact\Definition\EmailAddressPut($address);
281+
$contact = ['email_address' => $email_address];
282+
283+
$contactBody = new \PHPFUI\ConstantContact\Definition\ContactPutRequest($contact);
284+
$contactBody->update_source = 'Account';
285+
$contactBody->street_addresses = [new \PHPFUI\ConstantContact\Definition\StreetAddressPut([
286+
'kind' => 'home',
287+
'street' => 'address',
288+
'city' => 'town',
289+
'state' => 'state',
290+
'postal_code' => 'zip',
291+
'country' => 'USA', ])];
292+
$json = $contactBody->getJSON();
293+
294+
$this->assertStringContainsString('created_at', $json);
295+
}
273296
}

src/ConstantContact/Definition/Base.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ abstract class Base
3333
*/
3434
protected static array $requiredFields = [];
3535

36+
/**
37+
* @var bool $constructingFromArray set to true if we are constructing from an array so we don't type check for objects
38+
*/
39+
private bool $constructingFromArray = false;
40+
3641
/**
3742
* $var array<string, mixed> the actual object data by field name.
3843
*/
@@ -73,7 +78,9 @@ public function __construct(array $initialValues = [])
7378

7479
if (! empty(static::$fields[$field]))
7580
{
81+
$this->constructingFromArray = true;
7682
$this->{$actualField} = $value;
83+
$this->constructingFromArray = false;
7784
}
7885
elseif (! \is_array($type) && ! isset(self::$scalars[$type]))
7986
{
@@ -172,7 +179,7 @@ public function __set(string $field, mixed $value)
172179
}
173180
}
174181
}
175-
elseif ($expectedType != $type)
182+
elseif ($expectedType != $type && ! $this->constructingFromArray)
176183
{
177184
throw new \PHPFUI\ConstantContact\Exception\InvalidType(static::class . "::{$actualField} is of type {$type} but should be type {$expectedType}");
178185
}

0 commit comments

Comments
 (0)