<?php
namespace PHPFUI\ORM;
class MorphMany extends \PHPFUI\ORM\VirtualField
{
public function getValue(array $parameters) : \PHPFUI\ORM\RecordCursor
{
$morphTableClass = \array_shift($parameters);
$morphTable = new $morphTableClass();
$morphFieldPrefix = \array_shift($parameters);
$condition = new \PHPFUI\ORM\Condition($morphFieldPrefix . '_type', $this->currentRecord->getTableName());
$primaryKey = $this->currentRecord->getPrimaryKeys()[0];
$condition->and($morphFieldPrefix . \PHPFUI\ORM::$idSuffix, $this->currentRecord->{$primaryKey});
$morphTable->setWhere($condition);
$orderBy = \array_shift($parameters);
$sort = \array_shift($parameters) ?? 'asc';
if ($orderBy)
{
$morphTable->addOrderBy($orderBy, $sort);
}
return $morphTable->getRecordCursor();
}
public function setValue(mixed $value, array $parameters) : void
{
$morphTableClass = \array_shift($parameters);
$morphTable = new $morphTableClass();
$morphFieldPrefix = \array_shift($parameters);
$primaryKey = $this->currentRecord->getPrimaryKeys()[0];
$morphTypeField = $morphFieldPrefix . '_type';
$morphIdField = $morphFieldPrefix . \PHPFUI\ORM::$idSuffix;
$value->{$morphTypeField} = $this->currentRecord->getTableName();
$primaryKeyValue = $this->currentRecord->{$primaryKey};
if (! $primaryKeyValue)
{
$this->currentRecord->insert();
$primaryKeyValue = $this->currentRecord->{$primaryKey};
}
$value->{$morphIdField} = $primaryKeyValue;
$value->insert();
}
}