Git Product home page Git Product logo

Comments (4)

ronisaha avatar ronisaha commented on June 12, 2024

The changes made to simplify the entity event resolver. You can still copy the code from the older version and create your own EntityEventResolver by implementing Xiidea\EasyAuditBundle\Resolver\EventResolverInterface.

xiidea_easy_audit:
     ...       
    entity_event_resolver : App\Resolver\EntityEventResolver     
    
services:
    App\Resolver\EntityEventResolver: ~

The bundled EntityEventResolver is just an implementation example to support general cases. As not every body wants to use the name property to describe the description.

Have a nice day!

from easyauditbundle.

braianj avatar braianj commented on June 12, 2024

Thanks for your quick response.
Yes I got my own implementation

<?php
namespace LoginBundle\Resolver;
use Symfony\Component\EventDispatcher\Event;
use Xiidea\EasyAuditBundle\Events\DoctrineEntityEvent;
use Xiidea\EasyAuditBundle\Resolver\EntityEventResolver as BaseResolver;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Psr\Log\LoggerInterface;

class EntityEventResolver extends BaseResolver
{

    private $logger;
    private $serializer;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @param Event|DoctrineEntityEvent $event
     * @param $eventName
     *
     * @return array
     */
    public function getEventLogInfo(Event $event, $eventName)
    {
        if (!$event instanceof DoctrineEntityEvent) {
            return null;
        }
        $this->initialize($event, $eventName);
        $changesMetaData = $this->getChangeSets($this->entity);

        if ($this->isUpdateEvent() && $changesMetaData == NULL) {
            return NULL;
        }
        $reflectionClass = $this->getReflectionClassFromObject($this->entity);
        $typeName = $reflectionClass->getShortName();
        //$eventType = $this->getEventType($typeName);
        $eventDescription = $this->getDescriptionString($reflectionClass, $typeName);

        $datos = [];
        $ignorar = array('tu', 'ts', 'updated', 'created', 'transitions', '__initializer__', '__cloner__', '__isInitialized__', 'timezone', 'salt', 'password', 'nuevoPassword');


        if (empty($changesMetaData)) {
            $encoder = new JsonEncoder();
            $normalizer = new ObjectNormalizer();

            $this->serializer = new Serializer(array($normalizer), array($encoder));

            $reflClass = new \ReflectionClass($this->entity);

            $arrayDatos = [];
            foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflMethod) {
                if (
                    0 !== $reflMethod->getNumberOfRequiredParameters() ||
                    $reflMethod->isStatic() ||
                    $reflMethod->isConstructor() ||
                    $reflMethod->isDestructor()
                ) {
                    continue;
                }

                $name = $reflMethod->name;
                $attributeName = null;

                if (0 === strpos($name, 'get') || 0 === strpos($name, 'has')) {
                    // getters and hassers
                    $attributeName = substr($name, 3);

                    if (!$reflClass->hasProperty($attributeName)) {
                        $attributeName = lcfirst($attributeName);
                    }
                } elseif (0 === strpos($name, 'is')) {
                    // issers
                    $attributeName = substr($name, 2);

                    if (!$reflClass->hasProperty($attributeName)) {
                        $attributeName = lcfirst($attributeName);
                    }
                }

                if (!is_null($attributeName) && !in_array($attributeName, $ignorar))
                {
                    $val = $this->entity->$name();

                    $es_colecion = (is_array($val) || ($val instanceof \ArrayAccess && $val instanceof \Traversable));

                    if(!$es_colecion) {
                        $arrayDatos[$attributeName] = $this->extraerValor($val);
                    } else {
                        $arrayDatos[$attributeName] = [];
                        foreach ($val as $item) {
                            $arrayDatos[$attributeName][] = $this->extraerValor($item);
                        }
                    }
                }
            }

            $datos = $this->serializer->serialize($arrayDatos,'json');

        } elseif (is_string($changesMetaData)) {
            // porque esta esto??????
            $datos = $changesMetaData;
        } else {
            foreach ($changesMetaData as $key => $value) {
                if($value[0]!=$value[1] && !in_array($key, $ignorar)) {
                    if(gettype($value[0])== 'object') {

                        $entity = null;
                        foreach (explode('\\',get_class($value[0])) as $v) {
                            $entity = $v;
                        }

                        if((method_exists($value[0], 'getId'))) {

                            $value1 = $value[0]->getId();
                            $value2 = is_null($value[1]) ? null : $value[1]->getId();
                            $datos[$key] = array('entity' => $entity, 'id' => array($value1, $value2));

                        } else {
                            $value1 = $this->isDateOrNot($value[0]);
                            $value2 = $this->isDateOrNot($value[1]);
                            $datos[$key] = array($value1, $value2);
                        }
                    } else {
                        $datos[$key] = $value;
                    }
                }
            }
            if (!empty($datos)) {
                $datos = json_encode($datos);
            }
        }

        $infoFinal = array(
            'table'         => $typeName,
            'type'          => $this->traducirType(),
            'description'   => $eventDescription,
        );

        if ($typeName!='Agentes') {
            $infoFinal['tableId'] = $this->getProperty('id');
        }

        if (!empty($datos)) {
            $infoFinal['data'] = $datos;
        }
        return $infoFinal;
    }

    protected function extraerValor ($value) {
        $es_entidad = method_exists($value, 'getId');

        if($es_entidad) {
            return $value->getId();
        } elseif ($value instanceof \Date) {
            return $value->format("Y-m-d");
        } elseif ($value instanceof \DateTime) {
            return $value->format("Y-m-d H:i:s");
        } elseif (gettype($value)== 'object') {
            $value = json_encode($value, JSON_PRETTY_PRINT|JSON_ERROR_UNSUPPORTED_TYPE|JSON_PARTIAL_OUTPUT_ON_ERROR);
        }
        return $value;
    }

    /**
     * @param DoctrineEntityEvent $event
     * @param string $eventName
     */
    private function initialize(DoctrineEntityEvent $event, $eventName)
    {
        $this->eventShortName = null;
        $this->propertiesFound = array();
        $this->eventName = $eventName;
        $this->event = $event;
        $this->entity = $event->getLifecycleEventArgs()->getEntity();
    }

    protected function isDateOrNot($var) {
        if(is_a($var, 'DateTime')){
            return print_r(($var->format('H:i:s')!='00:00:00') ? $var->format('c') : $var->format('Y-m-d'), true);
        } else {
            return print_r($var, true);
        }
    }

    protected function getDescriptionString(\ReflectionClass $reflectionClass, $typeName)
    {
        $property = $this->getBestCandidatePropertyForIdentify($reflectionClass);
        $descriptionTemplate = '%s %s';//'%s ha sido %s ';
        if ($property) {
            $descriptionTemplate .= sprintf('.%s = %s', $property, $this->getProperty($property));
        }


        return sprintf($descriptionTemplate,
            $this->traducirType(),
            $typeName);
    }
    /**
     * @param $changesMetaData
     *
     * @return null|string
     */
    protected function getAsSerializedString($changesMetaData)
    {
        if (empty($changesMetaData)) {
            return NULL;
        } elseif (is_string($changesMetaData)) {
            return $changesMetaData;
        }
        return serialize($changesMetaData);
    }

    protected function traducirType() {
        $accion = null;
        switch ($this->getEventShortName()) {
            case 'created':
                $accion = 'Crear';
                break;

            case 'updated':
                $accion = 'Actualizar';
                break;

            case 'deleted':
                $accion = 'Eliminar';
                break;

            default:
                $accion = 'Acción';
                break;
        }
        return $accion;
    }
}

But I have conflight If I update the bundle or install in a new project, like today I spend 2 hours trying to fnd the error, so that's why I ask you to know if I need to change my entity resolver

from easyauditbundle.

ronisaha avatar ronisaha commented on June 12, 2024

Sorry for the inconvenience. I'll Try to add a change log file next time. It was my ignorance about sample implementation, that gave you such troubles. I've only kept the public API intact and forgot the possibility of user extending my Sample implementation :(

from easyauditbundle.

braianj avatar braianj commented on June 12, 2024

no problem! thanks again

from easyauditbundle.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.