collection-crud/src/Repository/AcquireTrait.php

43 lines
1.1 KiB
PHP
Raw Normal View History

2018-02-14 15:08:03 -05:00
<?php declare(strict_types=1);
namespace App\Repository;
2018-02-14 15:08:03 -05:00
use ReflectionObject;
use Throwable;
2018-02-14 15:08:03 -05:00
2022-03-03 10:53:48 -05:00
trait AcquireTrait
{
/**
* Move a record from the table represented by $currentRecord
* into the table represented by $newRecord
*
* @param mixed $currentRecord
* @param mixed $newRecord
*/
protected function moveRecord($currentRecord, $newRecord): void
{
$em = $this->getEntityManager();
2018-02-14 15:08:03 -05:00
2022-03-03 10:53:48 -05:00
$old = new ReflectionObject($currentRecord);
$new = new ReflectionObject($newRecord);
2018-02-14 15:08:03 -05:00
2022-03-03 10:53:48 -05:00
foreach ($old->getProperties() as $property) {
$propertyName = $property->getName();
if ($new->hasProperty($propertyName)) {
$newProperty = $new->getProperty($propertyName);
2022-03-03 11:15:12 -05:00
$newProperty->setAccessible(TRUE);
$property->setAccessible(TRUE);
2022-03-03 10:53:48 -05:00
$newProperty->setValue($newRecord, $property->getValue($currentRecord));
}
}
2018-02-14 15:08:03 -05:00
2022-03-03 10:53:48 -05:00
try {
$em->persist($newRecord);
$em->remove($currentRecord);
$em->flush();
} catch (Throwable) {
dump($newRecord);
}
}
2018-02-14 15:08:03 -05:00
}