2024-06-03 23:46:39 +00:00
|
|
|
<?php declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Test\Unit\Mapper;
|
|
|
|
|
2024-06-08 03:06:31 +00:00
|
|
|
use BitBadger\PDODocument\{DocumentException, Field};
|
2024-06-04 12:10:57 +00:00
|
|
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
2024-06-03 23:46:39 +00:00
|
|
|
use PHPUnit\Framework\Attributes\TestDox;
|
|
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
|
|
|
|
// ** Test class hierarchy for serialization **
|
|
|
|
|
|
|
|
class SubDocument
|
|
|
|
{
|
|
|
|
public function __construct(public int $id = 0, public string $name = '') { }
|
|
|
|
}
|
|
|
|
|
|
|
|
class TestDocument
|
|
|
|
{
|
|
|
|
public function __construct(public int $id = 0, public SubDocument $subDoc = new SubDocument()) { }
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2024-06-04 12:10:57 +00:00
|
|
|
* Unit tests for the DocumentMapper class
|
2024-06-03 23:46:39 +00:00
|
|
|
*/
|
2024-06-04 12:10:57 +00:00
|
|
|
class DocumentMapperTest extends TestCase
|
2024-06-03 23:46:39 +00:00
|
|
|
{
|
|
|
|
public function testConstructorSucceedsWithDefaultField(): void
|
|
|
|
{
|
2024-06-04 12:10:57 +00:00
|
|
|
$mapper = new DocumentMapper(Field::class);
|
2024-06-03 23:46:39 +00:00
|
|
|
$this->assertEquals('data', $mapper->fieldName, 'Default field name should have been "data"');
|
|
|
|
}
|
|
|
|
|
|
|
|
public function testConstructorSucceedsWithSpecifiedField(): void
|
|
|
|
{
|
2024-06-04 12:10:57 +00:00
|
|
|
$mapper = new DocumentMapper(Field::class, 'json');
|
2024-06-03 23:46:39 +00:00
|
|
|
$this->assertEquals('json', $mapper->fieldName, 'Field name not recorded correctly');
|
|
|
|
}
|
|
|
|
|
|
|
|
#[TestDox('Map succeeds with valid JSON')]
|
|
|
|
public function testMapSucceedsWithValidJSON(): void
|
|
|
|
{
|
2024-06-04 12:10:57 +00:00
|
|
|
$doc = (new DocumentMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']);
|
2024-06-03 23:46:39 +00:00
|
|
|
$this->assertNotNull($doc, 'The document should not have been null');
|
|
|
|
$this->assertEquals(7, $doc->id, 'ID not filled correctly');
|
|
|
|
$this->assertNotNull($doc->subDoc, 'The sub-document should not have been null');
|
|
|
|
$this->assertEquals(22, $doc->subDoc->id, 'Sub-document ID not filled correctly');
|
|
|
|
$this->assertEquals('tester', $doc->subDoc->name, 'Sub-document name not filled correctly');
|
|
|
|
}
|
|
|
|
|
|
|
|
#[TestDox('Map fails with invalid JSON')]
|
|
|
|
public function testMapFailsWithInvalidJSON(): void
|
|
|
|
{
|
|
|
|
$this->expectException(DocumentException::class);
|
2024-06-04 12:10:57 +00:00
|
|
|
(new DocumentMapper(TestDocument::class))->map(['data' => 'this is not valid']);
|
2024-06-03 23:46:39 +00:00
|
|
|
}
|
|
|
|
}
|