Skip to content

Commit bf1f317

Browse files
committed
Better support for corecting types of virtual fields
1 parent 90a98d3 commit bf1f317

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

src/PHPFUI/ORM/Record.php

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -421,41 +421,47 @@ public function loadFromSQL(string $sql, array $input = []) : bool
421421
$this->empty = false;
422422
$this->loaded = true;
423423

424+
$this->correctTypes();
425+
426+
return true;
427+
}
428+
429+
protected function correctTypes() : static
430+
{
424431
// cast to correct values as ints, floats, etc are read in from PDO as strings
425432
foreach (static::$fields as $field => $row)
426433
{
427-
if (null !== $this->current[$field])
434+
$relationship = static::$virtualFields[$field] ?? false;
435+
436+
if (\is_array($relationship))
437+
{
438+
$relationshipClass = \array_shift($relationship);
439+
$relationshipObject = new $relationshipClass($this, $field);
440+
$relationshipObject->setValue($relationshipObject->fromPHPValue($this->current[$field], $relationship), $relationship);
441+
}
442+
else if (\array_key_exists($field, $this->current))
428443
{
429444
switch ($row[1])
430445
{
431446
case 'int':
432-
if (\array_key_exists($field, $this->current))
433-
{
434-
$this->current[$field] = (int)$this->current[$field];
435-
}
447+
$this->current[$field] = (int)$this->current[$field];
436448

437449
break;
438450

439451
case 'float':
440-
if (\array_key_exists($field, $this->current))
441-
{
442-
$this->current[$field] = (float)$this->current[$field];
443-
}
452+
$this->current[$field] = (float)$this->current[$field];
444453

445454
break;
446455

447456
case 'bool':
448-
if (\array_key_exists($field, $this->current))
449-
{
450-
$this->current[$field] = (bool)$this->current[$field];
451-
}
457+
$this->current[$field] = (bool)$this->current[$field];
452458

453459
break;
454460
}
455461
}
456462
}
457463

458-
return true;
464+
return $this;
459465
}
460466

461467
/**
@@ -524,6 +530,8 @@ public function setEmpty() : static
524530
$this->current[$field] = $description[self::DEFAULT_INDEX] ?? null;
525531
}
526532

533+
$this->correctTypes();
534+
527535
return $this;
528536
}
529537

@@ -543,10 +551,12 @@ public function setFrom(array $values, bool $loaded = false) : static
543551
if (isset(static::$fields[$field]))
544552
{
545553
$this->empty = false;
546-
$this->{$field} = $value;
554+
$this->current[$field] = $value;
547555
}
548556
}
549557

558+
$this->correctTypes();
559+
550560
return $this;
551561
}
552562

0 commit comments

Comments
 (0)