├── .dockerignore
├── .editorconfig
├── .env.example
├── .gitattributes
├── .gitignore
├── .styleci.yml
├── README.md
├── app
├── Connectors
│ ├── Connector.php
│ ├── MailjetConnector.php
│ └── SendgridConnector.php
├── Console
│ ├── Commands
│ │ ├── Consumer
│ │ │ ├── EmailConsumer.php
│ │ │ ├── EmailConsumerCancel.php
│ │ │ ├── EmailConsumerData.php
│ │ │ ├── EmailConsumerResolver.php
│ │ │ └── EmailConsumerRetry.php
│ │ └── Creator
│ │ │ ├── EmailCreation.php
│ │ │ ├── EmailCreationConverter.php
│ │ │ └── EmailCreationValidator.php
│ └── Kernel.php
├── DTO
│ ├── Email.php
│ └── EmailDTO.php
├── Enum
│ ├── Email.php
│ ├── EmailConsumer.php
│ ├── EmailCreation.php
│ ├── EmailPublisher.php
│ ├── LogMessages.php
│ ├── MailjetEmail.php
│ └── SendgridEmail.php
├── Exceptions
│ └── Handler.php
├── Http
│ ├── Controllers
│ │ ├── Controller.php
│ │ └── EmailController.php
│ ├── Kernel.php
│ ├── Middleware
│ │ ├── CheckForMaintenanceMode.php
│ │ ├── TrimStrings.php
│ │ └── TrustProxies.php
│ └── Requests
│ │ └── StoreEmailPost.php
├── Model
│ ├── Email.php
│ └── EmailModel.php
├── Providers
│ ├── AppServiceProvider.php
│ ├── AuthServiceProvider.php
│ ├── BroadcastServiceProvider.php
│ ├── EmailConsumerServiceProvider.php
│ ├── EmailPublisherServiceProvider.php
│ ├── EmailServiceProvider.php
│ ├── EventServiceProvider.php
│ └── RouteServiceProvider.php
├── Publishers
│ ├── EmailPublisher.php
│ └── Publisher.php
├── Queue.php
├── Transactors
│ ├── LogError.php
│ ├── MailerTransactor.php
│ ├── MailjetTransactor.php
│ └── SendgridTransactor.php
└── Workers
│ ├── EmailWorker.php
│ └── Worker.php
├── artisan
├── bootstrap
├── app.php
└── cache
│ └── .gitignore
├── cghooks.lock
├── composer.json
├── composer.lock
├── config
├── amqp.php
├── app.php
├── auth.php
├── broadcasting.php
├── cache.php
├── database.php
├── filesystems.php
├── hashing.php
├── logging.php
├── mail.php
├── queue.php
├── services.php
├── session.php
└── view.php
├── database
├── .gitignore
├── factories
│ └── UserFactory.php
├── migrations
│ └── 2019_11_17_220614_create_queues_table.php
└── seeds
│ └── DatabaseSeeder.php
├── infrastructure
├── docker-compose.yml
├── email_microservice
│ ├── Dockerfile
│ └── Dockerfile.dev
├── email_microservice_consumer
│ ├── Dockerfile
│ └── Dockerfile.dev
├── nginx
│ ├── Dockerfile
│ └── default.conf
└── xdebug
│ └── xdebug.ini
├── package.json
├── phpunit.xml
├── public
├── .htaccess
├── favicon.ico
├── index.php
├── robots.txt
└── web.config
├── resources
└── lang
│ └── en
│ ├── auth.php
│ ├── pagination.php
│ ├── passwords.php
│ └── validation.php
├── routes
├── api.php
├── channels.php
├── console.php
└── web.php
├── server.php
├── storage
├── app
│ ├── .gitignore
│ └── public
│ │ └── .gitignore
├── framework
│ ├── .gitignore
│ ├── cache
│ │ ├── .gitignore
│ │ └── data
│ │ │ └── .gitignore
│ ├── sessions
│ │ └── .gitignore
│ ├── testing
│ │ └── .gitignore
│ └── views
│ │ └── .gitignore
└── logs
│ └── .gitignore
└── tests
├── CreatesApplication.php
├── Feature
├── EmailTest.php
├── InvalidEmailsDataProvider.php
└── ValidEmailsDataProvider.php
├── TestCase.php
└── Unit
├── Connectors
├── MailjetConnectorTest.php
└── SendgridConnectorTest.php
├── Console
└── Commands
│ └── Creator
│ └── EmailCreationTest.php
├── DTO
└── EmailDTOTest.php
├── DataProviders
├── InvalidEmailsDataProvider.php
└── ValidEmailsDataProvider.php
├── EmailDataCreator.php
├── Publishers
└── EmailPublisherTest.php
├── Transactors
├── MailjetTransactorTest.php
└── SendgridTransactorTest.php
└── Workers
└── EmailWorkerTest.php
/.dockerignore:
--------------------------------------------------------------------------------
1 | **/.git/
2 | **/vendor/
3 | **/node_modules/
4 | **/public/js/
5 | **/public/css/
6 | **/yarn-error.log
7 | **/report/
8 | **/.idea
9 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | insert_final_newline = true
7 | indent_style = space
8 | indent_size = 4
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
14 | [*.{yml,yaml}]
15 | indent_size = 2
16 |
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | APP_NAME="Email Transactions"
2 | APP_ENV=production
3 | APP_KEY=
4 | APP_DEBUG=false
5 | APP_URL=http://localhost
6 |
7 | LOG_CHANNEL=stack
8 |
9 | DB_CONNECTION=pgsql
10 | DB_HOST=postgres.dev
11 | DB_PORT=5432
12 | DB_DATABASE=email_service
13 | DB_USERNAME=postgres
14 | DB_PASSWORD=postgres
15 |
16 | BROADCAST_DRIVER=log
17 | CACHE_DRIVER=file
18 | QUEUE_CONNECTION=sync
19 | SESSION_DRIVER=file
20 | SESSION_LIFETIME=120
21 |
22 | REDIS_HOST=127.0.0.1
23 | REDIS_PASSWORD=null
24 | REDIS_PORT=6379
25 |
26 | MAIL_DRIVER=smtp
27 | MAIL_HOST=smtp.mailtrap.io
28 | MAIL_PORT=2525
29 | MAIL_USERNAME=null
30 | MAIL_PASSWORD=null
31 | MAIL_ENCRYPTION=null
32 |
33 | AWS_ACCESS_KEY_ID=
34 | AWS_SECRET_ACCESS_KEY=
35 | AWS_DEFAULT_REGION=us-east-1
36 | AWS_BUCKET=
37 |
38 | PUSHER_APP_ID=
39 | PUSHER_APP_KEY=
40 | PUSHER_APP_SECRET=
41 | PUSHER_APP_CLUSTER=mt1
42 |
43 | MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
44 | MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
45 |
46 | MAILJET_KEY=key
47 | MAILJET_SECRET=secret
48 | MAILJET_CALL_PERFORMER=true
49 | MAILJET_VERSION=v3.1
50 |
51 | SENDGRID_API_KEY=key
52 |
53 | RABBITMQ_HOST=rabbitmq.dev
54 | RABBITMQ_PORT=5672
55 | RABBITMQ_LOGIN=guest
56 | RABBITMQ_PASSWORD=guest
57 | RABBITMQ_EXCHANGE_NAME=email_exchange
58 | RABBITMQ_EXCHANGE_TYPE=direct
59 | RABBITMQ_EXCHANGE_DURABLE=true
60 | RABBITMQ_ROUTING_KEY_NAME=email_rk
61 | RABBITMQ_QUEUE=email_queue
62 | RABBITMQ_QUEUE_DURABLE=true
63 | RABBITMQ_MAXIMUM_RETRIES=5
64 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 | *.css linguist-vendored
3 | *.scss linguist-vendored
4 | *.js linguist-vendored
5 | CHANGELOG.md export-ignore
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | /public/hot
3 | /public/storage
4 | /storage/*.key
5 | /vendor
6 | .env
7 | .env.backup
8 | .phpunit.result.cache
9 | Homestead.json
10 | Homestead.yaml
11 | npm-debug.log
12 | yarn-error.log
13 | .idea
14 | report
15 | .php_cs.cache
16 |
--------------------------------------------------------------------------------
/.styleci.yml:
--------------------------------------------------------------------------------
1 | php:
2 | preset: laravel
3 | enabled:
4 | - alpha_ordered_imports
5 | disabled:
6 | - length_ordered_imports
7 | - unused_use
8 | finder:
9 | not-name:
10 | - index.php
11 | - server.php
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Email Microservice
2 |
3 | ## Table Of Contents
4 |
5 | 1. [Setup](#setup)
6 | 1. [Clone](#clone)
7 | 1. [Environment Variables](#environment-variables)
8 | 1. [Build](#build)
9 | 1. [API](#api)
10 | 1. [Console](#console)
11 | 1. [Composer Scripts](#composer-scripts)
12 | 1. [Tests](#tests)
13 | 1. [Git Hooks](#git-hooks)
14 | 1. [Project Definitions](#project-definitions)
15 | 1. [Organization](#organization)
16 | 1. [Transactors](#transactors)
17 | 1. [Worker](#worker)
18 | 1. [Queue](#queue)
19 | 1. [Postgres](#postgres)
20 | 1. [Laravel - AMQP](#laravel---amqp)
21 | 1. [Logs](#logs)
22 | 1. [Docker](#docker)
23 | 1. [Scaling Up](#scaling-up)
24 | 1. [Next Steps](#next-steps)
25 | 1. [API Resources](#api---resources)
26 |
27 | ## Setup
28 |
29 | ### Clone
30 |
31 | Clone the project and enter on its folder:
32 |
33 | ```bash
34 | $ git clone git@gihub.com:fecaps/email_microservice.git && \
35 | cd email_microservice
36 | ```
37 |
38 | ### Environment Variables
39 |
40 | Copy env variables file and edit it in case of willing to change its configuration:
41 |
42 | ```bash
43 | $ cp .env.example .env
44 | ```
45 |
46 | ** These env variables require API keys, versions and secrets related
47 | to the email vendors used within the application:
48 |
49 | - [Mailjet](https://app.mailjet.com):
50 |
51 | - `MAILJET_KEY`
52 | - `MAILJET_SECRET`
53 |
54 |
55 | - [Sendgrid](https://app.sendgrid.com/):
56 |
57 | - `SENDGRID_API_KEY`
58 |
59 |
60 | ### Build
61 |
62 | - Build Docker image in detach mode and run it:
63 |
64 | ```bash
65 | $ docker-compose -f infrastructure/docker-compose.yml up --build -d
66 | ```
67 |
68 | ## API
69 |
70 | The default API host:port is:
71 |
72 | http://localhost:8080
73 |
74 | ## Console
75 |
76 | The console command responsible for sending emails to the queue:
77 |
78 | ```bash
79 | docker exec -it infrastructure_email_1 php artisan create:email
80 | ```
81 |
82 | ## Composer Scripts
83 |
84 | The project has these `composer` scripts:
85 |
86 | *PS.: It requires the containers running*
87 |
88 | ```bash
89 | composer run-script codeStyle
90 | # code style check
91 |
92 | composer run-script copyPasteDetector
93 | # mess detector
94 |
95 | composer run-script messDetector
96 | # copy/paste detector
97 |
98 | composer run-script objectCalisthenics
99 | # object calisthenics rules
100 |
101 | composer run-script errorsAnalyse
102 | # errors analyse
103 |
104 | composer run-script fixStyle
105 | # fix style
106 | ```
107 |
108 | ### Tests
109 |
110 | *PS.: It requires the container running*
111 |
112 | - Running tests:
113 |
114 | ```bash
115 | $ composer run-script tests
116 | ```
117 |
118 | The tests generate a HTML and TXT reports which use **XDebug** and it's
119 | located on `report` folder.
120 |
121 | - Showing code coverage in TXT:
122 |
123 | ```bash
124 | $ composer run-script showCoverage
125 | ```
126 |
127 | In case of willing to see it in HTML, open `report/index.html`
128 | file in host machine. Example:
129 |
130 | ```bash
131 | $ google-chrome report/index.html
132 | ```
133 |
134 | ### Git Hooks
135 |
136 | There are two git hooks, which are composed of **composer scripts**
137 | and **testing scripts**.
138 |
139 | - `pre-commit`:
140 | - `codeStyle`
141 | - `copyPasteDetector`
142 | - `messDetector`
143 | - `objectCalisthenics`
144 |
145 | - `pre-push`:
146 | - `codeStyle`
147 | - `copyPasteDetector`
148 | - `messDetector`
149 | - `objectCalisthenics`
150 | - `tests`
151 | - `showCoverage`
152 |
153 | ## Project Definitions
154 |
155 | ### Organization
156 |
157 | The project is composed of 4 resources:
158 | - `infrastructure_email` (the publisher - **stateless**)
159 | - `infrastructure_email_consumer` (the queue consumer - **stateless**)
160 | - `email_rabbitmq` (the queue consumer - **stateful**)
161 | - `email_nginx` (the queue consumer - **stateless**)
162 | - `infrastructure_postgres_1` (the queue messages status - **stateful**)
163 |
164 | ### Transactors
165 |
166 | An implementation of `MailerTransactor`. At the moment the application uses two
167 | transactors/vendors for delivering emails (in this order):
168 |
169 | - **Mailjet**
170 | - **Sendgrid**
171 |
172 | **Attention**
173 |
174 | These two vendors responsible for delivering emails have daily and monthly limits.
175 |
176 | **Mailjet** has a limit of 200 requests/day.
177 |
178 | **Sendgrid** has a limit of 100 requests/day.
179 |
180 | Plus these limits, **Mailjet** requires to add sender addresses in their platform,
181 | so it's safer to add both `fellipecapelli@gmail.com` and `fellipe.capelli@outlook.com`
182 | on it (which are used by the tests).
183 |
184 | ### Worker
185 |
186 | The email worker has an array of `MailerTransactors` and it tries to send an email
187 | through each one, in case of one failing then it goes to the next,
188 | in case of success it finishes the worker with a boolean `true`, making it clear
189 | the email was sent. If none vendor worked, then the worker finishes with a `false`.
190 |
191 | In case of being needed to add a new vendor then these are the steps required:
192 |
193 | - Create a config for the new vendor service in `config/service.php` file. Like the API key, etc.
194 | - Create the env variables used by the new vendor service.
195 | - Create a connector class for the new vendor service
196 | - Example: the `Mailjet` connector creates an instance of a `Mailjet Client` (third-party vendor).
197 | - Create a **singleton** instance for the new connector created (in `EmailServiceProvider`).
198 | - Create a transactor class for the new vendor service. This transactor will be responsible for
199 | sending the email only. This transactor must implements `MailerTransactor` interface.
200 | - Add the new transactor to the `AppServiceProvider`, as a dependency in the `EmailWorker` bind.
201 |
202 | ### Queue
203 |
204 | Laravel officially supports relational databases and Redis as stateful resources
205 | for dealing with queueing, however this project uses **RabbitMQ**, a message broker for queuing,
206 | these are the reasons:
207 |
208 | - When compared to any relational databases it's easier to add nodes to the RabbitMQ
209 | cluster and natively deal with which message been managed by only one consumer. In a relational database
210 | a lock field/layer on the request should be added to deal with it. Therefore it's easier
211 | to scale up with RabbitMQ.
212 |
213 | - When having network issues/breaks before actually acknowledging a
214 | message in a consumer the broker itself manages to requeue the message.
215 | In a relational database this would be managed by some tool/framework/implementation.
216 |
217 | - When compared to any relational databases it's easier to deal with race conditions, as
218 | some configurations like `prefetch` can be set in order to facilitate this.
219 |
220 | - When compared to Redis it's safer, as all data (exchanges, queues and messages)
221 | can be set as `durable/persistent` (to save in the disk), this way a broker restart wouldn't cause
222 | all messages to be lost. While an in-memory queueing doesn't prevent this, plus in
223 | a cluster (for instance, through Kubernetes) more memory would be required when scaling
224 | up, while by using disks some volumes can be added.
225 |
226 | ### Postgres
227 |
228 | Despite the usage of RabbitMQ for queueing the messages status are kept in Postgres container,
229 | this in order to allow actions like retrieving which messages have been delivered, etc.
230 |
231 | ### Laravel - AMQP
232 |
233 | - Package used to deal with AMQP in Laravel: https://github.com/bschmitt/laravel-amqp
234 |
235 | Possible improvements:
236 |
237 | - Better usage of AMQP connections and channel by choosing whether both should be closed
238 | when publishing or consuming a message.
239 | - Improve prefetch configuration for channels.
240 | - Add support for custom properties (headers) when publishing messages, this way can be
241 | possible to set messages TTL, retries, etc.
242 |
243 | ### Logs
244 |
245 | As this microservice is still small there are no third-party services, such as Graylog
246 | (Mongo, Elasticsearch) to deal with logging. They are still managed through
247 | log files (which are docker volumes).
248 |
249 | Publisher logs:
250 | `/storage/logs/publisher.log`
251 |
252 | Consumer logs:
253 | `/storage/logs/consumer.log`
254 |
255 | ### Docker
256 |
257 | - **Docker:** All files related to **Docker** and **docker-compose**
258 | are set within `infrastructure` folder.
259 |
260 | The `infrastructure_email_1` and `infrastructure_email_consumer_1` resources have **multi-stage** builds.
261 | Which are composed of two steps:
262 |
263 | - Composer
264 | - Installing PHP extensions, Composer dependencies and configuring web/app server
265 |
266 | There are two `Dockerfiles`, one is used for
267 | `development` and another for `production`.
268 |
269 | The one used for `development` contains `XDebug` and **dev dependencies**.
270 |
271 | ### Scaling Up
272 |
273 | All **stateless** can be scaled horizontally. Examples:
274 |
275 | - Scaling up email consumers to 3:
276 |
277 | ```bash
278 | $ docker-compose -f infrastructure/docker-compose.yml up --scale email_consumer=3 --build
279 | ```
280 |
281 | - Scaling up email app servers to 2 and consumers to 3:
282 |
283 | ** Each app server added requires adding `server infrastructure_email_{count}:9000;` to
284 | the `upstream` config on **Nginx** file (`infrastructure/nginx/default.conf`).
285 |
286 | ```bash
287 | $ docker-compose -f infrastructure/docker-compose.yml up --scale email=2 --scale email_consumer=3 --build
288 | ```
289 |
290 | ### Next Steps
291 |
292 | - Create a frontend application to list the messages based on endpoint created above
293 | - Create a form in the frontend in order to also create new emails
294 | - Add Swagger for API documentation
295 | - Add a repository for the `Queue` entity
296 | - Add Kubernetes to the stateful and stateless resources
297 |
298 | ## API - Resources
299 |
300 | Host: `http://localhost:8080`
301 |
302 | - **Get all email transactions**
303 |
304 | - Resource: `GET /emails`
305 |
306 | - **Create email resource**
307 |
308 | - Resource: `POST /emails`
309 |
310 | - Input Payload:
311 |
312 | - Example of text content:
313 | ```json
314 | {
315 | "from": {
316 | "email": "testmail@test.com",
317 | "name": "test"
318 | },
319 | "to": [
320 | {
321 | "email": "testmail1@test.com",
322 | "name": "test1"
323 | }
324 | ],
325 | "subject": "hello - test",
326 | "textPart": "hello - text test"
327 | }
328 | ```
329 |
330 | - Example of html content:
331 | ```json
332 | {
333 | "from": {
334 | "email": "testmail@test.com",
335 | "name": "test"
336 | },
337 | "to": [
338 | {
339 | "email": "testmail1@test.com",
340 | "name": "test1"
341 | }
342 | ],
343 | "subject": "hello - test",
344 | "htmlPart": "hello
html test"
345 | }
346 | ```
347 |
348 | - Example of markdown content:
349 | ```json
350 | {
351 | "from": {
352 | "email": "testmail@test.com",
353 | "name": "test"
354 | },
355 | "to": [
356 | {
357 | "email": "testmail1@test.com",
358 | "name": "test1"
359 | }
360 | ],
361 | "subject": "hello - test",
362 | "markdownPart": "hello, **markdown** test"
363 | }
364 | ```
365 |
--------------------------------------------------------------------------------
/app/Connectors/Connector.php:
--------------------------------------------------------------------------------
1 | client = new Client(
20 | $config['key'],
21 | $config['secret'],
22 | $config['performer'],
23 | [
24 | 'version' => $config['version']
25 | ]
26 | );
27 | }
28 |
29 | /**
30 | * Get Mailjet client connection.
31 | *
32 | * @return Client
33 | */
34 | public function getClient(): Client
35 | {
36 | return $this->client;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/Connectors/SendgridConnector.php:
--------------------------------------------------------------------------------
1 | client = new SendGrid($config['key']);
20 | }
21 |
22 | /**
23 | * Get SendGrid client connection.
24 | *
25 | * @return SendGrid
26 | */
27 | public function getClient(): SendGrid
28 | {
29 | return $this->client;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/Console/Commands/Consumer/EmailConsumer.php:
--------------------------------------------------------------------------------
1 | publisher = $publisher;
62 | $this->worker = $worker;
63 | $this->queue = $queue;
64 | $this->emailDTO = $emailDTO;
65 | $this->queueName = $queueName;
66 | $this->maxRetries = $maxRetries;
67 | }
68 |
69 | /**
70 | * Execute the console command.
71 | *
72 | * @return mixed
73 | */
74 | public function handle(): void
75 | {
76 | try {
77 | $this->info(EmailConsumerEnum::CONSUMER_START);
78 |
79 | \Amqp::consume($this->queueName, function ($message, $resolver) {
80 | $messageData = $this->getMessageData($message);
81 | $this->saveEmailData($this->emailDTO, $messageData);
82 | $retries = $messageData[EmailConsumerEnum::RETRIES_KEY];
83 |
84 | if ($this->emailDTO->getId()) {
85 | $this->queue->updateStatusToBounced($this->emailDTO->getId());
86 | }
87 |
88 | $this->consumeMessage($resolver, $message, $retries);
89 | });
90 | } catch (\Exception $exception) {
91 | $this->logConsumerError($exception);
92 | }
93 | }
94 |
95 | private function consumeMessage($resolver, $message, int $retries): void
96 | {
97 | try {
98 | if (isset($retries) && $retries >= $this->maxRetries) {
99 | $this->cancelMessage($this->emailDTO, $this->queue, $resolver, $message);
100 | return;
101 | }
102 |
103 | $this->resolveMessage(
104 | $this->worker,
105 | $this->emailDTO,
106 | $this->queue,
107 | $this->publisher,
108 | $retries,
109 | $resolver,
110 | $message
111 | );
112 | } catch (\Exception $exception) {
113 | $this->retryMessage($this->publisher, $this->emailDTO, $retries, $resolver, $message);
114 | }
115 | }
116 |
117 | private function getMessageData($message): array
118 | {
119 | $body = (array)($message->body);
120 | return json_decode($body[0], true);
121 | }
122 |
123 | private function logConsumerError(\Exception $exception): void
124 | {
125 | $error = sprintf(
126 | '%s: %s',
127 | EmailConsumerEnum::CONSUMER_ERROR,
128 | $exception->getMessage()
129 | );
130 |
131 | $this->error($error);
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/app/Console/Commands/Consumer/EmailConsumerCancel.php:
--------------------------------------------------------------------------------
1 | info(EmailConsumerEnum::CONSUMER_REMOVED);
16 | $resolver->reject($message);
17 | $this->logCancel($emailDTO);
18 |
19 | if ($emailDTO->getId()) {
20 | $queue->updateStatusToFailed($emailDTO->getId());
21 | }
22 | }
23 |
24 | private function logCancel(Email $emailDTO): void
25 | {
26 | $logMessage = sprintf(
27 | LogMessages::MESSAGE_REMOVED,
28 | json_encode($emailDTO->get())
29 | );
30 |
31 | \Log::channel('consumer')->info($logMessage);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/app/Console/Commands/Consumer/EmailConsumerData.php:
--------------------------------------------------------------------------------
1 | defineId($emailData[EmailEnum::ID_KEY]);
18 | }
19 |
20 | $emailDTO->defineFrom($emailData[EmailEnum::FROM_KEY]);
21 | $emailDTO->defineTo($emailData[EmailEnum::TO_KEY]);
22 | $emailDTO->defineSubject($emailData[EmailEnum::SUBJECT_KEY]);
23 |
24 | $this->defineTextPart($emailDTO, $emailData);
25 | $this->defineHtmlPart($emailDTO, $emailData);
26 | $this->defineMarkdownPart($emailDTO, $emailData);
27 | }
28 |
29 | private function defineTextPart(Email $emailDTO, array $email): void
30 | {
31 | if (array_key_exists(EmailEnum::TEXT_PART_KEY, $email)) {
32 | $emailDTO->defineTextPart($email[EmailEnum::TEXT_PART_KEY]);
33 | }
34 | }
35 |
36 | private function defineHtmlPart(Email $emailDTO, array $email): void
37 | {
38 | if (array_key_exists(EmailEnum::HTML_PART_KEY, $email)) {
39 | $emailDTO->defineHtmlPart($email[EmailEnum::HTML_PART_KEY]);
40 | }
41 | }
42 |
43 | private function defineMarkdownPart(Email $emailDTO, array $email): void
44 | {
45 | if (array_key_exists(EmailEnum::MARKDOWN_PART_KEY, $email)) {
46 | $emailDTO->defineMarkdownPart($email[EmailEnum::MARKDOWN_PART_KEY]);
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/Console/Commands/Consumer/EmailConsumerResolver.php:
--------------------------------------------------------------------------------
1 | sendEmail($emailDTO);
25 |
26 | if (!$messageSent) {
27 | $this->retryMessage($publisher, $emailDTO, $retries, $resolver, $message);
28 | return;
29 | }
30 |
31 | $resolver->acknowledge($message);
32 | $this->logResolver($emailDTO);
33 |
34 | if ($emailDTO->getId()) {
35 | $queue->updateStatusToDelivered($emailDTO->getId());
36 | }
37 |
38 | $this->info(EmailConsumerEnum::CONSUMER_ACK);
39 | }
40 |
41 | private function logResolver(Email $emailDTO): void
42 | {
43 | $logMessage = sprintf(
44 | LogMessages::MESSAGE_RESOLVED,
45 | json_encode($emailDTO->get())
46 | );
47 |
48 | \Log::channel('consumer')->info($logMessage);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/Console/Commands/Consumer/EmailConsumerRetry.php:
--------------------------------------------------------------------------------
1 | reject($message);
15 |
16 | $this->info(EmailConsumerEnum::CONSUMER_NACK);
17 |
18 | $retriesPerformedMessage = sprintf(
19 | '%s: %s',
20 | EmailConsumerEnum::CONSUMER_RETRIES,
21 | $retries
22 | );
23 |
24 | $this->info($retriesPerformedMessage);
25 |
26 | $publisher->handle($emailDTO, ++$retries);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/Console/Commands/Creator/EmailCreation.php:
--------------------------------------------------------------------------------
1 | emailModel = $emailModel;
43 | }
44 |
45 | /**
46 | * Execute the console command.
47 | *
48 | * @return string
49 | */
50 | public function handle(): string
51 | {
52 | $this->info(EmailCreationEnum::START_MESSAGE);
53 |
54 | $fromEmail = $this->ask(EmailCreationEnum::FROM_EMAIL_MESSAGE);
55 | $fromName = $this->ask(EmailCreationEnum::FROM_NAME_MESSAGE);
56 | $toEmail = $this->ask(EmailCreationEnum::TO_EMAIL_MESSAGE);
57 | $toName = $this->ask(EmailCreationEnum::TO_NAME_MESSAGE);
58 | $subject = $this->ask(EmailCreationEnum::SUBJECT_MESSAGE);
59 | $textPart = $this->ask(EmailCreationEnum::TEXT_PART_MESSAGE);
60 | $htmlPart = $this->ask(EmailCreationEnum::HTML_PART_MESSAGE);
61 | $markdownPart = $this->ask(EmailCreationEnum::MARKDOWN_PART_MESSAGE);
62 |
63 | $validationData = $this
64 | ->createArrayData($fromEmail, $fromName, $toEmail, $toName, $subject, $textPart, $htmlPart, $markdownPart);
65 |
66 | return $this->validateEmail($validationData);
67 | }
68 |
69 | private function createArrayData(
70 | $fromEmail,
71 | $fromName,
72 | $toEmail,
73 | $toName,
74 | $subject,
75 | $textPart,
76 | $htmlPart,
77 | $markdownPart
78 | ): array {
79 | return [
80 | EmailCreationEnum::FROM_EMAIL_KEY => $fromEmail,
81 | EmailCreationEnum::FROM_NAME_KEY => $fromName,
82 | EmailCreationEnum::TO_EMAIL_KEY => $toEmail,
83 | EmailCreationEnum::TO_NAME_KEY => $toName,
84 | EmailCreationEnum::SUBJECT_KEY => $subject,
85 | EmailCreationEnum::TEXT_PART_KEY => $textPart,
86 | EmailCreationEnum::HTML_PART_KEY => $htmlPart,
87 | EmailCreationEnum::MARKDOWN_PART_KEY => $markdownPart,
88 | ];
89 | }
90 |
91 | private function validateEmail(array $emailData)
92 | {
93 | $validatorData = $this->defineValidatorData($emailData);
94 | $validatorRules = $this->defineValidatorRules();
95 |
96 | $validator = Validator::make($validatorData, $validatorRules);
97 |
98 | if ($validator->fails()) {
99 | return $this->showErrors($validator);
100 | }
101 |
102 | \Log::channel('publisher')->info(LogMessages::START_CONSOLE);
103 | return $this->createEmail($emailData);
104 | }
105 |
106 | private function createEmail(array $emailData): string
107 | {
108 | $data = $this->prepareEmailPayload($emailData);
109 | $this->emailModel->storeEmail($data);
110 |
111 | $this->info(EmailCreationEnum::END_MESSAGE);
112 | return EmailCreationEnum::END_MESSAGE;
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/app/Console/Commands/Creator/EmailCreationConverter.php:
--------------------------------------------------------------------------------
1 | [
14 | 'email' => $emailData[EmailCreationEnum::FROM_EMAIL_KEY],
15 | 'name' => $emailData[EmailCreationEnum::FROM_NAME_KEY],
16 | ],
17 | 'to' => [
18 | [
19 | 'email' => $emailData[EmailCreationEnum::TO_EMAIL_KEY],
20 | 'name' => $emailData[EmailCreationEnum::TO_NAME_KEY],
21 | ],
22 | ],
23 | EmailCreationEnum::SUBJECT_KEY => $emailData[EmailCreationEnum::SUBJECT_KEY],
24 | ];
25 |
26 | $payload = $this->addContentKeyToPayload($payload, $emailData, EmailCreationEnum::TEXT_PART_KEY);
27 | $payload = $this->addContentKeyToPayload($payload, $emailData, EmailCreationEnum::HTML_PART_KEY);
28 |
29 | return $this->addContentKeyToPayload($payload, $emailData, EmailCreationEnum::MARKDOWN_PART_KEY);
30 | }
31 |
32 | private function addContentKeyToPayload(array $payload, array $emailData, string $key): array
33 | {
34 | if ($emailData[$key]) {
35 | $payload = array_merge($payload, [ $key => $emailData[$key] ]);
36 | }
37 |
38 | return $payload;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/Console/Commands/Creator/EmailCreationValidator.php:
--------------------------------------------------------------------------------
1 | $defaultEmailRule,
18 | EmailCreationEnum::FROM_NAME_KEY => $defaultStringRule,
19 | EmailCreationEnum::TO_EMAIL_KEY => $defaultEmailRule,
20 | EmailCreationEnum::TO_NAME_KEY => $defaultStringRule,
21 | EmailCreationEnum::SUBJECT_KEY => $defaultStringRule,
22 | EmailCreationEnum::TEXT_PART_KEY => 'required_without_all:htmlPart,markdownPart|min:1|string',
23 | EmailCreationEnum::HTML_PART_KEY => 'required_without_all:textPart,markdownPart|min:1|string',
24 | EmailCreationEnum::MARKDOWN_PART_KEY => 'required_without_all:textPart,htmlPart|min:1|string',
25 | ];
26 | }
27 |
28 | protected function defineValidatorData(array $emailData): array
29 | {
30 | $payload = [
31 | EmailCreationEnum::FROM_EMAIL_KEY => $emailData[EmailCreationEnum::FROM_EMAIL_KEY],
32 | EmailCreationEnum::FROM_NAME_KEY => $emailData[EmailCreationEnum::FROM_NAME_KEY],
33 | EmailCreationEnum::TO_EMAIL_KEY => $emailData[EmailCreationEnum::TO_EMAIL_KEY],
34 | EmailCreationEnum::TO_NAME_KEY => $emailData[EmailCreationEnum::TO_NAME_KEY],
35 | EmailCreationEnum::SUBJECT_KEY => $emailData[EmailCreationEnum::SUBJECT_KEY],
36 | ];
37 |
38 | $payload = $this->defineContentPartData($payload, $emailData, EmailCreationEnum::TEXT_PART_KEY);
39 | $payload = $this->defineContentPartData($payload, $emailData, EmailCreationEnum::HTML_PART_KEY);
40 | return $this->defineContentPartData($payload, $emailData, EmailCreationEnum::MARKDOWN_PART_KEY);
41 | }
42 |
43 | private function defineContentPartData(array $payload, array $emailData, string $key): array
44 | {
45 | if (!$emailData[$key]) {
46 | return $payload;
47 | }
48 |
49 | return array_merge($payload, [ $key => $emailData[$key] ]);
50 | }
51 |
52 | protected function showErrors(ValidationValidator $validator)
53 | {
54 | $this->info(EmailCreationEnum::INVALID_MESSAGE);
55 |
56 | $errors = $validator->errors();
57 |
58 | foreach ($errors->all() as $error) {
59 | $this->error($error);
60 | }
61 |
62 | return 1;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/app/Console/Kernel.php:
--------------------------------------------------------------------------------
1 | command('inspire')
28 | // ->hourly();
29 | }
30 |
31 | /**
32 | * Register the commands for the application.
33 | *
34 | * @return void
35 | */
36 | protected function commands()
37 | {
38 | $this->load(__DIR__.'/Commands');
39 |
40 | require base_path('routes/console.php');
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/DTO/Email.php:
--------------------------------------------------------------------------------
1 | id;
24 | }
25 |
26 | /**
27 | * @param int $id
28 | * @return void
29 | */
30 | public function defineId($id): void
31 | {
32 | if ($id === null || !is_int($id)) {
33 | return;
34 | }
35 |
36 | $this->id = $id;
37 | }
38 |
39 | /**
40 | * @param array $from
41 | * @return void
42 | */
43 | public function defineFrom($from): void
44 | {
45 | if ($from === null || !is_array($from)) {
46 | return;
47 | }
48 |
49 | if (sizeof($from) === 0) {
50 | return;
51 | }
52 |
53 | $this->from = $from;
54 | }
55 |
56 | /**
57 | * @param array $to
58 | * @return void
59 | */
60 | public function defineTo($to): void
61 | {
62 | if ($to === null || !is_array($to)) {
63 | return;
64 | }
65 |
66 | if (sizeof($to) === 0) {
67 | return;
68 | }
69 |
70 | if (!is_array($to[0])) {
71 | return;
72 | }
73 |
74 | $this->to = $to;
75 | }
76 |
77 | /**
78 | * @param string $subject
79 | * @return void
80 | */
81 | public function defineSubject($subject): void
82 | {
83 | if ($subject === null || !is_string($subject)) {
84 | return;
85 | }
86 |
87 | $this->subject = $subject;
88 | }
89 |
90 | /**
91 | * @param string $textPart
92 | * @return void
93 | */
94 | public function defineTextPart($textPart): void
95 | {
96 | if ($textPart === null || !is_string($textPart)) {
97 | return;
98 | }
99 |
100 | $this->textPart = $textPart;
101 | }
102 |
103 | /**
104 | * @param string $htmlPart
105 | * @return void
106 | */
107 | public function defineHtmlPart($htmlPart): void
108 | {
109 | if ($htmlPart === null || !is_string($htmlPart)) {
110 | return;
111 | }
112 |
113 | $this->htmlPart = $htmlPart;
114 | }
115 |
116 | /**
117 | * @param string $markdownPart
118 | * @return void
119 | */
120 | public function defineMarkdownPart($markdownPart): void
121 | {
122 | if ($markdownPart === null || !is_string($markdownPart)) {
123 | return;
124 | }
125 |
126 | $this->markdownPart = $markdownPart;
127 | }
128 |
129 | /**
130 | * @return array
131 | */
132 | public function get(): array
133 | {
134 | $email = [
135 | EmailEnum::FROM_KEY => $this->from,
136 | EmailEnum::TO_KEY => $this->to,
137 | EmailEnum::SUBJECT_KEY => $this->subject,
138 | ];
139 |
140 | $email = $this->defineValueOnPath($this->textPart, EmailEnum::TEXT_PART_KEY, $email);
141 | $email = $this->defineValueOnPath($this->htmlPart, EmailEnum::HTML_PART_KEY, $email);
142 | $email = $this->defineValueOnPath($this->markdownPart, EmailEnum::MARKDOWN_PART_KEY, $email);
143 |
144 | return $this->defineValueOnPath($this->id, EmailEnum::ID_KEY, $email);
145 | }
146 |
147 | private function defineValueOnPath($value, string $path, array $email): array
148 | {
149 | if ($value !== null) {
150 | $email[$path] = $value;
151 | }
152 |
153 | return $email;
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/app/Enum/Email.php:
--------------------------------------------------------------------------------
1 | renderResourceNotFound();
57 | }
58 |
59 | if ($exception instanceof MethodNotAllowedHttpException) {
60 | return $this->renderResourceNotAllowed();
61 | }
62 |
63 | return parent::render($request, $exception);
64 | }
65 |
66 | /**
67 | * Render Resource Not found
68 | *
69 | * @return Response
70 | */
71 | private function renderResourceNotFound(): Response
72 | {
73 | return response()->json([
74 | 'message' => 'Resource Not Found',
75 | 'errors' => [
76 | 'http_headers;url' => 'Resource not found for this HTTP headers and URL'
77 | ]
78 | ], self::NOT_FOUND_HTTP_CODE);
79 | }
80 |
81 | /**
82 | * Render Resource Not Allowed
83 | *
84 | * @return Response
85 | */
86 | private function renderResourceNotAllowed(): Response
87 | {
88 | return response()->json([
89 | 'message' => 'Resource Not Allowed',
90 | 'errors' => [
91 | 'http_method;http_headers' => 'Resource not allowed for this HTTP method and HTTP headers'
92 | ]
93 | ], self::METHOD_NOT_ALLOWED_HTTP_CODE);
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/app/Http/Controllers/Controller.php:
--------------------------------------------------------------------------------
1 | all();
22 | $emailStored = $model->storeEmail($email);
23 |
24 | return response()
25 | ->json([ 'data' => $emailStored ])
26 | ->setStatusCode(201);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/Http/Kernel.php:
--------------------------------------------------------------------------------
1 | [
31 | \App\Http\Middleware\EncryptCookies::class,
32 | \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
33 | \Illuminate\Session\Middleware\StartSession::class,
34 | // \Illuminate\Session\Middleware\AuthenticateSession::class,
35 | \Illuminate\View\Middleware\ShareErrorsFromSession::class,
36 | \App\Http\Middleware\VerifyCsrfToken::class,
37 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
38 | ],
39 |
40 | 'api' => [
41 | 'throttle:60,1',
42 | 'bindings',
43 | ],
44 | ];
45 |
46 | /**
47 | * The application's route middleware.
48 | *
49 | * These middleware may be assigned to groups or used individually.
50 | *
51 | * @var array
52 | */
53 | protected $routeMiddleware = [
54 | 'auth' => \App\Http\Middleware\Authenticate::class,
55 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
56 | 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
57 | 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
58 | 'can' => \Illuminate\Auth\Middleware\Authorize::class,
59 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
60 | 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
61 | 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
62 | 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
63 | 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
64 | ];
65 |
66 | /**
67 | * The priority-sorted list of middleware.
68 | *
69 | * This forces non-global middleware to always be in the given order.
70 | *
71 | * @var array
72 | */
73 | protected $middlewarePriority = [
74 | \Illuminate\Session\Middleware\StartSession::class,
75 | \Illuminate\View\Middleware\ShareErrorsFromSession::class,
76 | \App\Http\Middleware\Authenticate::class,
77 | \Illuminate\Routing\Middleware\ThrottleRequests::class,
78 | \Illuminate\Session\Middleware\AuthenticateSession::class,
79 | \Illuminate\Routing\Middleware\SubstituteBindings::class,
80 | \Illuminate\Auth\Middleware\Authorize::class,
81 | ];
82 | }
83 |
--------------------------------------------------------------------------------
/app/Http/Middleware/CheckForMaintenanceMode.php:
--------------------------------------------------------------------------------
1 | 'required|array',
32 | 'from.email' => $defaultEmailRule,
33 | 'from.name' => $defaultStringRule,
34 | 'to' => 'required|array',
35 | 'to.*.email' => $defaultEmailRule,
36 | 'to.*.name' => $defaultStringRule,
37 | 'subject' => $defaultStringRule,
38 | 'textPart' => 'required_without_all:htmlPart,markdownPart|min:1|string',
39 | 'htmlPart' => 'required_without_all:textPart,markdownPart|min:1|string',
40 | 'markdownPart' => 'required_without_all:textPart,htmlPart|min:1|string',
41 | ];
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/app/Model/Email.php:
--------------------------------------------------------------------------------
1 | emailDTO = $emailDTO;
21 | $this->queue = $queue;
22 | $this->publisher = $publisher;
23 | }
24 |
25 | public function storeEmail(array $email): array
26 | {
27 | \Log::channel('publisher')->info(LogMessages::START_WEB);
28 |
29 | $id = $this->queue->addToQueue($email);
30 |
31 | $this->emailDTO->defineId($id);
32 | $this->emailDTO->defineFrom($email[EmailEnum::FROM_KEY]);
33 | $this->emailDTO->defineTo($email[EmailEnum::TO_KEY]);
34 | $this->emailDTO->defineSubject($email[EmailEnum::SUBJECT_KEY]);
35 |
36 | $this->defineTextPart($email);
37 | $this->defineHtmlPart($email);
38 | $this->defineMarkdownPart($email);
39 |
40 | $this->publisher->handle($this->emailDTO);
41 |
42 | return $this->emailDTO->get();
43 | }
44 |
45 | private function defineTextPart(array $email): void
46 | {
47 | if (array_key_exists(EmailEnum::TEXT_PART_KEY, $email)) {
48 | $this->emailDTO->defineTextPart($email[EmailEnum::TEXT_PART_KEY]);
49 | }
50 | }
51 |
52 | private function defineHtmlPart(array $email): void
53 | {
54 | if (array_key_exists(EmailEnum::HTML_PART_KEY, $email)) {
55 | $this->emailDTO->defineHtmlPart($email[EmailEnum::HTML_PART_KEY]);
56 | }
57 | }
58 |
59 | private function defineMarkdownPart(array $email): void
60 | {
61 | if (array_key_exists(EmailEnum::MARKDOWN_PART_KEY, $email)) {
62 | $this->emailDTO->defineMarkdownPart($email[EmailEnum::MARKDOWN_PART_KEY]);
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/app/Providers/AppServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->bind(DTO\Email::class, DTO\EmailDTO::class);
22 |
23 | $this->app->bind(Publishers\Publisher::class, Publishers\EmailPublisher::class);
24 |
25 | $this->app->bind(Workers\Worker::class, static function ($app) {
26 | return new Workers\EmailWorker([
27 | $app->make(Transactors\MailjetTransactor::class),
28 | $app->make(Transactors\SendgridTransactor::class),
29 | ]);
30 | });
31 |
32 | $this->app->bind(Model\Email::class, Model\EmailModel::class);
33 | }
34 |
35 | /**
36 | * Bootstrap any application services.
37 | *
38 | * @return void
39 | */
40 | public function boot()
41 | {
42 | //
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/Providers/AuthServiceProvider.php:
--------------------------------------------------------------------------------
1 | 'App\Policies\ModelPolicy',
17 | ];
18 |
19 | /**
20 | * Register any authentication / authorization services.
21 | *
22 | * @return void
23 | */
24 | public function boot()
25 | {
26 | $this->registerPolicies();
27 |
28 | //
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/Providers/BroadcastServiceProvider.php:
--------------------------------------------------------------------------------
1 | defineQueueName();
19 | $maxRetries = $this->defineMaxRetries();
20 |
21 | $queueNameWhen = $this->app->when(EmailConsumer::class);
22 | $queueNameNeeds = $queueNameWhen->needs('$queueName');
23 | $queueNameNeeds->give($queueName);
24 |
25 | $maxRetriesWhen = $this->app->when(EmailConsumer::class);
26 | $maxRetriesNeeds = $maxRetriesWhen->needs('$maxRetries');
27 | $maxRetriesNeeds->give($maxRetries);
28 | }
29 |
30 | private function defineQueueName(): string
31 | {
32 | return env('RABBITMQ_QUEUE', EmailConsumerEnum::DEFAULT_QUEUE);
33 | }
34 |
35 | private function defineMaxRetries(): int
36 | {
37 | return (int)(env('RABBITMQ_MAXIMUM_RETRIES', EmailConsumerEnum::DEFAULT_MAX_RETRIES));
38 | }
39 |
40 | /**
41 | * Bootstrap services.
42 | *
43 | * @return void
44 | */
45 | public function boot()
46 | {
47 | //
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/Providers/EmailPublisherServiceProvider.php:
--------------------------------------------------------------------------------
1 | defineRoutingKeyName();
19 | $exchangeName = $this->defineExchangeName();
20 | $queueName = $this->defineQueueName();
21 |
22 | $routingKeyWhen = $this->app->when(EmailPublisher::class);
23 | $routingKeyNeeds = $routingKeyWhen->needs('$routingKeyName');
24 | $routingKeyNeeds->give($routingKeyName);
25 |
26 | $exchangeWhen = $this->app->when(EmailPublisher::class);
27 | $exchangeNeeds = $exchangeWhen->needs('$exchangeName');
28 | $exchangeNeeds->give($exchangeName);
29 |
30 | $queueNameWhen = $this->app->when(EmailPublisher::class);
31 | $queueNameNeeds = $queueNameWhen->needs('$queueName');
32 | $queueNameNeeds->give($queueName);
33 | }
34 |
35 | private function defineRoutingKeyName(): string
36 | {
37 | return env('RABBITMQ_ROUTING_KEY_NAME', EmailPublisherEnum::DEFAULT_ROUTING_KEY);
38 | }
39 |
40 | private function defineExchangeName(): string
41 | {
42 | return env('RABBITMQ_EXCHANGE_NAME', EmailPublisherEnum::DEFAULT_EXCHANGE);
43 | }
44 |
45 | private function defineQueueName(): string
46 | {
47 | return env('RABBITMQ_QUEUE', EmailPublisherEnum::DEFAULT_QUEUE);
48 | }
49 |
50 |
51 | /**
52 | * Bootstrap services.
53 | *
54 | * @return void
55 | */
56 | public function boot()
57 | {
58 | //
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/app/Providers/EmailServiceProvider.php:
--------------------------------------------------------------------------------
1 | app->singleton(MailjetConnector::class, function ($app) {
19 | $config = $app->make('config');
20 | $maijetConfig = $config->get('services.mailjet', []);
21 |
22 | return new MailjetConnector($maijetConfig);
23 | });
24 |
25 | $this->app->singleton(SendgridConnector::class, function ($app) {
26 | $config = $app->make('config');
27 | $sendgridConfig = $config->get('services.sendgrid', []);
28 |
29 | return new SendgridConnector($sendgridConfig);
30 | });
31 | }
32 |
33 | /**
34 | * Bootstrap services.
35 | *
36 | * @return void
37 | */
38 | public function boot()
39 | {
40 | //
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/Providers/EventServiceProvider.php:
--------------------------------------------------------------------------------
1 | [
19 | SendEmailVerificationNotification::class,
20 | ],
21 | ];
22 |
23 | /**
24 | * Register any events for your application.
25 | *
26 | * @return void
27 | */
28 | public function boot()
29 | {
30 | parent::boot();
31 |
32 | //
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/Providers/RouteServiceProvider.php:
--------------------------------------------------------------------------------
1 | mapApiRoutes();
39 |
40 | $this->mapWebRoutes();
41 |
42 | //
43 | }
44 |
45 | /**
46 | * Define the "web" routes for the application.
47 | *
48 | * These routes all receive session state, CSRF protection, etc.
49 | *
50 | * @return void
51 | */
52 | protected function mapWebRoutes()
53 | {
54 | Route::middleware('web')
55 | ->namespace($this->namespace)
56 | ->group(base_path('routes/web.php'));
57 | }
58 |
59 | /**
60 | * Define the "api" routes for the application.
61 | *
62 | * These routes are typically stateless.
63 | *
64 | * @return void
65 | */
66 | protected function mapApiRoutes()
67 | {
68 | Route::middleware('api')
69 | ->namespace($this->namespace)
70 | ->group(base_path('routes/api.php'));
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/Publishers/EmailPublisher.php:
--------------------------------------------------------------------------------
1 | routingKeyName = $routingKeyName;
25 | $this->exchangeName = $exchangeName;
26 | $this->queueName = $queueName;
27 | }
28 |
29 | /**
30 | * Execute the job.
31 | *
32 | * @param Email $emailDTO
33 | * @param int $retries
34 | * @return void
35 | */
36 | public function handle(Email $emailDTO, int $retries = EmailPublisherEnum::DEFAULT_RETRY): void
37 | {
38 | $publisherData = [
39 | 'data' => $emailDTO->get(),
40 | 'retries' => $retries,
41 | ];
42 |
43 | $stringMessage = json_encode($publisherData);
44 |
45 | \Amqp::publish(
46 | $this->routingKeyName,
47 | $stringMessage,
48 | [
49 | 'queue' => $this->queueName,
50 | 'exchange' => $this->exchangeName
51 | ]
52 | );
53 |
54 | $this->logPublish($stringMessage, $retries);
55 | }
56 |
57 | private function logPublish(string $stringMessage, int $retries): void
58 | {
59 | $logMessage = sprintf(
60 | LogMessages::MESSAGE_PUBLISHED,
61 | $stringMessage,
62 | $retries
63 | );
64 |
65 | \Log::channel('publisher')->info($logMessage);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/app/Publishers/Publisher.php:
--------------------------------------------------------------------------------
1 | 'queued',
20 | 'message' => json_encode([ 'data' => $data ]),
21 | ]);
22 |
23 | return $data['id'];
24 | }
25 |
26 | public function updateStatusToBounced(int $id): void
27 | {
28 | self::where([ 'id' => $id ])
29 | ->update([ 'status' => 'bounced' ]);
30 | }
31 |
32 | public function updateStatusToFailed(int $id): void
33 | {
34 | self::where([ 'id' => $id ])
35 | ->update([ 'status' => 'failed' ]);
36 | }
37 |
38 | public function updateStatusToDelivered(int $id): void
39 | {
40 | self::where([ 'id' => $id ])
41 | ->update([ 'status' => 'delivered' ]);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/app/Transactors/LogError.php:
--------------------------------------------------------------------------------
1 | info($logMessage);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/app/Transactors/MailerTransactor.php:
--------------------------------------------------------------------------------
1 | client = $connector->getClient();
31 | $this->parsedown = new Parsedown();
32 | }
33 |
34 | /**
35 | * Send email
36 | *
37 | * @param Email $email
38 | * @return bool
39 | */
40 | public function send(Email $email): bool
41 | {
42 | try {
43 | $inputData = $email->get();
44 | $this->preparePayload($inputData);
45 | $response = $this->client->post(Resources::$Email, ['body' => $this->messageBody]);
46 |
47 | return $response->success();
48 | } catch (\Exception $exception) {
49 | $this->logError(LogMessages::MAILJET_SEND_ERROR, $exception->getMessage());
50 |
51 | return false;
52 | }
53 | }
54 |
55 | private function preparePayload(array $inputData): array
56 | {
57 | $this->messageBody[MailjetEmail::MESSAGES_KEY_MAILJET] = [];
58 | $this->messageBody[MailjetEmail::MESSAGES_KEY_MAILJET][0] = [];
59 |
60 | foreach ($inputData as $key => $value) {
61 | $this->defineEmailPayload($key, $value);
62 | }
63 |
64 | return $this->messageBody;
65 | }
66 |
67 | private function defineEmailPayload(string $key, $value): void
68 | {
69 | $payloadOptions = [
70 | EmailEnum::FROM_KEY => 'prepareFromPayload',
71 | EmailEnum::TO_KEY => 'prepareToPayload',
72 | EmailEnum::SUBJECT_KEY => 'prepareSubjectPayload',
73 | EmailEnum::TEXT_PART_KEY => 'prepareTextPartPayload',
74 | EmailEnum::HTML_PART_KEY => 'prepareHtmlPartPayload',
75 | EmailEnum::MARKDOWN_PART_KEY => 'prepareMarkdownPartPayload',
76 | ];
77 |
78 | if (!array_key_exists($key, $payloadOptions)) {
79 | return;
80 | }
81 |
82 | $payloadOption = $payloadOptions[$key];
83 | $payloadData = $this->{$payloadOption}($value);
84 |
85 | $this->messageBody[MailjetEmail::MESSAGES_KEY_MAILJET][0] =
86 | array_merge($this->messageBody[MailjetEmail::MESSAGES_KEY_MAILJET][0], $payloadData);
87 | }
88 |
89 | private function prepareFromPayload(array $userData): array
90 | {
91 | return [
92 | MailjetEmail::FROM_KEY_MAILJET => [
93 | MailjetEmail::EMAIL_KEY_MAILJET => $userData[EmailEnum::EMAIL_KEY],
94 | MailjetEmail::NAME_KEY_MAILJET => $userData[EmailEnum::NAME_KEY],
95 | ]
96 | ];
97 | }
98 |
99 | private function prepareToPayload(array $userData): array
100 | {
101 | $userPayload = [];
102 |
103 | foreach ($userData as $value) {
104 | $userPayload[] = [
105 | MailjetEmail::EMAIL_KEY_MAILJET => $value[EmailEnum::EMAIL_KEY],
106 | MailjetEmail::NAME_KEY_MAILJET => $value[EmailEnum::NAME_KEY],
107 | ];
108 | }
109 |
110 | return [ MailjetEmail::TO_KEY_MAILJET => $userPayload ];
111 | }
112 |
113 | private function prepareSubjectPayload(string $value): array
114 | {
115 | return [ MailjetEmail::SUBJECT_KEY_MAILJET => $value ];
116 | }
117 |
118 | private function prepareTextPartPayload(string $value): array
119 | {
120 | return [ MailjetEmail::TEXT_PART_KEY_MAILJET => $value ];
121 | }
122 |
123 | private function prepareHtmlPartPayload(string $value): array
124 | {
125 | return [ MailjetEmail::HTML_PART_KEY_MAILJET => $value ];
126 | }
127 |
128 | private function prepareMarkdownPartPayload(string $value): array
129 | {
130 | $this->parsedown->setSafeMode(true);
131 | $this->parsedown->setMarkupEscaped(true);
132 |
133 | $markdownValue = $this->parsedown->text($value);
134 |
135 | return [ MailjetEmail::HTML_PART_KEY_MAILJET => $markdownValue ];
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/app/Transactors/SendgridTransactor.php:
--------------------------------------------------------------------------------
1 | client = $connector->getClient();
32 | $this->email = new Mail();
33 | $this->parsedown = new Parsedown();
34 | }
35 |
36 | /**
37 | * Send email
38 | *
39 | * @param Email $email
40 | * @return bool
41 | */
42 | public function send(Email $email): bool
43 | {
44 | try {
45 | $inputData = $email->get();
46 | $this->preparePayload($inputData);
47 | $response = $this->client->send($this->email);
48 |
49 | return $response->statusCode() === SendgridEmail::SUCCESSFUL_HTTP_CODE;
50 | } catch (Exception $exception) {
51 | $this->logError(LogMessages::SENDGRID_SEND_ERROR, $exception->getMessage());
52 |
53 | return false;
54 | }
55 | }
56 |
57 | private function preparePayload(array $inputData): void
58 | {
59 | try {
60 | foreach ($inputData as $key => $value) {
61 | $this->defineEmailPayload($key, $value);
62 | }
63 | } catch (Exception $exception) {
64 | $this->logError(
65 | LogMessages::SENDGRID_PAYLOAD_ERROR,
66 | $exception->getMessage()
67 | );
68 | }
69 | }
70 |
71 | private function defineEmailPayload(string $key, $value): void
72 | {
73 | $payloadOptions = [
74 | EmailEnum::FROM_KEY => 'prepareFromPayload',
75 | EmailEnum::TO_KEY => 'prepareToPayload',
76 | EmailEnum::SUBJECT_KEY => 'prepareSubjectPayload',
77 | EmailEnum::TEXT_PART_KEY => 'prepareTextPartPayload',
78 | EmailEnum::HTML_PART_KEY => 'prepareHtmlPartPayload',
79 | EmailEnum::MARKDOWN_PART_KEY => 'prepareMarkdownPartPayload',
80 | ];
81 |
82 | if (!array_key_exists($key, $payloadOptions)) {
83 | return;
84 | }
85 |
86 | $payloadOption = $payloadOptions[$key];
87 | $this->{$payloadOption}($value);
88 | }
89 |
90 | private function prepareFromPayload(array $userData): void
91 | {
92 | $this->email->setFrom(
93 | $userData[EmailEnum::EMAIL_KEY],
94 | $userData[EmailEnum::NAME_KEY]
95 | );
96 | }
97 |
98 | private function prepareToPayload(array $userData): void
99 | {
100 | foreach ($userData as $value) {
101 | $this->email->addTo(
102 | $value[EmailEnum::EMAIL_KEY],
103 | $value[EmailEnum::NAME_KEY]
104 | );
105 | }
106 | }
107 |
108 | private function prepareSubjectPayload(string $value): void
109 | {
110 | $this->email->setSubject($value);
111 | }
112 |
113 | private function prepareTextPartPayload(string $value): void
114 | {
115 | $this->email->addContent(
116 | 'text/plain',
117 | $value
118 | );
119 | }
120 |
121 | private function prepareHtmlPartPayload(string $value): void
122 | {
123 | $this->email->addContent(
124 | 'text/html',
125 | $value
126 | );
127 | }
128 |
129 | private function prepareMarkdownPartPayload(string $value): void
130 | {
131 | $this->parsedown->setSafeMode(true);
132 | $this->parsedown->setMarkupEscaped(true);
133 |
134 | $markdownValue = $this->parsedown->text($value);
135 |
136 | $this->email->addContent(
137 | 'text/html',
138 | $markdownValue
139 | );
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/app/Workers/EmailWorker.php:
--------------------------------------------------------------------------------
1 | mailers = $mailers;
21 | }
22 |
23 | /**
24 | * Send email
25 | *
26 | * @param Email $email
27 | * @return bool
28 | */
29 | public function sendEmail(Email $email): bool
30 | {
31 | foreach ($this->mailers as $mailer) {
32 | if ($mailer->send($email)) {
33 | return true;
34 | }
35 | }
36 |
37 | return false;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/Workers/Worker.php:
--------------------------------------------------------------------------------
1 | make(Illuminate\Contracts\Console\Kernel::class);
34 |
35 | $status = $kernel->handle(
36 | $input = new Symfony\Component\Console\Input\ArgvInput,
37 | new Symfony\Component\Console\Output\ConsoleOutput
38 | );
39 |
40 | /*
41 | |--------------------------------------------------------------------------
42 | | Shutdown The Application
43 | |--------------------------------------------------------------------------
44 | |
45 | | Once Artisan has finished running, we will fire off the shutdown events
46 | | so that any final work may be done by the application before we shut
47 | | down the process. This is the last thing to happen to the request.
48 | |
49 | */
50 |
51 | $kernel->terminate($input, $status);
52 |
53 | exit($status);
54 |
--------------------------------------------------------------------------------
/bootstrap/app.php:
--------------------------------------------------------------------------------
1 | singleton(
30 | Illuminate\Contracts\Http\Kernel::class,
31 | App\Http\Kernel::class
32 | );
33 |
34 | $app->singleton(
35 | Illuminate\Contracts\Console\Kernel::class,
36 | App\Console\Kernel::class
37 | );
38 |
39 | $app->singleton(
40 | Illuminate\Contracts\Debug\ExceptionHandler::class,
41 | App\Exceptions\Handler::class
42 | );
43 |
44 | /*
45 | |--------------------------------------------------------------------------
46 | | Return The Application
47 | |--------------------------------------------------------------------------
48 | |
49 | | This script returns the application instance. The instance is given to
50 | | the calling script so we can separate the building of the instances
51 | | from the actual running of the application and sending responses.
52 | |
53 | */
54 |
55 | return $app;
56 |
--------------------------------------------------------------------------------
/bootstrap/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/cghooks.lock:
--------------------------------------------------------------------------------
1 | ["pre-commit","pre-push"]
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "fecaps/email_microservice",
3 | "type": "project",
4 | "description": "Email Microservice",
5 | "keywords": [
6 | "framework",
7 | "laravel"
8 | ],
9 | "license": "MIT",
10 | "require": {
11 | "php": "^7.2",
12 | "bschmitt/laravel-amqp": "^2.0",
13 | "erusev/parsedown": "^1.7",
14 | "fideloper/proxy": "^4.0",
15 | "laravel/framework": "^6.2",
16 | "laravel/tinker": "^1.0",
17 | "mailjet/mailjet-apiv3-php": "^1.4",
18 | "sendgrid/sendgrid": "~7"
19 | },
20 | "require-dev": {
21 | "brainmaestro/composer-git-hooks": "^2.8",
22 | "facade/ignition": "^1.4",
23 | "friendsofphp/php-cs-fixer": "^2.16",
24 | "fzaninotto/faker": "^1.4",
25 | "mockery/mockery": "^1.0",
26 | "nunomaduro/collision": "^3.0",
27 | "nunomaduro/larastan": "^0.4.3",
28 | "object-calisthenics/phpcs-calisthenics-rules": "^3.5",
29 | "phpmd/phpmd": "^2.7",
30 | "phpunit/phpunit": "^8.0",
31 | "sebastian/phpcpd": "^4.1",
32 | "squizlabs/php_codesniffer": "^3.5"
33 | },
34 | "config": {
35 | "optimize-autoloader": true,
36 | "preferred-install": "dist",
37 | "sort-packages": true
38 | },
39 | "extra": {
40 | "laravel": {
41 | "dont-discover": []
42 | },
43 | "hooks": {
44 | "pre-commit": [
45 | "composer run-script codeStyle",
46 | "composer run-script copyPasteDetector",
47 | "composer run-script messDetector",
48 | "composer run-script objectCalisthenics"
49 | ],
50 | "pre-push": [
51 | "composer run-script codeStyle",
52 | "composer run-script copyPasteDetector",
53 | "composer run-script messDetector",
54 | "composer run-script objectCalisthenics",
55 | "composer run-script tests",
56 | "composer run-script showCoverage"
57 | ]
58 | }
59 | },
60 | "autoload": {
61 | "psr-4": {
62 | "App\\": "app/"
63 | },
64 | "classmap": [
65 | "database/seeds",
66 | "database/factories"
67 | ]
68 | },
69 | "autoload-dev": {
70 | "psr-4": {
71 | "Tests\\": "tests/"
72 | }
73 | },
74 | "minimum-stability": "dev",
75 | "prefer-stable": true,
76 | "scripts": {
77 | "post-autoload-dump": [
78 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
79 | "@php artisan package:discover --ansi"
80 | ],
81 | "post-root-package-install": [
82 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
83 | ],
84 | "post-create-project-cmd": [
85 | "@php artisan key:generate --ansi"
86 | ],
87 | "codeStyle": "docker exec infrastructure_email_1 ./vendor/bin/phpcs -sw --standard=PSR2 app/",
88 | "copyPasteDetector": "docker exec infrastructure_email_1 vendor/bin/phpcpd --verbose app/",
89 | "messDetector": "docker exec infrastructure_email_1 vendor/bin/phpmd app/ text codesize",
90 | "objectCalisthenics": "docker exec infrastructure_email_1 vendor/bin/phpcs app/ -sp --standard=vendor/object-calisthenics/phpcs-calisthenics-rules/src/ObjectCalisthenics/ruleset.xml",
91 | "errorsAnalyse": "docker exec infrastructure_email_1 php artisan code:analyse",
92 | "fixStyle": "docker exec infrastructure_email_1 php ./vendor/bin/php-cs-fixer fix ./app",
93 | "tests": "docker exec infrastructure_email_1 ./vendor/bin/phpunit",
94 | "showCoverage": "docker exec infrastructure_email_1 cat report/txt-report"
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/config/amqp.php:
--------------------------------------------------------------------------------
1 | 'production',
6 |
7 | 'properties' => [
8 |
9 | 'production' => [
10 | 'host' => env('RABBITMQ_HOST', 'localhost'),
11 | 'port' => env('RABBITMQ_PORT', 5672),
12 | 'username' => env('RABBITMQ_LOGIN', 'guest'),
13 | 'password' => env('RABBITMQ_PASSWORD', 'guest'),
14 | 'vhost' => '/',
15 | 'connect_options' => [],
16 | 'ssl_options' => [],
17 |
18 | 'exchange' => env('RABBITMQ_EXCHANGE_NAME', 'amq.direct'),
19 | 'exchange_type' => env('RABBITMQ_EXCHANGE_TYPE', 'direct'),
20 | 'exchange_passive' => false,
21 | 'exchange_durable' => env('RABBITMQ_EXCHANGE_DURABLE', true),
22 | 'exchange_auto_delete' => false,
23 | 'exchange_internal' => false,
24 | 'exchange_nowait' => false,
25 | 'exchange_properties' => [],
26 |
27 | 'queue_force_declare' => false,
28 | 'queue_passive' => false,
29 | 'queue_durable' => env('RABBITMQ_QUEUE_DURABLE', true),
30 | 'queue_exclusive' => false,
31 | 'queue_auto_delete' => false,
32 | 'queue_nowait' => false,
33 | 'queue_properties' => ['x-ha-policy' => ['S', 'all']],
34 |
35 | 'consumer_tag' => '',
36 | 'consumer_no_local' => false,
37 | 'consumer_no_ack' => false,
38 | 'consumer_exclusive' => false,
39 | 'consumer_nowait' => false,
40 | 'timeout' => 0,
41 | 'persistent' => true,
42 |
43 | 'qos' => false,
44 | 'qos_prefetch_size' => 1,
45 | 'qos_prefetch_count' => 1,
46 | 'qos_a_global' => false
47 | ],
48 |
49 | ],
50 |
51 | ];
52 |
--------------------------------------------------------------------------------
/config/app.php:
--------------------------------------------------------------------------------
1 | env('APP_NAME', 'Laravel'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Application Environment
23 | |--------------------------------------------------------------------------
24 | |
25 | | This value determines the "environment" your application is currently
26 | | running in. This may determine how you prefer to configure various
27 | | services the application utilizes. Set this in your ".env" file.
28 | |
29 | */
30 |
31 | 'env' => env('APP_ENV', 'production'),
32 |
33 | /*
34 | |--------------------------------------------------------------------------
35 | | Application Debug Mode
36 | |--------------------------------------------------------------------------
37 | |
38 | | When your application is in debug mode, detailed error messages with
39 | | stack traces will be shown on every error that occurs within your
40 | | application. If disabled, a simple generic error page is shown.
41 | |
42 | */
43 |
44 | 'debug' => env('APP_DEBUG', false),
45 |
46 | /*
47 | |--------------------------------------------------------------------------
48 | | Application URL
49 | |--------------------------------------------------------------------------
50 | |
51 | | This URL is used by the console to properly generate URLs when using
52 | | the Artisan command line tool. You should set this to the root of
53 | | your application so that it is used when running Artisan tasks.
54 | |
55 | */
56 |
57 | 'url' => env('APP_URL', 'http://localhost'),
58 |
59 | 'asset_url' => env('ASSET_URL', null),
60 |
61 | /*
62 | |--------------------------------------------------------------------------
63 | | Application Timezone
64 | |--------------------------------------------------------------------------
65 | |
66 | | Here you may specify the default timezone for your application, which
67 | | will be used by the PHP date and date-time functions. We have gone
68 | | ahead and set this to a sensible default for you out of the box.
69 | |
70 | */
71 |
72 | 'timezone' => 'UTC',
73 |
74 | /*
75 | |--------------------------------------------------------------------------
76 | | Application Locale Configuration
77 | |--------------------------------------------------------------------------
78 | |
79 | | The application locale determines the default locale that will be used
80 | | by the translation service provider. You are free to set this value
81 | | to any of the locales which will be supported by the application.
82 | |
83 | */
84 |
85 | 'locale' => 'en',
86 |
87 | /*
88 | |--------------------------------------------------------------------------
89 | | Application Fallback Locale
90 | |--------------------------------------------------------------------------
91 | |
92 | | The fallback locale determines the locale to use when the current one
93 | | is not available. You may change the value to correspond to any of
94 | | the language folders that are provided through your application.
95 | |
96 | */
97 |
98 | 'fallback_locale' => 'en',
99 |
100 | /*
101 | |--------------------------------------------------------------------------
102 | | Faker Locale
103 | |--------------------------------------------------------------------------
104 | |
105 | | This locale will be used by the Faker PHP library when generating fake
106 | | data for your database seeds. For example, this will be used to get
107 | | localized telephone numbers, street address information and more.
108 | |
109 | */
110 |
111 | 'faker_locale' => 'en_US',
112 |
113 | /*
114 | |--------------------------------------------------------------------------
115 | | Encryption Key
116 | |--------------------------------------------------------------------------
117 | |
118 | | This key is used by the Illuminate encrypter service and should be set
119 | | to a random, 32 character string, otherwise these encrypted strings
120 | | will not be safe. Please do this before deploying an application!
121 | |
122 | */
123 |
124 | 'key' => env('APP_KEY'),
125 |
126 | 'cipher' => 'AES-256-CBC',
127 |
128 | /*
129 | |--------------------------------------------------------------------------
130 | | Autoloaded Service Providers
131 | |--------------------------------------------------------------------------
132 | |
133 | | The service providers listed here will be automatically loaded on the
134 | | request to your application. Feel free to add your own services to
135 | | this array to grant expanded functionality to your applications.
136 | |
137 | */
138 |
139 | 'providers' => [
140 |
141 | /*
142 | * Laravel Framework Service Providers...
143 | */
144 | Illuminate\Auth\AuthServiceProvider::class,
145 | Illuminate\Broadcasting\BroadcastServiceProvider::class,
146 | Illuminate\Bus\BusServiceProvider::class,
147 | Illuminate\Cache\CacheServiceProvider::class,
148 | Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
149 | Illuminate\Cookie\CookieServiceProvider::class,
150 | Illuminate\Database\DatabaseServiceProvider::class,
151 | Illuminate\Encryption\EncryptionServiceProvider::class,
152 | Illuminate\Filesystem\FilesystemServiceProvider::class,
153 | Illuminate\Foundation\Providers\FoundationServiceProvider::class,
154 | Illuminate\Hashing\HashServiceProvider::class,
155 | Illuminate\Mail\MailServiceProvider::class,
156 | Illuminate\Notifications\NotificationServiceProvider::class,
157 | Illuminate\Pagination\PaginationServiceProvider::class,
158 | Illuminate\Pipeline\PipelineServiceProvider::class,
159 | Illuminate\Queue\QueueServiceProvider::class,
160 | Illuminate\Redis\RedisServiceProvider::class,
161 | Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
162 | Illuminate\Session\SessionServiceProvider::class,
163 | Illuminate\Translation\TranslationServiceProvider::class,
164 | Illuminate\Validation\ValidationServiceProvider::class,
165 | Illuminate\View\ViewServiceProvider::class,
166 |
167 | /*
168 | * Package Service Providers...
169 | */
170 |
171 | /*
172 | * Application Service Providers...
173 | */
174 | App\Providers\AppServiceProvider::class,
175 | App\Providers\AuthServiceProvider::class,
176 | // App\Providers\BroadcastServiceProvider::class,
177 | App\Providers\EventServiceProvider::class,
178 | App\Providers\RouteServiceProvider::class,
179 | App\Providers\EmailServiceProvider::class,
180 | App\Providers\EmailConsumerServiceProvider::class,
181 | App\Providers\EmailPublisherServiceProvider::class,
182 | AmqpServiceProvider::class,
183 |
184 | ],
185 |
186 | /*
187 | |--------------------------------------------------------------------------
188 | | Class Aliases
189 | |--------------------------------------------------------------------------
190 | |
191 | | This array of class aliases will be registered when this application
192 | | is started. However, feel free to register as many as you wish as
193 | | the aliases are "lazy" loaded so they don't hinder performance.
194 | |
195 | */
196 |
197 | 'aliases' => [
198 |
199 | 'App' => Illuminate\Support\Facades\App::class,
200 | 'Arr' => Illuminate\Support\Arr::class,
201 | 'Artisan' => Illuminate\Support\Facades\Artisan::class,
202 | 'Auth' => Illuminate\Support\Facades\Auth::class,
203 | 'Blade' => Illuminate\Support\Facades\Blade::class,
204 | 'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
205 | 'Bus' => Illuminate\Support\Facades\Bus::class,
206 | 'Cache' => Illuminate\Support\Facades\Cache::class,
207 | 'Config' => Illuminate\Support\Facades\Config::class,
208 | 'Cookie' => Illuminate\Support\Facades\Cookie::class,
209 | 'Crypt' => Illuminate\Support\Facades\Crypt::class,
210 | 'DB' => Illuminate\Support\Facades\DB::class,
211 | 'Eloquent' => Illuminate\Database\Eloquent\Model::class,
212 | 'Event' => Illuminate\Support\Facades\Event::class,
213 | 'File' => Illuminate\Support\Facades\File::class,
214 | 'Gate' => Illuminate\Support\Facades\Gate::class,
215 | 'Hash' => Illuminate\Support\Facades\Hash::class,
216 | 'Lang' => Illuminate\Support\Facades\Lang::class,
217 | 'Log' => Illuminate\Support\Facades\Log::class,
218 | 'Mail' => Illuminate\Support\Facades\Mail::class,
219 | 'Notification' => Illuminate\Support\Facades\Notification::class,
220 | 'Password' => Illuminate\Support\Facades\Password::class,
221 | 'Queue' => Illuminate\Support\Facades\Queue::class,
222 | 'Redirect' => Illuminate\Support\Facades\Redirect::class,
223 | 'Redis' => Illuminate\Support\Facades\Redis::class,
224 | 'Request' => Illuminate\Support\Facades\Request::class,
225 | 'Response' => Illuminate\Support\Facades\Response::class,
226 | 'Route' => Illuminate\Support\Facades\Route::class,
227 | 'Schema' => Illuminate\Support\Facades\Schema::class,
228 | 'Session' => Illuminate\Support\Facades\Session::class,
229 | 'Storage' => Illuminate\Support\Facades\Storage::class,
230 | 'Str' => Illuminate\Support\Str::class,
231 | 'URL' => Illuminate\Support\Facades\URL::class,
232 | 'Validator' => Illuminate\Support\Facades\Validator::class,
233 | 'View' => Illuminate\Support\Facades\View::class,
234 | 'Amqp' => Bschmitt\Amqp\Facades\Amqp::class,
235 | ],
236 |
237 | ];
238 |
--------------------------------------------------------------------------------
/config/auth.php:
--------------------------------------------------------------------------------
1 | [
17 | 'guard' => 'web',
18 | 'passwords' => 'users',
19 | ],
20 |
21 | /*
22 | |--------------------------------------------------------------------------
23 | | Authentication Guards
24 | |--------------------------------------------------------------------------
25 | |
26 | | Next, you may define every authentication guard for your application.
27 | | Of course, a great default configuration has been defined for you
28 | | here which uses session storage and the Eloquent user provider.
29 | |
30 | | All authentication drivers have a user provider. This defines how the
31 | | users are actually retrieved out of your database or other storage
32 | | mechanisms used by this application to persist your user's data.
33 | |
34 | | Supported: "session", "token"
35 | |
36 | */
37 |
38 | 'guards' => [
39 | 'web' => [
40 | 'driver' => 'session',
41 | 'provider' => 'users',
42 | ],
43 |
44 | 'api' => [
45 | 'driver' => 'token',
46 | 'provider' => 'users',
47 | 'hash' => false,
48 | ],
49 | ],
50 |
51 | /*
52 | |--------------------------------------------------------------------------
53 | | User Providers
54 | |--------------------------------------------------------------------------
55 | |
56 | | All authentication drivers have a user provider. This defines how the
57 | | users are actually retrieved out of your database or other storage
58 | | mechanisms used by this application to persist your user's data.
59 | |
60 | | If you have multiple user tables or models you may configure multiple
61 | | sources which represent each model / table. These sources may then
62 | | be assigned to any extra authentication guards you have defined.
63 | |
64 | | Supported: "database", "eloquent"
65 | |
66 | */
67 |
68 | 'providers' => [
69 | 'users' => [
70 | 'driver' => 'eloquent',
71 | 'model' => App\User::class,
72 | ],
73 |
74 | // 'users' => [
75 | // 'driver' => 'database',
76 | // 'table' => 'users',
77 | // ],
78 | ],
79 |
80 | /*
81 | |--------------------------------------------------------------------------
82 | | Resetting Passwords
83 | |--------------------------------------------------------------------------
84 | |
85 | | You may specify multiple password reset configurations if you have more
86 | | than one user table or model in the application and you want to have
87 | | separate password reset settings based on the specific user types.
88 | |
89 | | The expire time is the number of minutes that the reset token should be
90 | | considered valid. This security feature keeps tokens short-lived so
91 | | they have less time to be guessed. You may change this as needed.
92 | |
93 | */
94 |
95 | 'passwords' => [
96 | 'users' => [
97 | 'provider' => 'users',
98 | 'table' => 'password_resets',
99 | 'expire' => 60,
100 | 'throttle' => 60,
101 | ],
102 | ],
103 |
104 | /*
105 | |--------------------------------------------------------------------------
106 | | Password Confirmation Timeout
107 | |--------------------------------------------------------------------------
108 | |
109 | | Here you may define the amount of seconds before a password confirmation
110 | | times out and the user is prompted to re-enter their password via the
111 | | confirmation screen. By default, the timeout lasts for three hours.
112 | |
113 | */
114 |
115 | 'password_timeout' => 10800,
116 |
117 | ];
118 |
--------------------------------------------------------------------------------
/config/broadcasting.php:
--------------------------------------------------------------------------------
1 | env('BROADCAST_DRIVER', 'null'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Broadcast Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may define all of the broadcast connections that will be used
26 | | to broadcast events to other systems or over websockets. Samples of
27 | | each available type of connection are provided inside this array.
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'pusher' => [
34 | 'driver' => 'pusher',
35 | 'key' => env('PUSHER_APP_KEY'),
36 | 'secret' => env('PUSHER_APP_SECRET'),
37 | 'app_id' => env('PUSHER_APP_ID'),
38 | 'options' => [
39 | 'cluster' => env('PUSHER_APP_CLUSTER'),
40 | 'useTLS' => true,
41 | ],
42 | ],
43 |
44 | 'redis' => [
45 | 'driver' => 'redis',
46 | 'connection' => 'default',
47 | ],
48 |
49 | 'log' => [
50 | 'driver' => 'log',
51 | ],
52 |
53 | 'null' => [
54 | 'driver' => 'null',
55 | ],
56 |
57 | ],
58 |
59 | ];
60 |
--------------------------------------------------------------------------------
/config/cache.php:
--------------------------------------------------------------------------------
1 | env('CACHE_DRIVER', 'file'),
22 |
23 | /*
24 | |--------------------------------------------------------------------------
25 | | Cache Stores
26 | |--------------------------------------------------------------------------
27 | |
28 | | Here you may define all of the cache "stores" for your application as
29 | | well as their drivers. You may even define multiple stores for the
30 | | same cache driver to group types of items stored in your caches.
31 | |
32 | */
33 |
34 | 'stores' => [
35 |
36 | 'apc' => [
37 | 'driver' => 'apc',
38 | ],
39 |
40 | 'array' => [
41 | 'driver' => 'array',
42 | ],
43 |
44 | 'database' => [
45 | 'driver' => 'database',
46 | 'table' => 'cache',
47 | 'connection' => null,
48 | ],
49 |
50 | 'file' => [
51 | 'driver' => 'file',
52 | 'path' => storage_path('framework/cache/data'),
53 | ],
54 |
55 | 'memcached' => [
56 | 'driver' => 'memcached',
57 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
58 | 'sasl' => [
59 | env('MEMCACHED_USERNAME'),
60 | env('MEMCACHED_PASSWORD'),
61 | ],
62 | 'options' => [
63 | // Memcached::OPT_CONNECT_TIMEOUT => 2000,
64 | ],
65 | 'servers' => [
66 | [
67 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'),
68 | 'port' => env('MEMCACHED_PORT', 11211),
69 | 'weight' => 100,
70 | ],
71 | ],
72 | ],
73 |
74 | 'redis' => [
75 | 'driver' => 'redis',
76 | 'connection' => 'cache',
77 | ],
78 |
79 | 'dynamodb' => [
80 | 'driver' => 'dynamodb',
81 | 'key' => env('AWS_ACCESS_KEY_ID'),
82 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
83 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
84 | 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
85 | 'endpoint' => env('DYNAMODB_ENDPOINT'),
86 | ],
87 |
88 | ],
89 |
90 | /*
91 | |--------------------------------------------------------------------------
92 | | Cache Key Prefix
93 | |--------------------------------------------------------------------------
94 | |
95 | | When utilizing a RAM based store such as APC or Memcached, there might
96 | | be other applications utilizing the same cache. So, we'll specify a
97 | | value to get prefixed to all our keys so we can avoid collisions.
98 | |
99 | */
100 |
101 | 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
102 |
103 | ];
104 |
--------------------------------------------------------------------------------
/config/database.php:
--------------------------------------------------------------------------------
1 | env('DB_CONNECTION', 'pgsql'),
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Database Connections
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here are each of the database connections setup for your application.
26 | | Of course, examples of configuring each database platform that is
27 | | supported by Laravel is shown below to make development simple.
28 | |
29 | |
30 | | All database work in Laravel is done through the PHP PDO facilities
31 | | so make sure you have the driver for your particular database of
32 | | choice installed on your machine before you begin development.
33 | |
34 | */
35 |
36 | 'connections' => [
37 |
38 | 'sqlite' => [
39 | 'driver' => 'sqlite',
40 | 'url' => env('DATABASE_URL'),
41 | 'database' => env('DB_DATABASE', database_path('database.sqlite')),
42 | 'prefix' => '',
43 | 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
44 | ],
45 |
46 | 'mysql' => [
47 | 'driver' => 'mysql',
48 | 'url' => env('DATABASE_URL'),
49 | 'host' => env('DB_HOST', '127.0.0.1'),
50 | 'port' => env('DB_PORT', '3306'),
51 | 'database' => env('DB_DATABASE', 'forge'),
52 | 'username' => env('DB_USERNAME', 'forge'),
53 | 'password' => env('DB_PASSWORD', ''),
54 | 'unix_socket' => env('DB_SOCKET', ''),
55 | 'charset' => 'utf8mb4',
56 | 'collation' => 'utf8mb4_unicode_ci',
57 | 'prefix' => '',
58 | 'prefix_indexes' => true,
59 | 'strict' => true,
60 | 'engine' => null,
61 | 'options' => extension_loaded('pdo_mysql') ? array_filter([
62 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
63 | ]) : [],
64 | ],
65 |
66 | 'pgsql' => [
67 | 'driver' => 'pgsql',
68 | 'url' => env('DATABASE_URL'),
69 | 'host' => env('DB_HOST', '127.0.0.1'),
70 | 'port' => env('DB_PORT', '5432'),
71 | 'database' => env('DB_DATABASE', 'email_service'),
72 | 'username' => env('DB_USERNAME', 'postgres'),
73 | 'password' => env('DB_PASSWORD', 'postgres'),
74 | 'charset' => 'utf8',
75 | 'prefix' => '',
76 | 'prefix_indexes' => true,
77 | 'schema' => 'public',
78 | 'sslmode' => 'prefer',
79 | ],
80 |
81 | 'sqlsrv' => [
82 | 'driver' => 'sqlsrv',
83 | 'url' => env('DATABASE_URL'),
84 | 'host' => env('DB_HOST', 'localhost'),
85 | 'port' => env('DB_PORT', '1433'),
86 | 'database' => env('DB_DATABASE', 'forge'),
87 | 'username' => env('DB_USERNAME', 'forge'),
88 | 'password' => env('DB_PASSWORD', ''),
89 | 'charset' => 'utf8',
90 | 'prefix' => '',
91 | 'prefix_indexes' => true,
92 | ],
93 |
94 | ],
95 |
96 | /*
97 | |--------------------------------------------------------------------------
98 | | Migration Repository Table
99 | |--------------------------------------------------------------------------
100 | |
101 | | This table keeps track of all the migrations that have already run for
102 | | your application. Using this information, we can determine which of
103 | | the migrations on disk haven't actually been run in the database.
104 | |
105 | */
106 |
107 | 'migrations' => 'migrations',
108 |
109 | /*
110 | |--------------------------------------------------------------------------
111 | | Redis Databases
112 | |--------------------------------------------------------------------------
113 | |
114 | | Redis is an open source, fast, and advanced key-value store that also
115 | | provides a richer body of commands than a typical key-value system
116 | | such as APC or Memcached. Laravel makes it easy to dig right in.
117 | |
118 | */
119 |
120 | 'redis' => [
121 |
122 | 'client' => env('REDIS_CLIENT', 'phpredis'),
123 |
124 | 'options' => [
125 | 'cluster' => env('REDIS_CLUSTER', 'redis'),
126 | 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
127 | ],
128 |
129 | 'default' => [
130 | 'url' => env('REDIS_URL'),
131 | 'host' => env('REDIS_HOST', '127.0.0.1'),
132 | 'password' => env('REDIS_PASSWORD', null),
133 | 'port' => env('REDIS_PORT', 6379),
134 | 'database' => env('REDIS_DB', 0),
135 | ],
136 |
137 | 'cache' => [
138 | 'url' => env('REDIS_URL'),
139 | 'host' => env('REDIS_HOST', '127.0.0.1'),
140 | 'password' => env('REDIS_PASSWORD', null),
141 | 'port' => env('REDIS_PORT', 6379),
142 | 'database' => env('REDIS_CACHE_DB', 1),
143 | ],
144 |
145 | ],
146 |
147 | ];
148 |
--------------------------------------------------------------------------------
/config/filesystems.php:
--------------------------------------------------------------------------------
1 | env('FILESYSTEM_DRIVER', 'local'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Default Cloud Filesystem Disk
21 | |--------------------------------------------------------------------------
22 | |
23 | | Many applications store files both locally and in the cloud. For this
24 | | reason, you may specify a default "cloud" driver here. This driver
25 | | will be bound as the Cloud disk implementation in the container.
26 | |
27 | */
28 |
29 | 'cloud' => env('FILESYSTEM_CLOUD', 's3'),
30 |
31 | /*
32 | |--------------------------------------------------------------------------
33 | | Filesystem Disks
34 | |--------------------------------------------------------------------------
35 | |
36 | | Here you may configure as many filesystem "disks" as you wish, and you
37 | | may even configure multiple disks of the same driver. Defaults have
38 | | been setup for each driver as an example of the required options.
39 | |
40 | | Supported Drivers: "local", "ftp", "sftp", "s3"
41 | |
42 | */
43 |
44 | 'disks' => [
45 |
46 | 'local' => [
47 | 'driver' => 'local',
48 | 'root' => storage_path('app'),
49 | ],
50 |
51 | 'public' => [
52 | 'driver' => 'local',
53 | 'root' => storage_path('app/public'),
54 | 'url' => env('APP_URL').'/storage',
55 | 'visibility' => 'public',
56 | ],
57 |
58 | 's3' => [
59 | 'driver' => 's3',
60 | 'key' => env('AWS_ACCESS_KEY_ID'),
61 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
62 | 'region' => env('AWS_DEFAULT_REGION'),
63 | 'bucket' => env('AWS_BUCKET'),
64 | 'url' => env('AWS_URL'),
65 | ],
66 |
67 | ],
68 |
69 | ];
70 |
--------------------------------------------------------------------------------
/config/hashing.php:
--------------------------------------------------------------------------------
1 | 'bcrypt',
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Bcrypt Options
23 | |--------------------------------------------------------------------------
24 | |
25 | | Here you may specify the configuration options that should be used when
26 | | passwords are hashed using the Bcrypt algorithm. This will allow you
27 | | to control the amount of time it takes to hash the given password.
28 | |
29 | */
30 |
31 | 'bcrypt' => [
32 | 'rounds' => env('BCRYPT_ROUNDS', 10),
33 | ],
34 |
35 | /*
36 | |--------------------------------------------------------------------------
37 | | Argon Options
38 | |--------------------------------------------------------------------------
39 | |
40 | | Here you may specify the configuration options that should be used when
41 | | passwords are hashed using the Argon algorithm. These will allow you
42 | | to control the amount of time it takes to hash the given password.
43 | |
44 | */
45 |
46 | 'argon' => [
47 | 'memory' => 1024,
48 | 'threads' => 2,
49 | 'time' => 2,
50 | ],
51 |
52 | ];
53 |
--------------------------------------------------------------------------------
/config/logging.php:
--------------------------------------------------------------------------------
1 | env('LOG_CHANNEL', 'stack'),
21 |
22 | /*
23 | |--------------------------------------------------------------------------
24 | | Log Channels
25 | |--------------------------------------------------------------------------
26 | |
27 | | Here you may configure the log channels for your application. Out of
28 | | the box, Laravel uses the Monolog PHP logging library. This gives
29 | | you a variety of powerful log handlers / formatters to utilize.
30 | |
31 | | Available Drivers: "single", "daily", "slack", "syslog",
32 | | "errorlog", "monolog",
33 | | "custom", "stack"
34 | |
35 | */
36 |
37 | 'channels' => [
38 | 'stack' => [
39 | 'driver' => 'stack',
40 | 'channels' => ['daily'],
41 | 'ignore_exceptions' => false,
42 | ],
43 |
44 | 'single' => [
45 | 'driver' => 'single',
46 | 'path' => storage_path('logs/laravel.log'),
47 | 'level' => 'debug',
48 | ],
49 |
50 | 'daily' => [
51 | 'driver' => 'daily',
52 | 'path' => storage_path('logs/laravel.log'),
53 | 'level' => 'debug',
54 | 'days' => 14,
55 | ],
56 |
57 | 'slack' => [
58 | 'driver' => 'slack',
59 | 'url' => env('LOG_SLACK_WEBHOOK_URL'),
60 | 'username' => 'Laravel Log',
61 | 'emoji' => ':boom:',
62 | 'level' => 'critical',
63 | ],
64 |
65 | 'papertrail' => [
66 | 'driver' => 'monolog',
67 | 'level' => 'debug',
68 | 'handler' => SyslogUdpHandler::class,
69 | 'handler_with' => [
70 | 'host' => env('PAPERTRAIL_URL'),
71 | 'port' => env('PAPERTRAIL_PORT'),
72 | ],
73 | ],
74 |
75 | 'stderr' => [
76 | 'driver' => 'monolog',
77 | 'handler' => StreamHandler::class,
78 | 'formatter' => env('LOG_STDERR_FORMATTER'),
79 | 'with' => [
80 | 'stream' => 'php://stderr',
81 | ],
82 | ],
83 |
84 | 'syslog' => [
85 | 'driver' => 'syslog',
86 | 'level' => 'debug',
87 | ],
88 |
89 | 'errorlog' => [
90 | 'driver' => 'errorlog',
91 | 'level' => 'debug',
92 | ],
93 |
94 | 'null' => [
95 | 'driver' => 'monolog',
96 | 'handler' => NullHandler::class,
97 | ],
98 |
99 | 'publisher' => [
100 | 'driver' => 'single',
101 | 'path' => storage_path('logs/publisher.log'),
102 | ],
103 |
104 | 'consumer' => [
105 | 'driver' => 'single',
106 | 'path' => storage_path('logs/consumer.log'),
107 | ],
108 | ],
109 |
110 | ];
111 |
--------------------------------------------------------------------------------
/config/mail.php:
--------------------------------------------------------------------------------
1 | env('MAIL_DRIVER', 'smtp'),
20 |
21 | /*
22 | |--------------------------------------------------------------------------
23 | | SMTP Host Address
24 | |--------------------------------------------------------------------------
25 | |
26 | | Here you may provide the host address of the SMTP server used by your
27 | | applications. A default option is provided that is compatible with
28 | | the Mailgun mail service which will provide reliable deliveries.
29 | |
30 | */
31 |
32 | 'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
33 |
34 | /*
35 | |--------------------------------------------------------------------------
36 | | SMTP Host Port
37 | |--------------------------------------------------------------------------
38 | |
39 | | This is the SMTP port used by your application to deliver e-mails to
40 | | users of the application. Like the host we have set this value to
41 | | stay compatible with the Mailgun e-mail application by default.
42 | |
43 | */
44 |
45 | 'port' => env('MAIL_PORT', 587),
46 |
47 | /*
48 | |--------------------------------------------------------------------------
49 | | Global "From" Address
50 | |--------------------------------------------------------------------------
51 | |
52 | | You may wish for all e-mails sent by your application to be sent from
53 | | the same address. Here, you may specify a name and address that is
54 | | used globally for all e-mails that are sent by your application.
55 | |
56 | */
57 |
58 | 'from' => [
59 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
60 | 'name' => env('MAIL_FROM_NAME', 'Example'),
61 | ],
62 |
63 | /*
64 | |--------------------------------------------------------------------------
65 | | E-Mail Encryption Protocol
66 | |--------------------------------------------------------------------------
67 | |
68 | | Here you may specify the encryption protocol that should be used when
69 | | the application send e-mail messages. A sensible default using the
70 | | transport layer security protocol should provide great security.
71 | |
72 | */
73 |
74 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'),
75 |
76 | /*
77 | |--------------------------------------------------------------------------
78 | | SMTP Server Username
79 | |--------------------------------------------------------------------------
80 | |
81 | | If your SMTP server requires a username for authentication, you should
82 | | set it here. This will get used to authenticate with your server on
83 | | connection. You may also set the "password" value below this one.
84 | |
85 | */
86 |
87 | 'username' => env('MAIL_USERNAME'),
88 |
89 | 'password' => env('MAIL_PASSWORD'),
90 |
91 | /*
92 | |--------------------------------------------------------------------------
93 | | Sendmail System Path
94 | |--------------------------------------------------------------------------
95 | |
96 | | When using the "sendmail" driver to send e-mails, we will need to know
97 | | the path to where Sendmail lives on this server. A default path has
98 | | been provided here, which will work well on most of your systems.
99 | |
100 | */
101 |
102 | 'sendmail' => '/usr/sbin/sendmail -bs',
103 |
104 | /*
105 | |--------------------------------------------------------------------------
106 | | Markdown Mail Settings
107 | |--------------------------------------------------------------------------
108 | |
109 | | If you are using Markdown based email rendering, you may configure your
110 | | theme and component paths here, allowing you to customize the design
111 | | of the emails. Or, you may simply stick with the Laravel defaults!
112 | |
113 | */
114 |
115 | 'markdown' => [
116 | 'theme' => 'default',
117 |
118 | 'paths' => [
119 | resource_path('views/vendor/mail'),
120 | ],
121 | ],
122 |
123 | /*
124 | |--------------------------------------------------------------------------
125 | | Log Channel
126 | |--------------------------------------------------------------------------
127 | |
128 | | If you are using the "log" driver, you may specify the logging channel
129 | | if you prefer to keep mail messages separate from other log entries
130 | | for simpler reading. Otherwise, the default channel will be used.
131 | |
132 | */
133 |
134 | 'log_channel' => env('MAIL_LOG_CHANNEL'),
135 |
136 | ];
137 |
--------------------------------------------------------------------------------
/config/queue.php:
--------------------------------------------------------------------------------
1 | env('QUEUE_CONNECTION', 'sync'),
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Queue Connections
21 | |--------------------------------------------------------------------------
22 | |
23 | | Here you may configure the connection information for each server that
24 | | is used by your application. A default configuration has been added
25 | | for each back-end shipped with Laravel. You are free to add more.
26 | |
27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
28 | |
29 | */
30 |
31 | 'connections' => [
32 |
33 | 'sync' => [
34 | 'driver' => 'sync',
35 | ],
36 |
37 | 'database' => [
38 | 'driver' => 'database',
39 | 'table' => 'jobs',
40 | 'queue' => 'default',
41 | 'retry_after' => 90,
42 | ],
43 |
44 | 'beanstalkd' => [
45 | 'driver' => 'beanstalkd',
46 | 'host' => 'localhost',
47 | 'queue' => 'default',
48 | 'retry_after' => 90,
49 | 'block_for' => 0,
50 | ],
51 |
52 | 'sqs' => [
53 | 'driver' => 'sqs',
54 | 'key' => env('AWS_ACCESS_KEY_ID'),
55 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
56 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
57 | 'queue' => env('SQS_QUEUE', 'your-queue-name'),
58 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
59 | ],
60 |
61 | 'redis' => [
62 | 'driver' => 'redis',
63 | 'connection' => 'default',
64 | 'queue' => env('REDIS_QUEUE', 'default'),
65 | 'retry_after' => 90,
66 | 'block_for' => null,
67 | ],
68 |
69 | ],
70 |
71 | /*
72 | |--------------------------------------------------------------------------
73 | | Failed Queue Jobs
74 | |--------------------------------------------------------------------------
75 | |
76 | | These options configure the behavior of failed queue job logging so you
77 | | can control which database and table are used to store the jobs that
78 | | have failed. You may change them to any database / table you wish.
79 | |
80 | */
81 |
82 | 'failed' => [
83 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
84 | 'database' => env('DB_CONNECTION', 'mysql'),
85 | 'table' => 'failed_jobs',
86 | ],
87 |
88 | ];
89 |
--------------------------------------------------------------------------------
/config/services.php:
--------------------------------------------------------------------------------
1 | [
18 | 'domain' => env('MAILGUN_DOMAIN'),
19 | 'secret' => env('MAILGUN_SECRET'),
20 | 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
21 | ],
22 |
23 | 'postmark' => [
24 | 'token' => env('POSTMARK_TOKEN'),
25 | ],
26 |
27 | 'ses' => [
28 | 'key' => env('AWS_ACCESS_KEY_ID'),
29 | 'secret' => env('AWS_SECRET_ACCESS_KEY'),
30 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
31 | ],
32 |
33 | 'mailjet' => [
34 | 'key' => env('MAILJET_KEY'),
35 | 'secret' => env('MAILJET_SECRET'),
36 | 'performer' => env('MAILJET_CALL_PERFORMER'),
37 | 'version' => env('MAILJET_VERSION')
38 | ],
39 |
40 | 'sendgrid' => [
41 | 'key' => env('SENDGRID_API_KEY'),
42 | ],
43 | ];
44 |
--------------------------------------------------------------------------------
/config/session.php:
--------------------------------------------------------------------------------
1 | env('SESSION_DRIVER', 'file'),
22 |
23 | /*
24 | |--------------------------------------------------------------------------
25 | | Session Lifetime
26 | |--------------------------------------------------------------------------
27 | |
28 | | Here you may specify the number of minutes that you wish the session
29 | | to be allowed to remain idle before it expires. If you want them
30 | | to immediately expire on the browser closing, set that option.
31 | |
32 | */
33 |
34 | 'lifetime' => env('SESSION_LIFETIME', 120),
35 |
36 | 'expire_on_close' => false,
37 |
38 | /*
39 | |--------------------------------------------------------------------------
40 | | Session Encryption
41 | |--------------------------------------------------------------------------
42 | |
43 | | This option allows you to easily specify that all of your session data
44 | | should be encrypted before it is stored. All encryption will be run
45 | | automatically by Laravel and you can use the Session like normal.
46 | |
47 | */
48 |
49 | 'encrypt' => false,
50 |
51 | /*
52 | |--------------------------------------------------------------------------
53 | | Session File Location
54 | |--------------------------------------------------------------------------
55 | |
56 | | When using the native session driver, we need a location where session
57 | | files may be stored. A default has been set for you but a different
58 | | location may be specified. This is only needed for file sessions.
59 | |
60 | */
61 |
62 | 'files' => storage_path('framework/sessions'),
63 |
64 | /*
65 | |--------------------------------------------------------------------------
66 | | Session Database Connection
67 | |--------------------------------------------------------------------------
68 | |
69 | | When using the "database" or "redis" session drivers, you may specify a
70 | | connection that should be used to manage these sessions. This should
71 | | correspond to a connection in your database configuration options.
72 | |
73 | */
74 |
75 | 'connection' => env('SESSION_CONNECTION', null),
76 |
77 | /*
78 | |--------------------------------------------------------------------------
79 | | Session Database Table
80 | |--------------------------------------------------------------------------
81 | |
82 | | When using the "database" session driver, you may specify the table we
83 | | should use to manage the sessions. Of course, a sensible default is
84 | | provided for you; however, you are free to change this as needed.
85 | |
86 | */
87 |
88 | 'table' => 'sessions',
89 |
90 | /*
91 | |--------------------------------------------------------------------------
92 | | Session Cache Store
93 | |--------------------------------------------------------------------------
94 | |
95 | | When using the "apc", "memcached", or "dynamodb" session drivers you may
96 | | list a cache store that should be used for these sessions. This value
97 | | must match with one of the application's configured cache "stores".
98 | |
99 | */
100 |
101 | 'store' => env('SESSION_STORE', null),
102 |
103 | /*
104 | |--------------------------------------------------------------------------
105 | | Session Sweeping Lottery
106 | |--------------------------------------------------------------------------
107 | |
108 | | Some session drivers must manually sweep their storage location to get
109 | | rid of old sessions from storage. Here are the chances that it will
110 | | happen on a given request. By default, the odds are 2 out of 100.
111 | |
112 | */
113 |
114 | 'lottery' => [2, 100],
115 |
116 | /*
117 | |--------------------------------------------------------------------------
118 | | Session Cookie Name
119 | |--------------------------------------------------------------------------
120 | |
121 | | Here you may change the name of the cookie used to identify a session
122 | | instance by ID. The name specified here will get used every time a
123 | | new session cookie is created by the framework for every driver.
124 | |
125 | */
126 |
127 | 'cookie' => env(
128 | 'SESSION_COOKIE',
129 | Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
130 | ),
131 |
132 | /*
133 | |--------------------------------------------------------------------------
134 | | Session Cookie Path
135 | |--------------------------------------------------------------------------
136 | |
137 | | The session cookie path determines the path for which the cookie will
138 | | be regarded as available. Typically, this will be the root path of
139 | | your application but you are free to change this when necessary.
140 | |
141 | */
142 |
143 | 'path' => '/',
144 |
145 | /*
146 | |--------------------------------------------------------------------------
147 | | Session Cookie Domain
148 | |--------------------------------------------------------------------------
149 | |
150 | | Here you may change the domain of the cookie used to identify a session
151 | | in your application. This will determine which domains the cookie is
152 | | available to in your application. A sensible default has been set.
153 | |
154 | */
155 |
156 | 'domain' => env('SESSION_DOMAIN', null),
157 |
158 | /*
159 | |--------------------------------------------------------------------------
160 | | HTTPS Only Cookies
161 | |--------------------------------------------------------------------------
162 | |
163 | | By setting this option to true, session cookies will only be sent back
164 | | to the server if the browser has a HTTPS connection. This will keep
165 | | the cookie from being sent to you if it can not be done securely.
166 | |
167 | */
168 |
169 | 'secure' => env('SESSION_SECURE_COOKIE', false),
170 |
171 | /*
172 | |--------------------------------------------------------------------------
173 | | HTTP Access Only
174 | |--------------------------------------------------------------------------
175 | |
176 | | Setting this value to true will prevent JavaScript from accessing the
177 | | value of the cookie and the cookie will only be accessible through
178 | | the HTTP protocol. You are free to modify this option if needed.
179 | |
180 | */
181 |
182 | 'http_only' => true,
183 |
184 | /*
185 | |--------------------------------------------------------------------------
186 | | Same-Site Cookies
187 | |--------------------------------------------------------------------------
188 | |
189 | | This option determines how your cookies behave when cross-site requests
190 | | take place, and can be used to mitigate CSRF attacks. By default, we
191 | | do not enable this as other CSRF protection services are in place.
192 | |
193 | | Supported: "lax", "strict"
194 | |
195 | */
196 |
197 | 'same_site' => null,
198 |
199 | ];
200 |
--------------------------------------------------------------------------------
/config/view.php:
--------------------------------------------------------------------------------
1 | [
17 | resource_path('views'),
18 | ],
19 |
20 | /*
21 | |--------------------------------------------------------------------------
22 | | Compiled View Path
23 | |--------------------------------------------------------------------------
24 | |
25 | | This option determines where all the compiled Blade templates will be
26 | | stored for your application. Typically, this is within the storage
27 | | directory. However, as usual, you are free to change this value.
28 | |
29 | */
30 |
31 | 'compiled' => env(
32 | 'VIEW_COMPILED_PATH',
33 | realpath(storage_path('framework/views'))
34 | ),
35 |
36 | ];
37 |
--------------------------------------------------------------------------------
/database/.gitignore:
--------------------------------------------------------------------------------
1 | *.sqlite
2 | *.sqlite-journal
3 |
--------------------------------------------------------------------------------
/database/factories/UserFactory.php:
--------------------------------------------------------------------------------
1 | define(User::class, function (Faker $faker) {
20 | return [
21 | 'name' => $faker->name,
22 | 'email' => $faker->unique()->safeEmail,
23 | 'email_verified_at' => now(),
24 | 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
25 | 'remember_token' => Str::random(10),
26 | ];
27 | });
28 |
--------------------------------------------------------------------------------
/database/migrations/2019_11_17_220614_create_queues_table.php:
--------------------------------------------------------------------------------
1 | bigIncrements('id');
18 | $table->json('message');
19 | $table->enum('status', ['queued', 'bounced', 'delivered', 'failed']);
20 | $table->timestamps();
21 | });
22 | }
23 |
24 | /**
25 | * Reverse the migrations.
26 | *
27 | * @return void
28 | */
29 | public function down()
30 | {
31 | Schema::dropIfExists('queues');
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/database/seeds/DatabaseSeeder.php:
--------------------------------------------------------------------------------
1 | call(UsersTableSeeder::class);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/infrastructure/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "3"
2 |
3 | services:
4 | email:
5 | build:
6 | context: ../
7 | dockerfile: infrastructure/email_microservice/Dockerfile.dev
8 | volumes:
9 | - "../report:/var/www/html/email_microservice/report"
10 | - "../storage/logs:/var/www/html/email_microservice/storage/logs"
11 | environment:
12 | WAIT_HOSTS: rabbitmq.dev:5672, postgres:5432
13 | restart: always
14 |
15 | email_consumer:
16 | build:
17 | context: ../
18 | dockerfile: infrastructure/email_microservice_consumer/Dockerfile.dev
19 | volumes:
20 | - "../report:/var/www/html/email_microservice/report"
21 | - "../storage/logs:/var/www/html/email_microservice/storage/logs"
22 | environment:
23 | WAIT_HOSTS: rabbitmq.dev:5672, postgres:5432
24 | restart: always
25 |
26 | nginx:
27 | build:
28 | context: ../
29 | dockerfile: infrastructure/nginx/Dockerfile
30 | container_name: email_nginx
31 | restart: always
32 | environment:
33 | WAIT_HOSTS: rabbitmq.dev:5672, postgres:5432
34 | ports:
35 | - "8080:80"
36 |
37 | rabbitmq:
38 | image: rabbitmq:3.8-rc-management-alpine
39 | container_name: email_rabbitmq
40 | volumes:
41 | - rabbitmq:/var/lib/rabbitmq
42 | networks:
43 | default:
44 | aliases:
45 | - rabbitmq.dev
46 | restart: always
47 | ports:
48 | - "15672:15672"
49 | - "5672:5672"
50 |
51 | postgres:
52 | image: postgres
53 | ports:
54 | - "5432:5432"
55 | networks:
56 | default:
57 | aliases:
58 | - postgres.dev
59 | environment:
60 | POSTGRES_USER: postgres
61 | POSTGRES_PASSWORD: postgres
62 | POSTGRES_DB: email_service
63 |
64 | volumes:
65 | rabbitmq:
66 | driver: local
67 |
--------------------------------------------------------------------------------
/infrastructure/email_microservice/Dockerfile:
--------------------------------------------------------------------------------
1 | # Stage 1 - Composer
2 | FROM composer:1.9 AS composer
3 |
4 | # Stage 2 - Email microservice Publisher
5 | FROM php:7.3-fpm
6 |
7 | # Install Dependencies
8 | RUN apt-get update && apt-get install -y \
9 | git \
10 | libzip-dev \
11 | zip \
12 | unzip \
13 | libpq-dev \
14 | librabbitmq-dev \
15 | libssh-dev && \
16 | pecl install amqp
17 |
18 | # Install PHP extensions
19 | RUN docker-php-ext-configure zip --with-libzip
20 | RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql
21 | RUN docker-php-ext-install pdo pdo_mysql pdo_pgsql pgsql zip bcmath sockets
22 | RUN docker-php-ext-enable amqp
23 |
24 | # Application Workdir
25 | WORKDIR /var/www/html/email_microservice
26 |
27 | # Copy Laravel and Composer files
28 | COPY database/ database/
29 | COPY composer.json composer.json
30 | COPY composer.lock composer.lock
31 |
32 | # Copy Composer binary
33 | COPY --from=composer /usr/bin/composer /usr/bin/composer
34 |
35 | # Install Composer Dependencies
36 | RUN composer install \
37 | --no-interaction \
38 | --no-plugins \
39 | --no-scripts \
40 | --prefer-dist \
41 | --no-dev
42 |
43 | # Copy project files
44 | COPY . /var/www/html/email_microservice
45 |
46 | # Update directory permissions
47 | RUN chown -R www-data:www-data \
48 | /var/www/html/email_microservice/storage \
49 | /var/www/html/email_microservice/bootstrap/cache
50 |
51 | # Generate Laravel Key
52 | RUN php artisan key:generate
53 |
54 | # Clean Laravel Config
55 | RUN php artisan config:clear
56 | RUN php artisan clear-compiled
57 |
58 | # Port to expose
59 | EXPOSE 9000
60 |
61 | # Run app server
62 | CMD php-fpm
63 |
--------------------------------------------------------------------------------
/infrastructure/email_microservice/Dockerfile.dev:
--------------------------------------------------------------------------------
1 | # Stage 1 - Composer
2 | FROM composer:1.9 AS composer
3 |
4 | # Stage 2 - Email microservice Publisher
5 | FROM php:7.3-fpm
6 |
7 | # Install Dependencies
8 | RUN apt-get update && apt-get install -y \
9 | git \
10 | libzip-dev \
11 | zip \
12 | unzip \
13 | libpq-dev \
14 | librabbitmq-dev \
15 | libssh-dev && \
16 | pecl install xdebug amqp && \
17 | docker-php-ext-enable xdebug
18 |
19 | # Install PHP extensions
20 | RUN docker-php-ext-configure zip --with-libzip
21 | RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql
22 | RUN docker-php-ext-install pdo pdo_mysql pdo_pgsql pgsql zip bcmath sockets
23 | RUN docker-php-ext-enable amqp
24 |
25 | # Application Workdir
26 | WORKDIR /var/www/html/email_microservice
27 |
28 | # Copy Laravel and Composer files
29 | COPY database/ database/
30 | COPY composer.json composer.json
31 | COPY composer.lock composer.lock
32 |
33 | # Copy Composer binary
34 | COPY --from=composer /usr/bin/composer /usr/bin/composer
35 |
36 | # Install Composer Dependencies
37 | RUN composer install \
38 | --no-interaction \
39 | --no-plugins \
40 | --no-scripts \
41 | --prefer-dist
42 |
43 | # Copy project files
44 | COPY . /var/www/html/email_microservice
45 |
46 | # Copy XDebug file
47 | COPY ./infrastructure/xdebug/xdebug.ini /usr/local/etc/php7.3/conf.d/
48 |
49 | # Update directory permissions
50 | RUN chown -R www-data:www-data \
51 | /var/www/html/email_microservice/storage \
52 | /var/www/html/email_microservice/bootstrap/cache
53 |
54 | # Generate Laravel Key
55 | RUN php artisan key:generate
56 |
57 | # Clean Laravel Config
58 | RUN php artisan config:clear
59 | RUN php artisan clear-compiled
60 |
61 | # Add Wait script
62 | ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.6.0/wait /wait
63 | RUN chmod +x /wait
64 |
65 | # Port to expose
66 | EXPOSE 9000
67 |
68 | # Run app server
69 | CMD /wait && php-fpm
70 |
--------------------------------------------------------------------------------
/infrastructure/email_microservice_consumer/Dockerfile:
--------------------------------------------------------------------------------
1 | # Stage 1 - Composer
2 | FROM composer:1.9 AS composer
3 |
4 | # Stage 2 - Email microservice Consumer
5 | FROM php:7.3-cli
6 |
7 | # Install Dependencies
8 | RUN apt-get update && apt-get install -y \
9 | git \
10 | libzip-dev \
11 | zip \
12 | unzip \
13 | libpq-dev \
14 | librabbitmq-dev \
15 | libssh-dev && \
16 | pecl install amqp
17 |
18 | # Install PHP extensions
19 | RUN docker-php-ext-configure zip --with-libzip
20 | RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql
21 | RUN docker-php-ext-install pdo pdo_mysql pdo_pgsql pgsql zip bcmath sockets
22 | RUN docker-php-ext-enable amqp
23 |
24 | # Application Workdir
25 | WORKDIR /var/www/html/email_microservice
26 |
27 | # Copy Laravel and Composer files
28 | COPY database/ database/
29 | COPY composer.json composer.json
30 | COPY composer.lock composer.lock
31 |
32 | # Copy Composer binary
33 | COPY --from=composer /usr/bin/composer /usr/bin/composer
34 |
35 | # Install Composer Dependencies
36 | RUN composer install \
37 | --no-interaction \
38 | --no-plugins \
39 | --no-scripts \
40 | --prefer-dist \
41 | --no-dev
42 |
43 | # Copy project files
44 | COPY . /var/www/html/email_microservice
45 |
46 | # Update directory permissions
47 | RUN chown -R www-data:www-data \
48 | /var/www/html/email_microservice/storage \
49 | /var/www/html/email_microservice/bootstrap/cache
50 |
51 | # Generate Laravel Key
52 | RUN php artisan key:generate
53 |
54 | # Clean Laravel Config
55 | RUN php artisan config:clear
56 | RUN php artisan clear-compiled
57 |
58 | # Run migrations and consumer command
59 | CMD php artisan migrate --force && php artisan consumer:emails
60 |
--------------------------------------------------------------------------------
/infrastructure/email_microservice_consumer/Dockerfile.dev:
--------------------------------------------------------------------------------
1 | # Stage 1 - Composer
2 | FROM composer:1.9 AS composer
3 |
4 | # Stage 2 - Email microservice Consumer
5 | FROM php:7.3-cli
6 |
7 | # Install Dependencies
8 | RUN apt-get update && apt-get install -y \
9 | git \
10 | libzip-dev \
11 | zip \
12 | unzip \
13 | libpq-dev \
14 | librabbitmq-dev \
15 | libssh-dev && \
16 | pecl install xdebug amqp && \
17 | docker-php-ext-enable xdebug
18 |
19 | # Install PHP extensions
20 | RUN docker-php-ext-configure zip --with-libzip
21 | RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql
22 | RUN docker-php-ext-install pdo pdo_mysql pdo_pgsql pgsql zip bcmath sockets
23 | RUN docker-php-ext-enable amqp
24 |
25 | # Application Workdir
26 | WORKDIR /var/www/html/email_microservice
27 |
28 | # Copy Laravel and Composer files
29 | COPY database/ database/
30 | COPY composer.json composer.json
31 | COPY composer.lock composer.lock
32 |
33 | # Copy Composer binary
34 | COPY --from=composer /usr/bin/composer /usr/bin/composer
35 |
36 | # Install Composer Dependencies
37 | RUN composer install \
38 | --no-interaction \
39 | --no-plugins \
40 | --no-scripts \
41 | --prefer-dist
42 |
43 | # Copy project files
44 | COPY . /var/www/html/email_microservice
45 |
46 | # Copy XDebug file
47 | COPY ./infrastructure/xdebug/xdebug.ini /usr/local/etc/php7.3/conf.d/
48 |
49 | # Update directory permissions
50 | RUN chown -R www-data:www-data \
51 | /var/www/html/email_microservice/storage \
52 | /var/www/html/email_microservice/bootstrap/cache
53 |
54 | # Generate Laravel Key
55 | RUN php artisan key:generate
56 |
57 | # Clean Laravel Config
58 | RUN php artisan config:clear
59 | RUN php artisan clear-compiled
60 |
61 | # Add Wait script
62 | ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.6.0/wait /wait
63 | RUN chmod +x /wait
64 |
65 | # Run migrations and consumer command
66 | CMD /wait && php artisan migrate --force && php artisan consumer:emails
67 |
--------------------------------------------------------------------------------
/infrastructure/nginx/Dockerfile:
--------------------------------------------------------------------------------
1 | # Nginx Web Server
2 | FROM nginx:1.15
3 |
4 | # Web Server Workdir
5 | WORKDIR /var/www/html/email_microservice
6 |
7 | # Copy Nginx config file
8 | ADD ./infrastructure/nginx/default.conf /etc/nginx/conf.d/default.conf
9 |
10 | # Copy public folder
11 | COPY ./public /var/www/html/email_microservice/public
12 |
--------------------------------------------------------------------------------
/infrastructure/nginx/default.conf:
--------------------------------------------------------------------------------
1 | upstream infrastructure_email {
2 | server infrastructure_email_1:9000;
3 | }
4 |
5 | server {
6 | listen 80;
7 |
8 | root /var/www/html/email_microservice/public;
9 | index index.php index.html index.htm;
10 |
11 | location / {
12 | try_files $uri $uri/ /index.php?$query_string;
13 | }
14 |
15 | location ~ \.php$ {
16 | try_files $uri =404;
17 | fastcgi_split_path_info ^(.+\.php)(/.+)$;
18 | fastcgi_pass infrastructure_email;
19 | fastcgi_index index.php;
20 | include fastcgi_params;
21 | fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
22 | fastcgi_param PATH_INFO $fastcgi_path_info;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/infrastructure/xdebug/xdebug.ini:
--------------------------------------------------------------------------------
1 | [Xdebug]
2 | xdebug.remote_autostart=0
3 | xdebug.remote_enable=1
4 | xdebug.default_enable=0
5 | xdebug.remote_host=host.docker.internal
6 | xdebug.remote_port=9000
7 | xdebug.remote_connect_back=0
8 | xdebug.profiler_enable=0
9 | xdebug.remote_log="/tmp/xdebug.log"
10 | xdebug.profiler_output_dir="/var/www/html/profiler"
11 | xdebug.profiler_output_name="cachegrind.out.%p"
12 | xdebug.cli_color=1
13 | xdebug.profiler_append=1
14 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "scripts": {
4 | "dev": "npm run development",
5 | "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
6 | "watch": "npm run development -- --watch",
7 | "watch-poll": "npm run watch -- --watch-poll",
8 | "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
9 | "prod": "npm run production",
10 | "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
11 | },
12 | "devDependencies": {
13 | "axios": "^0.19",
14 | "cross-env": "^5.1",
15 | "laravel-mix": "^4.0.7",
16 | "lodash": "^4.17.13",
17 | "resolve-url-loader": "^2.3.1",
18 | "sass": "^1.15.2",
19 | "sass-loader": "^7.1.0"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
15 | ./tests/Unit
16 |
17 |
18 |
19 | ./tests/Feature
20 |
21 |
22 |
23 |
24 | ./app
25 |
26 | ./app/Console/Commands/Consumer
27 | ./app/Http/Controllers/Auth
28 | ./app/Http/Middleware
29 |
30 |
31 |
32 |
33 |
35 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/public/.htaccess:
--------------------------------------------------------------------------------
1 |
2 |
3 | Options -MultiViews -Indexes
4 |
5 |
6 | RewriteEngine On
7 |
8 | # Handle Authorization Header
9 | RewriteCond %{HTTP:Authorization} .
10 | RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
11 |
12 | # Redirect Trailing Slashes If Not A Folder...
13 | RewriteCond %{REQUEST_FILENAME} !-d
14 | RewriteCond %{REQUEST_URI} (.+)/$
15 | RewriteRule ^ %1 [L,R=301]
16 |
17 | # Handle Front Controller...
18 | RewriteCond %{REQUEST_FILENAME} !-d
19 | RewriteCond %{REQUEST_FILENAME} !-f
20 | RewriteRule ^ index.php [L]
21 |
22 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fecaps/email_microservice/20d745d22189d7b055f52f251f438fe76b9f104b/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.php:
--------------------------------------------------------------------------------
1 |
8 | */
9 |
10 | define('LARAVEL_START', microtime(true));
11 |
12 | /*
13 | |--------------------------------------------------------------------------
14 | | Register The Auto Loader
15 | |--------------------------------------------------------------------------
16 | |
17 | | Composer provides a convenient, automatically generated class loader for
18 | | our application. We just need to utilize it! We'll simply require it
19 | | into the script here so that we don't have to worry about manual
20 | | loading any of our classes later on. It feels great to relax.
21 | |
22 | */
23 |
24 | require __DIR__.'/../vendor/autoload.php';
25 |
26 | /*
27 | |--------------------------------------------------------------------------
28 | | Turn On The Lights
29 | |--------------------------------------------------------------------------
30 | |
31 | | We need to illuminate PHP development, so let us turn on the lights.
32 | | This bootstraps the framework and gets it ready for use, then it
33 | | will load up this application so that we can run it and send
34 | | the responses back to the browser and delight our users.
35 | |
36 | */
37 |
38 | $app = require_once __DIR__.'/../bootstrap/app.php';
39 |
40 | /*
41 | |--------------------------------------------------------------------------
42 | | Run The Application
43 | |--------------------------------------------------------------------------
44 | |
45 | | Once we have the application, we can handle the incoming request
46 | | through the kernel, and send the associated response back to
47 | | the client's browser allowing them to enjoy the creative
48 | | and wonderful application we have prepared for them.
49 | |
50 | */
51 |
52 | $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
53 |
54 | $response = $kernel->handle(
55 | $request = Illuminate\Http\Request::capture()
56 | );
57 |
58 | $response->send();
59 |
60 | $kernel->terminate($request, $response);
61 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | User-agent: *
2 | Disallow:
3 |
--------------------------------------------------------------------------------
/public/web.config:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/resources/lang/en/auth.php:
--------------------------------------------------------------------------------
1 | 'These credentials do not match our records.',
17 | 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
18 |
19 | ];
20 |
--------------------------------------------------------------------------------
/resources/lang/en/pagination.php:
--------------------------------------------------------------------------------
1 | '« Previous',
17 | 'next' => 'Next »',
18 |
19 | ];
20 |
--------------------------------------------------------------------------------
/resources/lang/en/passwords.php:
--------------------------------------------------------------------------------
1 | 'Your password has been reset!',
17 | 'sent' => 'We have e-mailed your password reset link!',
18 | 'token' => 'This password reset token is invalid.',
19 | 'user' => "We can't find a user with that e-mail address.",
20 | 'throttled' => 'Please wait before retrying.',
21 |
22 | ];
23 |
--------------------------------------------------------------------------------
/resources/lang/en/validation.php:
--------------------------------------------------------------------------------
1 | 'The :attribute must be accepted.',
17 | 'active_url' => 'The :attribute is not a valid URL.',
18 | 'after' => 'The :attribute must be a date after :date.',
19 | 'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
20 | 'alpha' => 'The :attribute may only contain letters.',
21 | 'alpha_dash' => 'The :attribute may only contain letters, numbers, dashes and underscores.',
22 | 'alpha_num' => 'The :attribute may only contain letters and numbers.',
23 | 'array' => 'The :attribute must be an array.',
24 | 'before' => 'The :attribute must be a date before :date.',
25 | 'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
26 | 'between' => [
27 | 'numeric' => 'The :attribute must be between :min and :max.',
28 | 'file' => 'The :attribute must be between :min and :max kilobytes.',
29 | 'string' => 'The :attribute must be between :min and :max characters.',
30 | 'array' => 'The :attribute must have between :min and :max items.',
31 | ],
32 | 'boolean' => 'The :attribute field must be true or false.',
33 | 'confirmed' => 'The :attribute confirmation does not match.',
34 | 'date' => 'The :attribute is not a valid date.',
35 | 'date_equals' => 'The :attribute must be a date equal to :date.',
36 | 'date_format' => 'The :attribute does not match the format :format.',
37 | 'different' => 'The :attribute and :other must be different.',
38 | 'digits' => 'The :attribute must be :digits digits.',
39 | 'digits_between' => 'The :attribute must be between :min and :max digits.',
40 | 'dimensions' => 'The :attribute has invalid image dimensions.',
41 | 'distinct' => 'The :attribute field has a duplicate value.',
42 | 'email' => 'The :attribute must be a valid email address.',
43 | 'ends_with' => 'The :attribute must end with one of the following: :values',
44 | 'exists' => 'The selected :attribute is invalid.',
45 | 'file' => 'The :attribute must be a file.',
46 | 'filled' => 'The :attribute field must have a value.',
47 | 'gt' => [
48 | 'numeric' => 'The :attribute must be greater than :value.',
49 | 'file' => 'The :attribute must be greater than :value kilobytes.',
50 | 'string' => 'The :attribute must be greater than :value characters.',
51 | 'array' => 'The :attribute must have more than :value items.',
52 | ],
53 | 'gte' => [
54 | 'numeric' => 'The :attribute must be greater than or equal :value.',
55 | 'file' => 'The :attribute must be greater than or equal :value kilobytes.',
56 | 'string' => 'The :attribute must be greater than or equal :value characters.',
57 | 'array' => 'The :attribute must have :value items or more.',
58 | ],
59 | 'image' => 'The :attribute must be an image.',
60 | 'in' => 'The selected :attribute is invalid.',
61 | 'in_array' => 'The :attribute field does not exist in :other.',
62 | 'integer' => 'The :attribute must be an integer.',
63 | 'ip' => 'The :attribute must be a valid IP address.',
64 | 'ipv4' => 'The :attribute must be a valid IPv4 address.',
65 | 'ipv6' => 'The :attribute must be a valid IPv6 address.',
66 | 'json' => 'The :attribute must be a valid JSON string.',
67 | 'lt' => [
68 | 'numeric' => 'The :attribute must be less than :value.',
69 | 'file' => 'The :attribute must be less than :value kilobytes.',
70 | 'string' => 'The :attribute must be less than :value characters.',
71 | 'array' => 'The :attribute must have less than :value items.',
72 | ],
73 | 'lte' => [
74 | 'numeric' => 'The :attribute must be less than or equal :value.',
75 | 'file' => 'The :attribute must be less than or equal :value kilobytes.',
76 | 'string' => 'The :attribute must be less than or equal :value characters.',
77 | 'array' => 'The :attribute must not have more than :value items.',
78 | ],
79 | 'max' => [
80 | 'numeric' => 'The :attribute may not be greater than :max.',
81 | 'file' => 'The :attribute may not be greater than :max kilobytes.',
82 | 'string' => 'The :attribute may not be greater than :max characters.',
83 | 'array' => 'The :attribute may not have more than :max items.',
84 | ],
85 | 'mimes' => 'The :attribute must be a file of type: :values.',
86 | 'mimetypes' => 'The :attribute must be a file of type: :values.',
87 | 'min' => [
88 | 'numeric' => 'The :attribute must be at least :min.',
89 | 'file' => 'The :attribute must be at least :min kilobytes.',
90 | 'string' => 'The :attribute must be at least :min characters.',
91 | 'array' => 'The :attribute must have at least :min items.',
92 | ],
93 | 'not_in' => 'The selected :attribute is invalid.',
94 | 'not_regex' => 'The :attribute format is invalid.',
95 | 'numeric' => 'The :attribute must be a number.',
96 | 'password' => 'The password is incorrect.',
97 | 'present' => 'The :attribute field must be present.',
98 | 'regex' => 'The :attribute format is invalid.',
99 | 'required' => 'The :attribute field is required.',
100 | 'required_if' => 'The :attribute field is required when :other is :value.',
101 | 'required_unless' => 'The :attribute field is required unless :other is in :values.',
102 | 'required_with' => 'The :attribute field is required when :values is present.',
103 | 'required_with_all' => 'The :attribute field is required when :values are present.',
104 | 'required_without' => 'The :attribute field is required when :values is not present.',
105 | 'required_without_all' => 'The :attribute field is required when none of :values are present.',
106 | 'same' => 'The :attribute and :other must match.',
107 | 'size' => [
108 | 'numeric' => 'The :attribute must be :size.',
109 | 'file' => 'The :attribute must be :size kilobytes.',
110 | 'string' => 'The :attribute must be :size characters.',
111 | 'array' => 'The :attribute must contain :size items.',
112 | ],
113 | 'starts_with' => 'The :attribute must start with one of the following: :values',
114 | 'string' => 'The :attribute must be a string.',
115 | 'timezone' => 'The :attribute must be a valid zone.',
116 | 'unique' => 'The :attribute has already been taken.',
117 | 'uploaded' => 'The :attribute failed to upload.',
118 | 'url' => 'The :attribute format is invalid.',
119 | 'uuid' => 'The :attribute must be a valid UUID.',
120 |
121 | /*
122 | |--------------------------------------------------------------------------
123 | | Custom Validation Language Lines
124 | |--------------------------------------------------------------------------
125 | |
126 | | Here you may specify custom validation messages for attributes using the
127 | | convention "attribute.rule" to name the lines. This makes it quick to
128 | | specify a specific custom language line for a given attribute rule.
129 | |
130 | */
131 |
132 | 'custom' => [
133 | 'attribute-name' => [
134 | 'rule-name' => 'custom-message',
135 | ],
136 | ],
137 |
138 | /*
139 | |--------------------------------------------------------------------------
140 | | Custom Validation Attributes
141 | |--------------------------------------------------------------------------
142 | |
143 | | The following language lines are used to swap our attribute placeholder
144 | | with something more reader friendly such as "E-Mail Address" instead
145 | | of "email". This simply helps us make our message more expressive.
146 | |
147 | */
148 |
149 | 'attributes' => [],
150 |
151 | ];
152 |
--------------------------------------------------------------------------------
/routes/api.php:
--------------------------------------------------------------------------------
1 | name('emails.list');
19 |
20 | Route::post('/emails', 'EmailController@store')->name('emails.store');
21 |
22 |
--------------------------------------------------------------------------------
/routes/channels.php:
--------------------------------------------------------------------------------
1 | id === (int) $id;
16 | });
17 |
--------------------------------------------------------------------------------
/routes/console.php:
--------------------------------------------------------------------------------
1 | comment(Inspiring::quote());
18 | })->describe('Display an inspiring quote');
19 |
--------------------------------------------------------------------------------
/routes/web.php:
--------------------------------------------------------------------------------
1 |
8 | */
9 |
10 | $uri = urldecode(
11 | parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
12 | );
13 |
14 | // This file allows us to emulate Apache's "mod_rewrite" functionality from the
15 | // built-in PHP web server. This provides a convenient way to test a Laravel
16 | // application without having installed a "real" web server software here.
17 | if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
18 | return false;
19 | }
20 |
21 | require_once __DIR__.'/public/index.php';
22 |
--------------------------------------------------------------------------------
/storage/app/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !public/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/storage/app/public/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/.gitignore:
--------------------------------------------------------------------------------
1 | config.php
2 | routes.php
3 | schedule-*
4 | compiled.php
5 | services.json
6 | events.scanned.php
7 | routes.scanned.php
8 | down
9 |
--------------------------------------------------------------------------------
/storage/framework/cache/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !data/
3 | !.gitignore
4 |
--------------------------------------------------------------------------------
/storage/framework/cache/data/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/sessions/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/testing/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/framework/views/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/storage/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/tests/CreatesApplication.php:
--------------------------------------------------------------------------------
1 | make(Kernel::class)->bootstrap();
19 |
20 | return $app;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/tests/Feature/EmailTest.php:
--------------------------------------------------------------------------------
1 | json('PUT', 'emails', []);
18 |
19 | $response->assertStatus(405)
20 | ->assertHeader(
21 | 'Content-Type', 'application/json'
22 | )
23 | ->assertJsonStructure(
24 | [ 'message', 'errors' ], $response->json()
25 | )
26 | ->assertJson([
27 | 'message' => 'Resource Not Allowed',
28 | 'errors' => [
29 | 'http_method;http_headers' =>
30 | 'Resource not allowed for this HTTP method and HTTP headers'
31 | ]
32 | ], true);
33 | }
34 |
35 | /**
36 | * Test invalid route for emails resource
37 | *
38 | * @return void
39 | */
40 | public function testInvalidRouteForEmailsResource(): void
41 | {
42 | $response = $this
43 | ->json('PUT', 'emails2', []);
44 |
45 | $response->assertStatus(404)
46 | ->assertHeader(
47 | 'Content-Type', 'application/json'
48 | )
49 | ->assertJsonStructure(
50 | [ 'message', 'errors' ], $response->json()
51 | )
52 | ->assertJson([
53 | 'message' => 'Resource Not Found',
54 | 'errors' => [
55 | 'http_headers;url' =>
56 | 'Resource not found for this HTTP headers and URL'
57 | ]
58 | ], true);
59 | }
60 |
61 | /**
62 | * Test invalid cases for email resource
63 | *
64 | * @dataProvider \Tests\Feature\InvalidEmailsDataProvider::invalidEmails()
65 | * @param array $emailData
66 | * @return void
67 | */
68 | public function testInvalidPayloadsForEmailsResource(array $emailData): void
69 | {
70 | $response = $this
71 | ->json('POST', 'emails', $emailData);
72 |
73 | $response->assertStatus(422)
74 | ->assertHeader(
75 | 'Content-Type', 'application/json'
76 | )
77 | ->assertJsonStructure(
78 | [ 'message', 'errors' ], $response->json()
79 | )
80 | ->assertJsonCount(8, 'errors');
81 | }
82 |
83 | /**
84 | * Test valid cases for email resource
85 | *
86 | * @dataProvider \Tests\Feature\ValidEmailsDataProvider::emails()
87 | * @param array $emailData
88 | * @return void
89 | */
90 | public function testValidPayloadsForEmailsResource(array $emailData): void
91 | {
92 | $response = $this
93 | ->json('POST', 'emails', $emailData);
94 |
95 | $response->assertStatus(201)
96 | ->assertHeader(
97 | 'Content-Type', 'application/json'
98 | )
99 | ->assertJsonStructure(
100 | [ 'data' ], $response->json()
101 | )
102 | ->assertJsonCount(5, 'data');
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/tests/Feature/InvalidEmailsDataProvider.php:
--------------------------------------------------------------------------------
1 | [
15 | 'email' => $defaultNumberValue,
16 | 'name' => $defaultNumberValue
17 | ],
18 | 'to' => [
19 | 'email' => $defaultNumberValue,
20 | 'name' => $defaultNumberValue
21 | ],
22 | 'subject' => $defaultNumberValue,
23 | 'textPart' => $defaultNumberValue,
24 | ]
25 | ],
26 | [
27 |
28 | [
29 | 'from' => [
30 | 'email' => 'invalid',
31 | 'name' => function () {}
32 | ],
33 | 'to' => [
34 | 'email' => function () {},
35 | 'name' => str_repeat('a', 256)
36 | ],
37 | 'subject' => -10,
38 | 'htmlPart' => $defaultNumberValue,
39 | ]
40 | ],
41 | [
42 |
43 | [
44 | 'from' => [
45 | 'email' => 'invalid',
46 | 'name' => function () {}
47 | ],
48 | 'to' => [
49 | 'email' => function () {},
50 | 'name' => str_repeat('a', 256)
51 | ],
52 | 'subject' => -10,
53 | 'markdownPart' => $defaultNumberValue,
54 | ]
55 | ],
56 | ];
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/tests/Feature/ValidEmailsDataProvider.php:
--------------------------------------------------------------------------------
1 | [
13 | 'email' => 'fellipecapelli@gmail.com',
14 | 'name' => 'fellipe - from',
15 | ],
16 | 'to' => [
17 | [
18 | 'email' => 'fellipecapelli@gmail.com',
19 | 'name' => 'fellipe - to',
20 | ]
21 | ],
22 | 'subject' => 'hello - subject',
23 | 'textPart' => 'hello - text part'
24 | ]
25 | ],
26 | [
27 |
28 | [
29 | 'from' => [
30 | 'email' => 'fellipecapelli@gmail.com',
31 | 'name' => 'fellipe - from',
32 | ],
33 | 'to' => [
34 | [
35 | 'email' => 'fellipecapelli@gmail.com',
36 | 'name' => 'fellipe - to',
37 | ]
38 | ],
39 | 'subject' => 'hello - subject',
40 | 'htmlPart' => 'hello - html part'
41 | ],
42 | ],
43 | [
44 | [
45 | 'from' => [
46 | 'email' => 'fellipecapelli@gmail.com',
47 | 'name' => 'fellipe - from',
48 | ],
49 | 'to' => [
50 | [
51 | 'email' => 'fellipecapelli@gmail.com',
52 | 'name' => 'fellipe - to',
53 | ]
54 | ],
55 | 'subject' => 'hello - subject',
56 | 'markdownPart' => 'hello - markdown part'
57 | ],
58 | ],
59 | ];
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/tests/TestCase.php:
--------------------------------------------------------------------------------
1 | getClient();
21 |
22 | $this->assertInstanceOf(Client::class, $instanceType);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/tests/Unit/Connectors/SendgridConnectorTest.php:
--------------------------------------------------------------------------------
1 | getClient();
21 |
22 | $this->assertInstanceOf(SendGrid::class, $instanceType);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/tests/Unit/Console/Commands/Creator/EmailCreationTest.php:
--------------------------------------------------------------------------------
1 | artisan('create:email')
18 | ->expectsOutput(EmailCreation::START_MESSAGE)
19 | ->expectsQuestion(EmailCreation::FROM_EMAIL_MESSAGE, '')
20 | ->expectsQuestion(EmailCreation::FROM_NAME_MESSAGE, '')
21 | ->expectsQuestion(EmailCreation::TO_EMAIL_MESSAGE, '')
22 | ->expectsQuestion(EmailCreation::TO_NAME_MESSAGE, '')
23 | ->expectsQuestion(EmailCreation::SUBJECT_MESSAGE, '')
24 | ->expectsQuestion(EmailCreation::TEXT_PART_MESSAGE, '')
25 | ->expectsQuestion(EmailCreation::HTML_PART_MESSAGE, '')
26 | ->expectsQuestion(EmailCreation::MARKDOWN_PART_MESSAGE, '')
27 | ->expectsOutput(EmailCreation::INVALID_MESSAGE)
28 | ->expectsOutput('The from email field is required.')
29 | ->expectsOutput('The from name field is required.')
30 | ->expectsOutput('The to email field is required.')
31 | ->expectsOutput('The to name field is required.')
32 | ->expectsOutput('The subject field is required.');
33 | }
34 |
35 | /**
36 | * Email Creation with Text Part - Console test
37 | *
38 | * @return void
39 | */
40 | public function testEmailCreationWithText(): void
41 | {
42 | $this->artisan('create:email')
43 | ->expectsOutput(EmailCreation::START_MESSAGE)
44 | ->expectsQuestion(EmailCreation::FROM_EMAIL_MESSAGE, 'fellipecapelli@gmail.com')
45 | ->expectsQuestion(EmailCreation::FROM_NAME_MESSAGE, 'Fellipe')
46 | ->expectsQuestion(EmailCreation::TO_EMAIL_MESSAGE, 'fellipe.capelli@outlook.com')
47 | ->expectsQuestion(EmailCreation::TO_NAME_MESSAGE, 'Fellipe Capelli')
48 | ->expectsQuestion(EmailCreation::SUBJECT_MESSAGE, 'hello - subject')
49 | ->expectsQuestion(EmailCreation::TEXT_PART_MESSAGE, 'hello - text part')
50 | ->expectsQuestion(EmailCreation::HTML_PART_MESSAGE, '')
51 | ->expectsQuestion(EmailCreation::MARKDOWN_PART_MESSAGE, '')
52 | ->expectsOutput(EmailCreation::END_MESSAGE);
53 | }
54 |
55 | /**
56 | * Email Creation with Html Part - Console test
57 | *
58 | * @return void
59 | */
60 | public function testEmailCreationWithHtml(): void
61 | {
62 | $this->artisan('create:email')
63 | ->expectsOutput(EmailCreation::START_MESSAGE)
64 | ->expectsQuestion(EmailCreation::FROM_EMAIL_MESSAGE, 'fellipecapelli@gmail.com')
65 | ->expectsQuestion(EmailCreation::FROM_NAME_MESSAGE, 'Fellipe')
66 | ->expectsQuestion(EmailCreation::TO_EMAIL_MESSAGE, 'fellipe.capelli@outlook.com')
67 | ->expectsQuestion(EmailCreation::TO_NAME_MESSAGE, 'Fellipe Capelli')
68 | ->expectsQuestion(EmailCreation::SUBJECT_MESSAGE, 'hello - subject')
69 | ->expectsQuestion(EmailCreation::TEXT_PART_MESSAGE, '')
70 | ->expectsQuestion(EmailCreation::HTML_PART_MESSAGE, '
Hello
Html part')
71 | ->expectsQuestion(EmailCreation::MARKDOWN_PART_MESSAGE, '')
72 | ->expectsOutput(EmailCreation::END_MESSAGE);
73 | }
74 |
75 | /**
76 | * Email Creation with Markdown Part - Console test
77 | *
78 | * @return void
79 | */
80 | public function testEmailCreationWithMarkdown(): void
81 | {
82 | $this->artisan('create:email')
83 | ->expectsOutput(EmailCreation::START_MESSAGE)
84 | ->expectsQuestion(EmailCreation::FROM_EMAIL_MESSAGE, 'fellipecapelli@gmail.com')
85 | ->expectsQuestion(EmailCreation::FROM_NAME_MESSAGE, 'Fellipe')
86 | ->expectsQuestion(EmailCreation::TO_EMAIL_MESSAGE, 'fellipe.capelli@outlook.com')
87 | ->expectsQuestion(EmailCreation::TO_NAME_MESSAGE, 'Fellipe Capelli')
88 | ->expectsQuestion(EmailCreation::SUBJECT_MESSAGE, 'hello - subject')
89 | ->expectsQuestion(EmailCreation::TEXT_PART_MESSAGE, '')
90 | ->expectsQuestion(EmailCreation::HTML_PART_MESSAGE, '')
91 | ->expectsQuestion(EmailCreation::MARKDOWN_PART_MESSAGE, 'Hello, markdown part')
92 | ->expectsOutput(EmailCreation::END_MESSAGE);
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/tests/Unit/DTO/EmailDTOTest.php:
--------------------------------------------------------------------------------
1 | defineId(null);
20 | $id = $emailDTO->getId();
21 |
22 | $this->assertNull($id);
23 | }
24 |
25 | /**
26 | * Define ID Test With Int
27 | *
28 | * @return void
29 | */
30 | public function testDefineIdWithInt(): void
31 | {
32 | $value = 1;
33 |
34 | $emailDTO = new EmailDTO();
35 | $emailDTO->defineId($value);
36 | $id = $emailDTO->getId();
37 |
38 | $this->assertSame($value, $id);
39 | }
40 |
41 | /**
42 | * Define From Test With Null
43 | *
44 | * @return void
45 | */
46 | public function testDefineFromWithNull(): void
47 | {
48 | $emailDTO = new EmailDTO();
49 | $emailDTO->defineFrom(null);
50 | $email = $emailDTO->get();
51 |
52 | $this->assertEquals([], $email[Email::FROM_KEY]);
53 | }
54 |
55 | /**
56 | * Define From Test With Array
57 | *
58 | * @return void
59 | */
60 | public function testDefineFromWithArray(): void
61 | {
62 | $value = [
63 | 'name' => 'fellipe',
64 | 'email' => 'fellipe@gmail.com',
65 | ];
66 |
67 | $emailDTO = new EmailDTO();
68 | $emailDTO->defineFrom($value);
69 | $email = $emailDTO->get();
70 |
71 | $this->assertSame($value, $email[Email::FROM_KEY]);
72 | }
73 |
74 | /**
75 | * Define To Test With Null
76 | *
77 | * @return void
78 | */
79 | public function testDefineToWithNull(): void
80 | {
81 | $emailDTO = new EmailDTO();
82 | $emailDTO->defineTo(null);
83 | $email = $emailDTO->get();
84 |
85 | $this->assertEquals([], $email[Email::TO_KEY]);
86 | }
87 |
88 | /**
89 | * Define To Test With Array
90 | *
91 | * @return void
92 | */
93 | public function testDefineToWithArray(): void
94 | {
95 | $value = [
96 | [
97 | 'name' => 'fellipe',
98 | 'email' => 'fellipe@gmail.com',
99 | ],
100 | ];
101 |
102 | $emailDTO = new EmailDTO();
103 | $emailDTO->defineTo($value);
104 | $email = $emailDTO->get();
105 |
106 | $this->assertSame($value, $email[Email::TO_KEY]);
107 | }
108 |
109 | /**
110 | * Define Subject Test With Null
111 | *
112 | * @return void
113 | */
114 | public function testDefineSubjectWithNull(): void
115 | {
116 | $emailDTO = new EmailDTO();
117 | $emailDTO->defineSubject(null);
118 | $email = $emailDTO->get();
119 |
120 | $this->assertNull($email[Email::SUBJECT_KEY]);
121 | }
122 |
123 | /**
124 | * Define Subject Test With Array
125 | *
126 | * @return void
127 | */
128 | public function testDefineSubjectWithString(): void
129 | {
130 | $value = 'subject';
131 |
132 | $emailDTO = new EmailDTO();
133 | $emailDTO->defineSubject($value);
134 | $email = $emailDTO->get();
135 |
136 | $this->assertSame($value, $email[Email::SUBJECT_KEY]);
137 | }
138 |
139 | /**
140 | * Define TextPart Test With Null
141 | *
142 | * @return void
143 | */
144 | public function testDefineTextPartWithNull(): void
145 | {
146 | $emailDTO = new EmailDTO();
147 | $emailDTO->defineTextPart(null);
148 | $email = $emailDTO->get();
149 |
150 | $this->assertArrayNotHasKey(Email::TEXT_PART_KEY, $email);
151 | }
152 |
153 | /**
154 | * Define TextPart Test With Array
155 | *
156 | * @return void
157 | */
158 | public function testDefineTextPartWithString(): void
159 | {
160 | $value = 'text part';
161 |
162 | $emailDTO = new EmailDTO();
163 | $emailDTO->defineTextPart($value);
164 | $email = $emailDTO->get();
165 |
166 | $this->assertSame($value, $email[Email::TEXT_PART_KEY]);
167 | }
168 |
169 | /**
170 | * Define HtmlPart Test With Null
171 | *
172 | * @return void
173 | */
174 | public function testDefineHtmlPartWithNull(): void
175 | {
176 | $emailDTO = new EmailDTO();
177 | $emailDTO->defineHtmlPart(null);
178 | $email = $emailDTO->get();
179 |
180 | $this->assertArrayNotHasKey(Email::HTML_PART_KEY, $email);
181 | }
182 |
183 | /**
184 | * Define HtmlPart Test With Array
185 | *
186 | * @return void
187 | */
188 | public function testDefineHtmlPartWithString(): void
189 | {
190 | $value = 'html part';
191 |
192 | $emailDTO = new EmailDTO();
193 | $emailDTO->defineHtmlPart($value);
194 | $email = $emailDTO->get();
195 |
196 | $this->assertSame($value, $email[Email::HTML_PART_KEY]);
197 | }
198 |
199 | /**
200 | * Define MarkdownPart Test With Null
201 | *
202 | * @return void
203 | */
204 | public function testDefineMarkdownPartWithNull(): void
205 | {
206 | $emailDTO = new EmailDTO();
207 | $emailDTO->defineMarkdownPart(null);
208 | $email = $emailDTO->get();
209 |
210 | $this->assertArrayNotHasKey(Email::MARKDOWN_PART_KEY, $email);
211 | }
212 |
213 | /**
214 | * Define MarkdownPart Test With Array
215 | *
216 | * @return void
217 | */
218 | public function testDefineMarkdownPartWithString(): void
219 | {
220 | $value = 'html part';
221 |
222 | $emailDTO = new EmailDTO();
223 | $emailDTO->defineMarkdownPart($value);
224 | $email = $emailDTO->get();
225 |
226 | $this->assertSame($value, $email[Email::MARKDOWN_PART_KEY]);
227 | }
228 | }
229 |
--------------------------------------------------------------------------------
/tests/Unit/DataProviders/InvalidEmailsDataProvider.php:
--------------------------------------------------------------------------------
1 | [
13 | 'email' => 'fellipe',
14 | 'name' => 'Fellipe Capelli'
15 | ],
16 | 'to' => [
17 | [
18 | 'email' => 'fellipe.capelli@outlook.com',
19 | 'name' => 'Fellipe C. Fregoneze'
20 | ]
21 | ],
22 | 'subject' => 'Mailjet Transactor 1',
23 | 'textPart' => 'Hello, text part 1',
24 | ]
25 | ],
26 | [
27 |
28 | [
29 | 'from' => [
30 | 'email' => 'fellipecapelli@gmail.com',
31 | 'name' => 'Fellipe Capelli'
32 | ],
33 | 'to' => [
34 | [
35 | 'email' => 'fellipe',
36 | 'name' => 'Fellipe C. Fregoneze'
37 | ]
38 | ],
39 | 'subject' => 'Mailjet Transactor 2',
40 | 'htmlPart' => 'Hello, HTML part 2',
41 | ]
42 | ],
43 | [
44 |
45 | [
46 | 'from' => [
47 | 'email' => 'fellipe',
48 | 'name' => 'Fellipe Capelli'
49 | ],
50 | 'to' => [
51 | [
52 | 'email' => 'fellipe.capelli@outlook.com',
53 | 'name' => 'Fellipe C. Fregoneze'
54 | ]
55 | ],
56 | 'subject' => 'Mailjet Transactor 3',
57 | 'markdownPart' => 'Hello, markdown part 3',
58 | ]
59 | ],
60 | ];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/tests/Unit/DataProviders/ValidEmailsDataProvider.php:
--------------------------------------------------------------------------------
1 | [
13 | 'email' => 'fellipecapelli@gmail.com',
14 | 'name' => 'Fellipe Capelli',
15 | ],
16 | 'to' => [
17 | [
18 | 'email' => 'fellipe.capelli@outlook.com',
19 | 'name' => 'Fellipe C. Fregoneze',
20 | ]
21 | ],
22 | 'subject' => 'Mailjet Transactor 1',
23 | 'textPart' => 'Hello, text part 1',
24 | ]
25 | ],
26 | [
27 |
28 | [
29 | 'from' => [
30 | 'email' => 'fellipecapelli@gmail.com',
31 | 'name' => 'Fellipe Capelli'
32 | ],
33 | 'to' => [
34 | [
35 | 'email' => 'fellipe.capelli@outlook.com',
36 | 'name' => 'Fellipe C. Fregoneze'
37 | ]
38 | ],
39 | 'subject' => 'Mailjet Transactor 2',
40 | 'htmlPart' => 'Hello, HTML part 2',
41 | ]
42 | ],
43 | [
44 |
45 | [
46 | 'from' => [
47 | 'email' => 'fellipecapelli@gmail.com',
48 | 'name' => 'Fellipe Capelli'
49 | ],
50 | 'to' => [
51 | [
52 | 'email' => 'fellipe.capelli@outlook.com',
53 | 'name' => 'Fellipe C. Fregoneze'
54 | ]
55 | ],
56 | 'subject' => 'Mailjet Transactor 3',
57 | 'markdownPart' => 'Hello, markdown part 3',
58 | ]
59 | ],
60 | ];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/tests/Unit/EmailDataCreator.php:
--------------------------------------------------------------------------------
1 | defineFrom($email[EmailEnum::FROM_KEY]);
18 | }
19 |
20 | if (array_key_exists(EmailEnum::TO_KEY, $email)) {
21 | $emailDTO->defineTo($email[EmailEnum::TO_KEY]);
22 | }
23 |
24 | if (array_key_exists(EmailEnum::SUBJECT_KEY, $email)) {
25 | $emailDTO->defineSubject($email[EmailEnum::SUBJECT_KEY]);
26 | }
27 |
28 | if (array_key_exists(EmailEnum::TEXT_PART_KEY, $email)) {
29 | $emailDTO->defineTextPart($email[EmailEnum::TEXT_PART_KEY]);
30 | }
31 |
32 | if (array_key_exists(EmailEnum::HTML_PART_KEY, $email)) {
33 | $emailDTO->defineHtmlPart($email[EmailEnum::HTML_PART_KEY]);
34 | }
35 |
36 | if (array_key_exists(EmailEnum::MARKDOWN_PART_KEY, $email)) {
37 | $emailDTO->defineMarkdownPart($email[EmailEnum::MARKDOWN_PART_KEY]);
38 | }
39 |
40 | return $emailDTO;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/Unit/Publishers/EmailPublisherTest.php:
--------------------------------------------------------------------------------
1 | setEmailData($email);
22 |
23 | $testName = 'test';
24 | $publisher = new EmailPublisher($testName, $testName, $testName);
25 | $publisher->handle($emailDTO);
26 |
27 | $this->assertInstanceOf(EmailPublisher::class, $publisher);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/tests/Unit/Transactors/MailjetTransactorTest.php:
--------------------------------------------------------------------------------
1 | transactor = new MailjetTransactor($connector);
23 | }
24 |
25 | /**
26 | * Instance Type Return test
27 | *
28 | * @return void
29 | */
30 | public function testReturnInstanceType(): void
31 | {
32 | $this->assertInstanceOf(MailjetTransactor::class, $this->transactor);
33 | }
34 |
35 | /**
36 | * Email Transactions test
37 | *
38 | * @dataProvider \Tests\Unit\DataProviders\ValidEmailsDataProvider::emails()
39 | * @param array $email
40 | * @return void
41 | */
42 | public function testEmailTransactions(array $email): void
43 | {
44 | $emailDTO = $this->setEmailData($email);
45 | $send = $this->transactor->send($emailDTO);
46 |
47 | $this->assertTrue($send);
48 | }
49 |
50 | /**
51 | * Email Invalid Transactions test
52 | *
53 | * @dataProvider \Tests\Unit\DataProviders\InvalidEmailsDataProvider::invalidEmails()
54 | * @param array $email
55 | * @return void
56 | */
57 | public function testInvalidEmailTransactions(array $email): void
58 | {
59 | $emailDTO = $this->setEmailData($email);
60 | $send = $this->transactor->send($emailDTO);
61 |
62 | $this->assertFalse($send);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/tests/Unit/Transactors/SendgridTransactorTest.php:
--------------------------------------------------------------------------------
1 | transactor = new SendgridTransactor($connector);
23 | }
24 |
25 | /**
26 | * Instance Type Return test
27 | *
28 | * @return void
29 | */
30 | public function testReturnInstanceType(): void
31 | {
32 | $this->assertInstanceOf(SendgridTransactor::class, $this->transactor);
33 | }
34 |
35 | /**
36 | * Email Transactions test
37 | *
38 | * @dataProvider \Tests\Unit\DataProviders\ValidEmailsDataProvider::emails()
39 | * @param array $email
40 | * @return void
41 | */
42 | public function testEmailTransactions(array $email): void
43 | {
44 | $emailDTO = $this->setEmailData($email);
45 | $send = $this->transactor->send($emailDTO);
46 |
47 | $this->assertTrue($send);
48 | }
49 |
50 | /**
51 | * Email Invalid Transactions test
52 | *
53 | * @dataProvider \Tests\Unit\DataProviders\InvalidEmailsDataProvider::invalidEmails()
54 | * @param array $email
55 | * @return void
56 | */
57 | public function testInvalidEmailTransactions(array $email): void
58 | {
59 | $emailDTO = $this->setEmailData($email);
60 | $send = $this->transactor->send($emailDTO);
61 |
62 | $this->assertFalse($send);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/tests/Unit/Workers/EmailWorkerTest.php:
--------------------------------------------------------------------------------
1 | worker = new EmailWorker([$mailjetTransactor, $sendgridTransactor]);
32 | }
33 |
34 | /**
35 | * Instance Type Return test
36 | *
37 | * @return void
38 | */
39 | public function testReturnInstanceType(): void
40 | {
41 | $this->assertInstanceOf(EmailWorker::class, $this->worker);
42 | }
43 |
44 | /**
45 | * Email Transactions test
46 | *
47 | * @dataProvider \Tests\Unit\DataProviders\ValidEmailsDataProvider::emails()
48 | * @param array $email
49 | * @return void
50 | */
51 | public function testEmailTransactions(array $email): void
52 | {
53 | $emailDTO = $this->setEmailData($email);
54 | $send = $this->worker->sendEmail($emailDTO);
55 |
56 | $this->assertTrue($send);
57 | }
58 |
59 | /**
60 | * Email Invalid Transactions test
61 | *
62 | * @dataProvider \Tests\Unit\DataProviders\InvalidEmailsDataProvider::invalidEmails()
63 | * @param array $email
64 | * @return void
65 | */
66 | public function testInvalidEmailTransactions(array $email): void
67 | {
68 | $emailDTO = $this->setEmailData($email);
69 | $send = $this->worker->sendEmail($emailDTO);
70 |
71 | $this->assertFalse($send);
72 | }
73 | }
74 |
--------------------------------------------------------------------------------