auditor-bundle
auditor-bundle copied to clipboard
Enable auditing on all entities
Is there a way to enable auditing on all entities? As I want to make sure that we can't forget to enable an entity to be audited. So the idea was to enable auditing on all entities unless the entity has #[Audit\Auditable(enabled: false)] defined
With the addition of Resource Tags in Symfony 7.3 I could retrieve all entity classes without auditable disabled, but I'm not sure how to pass them to the bundle.
protected function build(ContainerBuilder $container): void
{
$container->registerAttributeForAutoconfiguration(Entity::class, static function (ChildDefinition $definition) {
$definition->addResourceTag('app.entity');
});
$container->addCompilerPass(new class implements CompilerPassInterface {
public function process(ContainerBuilder $containerBuilder)
{
$classes = [];
foreach ($containerBuilder->findTaggedResourceIds('app.entity') as $id => $tags) {
$class = $containerBuilder->getDefinition($id)->getClass();
if (null === $class) {
continue;
}
if ($this->skipClass($class)) {
continue;
}
$classes[] = $class;
}
$containerBuilder->setParameter('.app.auditable_classes', $classes);
}
private function skipClass(string $class): bool
{
if (!class_exists($class)) {
return false;
}
$reflectionClass = new \ReflectionClass($class);
$attributes = $reflectionClass->getAttributes(Auditable::class);
if ([] === $attributes) {
return false;
}
$auditableAttribute = $attributes[0];
$args = $auditableAttribute->getArguments();
return isset($args['enabled']) && false === $args['enabled'];
}
});
}