diff --git a/src/Schematic/Entry.php b/src/Schematic/Entry.php index 33106f7..3de1707 100644 --- a/src/Schematic/Entry.php +++ b/src/Schematic/Entry.php @@ -11,6 +11,7 @@ class Entry const INDEX_ENTRYCLASS = 0; const INDEX_MULTIPLICITY = 1; const INDEX_EMBEDDING = 2; + const INDEX_NULLABLE = 3; /** * @var array @@ -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]), ]; } } @@ -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; } diff --git a/tests/SchematicTests/EntryTest.phpt b/tests/SchematicTests/EntryTest.phpt index ba7ad8a..12f69d4 100644 --- a/tests/SchematicTests/EntryTest.phpt +++ b/tests/SchematicTests/EntryTest.phpt @@ -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([ diff --git a/tests/SchematicTests/entries.php b/tests/SchematicTests/entries.php index 67f0936..ec0082d 100644 --- a/tests/SchematicTests/entries.php +++ b/tests/SchematicTests/entries.php @@ -26,7 +26,7 @@ class Order extends Identified { protected static $associations = [ - 'customer' => Customer::class, + '?customer' => Customer::class, 'orderItems[]' => OrderItem::class, ];