Weave 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

Cns Client Bundle Laravel Package

ecphp/cns-client-bundle

Symfony bundle to send notifications via the EU Corporate Notification System (CNS). Provides a simple client to deliver GDPR-compliant emails to internal and external users. Requires PHP 7.4+ and Symfony 5.3+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require ecphp/cns-client-bundle
    

    Ensure your project meets the requirements: PHP ≥ 7.4 and Symfony ≥ 5.3.

  2. Configure the Bundle Add the bundle to config/bundles.php:

    return [
        // ...
        Ecphp\CnsClientBundle\EcphpCnsClientBundle::class => ['all' => true],
    ];
    
  3. Environment Configuration Add CNS credentials to .env:

    CNS_CLIENT_ID=your_client_id
    CNS_CLIENT_SECRET=your_client_secret
    CNS_ENDPOINT=https://api.cns.example.com
    
  4. First Usage Inject the CnsClientInterface into a service/controller:

    use Ecphp\CnsClientBundle\Service\CnsClientInterface;
    
    public function __construct(private CnsClientInterface $cnsClient) {}
    
    public function sendNotification()
    {
        $recipient = new NotificationRecipient('[email protected]', 'John Doe');
        $content = new NotificationContent('Hello from CNS!');
    
        $this->cnsClient->sendNotification($recipient, $content);
    }
    

Implementation Patterns

Core Workflow: Sending Notifications

  1. Define Recipients Use NotificationRecipient for internal/external users:

    $recipient = new NotificationRecipient('[email protected]', 'John Doe', true); // GDPR-compliant
    
  2. Structure Content Use NotificationContent for subject/body:

    $content = new NotificationContent('Welcome!');
    $content->setBody('Thanks for signing up.');
    
  3. Attach Files

    $content->addAttachmentFromUpload('/path/to/file.pdf');
    // OR for remote files:
    $content->addAttachmentFromUrl('https://example.com/file.pdf');
    
  4. Send via Service

    $this->cnsClient->sendNotification($recipient, $content);
    

Advanced Patterns

Bulk Notifications

$recipients = [
    new NotificationRecipient('[email protected]', 'User 1'),
    new NotificationRecipient('[email protected]', 'User 2'),
];
$this->cnsClient->sendBulkNotification($recipients, $content);

Template-Based Emails

$content = new NotificationContent('Template ID: welcome_email');
$content->setTemplateVariables(['name' => 'John']);

Error Handling

Wrap calls in try-catch:

try {
    $this->cnsClient->sendNotification($recipient, $content);
} catch (CnsClientException $e) {
    // Log or retry (e.g., for rate limits)
    $this->logger->error('CNS Error: ' . $e->getMessage());
}

Testing

Use the CnsClientMock for unit tests:

$mock = new CnsClientMock();
$mock->expects($this->once())->method('sendNotification');
$this->cnsClient = $this->createMock(CnsClientInterface::class);

Integration Tips

  1. Symfony Events Trigger notifications via Symfony events (e.g., user.registered):

    $eventDispatcher->addListener('user.registered', function (UserRegisteredEvent $event) {
        $recipient = new NotificationRecipient($event->getUser()->getEmail());
        $content = new NotificationContent('Welcome!');
        $this->cnsClient->sendNotification($recipient, $content);
    });
    
  2. Queue Delayed Sends Use Symfony Messenger for async processing:

    $message = new SendCnsNotification($recipient, $content);
    $this->messageBus->dispatch($message);
    
  3. Logging Enable debug logging in config/packages/dev/ecphp_cns_client.yaml:

    ecphp_cns_client:
        debug: true
    

Gotchas and Tips

Pitfalls

  1. Authentication Failures

    • Ensure CNS_CLIENT_ID/SECRET are correct and not hardcoded.
    • Verify the endpoint URL (fixed in v1.0.3).
  2. Attachment Limits

    • CNS may enforce file size/type restrictions. Validate attachments before sending:
      if ($file->getSize() > 10_000_000) { // 10MB
          throw new \RuntimeException('File too large');
      }
      
  3. GDPR Compliance

    • External recipients must have isExternal = true and valid consent. Use:
      $recipient = new NotificationRecipient('[email protected]', null, true);
      
  4. Rate Limiting

    • CNS may throttle requests. Implement exponential backoff:
      $retryAfter = $response->getHeader('Retry-After');
      if ($retryAfter) {
          sleep((int) $retryAfter);
      }
      

Debugging Tips

  1. Enable Verbose Logging Add to config/services.yaml:

    services:
        Ecphp\CnsClientBundle\Service\CnsClient:
            arguments:
                $logger: '@logger'
    

    Then check var/log/dev.log for raw API responses.

  2. Mock the Client For local testing, use the CnsClientMock to simulate responses:

    $mock = new CnsClientMock();
    $mock->setResponse(new Response(200, [], json_encode(['status' => 'success'])));
    
  3. Validate JSON Payloads CNS expects strict JSON formats. Use json_encode($data, JSON_THROW_ON_ERROR) to catch malformed data.


Extension Points

  1. Custom Headers Extend the CnsClient to add headers:

    $client = new CnsClient($httpClient, $config);
    $client->addHeader('X-Custom-Header', 'value');
    
  2. Middleware Add request/response middleware via Symfony’s HTTP client:

    # config/packages/ecphp_cns_client.yaml
    ecphp_cns_client:
        http_client:
            middleware:
                - 'some.middleware.service'
    
  3. Event Subscribers Listen for cns.notification.sent events to track metrics:

    $eventDispatcher->addListener('cns.notification.sent', function (NotificationSentEvent $event) {
        $this->stats->increment('notifications.sent');
    });
    

Configuration Quirks

  1. Symfony 6+ Compatibility

    • The bundle relaxes symfony/http-client-contracts dependencies in v1.0.4.
    • Ensure symfony/http-client is installed if using Symfony 6.
  2. Default Values

    • Recipient names default to null. Set explicitly for clarity:
      $recipient = new NotificationRecipient('[email protected]', 'John Doe');
      
  3. Endpoint Overrides

    • Override the endpoint in config/packages/ecphp_cns_client.yaml:
      ecphp_cns_client:
          endpoint: 'https://custom.cns.endpoint'
      
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel