Skip to content

Commit

Permalink
Merge pull request #3 from modernmcguire/feature/tags
Browse files Browse the repository at this point in the history
Feature/tags
  • Loading branch information
modernben authored Apr 11, 2024
2 parents e27493a + 66bbdbd commit 89148ce
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,42 @@ MailSpy::sent(function (MessageSent $event, Email $email) {
```


## Tags

If you want to tag your emails, you can do so by adding the `MailspyTags` concern to any of your mailable classes.

```php
use ModernMcGuire\MailSpy\Facades\MailSpy;
use ModernMcGuire\MailSpy\Traits\MailspyTags;

class MarketingPlan extends Mailable implements ShouldQueue
{
use Queueable;
use SerializesModels;
use MailspyTags;

/**
* Create a new message instance.
*
* @return void
*/
public function __construct(
public Client $client,
) {
//
}


public function tags(): array
{
return [
'client' => $this->client->id,
];
}

}

```

## Testing

Expand Down
20 changes: 20 additions & 0 deletions src/Listeners/LogSendingEmailListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Mail\Events\MessageSending;
use ModernMcGuire\MailSpy\Models\Email;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mime\Address;

class LogSendingEmailListener
Expand All @@ -26,6 +27,7 @@ public function handle(MessageSending $event)
$this->saveSenders($email, $message);
$this->saveRecipients($email, $message);
$this->saveContent($email, $message);
$this->saveTags($email, $message);
});
} catch (\Exception $e) {
report($e);
Expand Down Expand Up @@ -97,4 +99,22 @@ private function saveContent($email, $message)
'text' => $text,
]);
}

private function saveTags(Email $email, \Symfony\Component\Mime\Email $message): void
{
/** @var TagHeader $header */
$header = $message->getHeaders()->get('X-Tag');

// if method tags exists
foreach (json_decode($header->getValue(), true) as $tag => $value) {
if (is_array($value)) {
$value = json_encode($value);
}

$email->tags()->create([
'tag' => $tag,
'value' => $value,
]);
}
}
}
15 changes: 15 additions & 0 deletions src/Traits/MailspyTags.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace ModernMcGuire\MailSpy\Traits;

trait MailspyTags
{
abstract public function tags(): array;

protected function prepareMailableForDelivery()
{
$this->tag(json_encode($this->tags()));

parent::prepareMailableForDelivery();
}
}

0 comments on commit 89148ce

Please sign in to comment.