64 lines
2.0 KiB
PHP
64 lines
2.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace KTXF\Json;
|
|
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/**
|
|
* Test for JsonSerializableObject base functionality
|
|
*/
|
|
class JsonSerializableObjectTest extends TestCase
|
|
{
|
|
public function testJsonSerializeReturnsObjectVars(): void
|
|
{
|
|
$testObject = new class extends JsonSerializableObject {
|
|
public string $publicProperty = 'test';
|
|
private string $privateProperty = 'private';
|
|
protected string $protectedProperty = 'protected';
|
|
};
|
|
|
|
$serialized = $testObject->jsonSerialize();
|
|
|
|
$this->assertIsArray($serialized);
|
|
$this->assertArrayHasKey('publicProperty', $serialized);
|
|
$this->assertEquals('test', $serialized['publicProperty']);
|
|
$this->assertArrayHasKey('protectedProperty', $serialized); // get_object_vars includes protected
|
|
$this->assertEquals('protected', $serialized['protectedProperty']);
|
|
$this->assertArrayNotHasKey('privateProperty', $serialized); // but not private
|
|
}
|
|
|
|
public function testJsonDeserializeSetsProperties(): void
|
|
{
|
|
$testObject = new class extends JsonSerializableObject {
|
|
public string $name = '';
|
|
public int $age = 0;
|
|
};
|
|
|
|
$data = [
|
|
'name' => 'John Doe',
|
|
'age' => 30,
|
|
'nonexistent' => 'ignored'
|
|
];
|
|
|
|
$result = $testObject->jsonDeserialize($data);
|
|
|
|
$this->assertSame($testObject, $result);
|
|
$this->assertEquals('John Doe', $testObject->name);
|
|
$this->assertEquals(30, $testObject->age);
|
|
$this->assertObjectNotHasProperty('nonexistent', $testObject);
|
|
}
|
|
|
|
public function testJsonDeserializeHandlesJsonString(): void
|
|
{
|
|
$testObject = new class extends JsonSerializableObject {
|
|
public string $message = '';
|
|
};
|
|
|
|
$jsonString = '{"message": "Hello World"}';
|
|
$testObject->jsonDeserialize($jsonString);
|
|
|
|
$this->assertEquals('Hello World', $testObject->message);
|
|
}
|
|
} |