Skip to content

Commit

Permalink
Implemented nullable association using empty
Browse files Browse the repository at this point in the history
  • Loading branch information
stekycz committed Mar 1, 2017
1 parent 0d49e40 commit 5f49ba6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
16 changes: 9 additions & 7 deletions src/Schematic/Entry.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Entry
const INDEX_ENTRYCLASS = 0;
const INDEX_MULTIPLICITY = 1;
const INDEX_EMBEDDING = 2;
const INDEX_NULLABLE = 3;

/**
* @var array
Expand Down Expand Up @@ -64,18 +65,19 @@ private static function parseAssociations($class)

foreach (static::$associations as $association => $entryClass) {
$matches = [];
$result = preg_match('#^([^.[\]]+)(\.[^.[\]]*)?(\[\])?$#', $association, $matches);
$result = preg_match('#^(\?)?([^.[\]]+)(\.[^.[\]]*)?(\[\])?$#', $association, $matches);

if ($result === 0 || (!empty($matches[2]) && !empty($matches[3]))) {
if ($result === 0 || (!empty($matches[3]) && !empty($matches[4]))) {
throw new InvalidArgumentException('Invalid association definition given: ' . $association);
}

self::$parsedAssociations[$class][$matches[1]] = [
self::$parsedAssociations[$class][$matches[2]] = [
self::INDEX_ENTRYCLASS => $entryClass,
self::INDEX_MULTIPLICITY => !empty($matches[3]),
self::INDEX_EMBEDDING => !empty($matches[2]) ?
($matches[2] === '.' ? $matches[1] . '_' : substr($matches[2], 1)) :
self::INDEX_MULTIPLICITY => !empty($matches[4]),
self::INDEX_EMBEDDING => !empty($matches[3]) ?
($matches[3] === '.' ? $matches[2] . '_' : substr($matches[3], 1)) :
FALSE,
self::INDEX_NULLABLE => !empty($matches[1]),
];
}
}
Expand All @@ -101,7 +103,7 @@ public function __get($name)
$this->readEmbeddedEntry($association[self::INDEX_EMBEDDING]) :
$this->readData($name);

if ($data === NULL) {
if ($data === NULL || ($association[self::INDEX_NULLABLE] && empty($data))) {
return $this->data[$name] = NULL;
}

Expand Down
10 changes: 10 additions & 0 deletions tests/SchematicTests/EntryTest.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ class EntryTest extends TestCase
}


public function testEntriesAccessToNullableParameter()
{
$order = new Order([
'customer' => [],
'orderItems' => [],
]);
Assert::null($order->customer);
}


public function testEntriesClass()
{
$order = new Order([
Expand Down
2 changes: 1 addition & 1 deletion tests/SchematicTests/entries.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class Order extends Identified
{

protected static $associations = [
'customer' => Customer::class,
'?customer' => Customer::class,
'orderItems[]' => OrderItem::class,
];

Expand Down

0 comments on commit 5f49ba6

Please sign in to comment.