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

Flag Bundle Laravel Package

ed/flag-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require ed/flag-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        EtonDigital\FlagBundle\EDFlagBundle::class => ['all' => true],
    ];
    
  2. Database Migration Run migrations (if using Doctrine):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Flag Report Use the FlagReport entity to create a flag:

    use EtonDigital\FlagBundle\Entity\FlagReport;
    
    $flagReport = new FlagReport();
    $flagReport->setContent($yourContentEntity);
    $flagReport->setReason('Spam');
    $flagReport->setUser($currentUser);
    $em->persist($flagReport);
    $em->flush();
    
  4. Admin Panel (Optional) If using SonataAdminBundle, configure the admin class in config/packages/sonata_admin.yaml:

    sonata_admin:
        options:
            models:
                EtonDigital\FlagBundle\Entity\FlagReport: ~
    

Implementation Patterns

Core Workflows

  1. Flagging Content

    • Frontend: Expose a flag button (e.g., in a Twig template):
      <button onclick="flagContent({{ content.id }}, 'Inappropriate')">Flag</button>
      
    • Backend: Handle the flag submission via a controller or API endpoint (if using FOSRestBundle):
      use EtonDigital\FlagBundle\Entity\FlagReport;
      
      public function flagAction(Request $request, $contentId, $reason) {
          $flagReport = new FlagReport();
          $flagReport->setContent($this->getDoctrine()->getRepository('App\Entity\Content')->find($contentId));
          $flagReport->setReason($reason);
          $flagReport->setUser($this->getUser());
      
          $em = $this->getDoctrine()->getManager();
          $em->persist($flagReport);
          $em->flush();
      
          return new JsonResponse(['success' => true]);
      }
      
  2. Categorizing Reasons

    • Define reasons in the FlagReason entity (extend or override in your project):
      // Example: Add custom reasons in a service or entity listener
      $flagReport->setReason('CustomReason');
      
    • Use a SonataAdmin form to manage reasons dynamically (if configured).
  3. Admin Management

    • Access flag reports via SonataAdmin dashboard (if enabled).
    • Filter flags by content, user, reason, or status.
  4. API Integration (Optional)

    • Expose flag endpoints with FOSRestBundle:
      # config/routes.yaml
      ed_flag_report:
          resource: "@EDFlagBundle/Resources/config/routing/api.yaml"
          prefix: /api
      
    • Serialize responses with JMSSerializerBundle for JSON output.

Integration Tips

  1. Event Listeners Trigger actions when a flag is created (e.g., notify moderators):

    // src/EventListener/FlagListener.php
    namespace App\EventListener;
    
    use EtonDigital\FlagBundle\Event\FlagReportEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class FlagListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                FlagReportEvent::FLAG_CREATED => 'onFlagCreated',
            ];
        }
    
        public function onFlagCreated(FlagReportEvent $event) {
            // Send email to admins
        }
    }
    
  2. Custom Actions Extend the FlagReport entity to add custom fields (e.g., moderatorNotes):

    // src/Entity/FlagReport.php
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class FlagReport extends \EtonDigital\FlagBundle\Entity\FlagReport {
        #[ORM\Column(type: 'text', nullable: true)]
        private $moderatorNotes;
    }
    
  3. Frontend Integration

    • Use JavaScript to submit flags via AJAX:
      function flagContent(contentId, reason) {
          fetch(`/api/flag/${contentId}?reason=${reason}`, {
              method: 'POST',
              headers: { 'X-Requested-With': 'XMLHttpRequest' }
          })
          .then(response => response.json())
          .then(data => console.log('Flagged!', data));
      }
      

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies

    • The bundle was last updated in 2017. Test thoroughly with Symfony 5/6 and Doctrine ORM 2.x.
    • Workaround: Fork the repository and update dependencies (e.g., sonata-project/admin-bundle, symfony/*).
  2. Missing Documentation

    • The Resources/doc folder may lack details. Refer to the SonataAdminBundle for admin setup.
    • Tip: Use php bin/console debug:container to inspect services like ed_flag.admin.flag_report.
  3. API Serialization Issues

    • If using JMSSerializerBundle, ensure the FlagReport entity is properly annotated:
      use JMS\Serializer\Annotation as Serializer;
      
      #[Serializer\ExclusionPolicy("all")]
      class FlagReport {
          #[Serializer\Expose]
          private $id;
          // ...
      }
      
  4. Permission Handling

    • The bundle does not enforce user permissions by default. Add guards in controllers:
      public function flagAction(Request $request, $contentId, $reason) {
          if (!$this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
              throw $this->createAccessDeniedException();
          }
          // ...
      }
      

Debugging Tips

  1. Check Database Schema Verify the flag_report table exists and matches the entity structure:

    php bin/console doctrine:schema:validate
    
  2. Enable Debugging Add to config/packages/dev/doctrine.yaml:

    doctrine:
        orm:
            mappings:
                ed_flag:
                    type: attribute
                    dir: "%kernel.project_dir%/vendor/ed/flag-bundle/Resources/config/doctrine"
                    prefix: "EtonDigital\FlagBundle\Entity"
                    is_bundle: false
    
  3. Log Flag Events Configure Monolog to log flag submissions:

    // config/packages/monolog.yaml
    monolog:
        handlers:
            flag_handler:
                type: stream
                path: "%kernel.logs_dir%/flag.log"
                level: debug
                channels: ["flag"]
    

Extension Points

  1. Custom Flag Reasons Override the FlagReason entity or use a repository to fetch dynamic reasons:

    $reasons = $this->getDoctrine()
        ->getRepository(FlagReason::class)
        ->findBy(['active' => true]);
    
  2. Moderation Workflow Add a FlagStatus enum (e.g., PENDING, REVIEWED, RESOLVED) to track progress:

    #[ORM\Column(type: 'string', enumType: FlagStatus::class)]
    private $status = FlagStatus::PENDING;
    
  3. Bulk Actions Create a custom admin action to resolve multiple flags at once:

    // src/Admin/FlagReportAdmin.php
    use Sonata\AdminBundle\Form\FormMapper;
    use Sonata\AdminBundle\Datagrid\DatagridMapper;
    
    class FlagReportAdmin extends AbstractAdmin {
        protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
            $datagridMapper->add('status');
        }
    
        protected function configureFormFields(FormMapper $formMapper) {
            $formMapper->add('status', 'choice', [
                'choices' => FlagStatus::cases(),
            ]);
        }
    }
    
  4. Notification System Integrate with Symfony Messenger or Swiftmailer to notify users/admins:

    // src/Message/FlagCreatedMessage.php
    class FlagCreatedMessage {
        public function __construct(private FlagReport $flagReport) {}
        public function getFlagReport(): FlagReport { return $this->flagReport; }
    }
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle