Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Hydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ public function hydrate(array $data, Model $model)
} else {
$subjectClass = $relation->getTargetClass();
$subject = new $subjectClass();
$subject->setRelation($relation);
$parent->$relationName = $subject;
}
}
Expand Down Expand Up @@ -187,6 +188,7 @@ public function hydrate(array $data, Model $model)
if (! $subject->hasProperty($step)) {
$stepClass = $relation->getTargetClass();
$subject->$step = new $stepClass();
$subject->$step->setRelation($relation);
}

$subject = $subject->$step;
Expand Down
56 changes: 56 additions & 0 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ abstract class Model implements \ArrayAccess, \IteratorAggregate
{
use PropertiesWithDefaults;

private $relation;

public function setRelation(Relation $relation)
{
$this->relation = $relation;
}

private $nullableProperties;

final public function __construct(array $properties = null)
{
if ($this->hasProperties()) {
Expand Down Expand Up @@ -140,4 +149,51 @@ public function createRelations(Relations $relations)
protected function init()
{
}

private function nullableColumns()
{
if ($this->nullableProperties !== null) {
return $this->nullableProperties;
}

if ($this->relation === null) {
$this->nullableProperties = (function (): array {
$ref = new \ReflectionClass($this);
$doc = $ref->getDocComment();
preg_match_all('/@property\s+([^\s]+)\s+\$([^\s]+)/', $doc, $matches);
$cols = [];
foreach ($matches[1] as $i => $type) {
if (strpos($type, '?') === 0 || preg_match('~\|?null\|?~', $type)) {
$cols[] = $matches[2][$i];
}
}

return $cols;
})();
} elseif ($this->relation->getJoinType() === 'LEFT') {
$this->nullableProperties = array_merge($this->getColumns(), (array) $this->getKeyName());
} else {
$this->nullableProperties = [];
}

return $this->nullableProperties;
}

public function __get($key)
{
if (in_array($key, $this->nullableColumns(), true)) {
return null;
}

return $this->getProperty($key);
}

public function __isset($key)
{
if (in_array($key, $this->nullableColumns(), true)) {
return false;
}

return $this->hasProperty($key);
}
}