Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Audit Bundle Laravel Package

codyas/audit-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Enable Contrib Support Run in your project root:

    composer config extra.symfony.allow-contrib true
    composer require codyas/audit-bundle
    
  2. Register the Bundle Ensure Codyas\Audit\AuditBundle::class is added to config/bundles.php:

    return [
        // ...
        Codyas\Audit\AuditBundle::class => ['all' => true],
    ];
    
  3. Configure a Master Entity Annotate a Doctrine entity (e.g., User) with @Audit\Master to track its changes:

    use Codyas\Audit\Annotation\Master;
    
    /**
     * @Master()
     */
    #[ORM\Entity]
    class User { ... }
    
  4. Trigger an Audit Use the AuditManager service to manually trigger an audit (or rely on Doctrine lifecycle events):

    $auditManager = $this->container->get('codyas_audit.manager');
    $auditManager->audit($user);
    
  5. View Revisions Fetch revisions for an entity via the AuditRepository:

    $revisions = $this->container->get('codyas_audit.repository')->findRevisions($user);
    

Implementation Patterns

Workflow: Tracking Entity Changes

  1. Annotate Master Entities Mark entities with @Master to enable auditing. Example:

    /**
     * @Master(
     *     ignoreFields = {"password", "tempToken"},
     *     serializeGroups = {"api"}
     * )
     */
    class User { ... }
    
  2. Customize Serialization Use Symfony Serializer groups or custom serializers for complex fields:

    # config/packages/codyas_audit.yaml
    codyas_audit:
        serializers:
            - 'App\Serializer\UserSerializer'
    
  3. Automatic vs. Manual Auditing

    • Automatic: Doctrine lifecycle events (preUpdate, prePersist) trigger audits.
    • Manual: Call $auditManager->audit($entity) in business logic (e.g., after bulk updates).
  4. Querying Revisions Filter revisions by date, user, or changes:

    $revisions = $auditRepository->findRevisions($user, [
        'limit' => 5,
        'orderBy' => ['createdAt' => 'DESC'],
    ]);
    
  5. Integrate with API Responses Attach revisions to API responses for transparency:

    return $this->json([
        'data' => $user,
        'revisions' => $auditRepository->findRevisions($user),
    ]);
    

Integration Tips

  • Symfony Events: Listen to kernel.response to batch audit operations post-request:

    $eventDispatcher->addListener(KernelEvents::RESPONSE, function (RequestEvent $event) {
        $auditManager = $this->container->get('codyas_audit.manager');
        $auditManager->flushPendingAudits();
    });
    
  • Doctrine Events: Override default behavior by subscribing to codyas_audit.pre_audit:

    $eventDispatcher->addListener('codyas_audit.pre_audit', function (AuditEvent $event) {
        if (!$event->getEntity()->isActive()) {
            $event->stopPropagation();
        }
    });
    
  • Testing: Mock AuditManager to avoid DB writes in unit tests:

    $this->mock(AuditManager::class)
         ->shouldReceive('audit')
         ->once();
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Issue: Serializing large entities or collections may slow responses.
    • Fix: Exclude non-critical fields with ignoreFields or use serializeGroups.
    • Tip: Use compression (codyas_audit.compression_enabled: true) for text-heavy revisions.
  2. Circular References

    • Issue: Bidirectional relationships (e.g., User ↔ Address) cause serialization errors.
    • Fix: Implement NormalizerInterface or use @Groups to break cycles:
      #[Groups(['api'])]
      #[Assert\NotBlank]
      private string $street;
      
  3. Race Conditions

    • Issue: Concurrent updates may lose audit history.
    • Fix: Use flushPendingAudits() in a post-request event to batch writes.
  4. Configuration Overrides

    • Issue: Flex-generated config may conflict with manual config/packages/codyas_audit.yaml.
    • Fix: Merge configs explicitly:
      imports:
          - { resource: "@CodyasAuditBundle/Resources/config/config.yaml" }
      codyas_audit:
          <<: *default_config
          custom_setting: value
      

Debugging

  • Enable Logging Set debug: true in config to log audit events:

    codyas_audit:
        debug: true
    
  • Check Event Propagation Use stopPropagation() in listeners to debug skipped audits:

    $event->stopPropagation(); // Prevents audit for this entity
    
  • Verify Doctrine Events Ensure codyas_audit.subscriber is registered in doctrine.event_subscribers:

    doctrine:
        orm:
            event_subscribers:
                - Codyas\Audit\Doctrine\AuditSubscriber
    

Extension Points

  1. Custom Audit Storage Override the default AuditRepository to store revisions in a NoSQL database:

    class CustomAuditRepository implements AuditRepositoryInterface { ... }
    

    Register it as a service:

    services:
        Codyas\Audit\AuditRepositoryInterface: '@App\Repository\CustomAuditRepository'
    
  2. Dynamic Master Entities Skip annotations by implementing MasterEntityResolverInterface:

    class DynamicMasterResolver implements MasterEntityResolverInterface {
        public function isMaster(object $entity): bool {
            return $entity instanceof User && $entity->isAdmin();
        }
    }
    
  3. Webhook Notifications Dispatch events after audits to trigger external actions (e.g., Slack alerts):

    $eventDispatcher->addListener('codyas_audit.post_audit', function (AuditEvent $event) {
        $this->slackService->sendAlert($event->getChanges());
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware