Skip to content

Commit

Permalink
Merge pull request #102 from indjeto/v1.0
Browse files Browse the repository at this point in the history
Refactoring and add clean up command
  • Loading branch information
indjeto authored Feb 4, 2024
2 parents 274fa24 + 18e33e3 commit 349b2aa
Show file tree
Hide file tree
Showing 12 changed files with 115 additions and 92 deletions.
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
],
"require": {
"php": ">=8.1",
"doctrine/dbal": "^2.9|^3.1.4",
"doctrine/dbal": "^2.13|^3.1.4",
"doctrine/doctrine-bundle": "^2.9",
"doctrine/orm": "^2.9",
"doctrine/orm": "^2.13",
"symfony/security-bundle": "^6.4",
"symfony/framework-bundle": "^6.4"
},
Expand Down
31 changes: 31 additions & 0 deletions config/doctrine/Association.orm.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

<entity name="DataDog\AuditBundle\Entity\Association" table="audit_associations">

<id name="id" type="bigint" column="id">
<generator strategy="IDENTITY"/>
<options>
<option name="unsigned">true</option>
</options>
</id>

<field name="typ" length="128" />
<field name="tbl" length="128" nullable="true" />
<field name="label" nullable="true" />
<field name="fk" type="integer">
<options>
<option name="unsigned">true</option>
</options>
</field>
<field name="class" />

<indexes>
<index columns="fk"/>
</indexes>

</entity>

</doctrine-mapping>
32 changes: 32 additions & 0 deletions config/doctrine/AuditLog.orm.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

<entity name="DataDog\AuditBundle\Entity\AuditLog" table="audit_logs">

<id name="id" type="bigint" column="id">
<generator strategy="IDENTITY"/>
<options>
<option name="unsigned">true</option>
</options>
</id>

<field name="action" length="12" />
<field name="tbl" length="128" />
<field name="diff" type="json" nullable="true" />
<field name="loggedAt" type="datetime" column="logged_at" />

<one-to-one field="source" target-entity="Association">
<join-column nullable="false" />
</one-to-one>
<one-to-one field="target" target-entity="Association" />
<one-to-one field="blame" target-entity="Association" />

<indexes>
<index columns="logged_at"/>
</indexes>

</entity>

</doctrine-mapping>
26 changes: 26 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use DataDog\AuditBundle\Command\AuditLogDeleteOldLogsCommand;
use DataDog\AuditBundle\EventListener\AuditListener;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Events;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

return static function (ContainerConfigurator $container) {
// @formatter:off
$services = $container->services();
$services
->set('data_dog_audit.listener.audit', AuditListener::class)->private()
->arg(0, new Reference(TokenStorageInterface::class))
->tag('doctrine.event_listener', ['event' => Events::onFlush,])
;

$services->set('data_dog_audit.command.delete_old_logs', AuditLogDeleteOldLogsCommand::class)
->arg(0, new Reference(Connection::class))
->tag('console.command')
;
// @formatter:on
};
2 changes: 1 addition & 1 deletion docs/labeler.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Re-define the audit listener service to call the `setLabler` method of the `Audi

```yaml
services:
datadog.event_listener.audit:
data_dog_audit.listener.audit:
class: 'DataDog\AuditBundle\EventListener\AuditListener'
arguments: ['@security.token_storage']
tags:
Expand Down
12 changes: 7 additions & 5 deletions src/Command/AuditLogDeleteOldLogsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,10 @@

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\ParameterType;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
name: 'audit-logs:delete-old-logs',
description: 'Remove old records from the audit logs',
)]
class AuditLogDeleteOldLogsCommand extends Command
{
public const DEFAULT_RETENTION_PERIOD = 'P3M';
Expand All @@ -25,6 +20,13 @@ public function __construct(
parent::__construct();
}

#[\Override]
protected function configure(): void
{
$this->setName('audit-logs:delete-old-logs')
->setDescription('Remove old records from the audit logs');
}

#[\Override]
protected function execute(InputInterface $input, OutputInterface $output): int
{
Expand Down
3 changes: 2 additions & 1 deletion src/DataDogAuditBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ public function build(ContainerBuilder $container): void
parent::build($container);

if (class_exists(DoctrineOrmMappingsPass::class)) {
$namespaces = [__DIR__.'/../config/doctrine' => 'DataDog\\AuditBundle\\Entity'];
$container->addCompilerPass(
DoctrineOrmMappingsPass::createAttributeMappingDriver(['DataDog\\AuditBundle\\Entity'], [__DIR__.'/Entity'])
DoctrineOrmMappingsPass::createXmlMappingDriver($namespaces)
);
}
}
Expand Down
5 changes: 2 additions & 3 deletions src/DependencyInjection/DataDogAuditExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace DataDog\AuditBundle\DependencyInjection;

use DataDog\AuditBundle\EventListener\AuditListener;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
Expand All @@ -12,13 +11,13 @@ class DataDogAuditExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container): void
{
$loader = new PhpFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader = new PhpFileLoader($container, new FileLocator(__DIR__ . '/../../config'));
$loader->load('services.php');

$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$auditListener = $container->getDefinition(AuditListener::class);
$auditListener = $container->getDefinition('data_dog_audit.listener.audit');

if (isset($config['audited_entities']) && !empty($config['audited_entities'])) {
$auditListener->addMethodCall('addAuditedEntities', array($config['audited_entities']));
Expand Down
13 changes: 0 additions & 13 deletions src/Entity/Association.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,18 @@

namespace DataDog\AuditBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'audit_associations')]
#[ORM\Index(columns: ['fk'])]
class Association
{
#[ORM\Column(type: 'bigint', options: ['unsigned' => true])]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'IDENTITY')]
private ?string $id;

#[ORM\Column(length: 128)]
private string $typ;

#[ORM\Column(length: 128, nullable: true)]
private ?string $tbl;

#[ORM\Column(nullable: true)]
private ?string $label;

#[ORM\Column(type: 'integer', options: ['unsigned' => true])]
private int $fk;

#[ORM\Column]
private string $class;

public function getId(): ?string
Expand Down
18 changes: 0 additions & 18 deletions src/Entity/AuditLog.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,22 @@

namespace DataDog\AuditBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'audit_logs')]
#[ORM\Index(columns: ['logged_at'])]
class AuditLog
{
#[ORM\Column(type: 'bigint', options: ['unsigned' => true])]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'IDENTITY')]
private ?string $id;

#[ORM\Column(length: 12)]
private string $action;

#[ORM\Column(length: 128)]
private string $tbl;

#[ORM\OneToOne(targetEntity: Association::class)]
#[ORM\JoinColumn(unique: true, nullable: false)]
private Association $source;

#[ORM\OneToOne(targetEntity: Association::class)]
#[ORM\JoinColumn(unique: true)]
private ?Association $target;

#[ORM\OneToOne(targetEntity: Association::class)]
#[ORM\JoinColumn(unique: true)]
private ?Association $blame;

#[ORM\Column(type: 'json', nullable: true)]
private ?array $diff;

#[ORM\Column(name: 'logged_at', type: 'datetime')]
private \DateTimeInterface $loggedAt;

public function getId(): ?string
Expand Down
29 changes: 12 additions & 17 deletions src/EventListener/AuditListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,18 @@
use DataDog\AuditBundle\DBAL\AuditLogger;
use DataDog\AuditBundle\Entity\Association;
use DataDog\AuditBundle\Entity\AuditLog;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\DBAL\Logging\LoggerChain;
use Doctrine\DBAL\Logging\SQLLogger;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Symfony\Component\DependencyInjection\Attribute\AsAlias;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\UserInterface;

#[AsDoctrineListener(Events::onFlush)]
#[AsAlias(id: 'datadog.event_listener.audit', public: false)]
class AuditListener
{
/**
Expand Down Expand Up @@ -251,7 +246,7 @@ protected function flush(EntityManager $em)
$this->dissociated = [];
}

protected function associate(EntityManager $em, $source, $target, array $mapping)
protected function associate(EntityManager $em, $source, $target, array $mapping): void
{
$this->audit($em, [
'source' => $this->assoc($em, $source),
Expand All @@ -263,7 +258,7 @@ protected function associate(EntityManager $em, $source, $target, array $mapping
]);
}

protected function dissociate(EntityManager $em, $source, $target, $id, array $mapping)
protected function dissociate(EntityManager $em, $source, $target, $id, array $mapping): void
{
$this->audit($em, [
'source' => $this->assoc($em, $source),
Expand All @@ -275,7 +270,7 @@ protected function dissociate(EntityManager $em, $source, $target, $id, array $m
]);
}

protected function insert(EntityManager $em, $entity, array $ch)
protected function insert(EntityManager $em, $entity, array $ch): void
{
$diff = $this->diff($em, $entity, $ch);
if (empty($diff)) {
Expand All @@ -292,7 +287,7 @@ protected function insert(EntityManager $em, $entity, array $ch)
]);
}

protected function update(EntityManager $em, $entity, array $ch)
protected function update(EntityManager $em, $entity, array $ch): void
{
$diff = $this->diff($em, $entity, $ch);
if (empty($diff)) {
Expand All @@ -309,7 +304,7 @@ protected function update(EntityManager $em, $entity, array $ch)
]);
}

protected function remove(EntityManager $em, $entity, $id)
protected function remove(EntityManager $em, $entity, $id): void
{
$meta = $em->getClassMetadata(get_class($entity));
$source = array_merge($this->assoc($em, $entity), ['fk' => $id]);
Expand All @@ -323,7 +318,7 @@ protected function remove(EntityManager $em, $entity, $id)
]);
}

protected function audit(EntityManager $em, array $data)
protected function audit(EntityManager $em, array $data): void
{
$c = $em->getConnection();
$p = $c->getDatabasePlatform();
Expand Down Expand Up @@ -382,7 +377,7 @@ protected function id(EntityManager $em, $entity)
return $pk;
}

protected function diff(EntityManager $em, $entity, array $ch)
protected function diff(EntityManager $em, $entity, array $ch): array
{
$uow = $em->getUnitOfWork();
$meta = $em->getClassMetadata(get_class($entity));
Expand All @@ -409,7 +404,7 @@ protected function diff(EntityManager $em, $entity, array $ch)
return $diff;
}

protected function assoc(EntityManager $em, $association = null)
protected function assoc(EntityManager $em, $association = null): ?array
{
if (null === $association) {
return null;
Expand All @@ -431,7 +426,7 @@ protected function assoc(EntityManager $em, $association = null)
return $res;
}

protected function typ($className)
protected function typ($className): string
{
// strip prefixes and repeating garbage from name
$className = preg_replace("/^(.+\\\)?(.+)(Bundle\\\Entity)/", "$2", $className);
Expand Down Expand Up @@ -482,7 +477,7 @@ protected function value(EntityManager $em, Type $type, $value)
}
}

protected function blame(EntityManager $em)
protected function blame(EntityManager $em): ?array
{
if ($this->blameUser instanceof UserInterface && \method_exists($this->blameUser, 'getId')) {
return $this->assoc($em, $this->blameUser);
Expand Down Expand Up @@ -519,7 +514,7 @@ private function getImpersonatorUserFromSecurityToken($token)
* @param TokenInterface $token
* @return array
*/
private function getRoles(TokenInterface $token)
private function getRoles(TokenInterface $token): array
{
if (method_exists($token, 'getRoleNames')) {
return $token->getRoleNames();
Expand All @@ -528,7 +523,7 @@ private function getRoles(TokenInterface $token)
return $token->getRoles();
}

public function setBlameUser(UserInterface $user)
public function setBlameUser(UserInterface $user): void
{
$this->blameUser = $user;
}
Expand Down
Loading

0 comments on commit 349b2aa

Please sign in to comment.