Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added configuration option to disable auditing for object associations #622

Open
wants to merge 1 commit into
base: 1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ simple_things_entity_audit:
disable_foreign_keys: true
```

If you want to disable auditing for object relations, you can use the `disable_associations` parameter:
```yaml
simple_things_entity_audit:
disable_associations: true
```

### Creating new tables

Call the command below to see the new tables in the update schema queue.
Expand Down Expand Up @@ -290,5 +296,5 @@ This provides you with a few different routes:
## TODOS

* Currently only works with auto-increment databases
* Proper metadata mapping is necessary, allow to disable versioning for fields and associations.
* Proper metadata mapping is necessary, allow to disable versioning for fields.
* It does NOT work with Joined-Table-Inheritance (Single Table Inheritance should work, but not tested)
12 changes: 12 additions & 0 deletions src/AuditConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ class AuditConfiguration

private bool $disableForeignKeys = false;

private bool $disableAssociations = false;

/**
* @var string[]
*/
Expand Down Expand Up @@ -102,6 +104,16 @@ public function setDisabledForeignKeys(bool $disabled): void
$this->disableForeignKeys = $disabled;
}

public function areAssociationsDisabled(): bool
{
return $this->disableAssociations;
}

public function setDisableAssociations(bool $disabled): void
{
$this->disableAssociations = $disabled;
}

/**
* @return string
*
Expand Down
106 changes: 55 additions & 51 deletions src/AuditReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@
$columnName = $idKeys[0];
} elseif (isset($classMetadata->fieldMappings[$idField])) {
$columnName = $classMetadata->fieldMappings[$idField]['columnName'];
} elseif (isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
} elseif (!$this->config->areAssociationsDisabled() && isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
$columnName = $classMetadata->associationMappings[$idField]['joinColumns'][0]['name'];
} else {
throw new \RuntimeException('column name not found for'.$idField);
Expand Down Expand Up @@ -249,23 +249,25 @@
$columnMap[$field] = $this->getSQLResultCasing($this->platform, $columnName);
}

foreach ($classMetadata->associationMappings as $assoc) {
if (
($assoc['type'] & ClassMetadata::TO_ONE) === 0
|| false === $assoc['isOwningSide']
|| !isset($assoc['joinColumnFieldNames'])
) {
continue;
}
if (!$this->getConfiguration()->areAssociationsDisabled()) {
foreach ($classMetadata->associationMappings as $assoc) {
if (
($assoc['type'] & ClassMetadata::TO_ONE) === 0
|| false === $assoc['isOwningSide']
|| !isset($assoc['joinColumnFieldNames'])
) {
continue;
}

foreach ($assoc['joinColumnFieldNames'] as $sourceCol) {
$tableAlias = $classMetadata->isInheritanceTypeJoined()
foreach ($assoc['joinColumnFieldNames'] as $sourceCol) {
$tableAlias = $classMetadata->isInheritanceTypeJoined()
&& $classMetadata->isInheritedAssociation($assoc['fieldName'])
&& !$classMetadata->isIdentifier($assoc['fieldName'])
? 're' // root entity
: 'e';
$columnList[] = $tableAlias.'.'.$sourceCol;
$columnMap[$sourceCol] = $this->getSQLResultCasing($this->platform, $sourceCol);
$columnList[] = $tableAlias.'.'.$sourceCol;
$columnMap[$sourceCol] = $this->getSQLResultCasing($this->platform, $sourceCol);
}
}
}

Expand Down Expand Up @@ -423,15 +425,17 @@
$columnMap[$field] = $this->getSQLResultCasing($this->platform, $columnName);
}

foreach ($classMetadata->associationMappings as $assoc) {
if (
($assoc['type'] & ClassMetadata::TO_ONE) > 0
&& true === $assoc['isOwningSide']
&& isset($assoc['targetToSourceKeyColumns'])
) {
foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
$columnList .= ', '.$sourceCol;
$columnMap[$sourceCol] = $this->getSQLResultCasing($this->platform, $sourceCol);
if (!$this->config->areAssociationsDisabled()) {
foreach ($classMetadata->associationMappings as $assoc) {
if (
($assoc['type'] & ClassMetadata::TO_ONE) > 0
&& true === $assoc['isOwningSide']
&& isset($assoc['targetToSourceKeyColumns'])
) {
foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
$columnList .= ', '.$sourceCol;
$columnMap[$sourceCol] = $this->getSQLResultCasing($this->platform, $sourceCol);
}
}
}
}
Expand Down Expand Up @@ -544,7 +548,7 @@
$whereSQL .= ' AND ';
}
$whereSQL .= 'e.'.$classMetadata->fieldMappings[$idField]['columnName'].' = ?';
} elseif (isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
} elseif (!$this->config->areAssociationsDisabled() && isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
if ('' !== $whereSQL) {
$whereSQL .= ' AND ';
}
Expand Down Expand Up @@ -606,7 +610,7 @@
$whereSQL .= ' AND ';
}
$whereSQL .= 'e.'.$classMetadata->fieldMappings[$idField]['columnName'].' = ?';
} elseif (isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
} elseif (!$this->config->areAssociationsDisabled() && isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
if ('' !== $whereSQL) {
$whereSQL .= ' AND ';
}
Expand Down Expand Up @@ -716,14 +720,11 @@
$id = [$classMetadata->identifier[0] => $id];
}

/** @phpstan-var array<literal-string> $whereId */
$whereId = [];
foreach ($classMetadata->identifier as $idField) {
if (isset($classMetadata->fieldMappings[$idField])) {
/** @phpstan-var literal-string $columnName */
$columnName = $classMetadata->fieldMappings[$idField]['columnName'];
} elseif (isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
/** @phpstan-var literal-string $columnName */
} elseif (!$this->config->areAssociationsDisabled() && isset($classMetadata->associationMappings[$idField]['joinColumns'])) {
$columnName = $classMetadata->associationMappings[$idField]['joinColumns'][0]['name'];
} else {
continue;
Expand All @@ -738,42 +739,41 @@

foreach ($classMetadata->fieldNames as $columnName => $field) {
$type = Type::getType($classMetadata->fieldMappings[$field]['type']);
/** @phpstan-var literal-string $sqlExpr */
$sqlExpr = $type->convertToPHPValueSQL(
$columnList[] = $type->convertToPHPValueSQL(
$this->quoteStrategy->getColumnName($field, $classMetadata, $this->platform),
$this->platform
);
/** @phpstan-var literal-string $quotedField */
$quotedField = $this->platform->quoteSingleIdentifier($field);
$columnList[] = $sqlExpr.' AS '.$quotedField;
).' AS '.$this->platform->quoteSingleIdentifier($field);
$columnMap[$field] = $this->getSQLResultCasing($this->platform, $columnName);
}

foreach ($classMetadata->associationMappings as $assoc) {
if (
($assoc['type'] & ClassMetadata::TO_ONE) === 0
|| false === $assoc['isOwningSide']
|| !isset($assoc['targetToSourceKeyColumns'])
) {
continue;
}
if (!$this->config->areAssociationsDisabled()) {
foreach ($classMetadata->associationMappings as $assoc) {
if (
($assoc['type'] & ClassMetadata::TO_ONE) === 0
|| false === $assoc['isOwningSide']
|| !isset($assoc['targetToSourceKeyColumns'])
) {
continue;
}

/** @phpstan-var literal-string $sourceCol */
foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
$columnList[] = $sourceCol;
$columnMap[$sourceCol] = $this->getSQLResultCasing($this->platform, $sourceCol);
foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) {
$columnList[] = $sourceCol;
$columnMap[$sourceCol] = $this->getSQLResultCasing($this->platform, $sourceCol);
}
}
}

$values = array_values($id);

$query =
'SELECT '.implode(', ', $columnList)
.' FROM '.$tableName.' e'
.' WHERE '.$whereSQL
.' ORDER BY e.'.$this->config->getRevisionFieldName().' DESC';
$query = sprintf(
'SELECT %s FROM %s e WHERE %s ORDER BY e.%s DESC',
implode(', ', $columnList),
$tableName,
$whereSQL,
$this->config->getRevisionFieldName()
);

$stmt = $this->em->getConnection()->executeQuery($query, $values);

Check failure on line 776 in src/AuditReader.php

View workflow job for this annotation

GitHub Actions / PHPStan

Parameter #1 $sql of method Doctrine\DBAL\Connection::executeQuery() expects literal-string, non-falsy-string given.

$result = [];
while ($row = $stmt->fetchAssociative()) {
Expand Down Expand Up @@ -893,6 +893,10 @@
}
}

if ($this->config->areAssociationsDisabled()) {
return $entity;
}

foreach ($classMetadata->associationMappings as $field => $assoc) {
/** @phpstan-var class-string<T> $targetEntity */
$targetEntity = $assoc['targetEntity'];
Expand Down
1 change: 1 addition & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->scalarNode('revision_type_field_name')->defaultValue('revtype')->end()
->scalarNode('revision_table_name')->defaultValue('revisions')->end()
->scalarNode('disable_foreign_keys')->defaultValue(false)->end()
->scalarNode('disable_associations')->defaultValue(false)->end()
->scalarNode('revision_id_field_type')
->defaultValue(Types::INTEGER)
// NEXT_MAJOR: Use enumNode() instead.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public function load(array $configs, ContainerBuilder $container): void
'revision_id_field_type',
'global_ignore_columns',
'disable_foreign_keys',
'disable_associations',
];

foreach ($configurables as $key) {
Expand Down
12 changes: 8 additions & 4 deletions src/EventListener/CreateSchemaListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@ public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $eventArgs)
$revIndexName = $this->config->getRevisionFieldName().'_'.md5($revisionTable->getName()).'_idx';
$revisionTable->addIndex([$this->config->getRevisionFieldName()], $revIndexName);

if (!$this->config->areForeignKeysDisabled()) {
$this->createForeignKeys($revisionTable, $revisionsTable);
}

if ($this->config->areAssociationsDisabled()) {
return;
}

foreach ($cm->associationMappings as $associationMapping) {
if ($associationMapping['isOwningSide'] && isset($associationMapping['joinTable'])) {
if (isset($associationMapping['joinTable']['name'])) {
Expand All @@ -118,10 +126,6 @@ public function postGenerateSchemaTable(GenerateSchemaTableEventArgs $eventArgs)
}
}
}

if (!$this->config->areForeignKeysDisabled()) {
$this->createForeignKeys($revisionTable, $revisionsTable);
}
}

public function postGenerateSchema(GenerateSchemaEventArgs $eventArgs): void
Expand Down
8 changes: 7 additions & 1 deletion src/EventListener/LogRevisionsListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,10 @@ public function postFlush(PostFlushEventArgs $eventArgs): void
$em->getConnection()->executeQuery($sql, $params, $types);
}

if ($this->config->areAssociationsDisabled()) {
return;
}

foreach ($this->deferredChangedManyToManyEntityRevisionsToPersist as $deferredChangedManyToManyEntityRevisionToPersist) {
$this->recordRevisionForManyToManyEntity(
$deferredChangedManyToManyEntityRevisionToPersist->getEntity(),
Expand Down Expand Up @@ -568,7 +572,7 @@ private function saveRevisionEntityData(EntityManagerInterface $em, ClassMetadat
$types[] = $targetClass->getTypeOfField($targetClass->getFieldForColumn($targetColumn));
}
}
} elseif (($assoc['type'] & ClassMetadata::MANY_TO_MANY) > 0
} elseif (!$this->config->areAssociationsDisabled() && ($assoc['type'] & ClassMetadata::MANY_TO_MANY) > 0
&& isset($assoc['relationToSourceKeyColumns'], $assoc['relationToTargetKeyColumns'])) {
$targetClass = $em->getClassMetadata($assoc['targetEntity']);

Expand Down Expand Up @@ -646,6 +650,8 @@ private function saveRevisionEntityData(EntityManagerInterface $em, ClassMetadat
* @param array<string, mixed> $entityData
* @param ClassMetadata<object> $class
* @param ClassMetadata<object> $targetClass
*
* @throws Exception
*/
private function recordRevisionForManyToManyEntity(object $relatedEntity, EntityManagerInterface $em, string $revType, array $entityData, array $assoc, ClassMetadata $class, ClassMetadata $targetClass): void
{
Expand Down
5 changes: 4 additions & 1 deletion src/Resources/config/auditable.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@

->set('simplethings.entityaudit.revision_id_field_type', null)

->set('simplethings.entityaudit.disable_foreign_keys', null);
->set('simplethings.entityaudit.disable_foreign_keys', null)

->set('simplethings.entityaudit.disable_associations', false);

$containerConfigurator->services()
->set('simplethings_entityaudit.manager', AuditManager::class)
Expand Down Expand Up @@ -129,6 +131,7 @@
->call('setRevisionIdFieldType', [param('simplethings.entityaudit.revision_id_field_type')])
->call('setRevisionFieldName', [param('simplethings.entityaudit.revision_field_name')])
->call('setRevisionTypeFieldName', [param('simplethings.entityaudit.revision_type_field_name')])
->call('setDisableAssociations', [param('simplethings.entityaudit.disable_associations')])
->call('setUsernameCallable', [service('simplethings_entityaudit.username_callable')])
->alias(AuditConfiguration::class, 'simplethings_entityaudit.config');
};
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public function testItRegistersDefaultServices(): void
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setRevisionFieldName', ['%simplethings.entityaudit.revision_field_name%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setRevisionTypeFieldName', ['%simplethings.entityaudit.revision_type_field_name%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setDisabledForeignKeys', ['%simplethings.entityaudit.disable_foreign_keys%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setDisableAssociations', ['%simplethings.entityaudit.disable_associations%']);
$this->assertContainerBuilderHasServiceDefinitionWithMethodCall('simplethings_entityaudit.config', 'setUsernameCallable', ['simplethings_entityaudit.username_callable']);
}

Expand Down Expand Up @@ -121,6 +122,7 @@ public function testItSetsDefaultParameters(): void
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_type_field_name', 'revtype');
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_id_field_type', Types::INTEGER);
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.disable_foreign_keys', false);
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.disable_associations', false);
}

public function testItSetsConfiguredParameters(): void
Expand All @@ -137,6 +139,7 @@ public function testItSetsConfiguredParameters(): void
'revision_field_name' => 'revision',
'revision_type_field_name' => 'action',
'disable_foreign_keys' => false,
'disable_associations' => true,
]);

$this->assertContainerBuilderHasParameter('simplethings.entityaudit.connection', 'my_custom_connection');
Expand All @@ -150,6 +153,7 @@ public function testItSetsConfiguredParameters(): void
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_field_name', 'revision');
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.revision_type_field_name', 'action');
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.disable_foreign_keys', false);
$this->assertContainerBuilderHasParameter('simplethings.entityaudit.disable_associations', true);

foreach ([Events::onFlush, Events::postPersist, Events::postUpdate, Events::postFlush, Events::onClear] as $event) {
$this->assertContainerBuilderHasServiceDefinitionWithTag('simplethings_entityaudit.log_revisions_listener', 'doctrine.event_listener', ['event' => $event, 'connection' => 'my_custom_connection']);
Expand Down
Loading