Upgrade from 4.x to 5.0
This guide covers the changes needed when upgrading from auditor 4.x to 5.0.
Overview
auditor 5.0 completes the extraction of the Doctrine ORM provider into the standalone
damienharper/auditor-doctrine-provider
package. The DH\Auditor\Provider\Doctrine namespace has been removed from the core library.
The class FQCNs are identical in the external package. auditor 5.0 also introduces a new audit format (schema v2): existing audit tables must be migrated, see Schema Version 2. Upgrade auditor along with auditor-doctrine-provider 2.0 (and auditor-bundle 8.0 for Symfony applications).
Who is affected?
| Scenario | Impact |
|---|---|
Using damienharper/auditor-bundle | ⚠️ Upgrade to 8.0 and migrate the audit tables (8.0 guide) |
Using auditor-doctrine-provider standalone | ⚠️ Upgrade to 2.0 and migrate the audit tables (2.0 guide) |
Reading $entry->transactionHash, or raw SQL on the audit tables | ⚠️ See Schema Version 2 |
| Implementing a custom provider | ⚠️ LifecycleEvent payload keys changed |
Direct composer require damienharper/auditor only (raw) | ⚠️ Must install provider separately |
Implementing NeedsConversionToAuditableType | ⚠️ Must update the import |
Implementing or calling TransactionInterface | ⚠️ getTransactionHash() is renamed getTransactionId() |
Migration Steps
1. Install the Doctrine provider package (if not already installed)
composer require damienharper/auditor-doctrine-provider:^2.0
2. Update auditor itself
composer require damienharper/auditor:^5.0
3. Update NeedsConversionToAuditableType imports (if applicable)
The interface has moved from the core package to the doctrine-provider package.
// Before (4.x)
use DH\Auditor\Transaction\NeedsConversionToAuditableType;
// After (5.0)
use DH\Auditor\Provider\Doctrine\Transaction\NeedsConversionToAuditableType;
4. Migrate the audit tables to schema v2
Existing audit tables must be converted with audit:schema:migrate before audit:schema:update runs: see
Migrating existing audit tables and the provider's upgrade guide.
Breaking Changes
Removed: DH\Auditor\Provider\Doctrine\* from core
The entire src/Provider/Doctrine/ namespace has been removed from damienharper/auditor.
It is now exclusively provided by damienharper/auditor-doctrine-provider under the same namespace.
Removed: DH\Auditor\Transaction\NeedsConversionToAuditableType
This interface (introduced in 4.1, PR #309) required doctrine/dbal as a core dependency.
It has moved to DH\Auditor\Provider\Doctrine\Transaction\NeedsConversionToAuditableType
in auditor-doctrine-provider.
Renamed: TransactionInterface::getTransactionHash() to getTransactionId()
DH\Auditor\Model\TransactionInterface::getTransactionHash() is renamed getTransactionId(), and returns the ULID
that every entry of the transaction carries in transaction_id. DH\Auditor\Model\Transaction follows. A provider
that implements the interface or calls the method must be updated.
Removed: Doctrine packages from core require-dev
doctrine/dbal, doctrine/orm, doctrine/data-fixtures, and gedmo/doctrine-extensions
are no longer installed when running composer install on damienharper/auditor alone.
Changed: an audit entry that no storage provider could persist now throws
In 4.x, AuditEventSubscriber swallowed every exception thrown by ProviderInterface::persist():
when the only storage provider failed, the audit entry was lost without any error, and the
application only saw a closed connection later on, without a stack trace.
AuditEventSubscriber now throws a DH\Auditor\Exception\ProviderException when every storage
provider failed. Its message lists the failing providers and their errors, and getPrevious()
returns the first provider's exception. A failure is still ignored when another storage provider
persisted the entry.
With the Doctrine provider, the exception fails the flush and the database transaction is rolled
back, as it already did when batch_size is enabled.
Changed: UserInterface declares the class of the user and the impersonator
UserInterface declares two new properties: ?string $fqdn (the class of the user in the application, written as
user_fqdn) and ?UserInterface $impersonator (the user who impersonates this one, written in a new impersonator
key of the blame JSON only when set). Custom implementations must declare both (null when unknown); the built-in
User takes them as optional constructor arguments.
user_fqdn used to be the class of the object returned by the user provider, so DH\Auditor\User\User whenever
the built-in class was used: it is now the fqdn supplied by the user provider (null when it supplies none).
Requirements Changes
| Requirement | 4.x | 5.0 |
|---|---|---|
| PHP | >= 8.4 | >= 8.4 |
| Symfony | >= 8.1 | >= 8.1 |
| Doctrine DBAL | >= 4.0 | via auditor-doctrine-provider |
| Doctrine ORM | >= 3.2 | via auditor-doctrine-provider |
symfony/uid | - | ^8.1 (new, generates the ULID transaction_id) |
Schema Version 2 (Breaking Changes)
auditor 5.0 also introduces a revised audit table format (schema v2). This section documents
the breaking changes to the Entry read model and LifecycleEvent payload. The actual DDL
migration is handled by audit:schema:migrate in auditor-doctrine-provider.
Removed: $entry->transactionHash
The transactionHash property has been removed. Use transactionId instead.
// Before (4.x)
$entry->transactionHash; // SHA-1 VARCHAR(40) from transaction_hash column
// After (5.0)
$entry->transactionId; // ULID CHAR(26) from transaction_id column
For un-migrated v1 rows, Entry::fromArray() automatically falls back to transaction_hash
so that $entry->transactionId is still populated before your tables are migrated.
Changed: blame columns unified into $entry->blame
The four individual DB columns (blame_user, blame_user_fqdn, blame_user_firewall, ip)
are replaced by a single blame JSON column. The convenience accessors are unchanged:
$entry->username; // blame JSON → username key
$entry->userFqdn; // blame JSON → user_fqdn key
$entry->userFirewall; // blame JSON → user_firewall key
$entry->ip; // blame JSON → ip key
// New: access the full blame array
$entry->blame; // ['username' => ..., 'user_fqdn' => ..., 'user_firewall' => ..., 'ip' => ...]
For un-migrated v1 rows the individual columns are synthesised into a blame array automatically.
Changed: getDiffs() return value for schema v2 rows
For entries written with schema_version >= 2, getDiffs() now returns the changes sub-array
from the unified diffs envelope. Legacy v1 entries are returned as-is (unchanged behaviour).
// schema_version = 1 (legacy): raw ['field' => ['old' => x, 'new' => y], ...] + @source stripped
// schema_version >= 2: envelope['changes'] = ['field' => ['old' => x, 'new' => y], ...]
$changes = $entry->getDiffs();
New: getDiffSource() — entity metadata from the diffs envelope
Returns the source block embedded in every v2 diffs envelope:
$source = $entry->getDiffSource();
// ['id' => '42', 'class' => 'App\Entity\Post', 'label' => 'My post', 'table' => 'post']
// Returns null for schema_version = 1 entries.
New: getDiffTarget() — target metadata for association entries
Returns the target block for associate/dissociate entries (schema v2 only):
$target = $entry->getDiffTarget();
// ['id' => '7', 'class' => 'App\Entity\Tag', 'label' => 'PHP', 'table' => 'tag']
// Returns null for non-association entries or schema_version = 1.
New: isSnapshot() — entries recording an existing entity
audit:snapshot (auditor-doctrine-provider 2.0) writes an insert entry per existing entity, flagged with
"snapshot": true in the diffs envelope. isSnapshot() tells them from real insertions:
if ('insert' === $entry->type && $entry->isSnapshot()) {
// state of the entity when auditing started, not its creation
}
// Always false for schema_version = 1 entries.
New: $entry->schemaVersion
$entry->schemaVersion; // int: 1 (legacy) or 2 (current)
Changed: LifecycleEvent payload keys
| Key (4.x) | Key (5.0) | Notes |
|---|---|---|
transaction_hash | transaction_id | ULID (CHAR 26) instead of SHA-1 (VARCHAR 40) |
blame_user | blame → username | Key of the blame JSON string |
blame_user_fqdn | blame → user_fqdn | Key of the blame JSON string |
blame_user_firewall | blame → user_firewall | Key of the blame JSON string |
ip | blame → ip | Key of the blame JSON string |
| (new) | schema_version | Row format version — 2 for current |
Providers implementing persist(LifecycleEvent $event) must update any code that reads the
old flat keys from $event->getPayload(). blame (like diffs and extra_data) is a JSON string:
json_decode($payload['blame'] ?? 'null', true)['username'] ?? null.
Migrating existing audit tables
Existing audit tables must be migrated to schema v2 with audit:schema:migrate (Doctrine provider). The
migration converts the existing entries, then drops the legacy columns: there is no rollback, back up the
audit tables first, and stop writing audits while it runs (count 3 to 5 minutes per million audit rows).
IMPORTANT
audit:schema:update refuses to run while any audit table still has the legacy v1 schema.
Run audit:schema:migrate first.
# Migrate DDL + convert transaction hashes + convert diffs in one pass
bin/console audit:schema:migrate --force --convert-all
# Then add the indexes of the v2 schema
bin/console audit:schema:update --force
Follow the auditor-doctrine-provider 2.0 upgrade guide for the complete procedure: backup, rehearsal and duration estimate, order of the steps, options and troubleshooting.
New Features
These additions are optional: code written for 4.x does not need them. They are documented in the API reference.
Blame contexts ($entry->via)
A blame context records how a change was made (an import, a console command, a Messenger message…) in the
via key of the blame JSON, next to the user. No schema change: it is one more key of the blame column.
use DH\Auditor\Blame\BlameContext;
$auditor->getConfiguration()->getBlameContextStack()->run(
new BlameContext('import', 'Import batch #42', ['file' => 'products.csv']),
fn () => $entityManager->flush(),
);
$entry->via; // ['type' => 'import', 'label' => 'Import batch #42', 'data' => ['file' => 'products.csv']]
Entry::toArray() returns it as blame_via. See Blame Context.
Impersonator ($entry->impersonator)
When the user provider returns a user with an impersonator (switch user), the blame JSON gets an impersonator
key: {"id", "username", "fqdn"}. $entry->impersonator and HistoryItem::$impersonator return it (only its string
values, null without impersonator), and Entry::toArray() exports it as blame_impersonator_id, blame_impersonator
and blame_impersonator_fqdn.
Entries written before keep the impersonator that the user provider may have appended to the username (such as
alice[impersonator admin], the format of auditor-bundle before 8.0), which is not parsed. To find them:
-- MySQL, MariaDB, SQLite
SELECT * FROM post_audit WHERE JSON_EXTRACT(blame, '$.username') LIKE '%[impersonator %';
-- PostgreSQL
SELECT * FROM post_audit WHERE CAST(blame AS jsonb) ->> 'username' LIKE '%[impersonator %';
Per-entity retention policy
#[Auditable] takes an optional retention policy, applied by the providers that support pruning (the Doctrine
provider's audit:clean command, and the scheduled retention of auditor-bundle):
use DH\Auditor\Attribute\Auditable;
#[Auditable(maxAge: 'P7Y')] // keep 7 years of history
class Payment {}
#[Auditable(maxEntries: 10_000)] // keep the 10,000 most recent entries
class Session {}
maxAge is an ISO 8601 duration and maxEntries a positive integer; invalid values throw as soon as the attribute
is read. The policy is exposed as a DH\Auditor\Model\RetentionPolicy (Auditable::getRetentionPolicy()).
Readable values in diffs: #[DiffLabel]
#[DiffLabel(resolver: …)] on a property stores a human-readable label next to the raw value in the diff
({"value": 2, "label": "Processing"}). The resolver is a service implementing
DH\Auditor\Contract\DiffLabelResolverInterface, called when the audit entry is written.
Values kept out of the audit: #[Mask]
#[Mask] on a property records that the field changed without storing its values. The strategy is a
DH\Auditor\Masking\MaskStrategy: MaskStrategy::Hidden (the default) stores "***", MaskStrategy::KeyedHash
stores an HMAC-SHA256 of the value keyed with the mask secret of the provider, so the entries of one value can be found
without storing it. A null value stays null. Unlike #[Ignore], the change still shows in the history. Like the other
field attributes, it can be put on the class with a field argument. Providers mask the values through
DH\Auditor\Masking\Masker.
WARNING
Only the values of the field in the diffs are masked. A value written elsewhere is not: in particular the label of
the entity (its __toString() or a label resolver), recorded in the source of every entry. Do not build that label
from a masked field.
#[Ignore], #[DiffLabel] and #[Mask] on the class
These attributes can also be put on the class, repeated, with a field argument naming the field:
#[Ignore(field: 'password')], #[DiffLabel(resolver: …, field: 'status')], #[Mask(field: 'email')]. This is the form for models that do
not declare a property per column, such as Eloquent models. On a property, leave field out.
Entry::toArray()
Returns an entry as a flat array (id, schema_version, type, object_id, discriminator, transaction_id,
diffs, blame_id, blame_user, blame_user_fqdn, blame_user_firewall, blame_impersonator_id,
blame_impersonator, blame_impersonator_fqdn, ip, blame_via, extra_data,
created_at in ISO 8601), with the same keys for legacy and schema v2 entries. Export formats (NDJSON, JSON, CSV) are built on it.
JSON deep diffs: isDeepDiff() and isDiffLeaf()
A change of a JSON field can be stored as a deep diff (a tree of the keys that changed) rather than as an
{old, new} pair. $entry->isDeepDiff($field) tells which one getDiffs()[$field] holds, and
Entry::isDiffLeaf($node) tells a leaf ({old}, {new} or {old, new}) from an intermediate node while walking
the tree. Use them instead of testing the keys of the changeset.