Skip to content

Commit

Permalink
Refactored code after first test
Browse files Browse the repository at this point in the history
  • Loading branch information
korridor committed Jan 6, 2023
1 parent 7dc72f7 commit c074320
Show file tree
Hide file tree
Showing 10 changed files with 173 additions and 209 deletions.
2 changes: 1 addition & 1 deletion .php-cs-fixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
return (new PhpCsFixer\Config())
->setRiskyAllowed(false)
->setRules([
'@PSR2' => true,
'@PSR12' => true,
])
->setUsingCache(true)
->setFinder(
Expand Down
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "korridor/symfony-scaleway-tem-mailer",
"type": "symfony-mailer-bridge",
"description": "Symfony Scaleway transaction email (TEM) Mailer Bridge",
"keywords": [],
"keywords": ["symfony", "scaleway", "symfony-mailer", "scaleway-api"],
"homepage": "https://github.com/korridor/symfony-scaleway-tem-mailer",
"license": "MIT",
"authors": [
Expand All @@ -29,12 +29,12 @@
},
"autoload": {
"psr-4": {
"Symfony\\Component\\Mailer\\Bridge\\Scaleway\\": "src/"
"Korridor\\SymfonyScalewayTemMailer\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Symfony\\Component\\Mailer\\Bridge\\Scaleway\\Tests\\": "tests/"
"Korridor\\SymfonyScalewayTemMailer\\Tests\\": "tests/"
}
},
"minimum-stability": "dev"
Expand Down
65 changes: 63 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Symfony Scaleway TEM mailer

[![Latest Version on Packagist](https://img.shields.io/packagist/v/korridor/symfony-scaleway-tem-mailer?style=flat-square)](https://packagist.org/packages/korridor/symfony-scaleway-tem-mailer)
[![License](https://img.shields.io/packagist/l/korridor/symfony-scaleway-tem-mailer?style=flat-square)](license.md)
[![Supported PHP versions](https://img.shields.io/packagist/php-v/korridor/symfony-scaleway-tem-mailer?style=flat-square)](https://packagist.org/packages/korridor/symfony-scaleway-tem-mailer)

## Installation

You can install the package via composer with following command:
Expand All @@ -8,11 +12,63 @@ You can install the package via composer with following command:
composer require korridor/symfony-scaleway-tem-mailer
```

### Requirements

This package is tested for the following Laravel and PHP versions:

- 9.* (PHP 8.1)

## Usage examples

### Laravel

TODO
Add the following code to the `AppServiceProvider`:

```php
use Korridor\SymfonyScalewayTemMailer\Transport\ScalewayApiTransport;
use Korridor\SymfonyScalewayTemMailer\Transport\ScalewaySmtpTransport;

// ..

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(): void
{
// ...
Mail::extend('scaleway-api', function (array $config = []) {
return new ScalewayApiTransport($config['token'], $config['region'], $config['project_id']);
});
Mail::extend('scaleway-smtp', function (array $config = []) {
return new ScalewaySmtpTransport($config['token'], $config['region'], $config['project_id']);
});
}

```

Now add the following lines to the `config/mail.php` file in the `mailers` array:

```php
'scaleway' => [
'transport' => 'scaleway-api',
'region' => env('MAIL_SCALEWAY_REGION', 'fr-par'),
'token' => env('MAIL_SCALEWAY_TOKEN'),
'project_id' => env('MAIL_SCALEWAY_PROJECT_ID'),
],
```

If you want to use the SMTP integration instead use following lines:

```php
'scaleway' => [
'transport' => 'scaleway-smtp',
'region' => env('MAIL_SCALEWAY_REGION', 'fr-par'),
'token' => env('MAIL_SCALEWAY_TOKEN'),
'project_id' => env('MAIL_SCALEWAY_PROJECT_ID'),
],
```

## Contributing

Expand All @@ -30,13 +86,18 @@ docker-compose run workspace bash
### Testing

The `composer test` command runs all tests with [phpunit](https://phpunit.de/).
The `composer test-coverage` command runs all tests with phpunit and creates a coverage report into the `coverage` folder.
The `composer test-coverage` command runs all tests with phpunit and creates a coverage report into the `coverage`
folder.

### Codeformatting/Linting

The `composer fix` command formats the code with [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer).
The `composer lint` command checks the code with [phpcs](https://github.com/squizlabs/PHP_CodeSniffer).

## Credits

The structure of the repository is inspired by the project [symfony/postmark-mailer](https://github.com/symfony/postmark-mailer).

## License

This package is licensed under the MIT License (MIT). Please see [license file](license.md) for more information.
13 changes: 0 additions & 13 deletions src/Transport/MessageStreamHeader.php

This file was deleted.

65 changes: 18 additions & 47 deletions src/Transport/ScalewayApiTransport.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
<?php

namespace Symfony\Component\Mailer\Bridge\Scaleway\Transport;
namespace Korridor\SymfonyScalewayTemMailer\Transport;

use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Exception\HttpTransportException;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractApiTransport;
use Symfony\Component\Mime\Address;
Expand All @@ -18,9 +15,6 @@
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

/**
* @author Kevin Verschaeve
*/
class ScalewayApiTransport extends AbstractApiTransport
{
private const HOST = 'api.scaleway.com';
Expand All @@ -29,18 +23,19 @@ class ScalewayApiTransport extends AbstractApiTransport

private string $region;

private $messageStream;
private string $projectId;

public function __construct(string $token, string $region, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
public function __construct(string $token, string $region, string $projectId, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
$this->token = $token;
$this->region = $region;
$this->projectId = $projectId;
parent::__construct($client, $dispatcher, $logger);
}

public function __toString(): string
{
return sprintf('scaleway+api://%s', $this->getEndpoint()).($this->messageStream ? '?message_stream='.$this->messageStream : '');
return sprintf('scaleway+api://%s', $this->getEndpoint());
}

protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $envelope): ResponseInterface
Expand All @@ -63,10 +58,10 @@ protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $e
}

if (200 !== $statusCode) {
throw new HttpTransportException('Unable to send an email: '.$result['Message'].sprintf(' (code %d).', $result['ErrorCode']), $response);
throw new HttpTransportException('Unable to send an email: '.$result['message'].' Details: '.print_r($result, true), $response);
}

$sentMessage->setMessageId($result['MessageID']);
$sentMessage->setMessageId($result['id']); // TODO: what is message_id

return $response;
}
Expand All @@ -81,6 +76,7 @@ private function getPayload(Email $email, Envelope $envelope): array
'subject' => $email->getSubject(),
'text' => $email->getTextBody(),
'html' => $email->getHtmlBody(),
'project_id' => $this->projectId,
'attachments' => $this->getAttachments($email),
];

Expand All @@ -90,36 +86,7 @@ private function getPayload(Email $email, Envelope $envelope): array
continue;
}

if ($header instanceof TagHeader) {
if (isset($payload['Tag'])) {
throw new TransportException('Scaleway only allows a single tag per email.');
}

$payload['Tag'] = $header->getValue();

continue;
}

if ($header instanceof MetadataHeader) {
$payload['Metadata'][$header->getKey()] = $header->getValue();

continue;
}

if ($header instanceof MessageStreamHeader) {
$payload['MessageStream'] = $header->getValue();

continue;
}

$payload['Headers'][] = [
'Name' => $header->getName(),
'Value' => $header->getBodyAsString(),
];
}

if (null !== $this->messageStream && !isset($payload['MessageStream'])) {
$payload['MessageStream'] = $this->messageStream;
// TODO: ?
}

return $payload;
Expand Down Expand Up @@ -171,23 +138,27 @@ private function getAttachments(Email $email): array
return $attachments;
}

/**
* @return string|null
*/
private function getEndpoint(): ?string
{
return ($this->host ?: self::HOST).($this->port ? ':'.$this->port : '');
}

/**
* @return string
*/
private function getRegion(): string
{
return $this->region;
}

/**
* @return $this
* @return string
*/
public function setMessageStream(string $messageStream): static
public function getProjectId(): string
{
$this->messageStream = $messageStream;

return $this;
return $this->projectId;
}
}
47 changes: 31 additions & 16 deletions src/Transport/ScalewaySmtpTransport.php
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
<?php

namespace Symfony\Component\Mailer\Bridge\Scaleway\Transport;
namespace Korridor\SymfonyScalewayTemMailer\Transport;

use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Component\Mime\Message;
use Symfony\Component\Mime\RawMessage;

/**
* @author Kevin Verschaeve
*/
class ScalewaySmtpTransport extends EsmtpTransport
{
private $messageStream;

private const HOSTNAME = 'smtp.tem.scw.cloud';

public function __construct(string $id, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
private string $token;

private string $region;

private string $projectId;

public function __construct(string $token, string $region, string $projectId, EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)
{
$this->token = $token;
$this->region = $region;
$this->projectId = $projectId;
parent::__construct(self::HOSTNAME, 587, false, $dispatcher, $logger);

$this->setUsername($id);
$this->setPassword($id);
$this->setUsername($projectId);
$this->setPassword($token);
}

public function send(RawMessage $message, Envelope $envelope = null): ?SentMessage
Expand All @@ -47,12 +48,26 @@ private function addScalewayHeaders(Message $message): void
}

/**
* @return $this
* @return string
*/
public function setMessageStream(string $messageStream): static
public function getToken(): string
{
$this->messageStream = $messageStream;
return $this->token;
}

return $this;
/**
* @return string
*/
public function getRegion(): string
{
return $this->region;
}

/**
* @return string
*/
public function getProjectId(): string
{
return $this->projectId;
}
}
Loading

0 comments on commit c074320

Please sign in to comment.