Skip to content

Commit

Permalink
Construct from text array
Browse files Browse the repository at this point in the history
  • Loading branch information
phpfui committed Oct 31, 2023
1 parent a399bbc commit de65d1e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
23 changes: 23 additions & 0 deletions Tests/DefinitionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -270,4 +270,27 @@ public function testMinLength() : void
$this->expectException(\PHPFUI\ConstantContact\Exception\InvalidLength::class);
$fixture->string = 'fred';
}

public function testDefaultObjects() : void
{
$address = [];
$address['created_at'] = (string)new \PHPFUI\ConstantContact\DateTime();
$address['permission_to_send'] = 'explicit';

$email_address = new \PHPFUI\ConstantContact\Definition\EmailAddressPut($address);
$contact = ['email_address' => $email_address];

$contactBody = new \PHPFUI\ConstantContact\Definition\ContactPutRequest($contact);
$contactBody->update_source = 'Account';
$contactBody->street_addresses = [new \PHPFUI\ConstantContact\Definition\StreetAddressPut([
'kind' => 'home',
'street' => 'address',
'city' => 'town',
'state' => 'state',
'postal_code' => 'zip',
'country' => 'USA', ])];
$json = $contactBody->getJSON();

$this->assertStringContainsString('created_at', $json);
}
}
9 changes: 8 additions & 1 deletion src/ConstantContact/Definition/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ abstract class Base
*/
protected static array $requiredFields = [];

/**
* @var bool $constructingFromArray set to true if we are constructing from an array so we don't type check for objects
*/
private bool $constructingFromArray = false;

/**
* $var array<string, mixed> the actual object data by field name.
*/
Expand Down Expand Up @@ -73,7 +78,9 @@ public function __construct(array $initialValues = [])

if (! empty(static::$fields[$field]))
{
$this->constructingFromArray = true;
$this->{$actualField} = $value;
$this->constructingFromArray = false;
}
elseif (! \is_array($type) && ! isset(self::$scalars[$type]))
{
Expand Down Expand Up @@ -172,7 +179,7 @@ public function __set(string $field, mixed $value)
}
}
}
elseif ($expectedType != $type)
elseif ($expectedType != $type && ! $this->constructingFromArray)
{
throw new \PHPFUI\ConstantContact\Exception\InvalidType(static::class . "::{$actualField} is of type {$type} but should be type {$expectedType}");
}
Expand Down

0 comments on commit de65d1e

Please sign in to comment.