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

Mattermost Bundle Laravel Package

creatissimo/mattermost-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require creatissimo/mattermost-bundle
    

    Ensure your project uses Symfony 3.4 (or adjust compatibility if using a newer version via flex overrides).

  2. Enable the Bundle Add to config/bundles.php:

    Creatissimo\MattermostBundle\CreatissimoMattermostBundle::class => ['all' => true],
    
  3. Basic Configuration Add to config/packages/creatissimo_mattermost.yaml:

    creatissimo_mattermost:
        webhook: "https://your-mattermost-instance/hooks/abc123"
        appname: "MyApp"
        username: "AppBot"
        channel: "#general"
        icon_url: "https://example.com/logo.png"
    
  4. First Use Case: Sending a Message Inject the service in a controller or command:

    use Creatissimo\MattermostBundle\Service\MattermostService;
    
    class MyController extends AbstractController
    {
        public function __construct(private MattermostService $mattermost) {}
    
        public function sendAlert()
        {
            $this->mattermost->sendMessage("Hello from Symfony!");
        }
    }
    

Implementation Patterns

Core Workflows

  1. Environment-Specific Configs Leverage the environments key to override settings per environment (e.g., dev vs. prod):

    environments:
        dev:
            channel: "#dev-alerts"
            exception:
                trace: false  # Disable stack traces in dev
    
  2. Exception Handling Automatically log exceptions to Mattermost:

    // In a service or controller
    try {
        // Risky operation
    } catch (\Exception $e) {
        $this->mattermost->sendException($e);
    }
    

    Configure exclusions in yaml to filter specific exceptions (e.g., NotFoundHttpException).

  3. Command-Line Integration Use in Symfony console commands for CI/CD or cron jobs:

    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class DeployCommand extends Command
    {
        protected static $defaultName = 'app:deploy';
    
        public function __construct(private MattermostService $mattermost) {}
    
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $this->mattermost->sendMessage("Deploy started!");
            // ... deployment logic ...
            $this->mattermost->sendMessage("Deploy completed!");
            return Command::SUCCESS;
        }
    }
    
  4. Termination Notifications Hook into Symfony’s kernel events to notify on process termination:

    terminate:
        enable: true
        exclude_exitcode: [0, 255]  # Ignore success/failure codes
    

    Trigger via event listener:

    use Symfony\Component\HttpKernel\Event\TerminateEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class MattermostTerminateSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [TerminateEvent::class => 'onTerminate'];
        }
    
        public function __construct(private MattermostService $mattermost) {}
    
        public function onTerminate(TerminateEvent $event): void
        {
            $this->mattermost->sendTerminationMessage($event->getRequest()->getServerParams());
        }
    }
    

Integration Tips

  • Dependency Injection: Prefer constructor injection for MattermostService in controllers/services.
  • Configuration Validation: Use Symfony’s validator to enforce required fields (e.g., webhook).
  • Rate Limiting: Mattermost webhooks may throttle requests. Implement retries with exponential backoff:
    $this->mattermost->sendMessage("Alert!", 3); // Retry 3 times
    
  • Dynamic Channels: Override the channel dynamically based on context:
    $this->mattermost->setChannel("#" . $user->getTeam()->getSlug());
    $this->mattermost->sendMessage("Team update!");
    

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony Version The bundle targets Symfony 3.4. For Symfony 5/6:

    • Use symfony/flex to override dependencies or fork the bundle.
    • Replace EventDispatcher calls with Symfony 5’s EventDispatcherInterface.
  2. Webhook Authentication Mattermost webhooks require incoming webhook URLs (not generic URLs). Ensure:

    • The webhook URL is from Mattermost’s Integrations > Incoming Webhooks.
    • The username and icon_url are set correctly (Mattermost validates these).
  3. Exception Trace Length Long stack traces may be truncated. Configure exception.trace carefully:

    exception:
        trace: true
        max_trace_length: 500  # Customize if needed (not natively supported; extend the service)
    
  4. Async Operations Sending messages synchronously blocks execution. For high-throughput apps:

    • Use Symfony’s Messenger component to queue messages:
      $this->messenger->dispatch(new MattermostMessage($message));
      
    • Extend the bundle to support async via doctrine/messenger or symfony/messenger.
  5. Configuration Overrides Avoid hardcoding values in services. Always use dependency-injected configs:

    // ❌ Anti-pattern
    $this->mattermost->setWebhook("hardcoded-url");
    
    // ✅ Preferred
    $this->mattermost->sendMessage("..."); // Uses injected config
    

Debugging

  1. Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        mattermost:
            type: stream
            path: "%kernel.logs_dir%/mattermost.log"
            level: debug
    

    Then enable debug mode in the bundle’s service:

    debug: true  # Add to root config
    
  2. HTTP Client Errors If messages fail silently:

    • Check Mattermost’s Audit Log for blocked webhooks.
    • Validate the webhook URL format (must include /hooks/).
    • Use GuzzleHttp\Exception\RequestException to catch HTTP errors:
      try {
          $this->mattermost->sendMessage("Test");
      } catch (RequestException $e) {
          // Log $e->getResponse()->getBody()
      }
      
  3. Channel Permissions Ensure the Mattermost user (configured via username) has post permissions in the target channel.


Extension Points

  1. Custom Message Formats Extend the MattermostService to add fields like attachments or props:

    // src/Service/ExtendedMattermostService.php
    class ExtendedMattermostService extends MattermostService
    {
        public function sendFormattedMessage(string $text, array $props = []): void
        {
            $this->sendMessage($text, [
                'props' => $props,
                'mrkdwn' => true,
            ]);
        }
    }
    

    Register as a service alias:

    services:
        Creatissimo\MattermostBundle\Service\MattermostService:
            alias: App\Service\ExtendedMattermostService
    
  2. Event Listeners Subscribe to Symfony events to auto-send messages:

    // src/EventListener/MattermostListener.php
    class MattermostListener implements KernelEvents
    {
        public function __construct(private MattermostService $mattermost) {}
    
        public function onKernelRequest(GetResponseEvent $event): void
        {
            if ($event->isMainRequest()) {
                $this->mattermost->sendMessage("Request received: " . $event->getRequest()->getPathInfo());
            }
        }
    }
    
  3. Testing Mock the service in PHPUnit:

    $mockMattermost = $this->createMock(MattermostService::class);
    $mockMattermost->expects($this->once())
        ->method('sendMessage')
        ->with("Test message");
    
    $this->container->set(MattermostService::class, $mockMattermost);
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit