Skip to content
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
41 changes: 23 additions & 18 deletions adr/004-m2m-audit-logging-join-table-query.md
Original file line number Diff line number Diff line change
Expand Up @@ -414,26 +414,14 @@ case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE:

To add M2M audit support for a new entity:

1. Add a combined `EVENT_COLLECTION_MANYTOMANY_UPDATE`/`DELETE` case to the entity's formatter's `switch`:
1. Add a combined `EVENT_COLLECTION_MANYTOMANY_UPDATE`/`DELETE` case to the entity's formatter's `switch`, routing both events to the shared base method with the entity wording as the label:
```php
case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE:
case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE:
return $this->handleEntityManyToManyCollection($change_set, $id, $name);
return $this->formatManyToManyCollectionChange($change_set, sprintf("Entity '%s' (%s)", $name, $id));
```
2. Implement the private handler following the two-step pattern:
```php
private function handleEntityManyToManyCollection(array $change_set, $id, $name): ?string
{
$metadata = $this->handleManyToManyCollection($change_set);
if (!$metadata) return null;
$collectionData = $this->processCollection($metadata);
if (!$collectionData) return null;
return $this->event_type === IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE
? $this->formatManyToManyDelete($collectionData, $id, $name)
: $this->formatManyToManyUpdate($collectionData, $id, $name);
}
```
3. Implement private `formatManyToManyUpdate()` and `formatManyToManyDelete()` with entity-specific message formatting.
2. Nothing else is needed in the formatter. `AbstractAuditLogFormatter::formatManyToManyCollectionChange(array $change_set, string $label): ?string` runs the two-step pipeline (`handleManyToManyCollection()` then `processCollection()`), picks update or delete from `$this->event_type`, and builds the message `<label> <field> (<TargetEntity>) updated: Added IDs: [..], Removed IDs: [..] by user X` or `<label> <field> (<TargetEntity>) deleted: Removed IDs: [..] by user X`. It returns `null` when there is nothing to report. Do not copy private `formatManyToManyUpdate()` / `formatManyToManyDelete()` methods into a new formatter.
3. If an entity needs a message that does not fit the shared shape, build it from `handleManyToManyCollection()` + `processCollection()` directly instead of overriding the base method.
4. Register the entity in `config/audit_log.php` if not already present.

When one entity is formatted by several classes — `Presentation` has a default strategy plus route-scoped strategies in `config/audit_log.php` — keep the handler in a single per-entity trait (`FormatsPresentationManyToManyCollections`) so every formatter of that entity shares it. An update without diff, or a delete with nothing to remove, returns `null` so no empty entry is emitted.
Expand All @@ -443,8 +431,25 @@ Current entities with M2M audit support:
- `PresentationCategoryGroup` — `$categories` collection (`PresentationCategoryGroup_Categories`)
- `Presentation` — `$sponsors`, `$tags`, `$allowed_ticket_types` (`BasePresentationAuditLogFormatter` subclasses and `PresentationUserSubmissionAuditLogFormatter`, via the `FormatsPresentationManyToManyCollections` trait)
- `SummitEvent` — `$sponsors`, `$tags`, `$allowed_ticket_types` (`SummitEventAuditLogFormatter`)

Every other entity registered in `config/audit_log.php` that owns a many-to-many collection still drops these events, because the factory resolves the configured formatter and only falls back to the `Default*` formatters when an entity has no configuration. Extending them follows the steps above, one entity at a time.
- `Summit` — `$excluded_categories_for_accepted_presentations`, `$excluded_categories_for_alternate_presentations`, `$excluded_categories_for_rejected_presentations`, `$excluded_categories_for_upload_slide_decks`, `$registration_companies` (`SummitAuditLogFormatter`)
- `SelectionPlan` — `$category_groups`, `$event_types` (`SelectionPlanAuditLogFormatter`)
- `SummitTrackChair` — `$categories` (`SummitTrackChairAuditLogFormatter`)
- `SummitSubmissionInvitation` — `$tags` (`SubmissionInvitationAuditLogFormatter`)
- `PresentationSpeaker` — `$languages`, `$organizational_roles`, `$active_involvements` (`PresentationSpeakerAuditLogFormatter`)
- `PresentationCategory` — `$allowed_access_levels`, `$allowed_tags`, `$extra_questions` (`PresentationCategoryAuditLogFormatter`)
- `PresentationType` — `$allowed_ticket_types` (`PresentationTypeAuditLogFormatter`)
- `SummitEventType` — `$allowed_ticket_types` (`SummitEventTypeAuditLogFormatter`)
- `SummitMediaUploadType` — `$presentation_types` (`SummitMediaUploadTypeAuditLogFormatter`)
- `SummitDocument` — `$event_types` (`SummitDocumentAuditLogFormatter`)
- `SummitBadgeType` — `$access_levels`, `$badge_features`, `$allowed_view_types` (`SummitBadgeTypeAuditLogFormatter`)
- `SummitAttendeeBadge` — `$features` (`SummitAttendeeBadgeAuditLogFormatter`)
- `SummitOrderExtraQuestionType` — `$allowed_ticket_types`, `$allowed_badge_features_types` (`SummitOrderExtraQuestionTypeAuditLogFormatter`)
- `SummitTaxType` — `$ticket_types` (`SummitTaxTypeAuditLogFormatter`)
- `PrePaidSummitRegistrationDiscountCode`, `SponsorSummitRegistrationDiscountCode`, `SponsorSummitRegistrationPromoCode` — `$badge_features`, `$allowed_ticket_types`, `$tags`, inherited from `SummitRegistrationPromoCode` (their three formatters)
- `Sponsor` — `$members` (`SponsorAuditLogFormatter`)
- `SummitBookableVenueRoom` — `$attributes` (`SummitBookableVenueRoomAuditLogFormatter`)

The factory resolves the configured formatter and only falls back to the `Default*` formatters when an entity has no configuration, so a configured entity whose formatter has no M2M case would drop these events. `tests/Unit/Audit/ManyToManyAuditCoverageTest.php` prevents that: for every entity in `config/audit_log.php` that owns a many-to-many collection (Doctrine metadata, owning side) it asserts that each configured formatter, including route-scoped `strategies[]` entries, handles `EVENT_COLLECTION_MANYTOMANY_UPDATE` and `DELETE`. There is no allowlist; configuring a new entity with an unhandled collection fails the test and names the entity, its collections and the formatter to fix.

### Test infrastructure

Expand Down
4 changes: 4 additions & 0 deletions app/Audit/ConcreteFormatters/SponsorAuditLogFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ public function format($subject, array $change_set): ?string
$summit_name,
$this->getUserInfo()
);

case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE:
case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE:
return $this->formatManyToManyCollectionChange($change_set, sprintf("Sponsor (%s) for Company '%s' in Summit '%s'", $id, $company_name, $summit_name));
}
} catch (\Exception $ex) {
Log::warning("SponsorAuditLogFormatter error: " . $ex->getMessage());
Expand Down
4 changes: 4 additions & 0 deletions app/Audit/ConcreteFormatters/SummitAuditLogFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ public function format($subject, array $change_set): ?string
$id,
$this->getUserInfo()
);

case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE:
case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE:
return $this->formatManyToManyCollectionChange($change_set, sprintf("Summit '%s' (%s)", $name, $id));
}
} catch (\Exception $ex) {
Log::warning("SummitAuditLogFormatter error: " . $ex->getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ public function format($subject, array $change_set): ?string
$summit_name,
$this->getUserInfo()
);

case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE:
case IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE:
return $this->formatManyToManyCollectionChange($change_set, sprintf("Bookable Venue Room '%s' (%s) in Venue '%s' for Summit '%s'", $name, $id, $venue_name, $summit_name));
}
} catch (\Exception $ex) {
Log::warning("SummitBookableVenueRoomAuditLogFormatter error: " . $ex->getMessage());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
<?php

namespace Tests\OpenTelemetry\Formatters;

/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use App\Audit\ConcreteFormatters\SponsorAuditLogFormatter;
use App\Audit\Interfaces\IAuditStrategy;
use Mockery;
use models\main\Company;
use models\main\Member;
use models\summit\Sponsor;
use models\summit\Summit;
use Tests\OpenTelemetry\Formatters\Support\AuditContextBuilder;
use Tests\OpenTelemetry\Formatters\Support\PersistentCollectionTestHelper;
use Tests\TestCase;

/**
* Sponsor owns one many-to-many collection: members.
*/
class SponsorManyToManyAuditLogFormatterTest extends TestCase
{
private const MESSAGE_PREFIX = "Sponsor (17) for Company 'Acme' in Summit 'Test Summit'";

protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}

public function testUpdateEventReportsAddedAndRemovedIdsFromDiff(): void
{
$formatter = $this->makeFormatter(IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE);

$result = $formatter->format($this->makeSubject(), [
'collection' => $this->makeCollection('members', Member::class, [10, 11], [11, 12]),
]);

$this->assertStringStartsWith(
self::MESSAGE_PREFIX . " members (Member) updated: Added IDs: [12], Removed IDs: [10] by user ",
$result
);
}

public function testUpdateEventReportsAddedIds(): void
{
$formatter = $this->makeFormatter(IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE);

$result = $formatter->format($this->makeSubject(), [
'collection' => $this->makeCollection('members', Member::class, [], [5, 6]),
]);

$this->assertStringStartsWith(
self::MESSAGE_PREFIX . " members (Member) updated: Added IDs: [5,6] by user ",
$result
);
}

public function testDeleteEventReportsRemovedIdsFromPayload(): void
{
$formatter = $this->makeFormatter(IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE);

$result = $formatter->format($this->makeSubject(), [
'collection' => $this->makeCollection('members', Member::class, [], []),
'deleted_ids' => [3, 4],
]);

$this->assertStringStartsWith(
self::MESSAGE_PREFIX . " members (Member) deleted: Removed IDs: [3,4] by user ",
$result
);
}

public function testUpdateEventWithoutDiffIsSuppressed(): void
{
$formatter = $this->makeFormatter(IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE);

$result = $formatter->format($this->makeSubject(), [
'collection' => $this->makeCollection('members', Member::class, [3], [3]),
]);

$this->assertNull($result);
}

public function testDeleteEventWithNothingToRemoveIsSuppressed(): void
{
$formatter = $this->makeFormatter(IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_DELETE);

$result = $formatter->format($this->makeSubject(), [
'collection' => $this->makeCollection('members', Member::class, [], []),
'deleted_ids' => [],
]);

$this->assertNull($result);
}

public function testManyToManyEventWithoutCollectionReturnsNull(): void
{
$formatter = $this->makeFormatter(IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE);

$this->assertNull($formatter->format($this->makeSubject(), []));
}

public function testManyToManyEventWithInvalidSubjectReturnsNull(): void
{
$formatter = $this->makeFormatter(IAuditStrategy::EVENT_COLLECTION_MANYTOMANY_UPDATE);

$this->assertNull($formatter->format(new \stdClass(), [
'collection' => $this->makeCollection('members', Member::class, [], [7]),
]));
}

private function makeFormatter(string $eventType): SponsorAuditLogFormatter
{
$formatter = new SponsorAuditLogFormatter($eventType);
$formatter->setContext(AuditContextBuilder::default()->build());
return $formatter;
}

private function makeCollection(string $field, string $targetEntity, array $snapshotIds, array $currentIds)
{
return PersistentCollectionTestHelper::buildManyToManyCollection(
Sponsor::class,
$field,
$targetEntity,
$snapshotIds,
$currentIds
);
}

private function makeSubject(): Sponsor
{
$company = Mockery::mock(Company::class);
$company->shouldReceive('getName')->andReturn('Acme');

$summit = Mockery::mock(Summit::class);
$summit->shouldReceive('getName')->andReturn('Test Summit');

$sponsor = Mockery::mock(Sponsor::class);
$sponsor->shouldReceive('getId')->andReturn(17);
$sponsor->shouldReceive('getCompany')->andReturn($company);
$sponsor->shouldReceive('getSummit')->andReturn($summit);
$sponsor->shouldReceive('getOrder')->andReturn(1);

return $sponsor;
}
}
Loading
Loading