<commit_before><?php
/**
 * This file is part of the Juvem package.
 *
 * (c) <NAME> <<EMAIL>>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AppBundle\EventListeners;


use AppBundle\Entity\ChangeTracking\EntityChange;
use AppBundle\Entity\ChangeTracking\EntityCollectionChange;
use AppBundle\Entity\ChangeTracking\ScheduledEntityChange;
use AppBundle\Entity\ChangeTracking\SpecifiesChangeTrackingComparableRepresentationInterface;
use AppBundle\Entity\ChangeTracking\SpecifiesChangeTrackingStorableRepresentationInterface;
use AppBundle\Entity\ChangeTracking\SupportsChangeTrackingInterface;
use AppBundle\Entity\User;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\PersistentCollection;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class ChangeTrackingListener
{
    /**
     * Token storage interface
     *
     * @var TokenStorageInterface
     */
    private $tokenStorage;
    
    /**
     * @var LoggerInterface
     */
    private $logger;
    
    /**
     * List of {@see EntityChange} scheduled to be persisted
     *
     * @var \SplQueue
     */
    private $changes;
    
    /**
     * ChangeTrackingListener constructor.
     *
     * @param TokenStorageInterface $tokenStorage
     * @param LoggerInterface $logger
     */
    public function __construct(TokenStorageInterface $tokenStorage, LoggerInterface $logger)
    {
        $this->tokenStorage = $tokenStorage;
        $this->logger       = $logger;
        $this->changes      = new \SplQueue();
    }
    
    /**
     * Update entity
     *
     * @param PreUpdateEventArgs $args Pre update args
     */
    public function preUpdate(PreUpdateEventArgs $args): void
    {
        $entity = $args->getEntity();
        if (!$entity instanceof SupportsChangeTrackingInterface) {
            return;
        }
        $changes = $args->getEntityChangeSet();
        
        $change = $this->getScheduledChangeForEntity($entity);
        if (!$change) {
            $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_UPDATE);
        }
        if (array_key_exists('deletedAt', $changes)) {
            $change->setOperation(
                ($changes['deletedAt'][1] === null)
                    ? EntityChange::OPERATION_RESTORE : EntityChange::OPERATION_TRASH
            );
        }
        if (array_key_exists('modifiedAt', $changes)) {
            $change->setOccurrenceDate($changes['modifiedAt'][1]);
        }
        
        foreach ($changes as $attribute => $values) {
            if ($attribute === 'deletedAt' || $attribute === 'modifiedAt') {
                //do not treat deletedAt changes as update
                continue;
            }
            $comparableBefore = $this->getComparableRepresentation($attribute, $entity, $values[0]);
            $comparableAfter  = $this->getComparableRepresentation($attribute, $entity, $values[1]);
            
            if (is_float($comparableBefore) || is_float($comparableAfter)) {
                $comparableBefore = ($comparableBefore === null) ?: round($comparableBefore, 10);
                $comparableAfter  = ($comparableAfter === null) ?: round($comparableAfter, 10);
            }
            
            if ($comparableBefore !== $comparableAfter) {
                $change->addAttributeChange(
                    $attribute,
                    $this->getStorableRepresentation($attribute, $entity, $values[0]),
                    $this->getStorableRepresentation($attribute, $entity, $values[1])
                );
            }
        }
        if (count($change) || $change->getOperation() !== EntityChange::OPERATION_UPDATE) {
            $this->changes->enqueue($change);
        }
    }
    
    /**
     * On entity remove
     *
     * @param LifecycleEventArgs $args
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if (!$entity instanceof SupportsChangeTrackingInterface) {
            return;
        }
        $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_DELETE);
        $this->changes->enqueue($change);
    }
    
    /**
     * On entity flush check for entity inserts & deletes
     *
     * @param OnFlushEventArgs $args
     */
    public function onFlush(OnFlushEventArgs $args)
    {
        $em  = $args->getEntityManager();
        $uow = $em->getUnitOfWork();
        
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
            if ($entity instanceof SupportsChangeTrackingInterface) {
                $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_CREATE);
                $this->changes->enqueue($change);
            }
        }
        unset($entity);
        
        foreach ($uow->getScheduledEntityDeletions() as $entity) {
            if ($entity instanceof SupportsChangeTrackingInterface) {
                $change = $this->createChangeTrackingEntity(
                    $entity,
                    EntityChange::OPERATION_DELETE
                );
                $this->changes->enqueue($change);
            }
        }
        unset($entity);
        
        /** @var PersistentCollection $collection */
        foreach ($uow->getScheduledCollectionUpdates() as $collection) {
            $entity = $collection->getOwner();
            if (!$entity instanceof SupportsChangeTrackingInterface) {
                continue;
            }
            $change   = $this->getScheduledChangeForEntity($entity);
            $schedule = false;
            if (!$change) {
                $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_UPDATE);
            }
            
            $mapping = $collection->getMapping();
            if (!isset($mapping['fieldName'])) {
                $this->logger->warning(
                    'Collection of owner {ownerClass}:{ownerId} did not provide a fieldName in mapping',
                    [
                        'ownerClass' => get_class($collection->getOwner()),
                        'ownerId'    => $collection->getOwner()->getId(),
                    ]
                );
                continue;
            }
            $property = $mapping['fieldName'];<commit_msg>Now respecting excluded fields when looking for entity changes<commit_after><?php
/**
 * This file is part of the Juvem package.
 *
 * (c) <NAME> <<EMAIL>>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AppBundle\EventListeners;


use AppBundle\Entity\ChangeTracking\EntityChange;
use AppBundle\Entity\ChangeTracking\EntityCollectionChange;
use AppBundle\Entity\ChangeTracking\ScheduledEntityChange;
use AppBundle\Entity\ChangeTracking\SpecifiesChangeTrackingComparableRepresentationInterface;
use AppBundle\Entity\ChangeTracking\SpecifiesChangeTrackingStorableRepresentationInterface;
use AppBundle\Entity\ChangeTracking\SupportsChangeTrackingInterface;
use AppBundle\Entity\User;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\PersistentCollection;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class ChangeTrackingListener
{
    /**
     * Token storage interface
     *
     * @var TokenStorageInterface
     */
    private $tokenStorage;
    
    /**
     * @var LoggerInterface
     */
    private $logger;
    
    /**
     * List of {@see EntityChange} scheduled to be persisted
     *
     * @var \SplQueue
     */
    private $changes;
    
    /**
     * ChangeTrackingListener constructor.
     *
     * @param TokenStorageInterface $tokenStorage
     * @param LoggerInterface $logger
     */
    public function __construct(TokenStorageInterface $tokenStorage, LoggerInterface $logger)
    {
        $this->tokenStorage = $tokenStorage;
        $this->logger       = $logger;
        $this->changes      = new \SplQueue();
    }
    
    /**
     * Update entity
     *
     * @param PreUpdateEventArgs $args Pre update args
     */
    public function preUpdate(PreUpdateEventArgs $args): void
    {
        $entity = $args->getEntity();
        if (!$entity instanceof SupportsChangeTrackingInterface) {
            return;
        }
        $changes = $args->getEntityChangeSet();
        
        $change = $this->getScheduledChangeForEntity($entity);
        if (!$change) {
            $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_UPDATE);
        }
        if (array_key_exists('deletedAt', $changes)) {
            $change->setOperation(
                ($changes['deletedAt'][1] === null)
                    ? EntityChange::OPERATION_RESTORE : EntityChange::OPERATION_TRASH
            );
        }
        if (array_key_exists('modifiedAt', $changes)) {
            $change->setOccurrenceDate($changes['modifiedAt'][1]);
        }
        
        foreach ($changes as $attribute => $values) {
            if ($attribute === 'deletedAt' || $attribute === 'modifiedAt'
                || in_array($attribute, $entity::getExcludedAttributes())) {
                //do not treat deletedAt changes as update
                continue;
            }
            $comparableBefore = $this->getComparableRepresentation($attribute, $entity, $values[0]);
            $comparableAfter  = $this->getComparableRepresentation($attribute, $entity, $values[1]);
            
            if (is_float($comparableBefore) || is_float($comparableAfter)) {
                $comparableBefore = ($comparableBefore === null) ?: round($comparableBefore, 10);
                $comparableAfter  = ($comparableAfter === null) ?: round($comparableAfter, 10);
            }
            
            if ($comparableBefore !== $comparableAfter) {
                $change->addAttributeChange(
                    $attribute,
                    $this->getStorableRepresentation($attribute, $entity, $values[0]),
                    $this->getStorableRepresentation($attribute, $entity, $values[1])
                );
            }
        }
        if (count($change) || $change->getOperation() !== EntityChange::OPERATION_UPDATE) {
            $this->changes->enqueue($change);
        }
    }
    
    /**
     * On entity remove
     *
     * @param LifecycleEventArgs $args
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if (!$entity instanceof SupportsChangeTrackingInterface) {
            return;
        }
        $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_DELETE);
        $this->changes->enqueue($change);
    }
    
    /**
     * On entity flush check for entity inserts & deletes
     *
     * @param OnFlushEventArgs $args
     */
    public function onFlush(OnFlushEventArgs $args)
    {
        $em  = $args->getEntityManager();
        $uow = $em->getUnitOfWork();
        
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
            if ($entity instanceof SupportsChangeTrackingInterface) {
                $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_CREATE);
                $this->changes->enqueue($change);
            }
        }
        unset($entity);
        
        foreach ($uow->getScheduledEntityDeletions() as $entity) {
            if ($entity instanceof SupportsChangeTrackingInterface) {
                $change = $this->createChangeTrackingEntity(
                    $entity,
                    EntityChange::OPERATION_DELETE
                );
                $this->changes->enqueue($change);
            }
        }
        unset($entity);
        
        /** @var PersistentCollection $collection */
        foreach ($uow->getScheduledCollectionUpdates() as $collection) {
            $entity = $collection->getOwner();
            if (!$entity instanceof SupportsChangeTrackingInterface) {
                continue;
            }
            $change   = $this->getScheduledChangeForEntity($entity);
            $schedule = false;
            if (!$change) {
                $change = $this->createChangeTrackingEntity($entity, EntityChange::OPERATION_UPDATE);
            }
            
            $mapping = $collection->getMapping();
            if (!isset($mapping['fieldName'])) {
                $this->logger->warning(
                    'Collection of owner {ownerClass}:{ownerId} did not provide a fieldName in mapping',
                    [
                        'ownerClass' => get_class($collection->getOwner()),
                        'ownerId'    => $collection->getOwner()->getId(),
                    ]
                );
                continue;
            }
            $property = $mapping['fieldName'];
            if (in_array($property, $entity::getExcludedAttributes())) {
                continue;
            }
{'fraction_non_alphanumeric': 0.11514195583596215, 'fraction_numerical': 0.0015021781583295778, 'mean_word_length': 2.196111377820451, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 97, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3398275', 'n_tokens_mistral': 3427, 'n_tokens_neox': 3375, 'n_words': 645}