Skip to content

Commit

Permalink
Merge pull request #56 from proophsoftware/feature/init_immutable_record
Browse files Browse the repository at this point in the history
Init method for immutable records
  • Loading branch information
codeliner authored Jan 25, 2018
2 parents 18ab984 + 323669d commit 54ce5a7
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Data/ImmutableRecordLogic.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,19 @@ private function __construct(array $recordData = null, array $nativeData = null)
$this->setNativeData($nativeData);
}

$this->init();

$this->assertAllNotNull();
}

/**
* Called in constructor after setting props but before not null assertion
*
* Override to set default props after construction
*/
private function init(): void {}


/**
* @param array $recordData
* @return self
Expand Down
11 changes: 11 additions & 0 deletions tests/Data/ImmutableRecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Prooph\EventMachine\JsonSchema\JsonSchema;
use Prooph\EventMachineTest\Data\Stubs\TestBuildingVO;
use Prooph\EventMachineTest\Data\Stubs\TestCommentVO;
use Prooph\EventMachineTest\Data\Stubs\TestDefaultPrice;
use Prooph\EventMachineTest\Data\Stubs\TestIdentityVO;
use Prooph\EventMachineTest\Data\Stubs\TestProduct;
use Prooph\EventMachineTest\Data\Stubs\TestProductVO;
Expand Down Expand Up @@ -171,4 +172,14 @@ public function it_uses_default_value_if_val_is_not_passed_to_constructor()

$this->assertEquals(['name' => 'My House', 'type' => 'house'], $testBuilding->toArray());
}

/**
* @test
*/
public function it_calls_init_to_give_immutable_record_the_chance_to_set_defaults_before_not_null_assertion()
{
$defaultPrice = TestDefaultPrice::fromArray([]);

$this->assertEquals(['amount' => 9.99, 'currency' => 'EUR'], $defaultPrice->toArray());
}
}
46 changes: 46 additions & 0 deletions tests/Data/Stubs/TestDefaultPrice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);

namespace Prooph\EventMachineTest\Data\Stubs;

use Prooph\EventMachine\Data\ImmutableRecord;
use Prooph\EventMachine\Data\ImmutableRecordLogic;

final class TestDefaultPrice implements ImmutableRecord
{
use ImmutableRecordLogic;

/**
* @var TestAmountVO
*/
private $amount;

/**
* @var TestCurrencyVO
*/
private $currency;

private function init(): void
{
$this->amount = TestAmountVO::fromFloat(9.99);
$this->currency = TestCurrencyVO::fromString('EUR');
}

/**
* @return TestAmountVO
*/
public function amount(): TestAmountVO
{
return $this->amount;
}

/**
* @return null|TestCurrencyVO
*/
public function currency(): TestCurrencyVO
{
return $this->currency;
}


}

0 comments on commit 54ce5a7

Please sign in to comment.