lean-api/src/Form/Save.php

91 lines
3.0 KiB
PHP

<?php
namespace Lean\Api\Form;
use CSLSJ\Lean\Form\Session\EmailContext;
use Picea\Ui\Method\{ FormContextInterface, };
use Ulmus\Attribute\Property\Field;
use Lean\Api\Attribute\EntityField;
use Ulmus\Entity\EntityInterface;
use Ulmus\Entity\Field\Datetime;
abstract class Save implements \Picea\Ui\Method\FormInterface {
use FormTrait;
protected string $contextClass;
public function validate(FormContextInterface $context) : bool
{
# Context is validating inputs
return $context->valid($this->getEntity()->isLoaded() ? $this->getEntity() : null);
}
public function execute(FormContextInterface $context) : mixed
{
$entity = $this->getEntity();
if ($entity->isLoaded()) {
if (property_exists($entity, 'updatedAt') && $entity->repository()->generateDatasetDiff($entity) ) {
$entity->updatedAt = new Datetime();
}
}
else {
if (property_exists($entity, 'createdAt') && empty($entity->createdAt)) {
$entity->createdAt = new Datetime();
}
}
try {
$this->assignContextToEntity($context);
if ( $saved = $entity::repository()->save($entity) ) {
$context->pushMessage($this->message::generateSuccess(
$this->lang('lean.api.form.save.success.entity')
));
}
else {
$context->pushMessage($this->message::generateWarning(
$this->lang('lean.api.form.save.error.entity', [ 'entity' => $this->entity::class ])
));
}
}
catch(\PDOException $ex) {
throw new \PDOException($this->lang('lean.api.form.save.error.pdo', [ 'error' => $ex->getMessage() ]));
}
catch(\Throwable $ex) {
throw $ex;
}
return $saved;
}
protected function assignContextToEntity(FormContextInterface $context) : void
{
$entity = $this->getEntity();
foreach($entity::resolveEntity()->fieldList() as $key => $property) {
$field = $property->getAttribute(Field::class)->object;
if (! $field->readonly || ! $entity->isLoaded()) {
$apiField = $property->getAttribute(EntityField::class)->object ?? null;
if ($apiField) {
$var = $apiField->field ?: $key;
if ( property_exists($context, $var) && ( new \ReflectionProperty($context, $var) )->isInitialized($context) ) {
if ($apiField->setterMethod) {
# Use a setter method
call_user_func([ $entity, $apiField->setterMethod ], $context->{$var});
}
else {
# Direct property set
$entity->$key = $context->{$var};
}
}
}
}
}
}
}