iterating through Doctrine's changeSet

2019-04-12 01:53发布

I am attempting to log specific actions users are taking on my site and have a listener check if certain entities are being updated, and if so, my goal is to log the fields they are editing, but not all the fields (some are not important or too long).

I have a problem saving the changeset to my database which is why I want to filter for important fields. This works to save the changeset, but when there are several nested arrays within the changeset, the array is not saved correctly (it cuts off after 3 or so arrays within arrays). I am using the array type in postgres. In my postupdate event I have:

if ($entity instanceof ListingQuery) {
        $entityManager = $eventArgs->getEntityManager();
        $ul = new UserLog();
        $uow = $entityManager->getUnitOfWork();
        $changeset = $uow->getEntityChangeSet($entity);
        $ul = new UserLog();
        $ul->setLog($changeset);
        $ul->setUser($entity->getUser());
        $entityManager->persist($ul);
        $entityManager->flush();
    }

I've been looking over the docs, but am not really sure how to iterate over the $changeset. It's a multidimension array that can have a variable amount of arrays within based on the number of fields updated. Userlog is a simple entity I have for saving the $changeset and the log field is an array.

I created a function that takes the $changeset and loops through the first three levels of the array, but its not saving the name of the field and only saves the values before and after. How do I access the field names changed in the $changeset?

1条回答
我只想做你的唯一
2楼-- · 2019-04-12 02:07

I think I have a solution that works well. It adds the entity type so it does not match the changeset exactly from Doctrine2, but I think works for my purpose. I found a bunch of other posts form people trying to log specific changes in Doctrine with mixed results so please post if anyone else has a better solution.

public function looparray($arr, $type) {
    $recordset[] = array($type);
    $keys[] = array_keys($arr);
    foreach ($keys as $key) {
        if (!is_array($key)) {
            if (array_key_exists($key, $arr)) {
                $recordset[] = array($key => $arr[$key]);
            }
        } else {
            foreach ($key as $key1) {
                if (!is_array([$key1])) {
                    $recordset[] = array($key1 => $arr[$key1]);
                } else {
                    if (!is_array([$key1])) {
                        $recordset[] = array($key1 => $arr[$key1]);
                    } else {
                        $recordset[] = array($key1 . ' changed ' => $key1);
                    }
                }
            }
        }
    }
    return $recordset;
}
查看更多
登录 后发表回答