├── docs └── logo.png ├── resources └── views │ ├── mails │ ├── empty_layout.blade.php │ ├── welcome_mailator.blade.php │ ├── stub_invoice_reminder_view.blade.php │ └── template_layout.blade.php │ └── publish │ └── laravel.blade.php ├── src ├── MailatorManager.php ├── Contracts │ ├── Afterable.php │ └── Beforeable.php ├── Dto │ └── WormholeConfiguration.php ├── Constraints │ ├── Constraintable.php │ ├── Descriptionable.php │ ├── ConstraintsCollection.php │ ├── SendScheduleConstraint.php │ ├── ManyConstraint.php │ ├── NeverConstraint.php │ ├── ManualConstraint.php │ ├── OnceConstraint.php │ ├── HoursSchedulerCheckerConstraint.php │ ├── DailyConstraint.php │ ├── WeeklyConstraint.php │ ├── AfterConstraint.php │ └── BeforeConstraint.php ├── Actions │ ├── Action.php │ ├── RunSchedulersAction.php │ ├── PersonalizeMailAction.php │ ├── ResolveGarbageAction.php │ └── SendMailAction.php ├── Replacers │ ├── Replacer.php │ ├── SampleReplacer.php │ ├── ModelAttributesReplacer.php │ └── Concerns │ │ └── ReplaceModelAttributes.php ├── Support │ ├── ConverterEnum.php │ ├── ClassResolver.php │ └── WithMailTemplate.php ├── Events │ └── ScheduleMailSentEvent.php ├── Mailator.php ├── Models │ ├── Builders │ │ └── MailatorSchedulerBuilder.php │ ├── MailTemplateable.php │ ├── Concerns │ │ ├── HasMailatorSchedulers.php │ │ ├── WithPrune.php │ │ ├── WithUuid.php │ │ ├── HasTarget.php │ │ ├── HasFuture.php │ │ └── ConstraintsResolver.php │ ├── MailTemplatePlaceholder.php │ ├── PlainHtmlTemplate.php │ ├── MailatorLog.php │ ├── MailTemplate.php │ └── MailatorSchedule.php ├── Scheduler.php ├── Exceptions │ ├── InvalidTemplateException.php │ └── InstanceException.php ├── Console │ └── Commands │ │ ├── MailatorSchedulerCommand.php │ │ ├── PruneMailatorLogsCommand.php │ │ ├── PruneMailatorScheduleCommand.php │ │ └── GarbageCollectorCommand.php ├── SchedulerManager.php ├── Jobs │ └── SendMailJob.php └── LaravelMailatorServiceProvider.php ├── Upgrade.md ├── phpstan.neon.dist ├── .github ├── ISSUE_TEMPLATE │ └── config.yml └── workflows │ ├── release.yml │ ├── php-cs-fixer.yml │ ├── phpstan.yml │ ├── update-changelog.yml │ └── run-tests.yml ├── phpstan-baseline.neon ├── database └── migrations │ ├── alter_mail_logs_table_add_cascade_delete.php.stub │ └── create_mailator_tables.php.stub ├── CHANGELOG.md ├── LICENSE.md ├── .php_cs.dist.php ├── composer.json ├── config └── mailator.php ├── CONTRIBUTING.md └── README.md /docs/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BinarCode/laravel-mailator/HEAD/docs/logo.png -------------------------------------------------------------------------------- /resources/views/mails/empty_layout.blade.php: -------------------------------------------------------------------------------- 1 | {{ $template->getContent() ?? '' }} 2 | -------------------------------------------------------------------------------- /resources/views/publish/laravel.blade.php: -------------------------------------------------------------------------------- 1 | @component('mail::message') 2 | {!! $slot !!} 3 | @endcomponent 4 | -------------------------------------------------------------------------------- /src/MailatorManager.php: -------------------------------------------------------------------------------- 1 | schedule = $schedule; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Mailator.php: -------------------------------------------------------------------------------- 1 | whereNull('completed_at'); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Scheduler.php: -------------------------------------------------------------------------------- 1 | isMany() 13 | ? true 14 | : true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Constraints/NeverConstraint.php: -------------------------------------------------------------------------------- 1 | isNever() 13 | ? false 14 | : true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Constraints/ManualConstraint.php: -------------------------------------------------------------------------------- 1 | isManual() 13 | ? false 14 | : true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Constraints/OnceConstraint.php: -------------------------------------------------------------------------------- 1 | isOnce() 13 | ? is_null($schedule->last_sent_at) 14 | : true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Models/MailTemplateable.php: -------------------------------------------------------------------------------- 1 | morphMany(config('mailator.scheduler.model'), 'targetable'); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Ask a question 4 | url: https://github.com/BinarCode/laravel-mailator/discussions/new?category=q-a 5 | about: Ask the community for help 6 | - name: Request a feature 7 | url: https://github.com/BinarCode/laravel-mailator/discussions/new?category=ideas 8 | about: Share ideas for new features 9 | - name: Report a bug 10 | url: https://github.com/BinarCode/laravel-mailator/issues/new 11 | about: Report a reproducable bug 12 | -------------------------------------------------------------------------------- /src/Constraints/HoursSchedulerCheckerConstraint.php: -------------------------------------------------------------------------------- 1 | hasPrecision()) { 13 | return true; 14 | } 15 | 16 | return in_array(now()->hour, $schedule->schedule_at_hours); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Console/Commands/MailatorSchedulerCommand.php: -------------------------------------------------------------------------------- 1 | ready() 16 | ->with('logs') 17 | ->cursor() 18 | ->filter(fn (MailatorSchedule $schedule) => $schedule->shouldSend()) 19 | ->each(fn (MailatorSchedule $schedule) => $schedule->execute()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - closed 7 | branches: 8 | - "master" 9 | 10 | jobs: 11 | release: 12 | name: Create release 13 | if: github.event.pull_request.merged == true 14 | runs-on: "ubuntu-latest" 15 | steps: 16 | - uses: actions/checkout@v4 17 | 18 | - uses: ncipollo/release-action@v1 19 | with: 20 | name: ${{ github.event.pull_request.title }} 21 | tag: ${{ github.event.pull_request.title }} 22 | body: ${{ github.event.pull_request.body }} 23 | prerelease: false 24 | -------------------------------------------------------------------------------- /.github/workflows/php-cs-fixer.yml: -------------------------------------------------------------------------------- 1 | name: Check & fix styling 2 | 3 | on: [push] 4 | 5 | jobs: 6 | php-cs-fixer: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - name: Checkout code 11 | uses: actions/checkout@v4 12 | with: 13 | ref: ${{ github.head_ref }} 14 | 15 | - name: Run PHP CS Fixer 16 | uses: docker://oskarstark/php-cs-fixer-ga 17 | with: 18 | args: --config=.php_cs.dist.php --allow-risky=yes 19 | 20 | - name: Commit changes 21 | uses: stefanzweifel/git-auto-commit-action@v4 22 | with: 23 | commit_message: Fix styling 24 | -------------------------------------------------------------------------------- /phpstan-baseline.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | ignoreErrors: 3 | - 4 | message: "#^Unsafe usage of new static\\(\\)\\.$#" 5 | count: 1 6 | path: src/Models/MailatorSchedule.php 7 | - 8 | message: "#^Unsafe usage of new static\\(\\)\\.$#" 9 | count: 1 10 | path: src/Replacers/ModelAttributesReplacer.php 11 | - 12 | message: "#^Unsafe usage of new static\\(\\)\\.$#" 13 | count: 1 14 | path: src/Exceptions/InvalidTemplateException.php 15 | - 16 | message: "#^Unsafe usage of new static\\(\\)\\.$#" 17 | count: 1 18 | path: src/Exceptions/InstanceException.php 19 | -------------------------------------------------------------------------------- /src/Console/Commands/PruneMailatorLogsCommand.php: -------------------------------------------------------------------------------- 1 | info( 17 | MailatorLog::prune( 18 | now()->subDays((int)$this->option('days')) 19 | ) . ' entries pruned.' 20 | ); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /.github/workflows/phpstan.yml: -------------------------------------------------------------------------------- 1 | name: PHPStan 2 | 3 | on: 4 | push: 5 | paths: 6 | - '**.php' 7 | - 'phpstan.neon.dist' 8 | 9 | jobs: 10 | phpstan: 11 | name: phpstan 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Setup PHP 17 | uses: shivammathur/setup-php@v2 18 | with: 19 | php-version: '8.2' 20 | coverage: none 21 | 22 | - name: Install composer dependencies 23 | uses: ramsey/composer-install@v1 24 | 25 | - name: Run PHPStan 26 | run: ./vendor/bin/phpstan --error-format=github 27 | -------------------------------------------------------------------------------- /src/Console/Commands/PruneMailatorScheduleCommand.php: -------------------------------------------------------------------------------- 1 | info( 17 | MailatorSchedule::prune( 18 | now()->subDays((int)$this->option('days')), 19 | ['logs'] 20 | ) . ' entries pruned.' 21 | ); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Models/MailTemplatePlaceholder.php: -------------------------------------------------------------------------------- 1 | belongsTo( 28 | config('mailator.templates.template_model') ?? MailTemplate::class, 29 | 'mail_template_id' 30 | ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Models/Concerns/WithPrune.php: -------------------------------------------------------------------------------- 1 | when( 17 | $with !== [], 18 | fn ($query) => $query->with($with) 19 | ) 20 | ->where('created_at', '<', $before); 21 | 22 | $totalDeleted = 0; 23 | 24 | do { 25 | $deleted = $query->take(1000)->delete(); 26 | 27 | $totalDeleted += $deleted; 28 | } while ($deleted !== 0); 29 | 30 | return $totalDeleted; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Actions/PersonalizeMailAction.php: -------------------------------------------------------------------------------- 1 | filter(fn (object $class) => $class instanceof Replacer) 15 | ->reduce(fn (string $html, Replacer $replacer) => $replacer->replace($html, $template), $html); 16 | 17 | return collect($replacers) 18 | ->filter(fn (object $class) => $class instanceof Closure) 19 | ->reduce(fn (string $html, $replacer) => call_user_func($replacer, $html, $template), $html); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /database/migrations/alter_mail_logs_table_add_cascade_delete.php.stub: -------------------------------------------------------------------------------- 1 | dropForeign(['mailator_schedule_id']); 15 | 16 | $table->foreign('mailator_schedule_id') 17 | ->references('id') 18 | ->on(config('mailator.schedulers_table_name', 'mailator_schedulers')) 19 | ->cascadeOnDelete(); 20 | }); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Models/Concerns/WithUuid.php: -------------------------------------------------------------------------------- 1 | uuid) { 18 | $model->setAttribute('uuid', Str::uuid()); 19 | } 20 | }); 21 | } 22 | 23 | public static function whereUuid(string $uuid): Builder 24 | { 25 | return static::query()->where('uuid', $uuid); 26 | } 27 | 28 | public static function firstWhereUuid(string $uuid): Model 29 | { 30 | return static::where('uuid', $uuid)->firstOrFail(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/SchedulerManager.php: -------------------------------------------------------------------------------- 1 | instance = (static::scheduler())::init($name); 18 | } 19 | 20 | public function run(): void 21 | { 22 | app(RunSchedulersAction::class)(); 23 | } 24 | 25 | public function __destruct() 26 | { 27 | if (isset($this->instance) && $this->instance && ! $this->instance->wasRecentlyCreated) { 28 | $this->instance->save(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /.github/workflows/update-changelog.yml: -------------------------------------------------------------------------------- 1 | name: "Update Changelog" 2 | 3 | on: 4 | release: 5 | types: [released] 6 | 7 | jobs: 8 | update: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v4 14 | with: 15 | ref: main 16 | 17 | - name: Update Changelog 18 | uses: stefanzweifel/changelog-updater-action@v1 19 | with: 20 | latest-version: ${{ github.event.release.name }} 21 | release-notes: ${{ github.event.release.body }} 22 | 23 | - name: Commit updated CHANGELOG 24 | uses: stefanzweifel/git-auto-commit-action@v4 25 | with: 26 | branch: main 27 | commit_message: Update CHANGELOG 28 | file_pattern: CHANGELOG.md 29 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-mailator` will be documented in this file 4 | 5 | ## 3.0.0 - 2021-06-08 6 | 7 | - `actionClass` from MailatorScheduler now accept an instance of `Binarcode\LaravelMailator\Actions\Action` 8 | - `toDays()` helper added to MailatorScheduler 9 | - `tags()` added to MailatorScheduler 10 | 11 | ## 2.0.0 - 2021-08-03 12 | 13 | - The `before` and `after` methods now accept only an instance of Carbon 14 | - You can add custom contraints using `->contraint( Binarcode\LaravelMailator\Constraints\SendScheduleConstraint)` method. 15 | 16 | - The scheduler will now take care of your configurations, so if you don't specify any constraint, it will send the email based on the scheduler configurations. 17 | - Changed `events` column name to `constraints` 18 | - Added `timestamp_target` timestamp column 19 | 20 | 21 | 22 | ## 1.0.0 - 2020-02-07 23 | 24 | - initial release 25 | -------------------------------------------------------------------------------- /src/Constraints/DailyConstraint.php: -------------------------------------------------------------------------------- 1 | isDaily()) { 14 | return true; 15 | } 16 | 17 | if ($logs->count() === 0) { 18 | return true; 19 | } 20 | 21 | $lastLog = $logs 22 | ->filter(fn (MailatorLog $log) => $log->isSent()) 23 | ->last(); 24 | 25 | if ($lastLog instanceof MailatorLog) { 26 | return $lastLog->created_at->diffInDays(now()) >= 1; 27 | } else { 28 | return true; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Constraints/WeeklyConstraint.php: -------------------------------------------------------------------------------- 1 | isWeekly()) { 14 | return true; 15 | } 16 | 17 | if ($logs->count() === 0) { 18 | return true; 19 | } 20 | 21 | $lastLog = $logs 22 | ->filter(fn (MailatorLog $log) => $log->isSent()) 23 | ->last(); 24 | 25 | if ($lastLog instanceof MailatorLog) { 26 | return $lastLog->created_at->diffInDays(now()) >= 7; 27 | } else { 28 | return true; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Support/ClassResolver.php: -------------------------------------------------------------------------------- 1 | preparePlaceholders() 19 | ->flatten() 20 | ->reduce(function (string $html, $placeholder) { 21 | return $this->replaceModelAttributes($html, $placeholder, $this->model); 22 | }, $html); 23 | } 24 | 25 | public function usingModel(Model $model) 26 | { 27 | $this->model = $model; 28 | 29 | return $this; 30 | } 31 | 32 | public static function makeWithModel(Model $model) 33 | { 34 | return (new static)->usingModel($model); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Eduard Lupacescu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/Jobs/SendMailJob.php: -------------------------------------------------------------------------------- 1 | schedule = $schedule; 31 | 32 | $this->queue = config('mailator.scheduler.send_mail_job_queue', 'default'); 33 | } 34 | 35 | public function handle(): void 36 | { 37 | static::sendMailAction()->handle($this->schedule); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Models/PlainHtmlTemplate.php: -------------------------------------------------------------------------------- 1 | 'name', 18 | 'description' => 'Client name', 19 | ]; 20 | } 21 | 22 | public function preparePlaceholders(): Collection 23 | { 24 | return collect($this->placeholders()); 25 | } 26 | 27 | public function getContent(): string 28 | { 29 | return SendGrid::html(); 30 | } 31 | 32 | public function getSubject(): ?string 33 | { 34 | return null; 35 | } 36 | 37 | public function getFromEmail(): ?string 38 | { 39 | return null; 40 | } 41 | 42 | public function getFromName(): ?string 43 | { 44 | return null; 45 | } 46 | 47 | public function setHtml(string $html): self 48 | { 49 | $this->html = $html; 50 | 51 | return $this; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Actions/ResolveGarbageAction.php: -------------------------------------------------------------------------------- 1 | shouldMarkComplete($schedule)) { 12 | $schedule->markComplete(); 13 | } 14 | } 15 | 16 | public function shouldMarkComplete(MailatorSchedule $schedule): bool 17 | { 18 | $sentOnce = $schedule->fresh()->wasSentOnce(); 19 | 20 | if ($schedule->isOnce() && $sentOnce) { 21 | return true; 22 | } 23 | 24 | if ($schedule->isManual()) { 25 | return true; 26 | } 27 | 28 | if ($schedule->isNever()) { 29 | return true; 30 | } 31 | 32 | if ($schedule->isMany()) { 33 | return false; 34 | } 35 | 36 | if (! $schedule->nextTrigger()) { 37 | return true; 38 | } 39 | 40 | if ($schedule->failedLastTimes(config('mailator.scheduler.mark_complete_after_fails_count', 3))) { 41 | return true; 42 | } 43 | 44 | return false; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Replacers/Concerns/ReplaceModelAttributes.php: -------------------------------------------------------------------------------- 1 | "Welcome ::first_name::" 13 | * $replaceText => "first_name" 14 | * $model => {first_name: 'Eduard', ...} 15 | * 16 | * return => "Welcome Eduard" 17 | */ 18 | trait ReplaceModelAttributes 19 | { 20 | public function replaceModelAttributes(string $text, string $replaceText, Model $model) 21 | { 22 | return preg_replace_callback('/::'.$replaceText.'::/', function ($match) use ($model) { 23 | $parts = collect(explode('.', $match[0] ?? '')); 24 | 25 | $replace = $parts->reduce(function ($value, $part) { 26 | $part = Str::between($part, '::', '::'); 27 | 28 | return $value->$part ?? $value[$part] ?? ''; 29 | }, $model); 30 | 31 | if (is_array($replace)) { 32 | return implode(', ', $replace); 33 | } 34 | 35 | return $replace ?: $match[0]; 36 | }, $text); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Models/Concerns/HasTarget.php: -------------------------------------------------------------------------------- 1 | morphTo(); 23 | } 24 | 25 | public function target(Model $target): self 26 | { 27 | $this->targetable_type = $target->getMorphClass(); 28 | $this->targetable_id = $target->getKey(); 29 | 30 | return $this; 31 | } 32 | 33 | public function scopeTargetableType($query, $class) 34 | { 35 | $query->where('targetable_type', $class); 36 | } 37 | 38 | public function scopeMailableClass($query, $class) 39 | { 40 | $query->where('mailable_class', 'LIKE', "%{$class}%"); 41 | } 42 | 43 | public function scopeTargetableId($query, $id) 44 | { 45 | $query->where('targetable_id', $id); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.php_cs.dist.php: -------------------------------------------------------------------------------- 1 | in([ 5 | __DIR__ . '/src', 6 | __DIR__ . '/tests', 7 | ]) 8 | ->name('*.php') 9 | ->notName('*.blade.php') 10 | ->ignoreDotFiles(true) 11 | ->ignoreVCS(true); 12 | 13 | return (new PhpCsFixer\Config()) 14 | ->setRules([ 15 | '@PSR2' => true, 16 | 'array_syntax' => ['syntax' => 'short'], 17 | 'ordered_imports' => ['sort_algorithm' => 'alpha'], 18 | 'no_unused_imports' => true, 19 | 'not_operator_with_successor_space' => true, 20 | 'trailing_comma_in_multiline' => true, 21 | 'phpdoc_scalar' => true, 22 | 'unary_operator_spaces' => true, 23 | 'binary_operator_spaces' => true, 24 | 'blank_line_before_statement' => [ 25 | 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], 26 | ], 27 | 'phpdoc_single_line_var_spacing' => true, 28 | 'phpdoc_var_without_name' => true, 29 | 'class_attributes_separation' => [ 30 | 'elements' => [ 31 | 'method' => 'one', 32 | ], 33 | ], 34 | 'method_argument_space' => [ 35 | 'on_multiline' => 'ensure_fully_multiline', 36 | 'keep_multiple_spaces_after_comma' => true, 37 | ], 38 | 'single_trait_insert_per_statement' => true, 39 | ]) 40 | ->setFinder($finder); 41 | -------------------------------------------------------------------------------- /resources/views/mails/template_layout.blade.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 25 | 26 | 27 | 28 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/Console/Commands/GarbageCollectorCommand.php: -------------------------------------------------------------------------------- 1 | info('----- Starting garbage cleaning -----'); 22 | $ids = collect(); 23 | 24 | MailatorSchedule::query() 25 | ->ready() 26 | ->cursor() 27 | ->each(function (MailatorSchedule $mailatorSchedule) use ($ids) { 28 | if ($this->option('dry')) { 29 | static::garbageResolver()->handle($mailatorSchedule); 30 | } elseif (static::garbageResolver()->shouldMarkComplete($mailatorSchedule)) { 31 | $ids->push($mailatorSchedule->id); 32 | } 33 | }); 34 | 35 | if (! $this->option('dry')) { 36 | $ids->each(fn ($i) => $this->info('Scheduler id to complete: '.$i)); 37 | } 38 | 39 | $this->info("[".$ids->count()."] items matched."); 40 | $this->info('All done.'); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Models/MailatorLog.php: -------------------------------------------------------------------------------- 1 | 'datetime', 46 | 'created_at' => 'datetime', 47 | 'updated_at' => 'datetime', 48 | 'recipients' => 'array', 49 | ]; 50 | 51 | public function isSent(): bool 52 | { 53 | return $this->status === static::STATUS_SENT; 54 | } 55 | 56 | public function isFailed(): bool 57 | { 58 | return $this->status === static::STATUS_FAILED; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Actions/SendMailAction.php: -------------------------------------------------------------------------------- 1 | sendMail($schedule); 22 | 23 | static::garbageResolver()->handle($schedule); 24 | } catch (Exception $exception) { 25 | $schedule->markAsFailed($exception->getMessage()); 26 | 27 | report($exception); 28 | } 29 | } 30 | 31 | protected function sendMail(MailatorSchedule $schedule) 32 | { 33 | //todo - apply replacers for variables maybe 34 | $mailable = $schedule->getMailable(); 35 | 36 | if ($mailable instanceof Mailable) { 37 | if ($mailable instanceof Beforeable) { 38 | $mailable->before(); 39 | } 40 | 41 | Mail::to($schedule->getRecipients())->send($mailable); 42 | 43 | $schedule->markAsSent(); 44 | 45 | if ($mailable instanceof Afterable) { 46 | $mailable->after(); 47 | } 48 | 49 | event(new ScheduleMailSentEvent($schedule)); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | test: 9 | runs-on: ${{ matrix.os }} 10 | 11 | strategy: 12 | fail-fast: true 13 | matrix: 14 | os: [ubuntu-latest, windows-latest] 15 | php: [8.3, 8.2] 16 | laravel: ['10.*', '11.*', '12.*'] 17 | stability: [prefer-stable] 18 | include: 19 | - laravel: 10.* 20 | testbench: 8.* 21 | - laravel: 11.* 22 | testbench: 9.* 23 | - laravel: 12.* 24 | testbench: 10.* 25 | 26 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} 27 | 28 | steps: 29 | - name: Checkout code 30 | uses: actions/checkout@v4 31 | 32 | - name: Setup PHP 33 | uses: shivammathur/setup-php@v2 34 | with: 35 | php-version: ${{ matrix.php }} 36 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo 37 | coverage: none 38 | 39 | - name: Setup problem matchers 40 | run: | 41 | echo "::add-matcher::${{ runner.tool_cache }}/php.json" 42 | echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" 43 | 44 | - name: Install dependencies 45 | run: | 46 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 47 | composer update --${{ matrix.stability }} --prefer-dist --no-interaction 48 | 49 | - name: Clear Composer cache 50 | run: composer clear-cache 51 | 52 | - name: Wait for a few seconds 53 | run: sleep 5 54 | 55 | - name: Execute tests 56 | run: ./vendor/bin/testbench package:test --no-coverage 57 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "binarcode/laravel-mailator", 3 | "description": "Laravel email scheduler", 4 | "keywords": [ 5 | "binarcode", 6 | "laravel-mailator" 7 | ], 8 | "homepage": "https://github.com/binarcode/laravel-mailator", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "Eduard Lupacescu", 14 | "email": "eduard.lupacescu@binarcode.com", 15 | "homepage": "https://binarcode.com", 16 | "role": "Developer" 17 | } 18 | ], 19 | "require": { 20 | "php": "^8.2", 21 | "illuminate/support": "^10.0|^11.0|^12.0", 22 | "opis/closure": "^3.6|^4.3" 23 | }, 24 | "require-dev": { 25 | "brianium/paratest": "^7.0.6", 26 | "nunomaduro/collision": "^7.0|^8.0", 27 | "nunomaduro/larastan": "^2.0", 28 | "orchestra/testbench": "^8.0|^9.0|^10.0", 29 | "phpstan/extension-installer": "^1.1", 30 | "phpunit/phpunit": "^10.0|^11.0", 31 | "spatie/laravel-ray": "^1.9", 32 | "spatie/test-time": "^1.2" 33 | }, 34 | "autoload": { 35 | "psr-4": { 36 | "Binarcode\\LaravelMailator\\": "src" 37 | } 38 | }, 39 | "autoload-dev": { 40 | "psr-4": { 41 | "Binarcode\\LaravelMailator\\Tests\\": "tests" 42 | } 43 | }, 44 | "scripts": { 45 | "analyse": "vendor/bin/phpstan analyse", 46 | "test": "./vendor/bin/testbench package:test --parallel --no-coverage", 47 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 48 | }, 49 | "config": { 50 | "sort-packages": true, 51 | "allow-plugins": { 52 | "phpstan/extension-installer": true 53 | } 54 | }, 55 | "extra": { 56 | "laravel": { 57 | "providers": [ 58 | "Binarcode\\LaravelMailator\\LaravelMailatorServiceProvider" 59 | ], 60 | "aliases": { 61 | "LaravelMailator": "Mailator" 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Constraints/AfterConstraint.php: -------------------------------------------------------------------------------- 1 | isAfter()) { 13 | return true; 14 | } 15 | 16 | if (is_null($schedule->timestamp_target)) { 17 | return true; 18 | } 19 | 20 | if ($schedule->toDays() > 0) { 21 | if (now()->floorSeconds()->lt($schedule->timestampTarget()->addDays($schedule->toDays()))) { 22 | return false; 23 | } 24 | 25 | $diff = (int) $schedule->timestamp_target->diffInDays( 26 | now()->floorSeconds(), 27 | absolute: true 28 | ); 29 | 30 | return $schedule->isOnce() 31 | ? $diff === $schedule->toDays() 32 | : $diff > $schedule->toDays(); 33 | } 34 | 35 | if ($schedule->toHours() > 0) { 36 | if (now()->floorSeconds()->lt($schedule->timestampTarget()->addHours($schedule->toHours()))) { 37 | return false; 38 | } 39 | 40 | $diff = (int) $schedule->timestamp_target->diffInHours( 41 | now()->floorSeconds(), 42 | absolute: true 43 | ); 44 | 45 | //till ends we should have at least toDays days 46 | return $schedule->isOnce() 47 | ? $diff === $schedule->toHours() 48 | : $diff > $schedule->toHours(); 49 | } 50 | 51 | if (now()->floorSeconds()->lte($schedule->timestampTarget()->addMinutes($schedule->delay_minutes))) { 52 | return false; 53 | } 54 | 55 | $diff = (int) $schedule->timestamp_target->diffInHours( 56 | now()->floorSeconds(), 57 | absolute: true 58 | ); 59 | 60 | //till ends we should have at least toDays days 61 | return $schedule->isOnce() 62 | ? $diff === $schedule->delay_minutes 63 | : $diff > $schedule->delay_minutes; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Constraints/BeforeConstraint.php: -------------------------------------------------------------------------------- 1 | isBefore()) { 13 | return true; 14 | } 15 | 16 | if (is_null($schedule->timestampTarget())) { 17 | return true; 18 | } 19 | 20 | // if already expired 21 | if ($schedule->timestampTarget()->lte(now()->floorSeconds())) { 22 | return false; 23 | } 24 | 25 | if ($schedule->toDays() > 0) { 26 | if (now()->floorSeconds()->gt($schedule->timestampTarget()->addDays($schedule->toDays()))) { 27 | return false; 28 | } 29 | 30 | $diff = (int) $schedule->timestampTarget()->diffInDays( 31 | now()->floorSeconds(), 32 | absolute: true 33 | ); 34 | 35 | //till ends we should have at least toDays days 36 | return $schedule->isOnce() 37 | ? $diff === $schedule->toDays() 38 | : $diff < $schedule->toDays(); 39 | } 40 | 41 | if ($schedule->toHours() > 0) { 42 | if (now()->floorSeconds()->gt($schedule->timestampTarget()->addHours($schedule->toHours()))) { 43 | return false; 44 | } 45 | 46 | $diff = (int) $schedule->timestamp_target->diffInHours( 47 | now()->floorSeconds(), 48 | absolute: true 49 | ); 50 | 51 | //till ends we should have at least toHours days 52 | return $schedule->isOnce() 53 | ? $diff === $schedule->toHours() 54 | : $diff < $schedule->toHours(); 55 | } 56 | 57 | $diff = (int) $schedule->timestampTarget()->diffInDays( 58 | now()->floorSeconds(), 59 | absolute: true 60 | ); 61 | 62 | //till ends we should have at least toDays days 63 | return $schedule->isOnce() 64 | ? $diff === $schedule->toDays() 65 | : $diff < $schedule->toDays(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Support/WithMailTemplate.php: -------------------------------------------------------------------------------- 1 | ensureValidView(); 25 | 26 | $this->template = $template; 27 | 28 | /** @var PersonalizeMailAction $replacerAction */ 29 | $replacerAction = app(PersonalizeMailAction::class); 30 | 31 | // replace placehlders 32 | $this->slot = $replacerAction->execute( 33 | $template->getContent(), 34 | $this->getTemplate(), 35 | $this->getReplacers(), 36 | ); 37 | 38 | $this->subject($template->getSubject()); 39 | 40 | if ($from = $template->getFromEmail()) { 41 | $this->from( 42 | $from, 43 | $template->getFromName() 44 | ); 45 | } 46 | 47 | return $this; 48 | } 49 | 50 | /** 51 | * Set the mailator template layout. 52 | * 53 | * @param string $layout 54 | * @return $this 55 | */ 56 | public function useLayout(string $layout) 57 | { 58 | $this->layout = $layout; 59 | 60 | return $this; 61 | } 62 | 63 | public function getLayout() 64 | { 65 | return $this->layout ?? config('mailator.templates.template_layout', 'laravel-mailator::laravel'); 66 | } 67 | 68 | public function getTemplate(): ?MailTemplateable 69 | { 70 | return $this->template; 71 | } 72 | 73 | /** 74 | * Return an array of instances of Replacer interface. 75 | * @return array 76 | */ 77 | abstract public function getReplacers(): array; 78 | 79 | protected function ensureValidView() 80 | { 81 | if (! $this->markdown) { 82 | $this->markdown($this->getLayout()); 83 | } 84 | 85 | return $this; 86 | } 87 | 88 | protected function ensureValidSlot() 89 | { 90 | if (! $this->slot) { 91 | $this->slot = $this->template->getContent() ?? ''; 92 | } 93 | 94 | return $this; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/Models/MailTemplate.php: -------------------------------------------------------------------------------- 1 | hasMany( 46 | config('mailator.templates.placeholder_model') ?? MailTemplatePlaceholder::class, 47 | 'mail_template_id' 48 | ); 49 | } 50 | 51 | public function htmlWithInlinedCss(): string 52 | { 53 | return (new CssToInlineStyles())->convert($this->html ?? ''); 54 | } 55 | 56 | public function getMailable(): Mailable 57 | { 58 | $mailableClass = $this->mailable_class; 59 | 60 | return app($mailableClass); 61 | } 62 | 63 | public function scopeWithMailable($query, string $mailable) 64 | { 65 | $query->where('mailable_class', $mailable); 66 | } 67 | 68 | public function preparePlaceholders(): Collection 69 | { 70 | return $this->placeholders->map->only('name'); 71 | } 72 | 73 | public function getContent(): string 74 | { 75 | return $this->html; 76 | } 77 | 78 | public function getSubject(): ?string 79 | { 80 | return $this->subject; 81 | } 82 | 83 | public function getFromEmail(): ?string 84 | { 85 | return $this->from_email; 86 | } 87 | 88 | public function getFromName(): ?string 89 | { 90 | return $this->from_name; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /config/mailator.php: -------------------------------------------------------------------------------- 1 | The table name for the main schedulers. 6 | */ 7 | 'schedulers_table_name' => 'mailator_schedulers', 8 | 9 | /* 10 | > The table name for the logs of sends history. 11 | */ 12 | 'logs_table' => 'mailator_logs', 13 | 14 | 'scheduler' => [ 15 | /** 16 | * > The base model for the mail schedule. 17 | */ 18 | 'model' => Binarcode\LaravelMailator\Models\MailatorSchedule::class, 19 | 20 | /** 21 | * > The queue used for sending emails. 22 | */ 23 | 'send_mail_job_queue' => 'default', 24 | 25 | /** 26 | > The email sender class. It will be executed from the sender job. 27 | */ 28 | 'send_mail_action' => Binarcode\LaravelMailator\Actions\SendMailAction::class, 29 | 30 | /** 31 | * Class that will mark the scheduled action as being completed so the action will do not be counted into the next iteration. 32 | */ 33 | 'garbage_resolver' => Binarcode\LaravelMailator\Actions\ResolveGarbageAction::class, 34 | 35 | /** 36 | * Mark action completed after this count of fails. 37 | */ 38 | 'mark_complete_after_fails_count' => env('MAILATOR_FAILED_COUNTS', 3), 39 | ], 40 | 41 | 'log_model' => Binarcode\LaravelMailator\Models\MailatorLog::class, 42 | 43 | 'templates' => [ 44 | /** 45 | * > The base model for the mail templates. 46 | */ 47 | 'template_model' => Binarcode\LaravelMailator\Models\MailTemplate::class, 48 | 49 | /** 50 | * > The base model for the mail template placeholders. 51 | */ 52 | 'placeholder_model' => Binarcode\LaravelMailator\Models\MailTemplatePlaceholder::class, 53 | 54 | /** 55 | > The email layout, used to wrap the template. 56 | */ 57 | 'template_layout' => 'laravel-mailator::laravel', 58 | 59 | /** 60 | > The default list with replacers for the template. 61 | */ 62 | 'replacers' => [ 63 | Binarcode\LaravelMailator\Replacers\SampleReplacer::class, 64 | ], 65 | ], 66 | 67 | 'serialization' => [ 68 | /* 69 | > Controls constructor property accessibility in mailable objects for PostgreSQL compatibility. 70 | > When set to false, allows private/protected properties. When true, enforces 71 | > public properties only to prevent PostgreSQL serialization errors caused by 72 | > null bytes (\x00) in non-public properties. 73 | */ 74 | 'enforce_public_properties' => false, 75 | ] 76 | ]; 77 | -------------------------------------------------------------------------------- /src/Models/Concerns/HasFuture.php: -------------------------------------------------------------------------------- 1 | isFutureAction()) { 18 | return null; 19 | } 20 | 21 | if ($this->isOnce() && $this->last_sent_at) { 22 | return null; 23 | } 24 | 25 | return $this->triggerTarget(); 26 | } 27 | 28 | public function isFutureAction(): bool 29 | { 30 | if ($this->isManual()) { 31 | return false; 32 | } 33 | 34 | if (is_null($this->timestampTarget())) { 35 | return false; 36 | } 37 | 38 | if (is_null($this->time_frame_origin)) { 39 | return false; 40 | } 41 | 42 | if ($this->isAfter()) { 43 | return now()->lt($this->triggerTarget()); 44 | } 45 | 46 | if ($this->isBefore()) { 47 | if ($this->isRepetitive()) { 48 | return true; 49 | } 50 | 51 | return now()->lt($this->triggerTarget()); 52 | } 53 | 54 | return false; 55 | } 56 | 57 | public function triggerTarget(): ?CarbonInterface 58 | { 59 | if (is_null($this->timestampTarget())) { 60 | return null; 61 | } 62 | 63 | if ($this->isAfter()) { 64 | return $this->resolveAfterTriggerTime(); 65 | } 66 | 67 | if ($this->isBefore()) { 68 | return $this->resolveBeforeTriggerTime(); 69 | } 70 | 71 | return null; 72 | } 73 | 74 | private function resolveAfterTriggerTime(): CarbonInterface 75 | { 76 | if ($this->toDays() > 0) { 77 | return $this->timestampTarget()->addDays($this->toDays()); 78 | } 79 | 80 | if ($this->toHours() > 0) { 81 | return $this->timestampTarget()->addHours($this->toHours()); 82 | } 83 | 84 | return $this->timestampTarget()->addMinutes($this->delay_minutes); 85 | } 86 | 87 | private function resolveBeforeTriggerTime(): CarbonInterface 88 | { 89 | if ($this->toDays() > 0) { 90 | return $this->timestampTarget()->subDays($this->toDays()); 91 | } 92 | 93 | if ($this->toHours() > 0) { 94 | return $this->timestampTarget()->subHours($this->toHours()); 95 | } 96 | 97 | return $this->timestampTarget()->addMinutes($this->delay_minutes); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /src/Models/Concerns/ConstraintsResolver.php: -------------------------------------------------------------------------------- 1 | map(fn ($class) => app($class)) 41 | ->every(fn (SendScheduleConstraint $event) => $event->canSend($this, $this->logs)); 42 | } 43 | 44 | public function whenPasses(): bool 45 | { 46 | return true; 47 | } 48 | 49 | public function eventsPasses(): bool 50 | { 51 | return collect($this->constraints) 52 | ->map(fn (string $event) => unserialize($event)) 53 | ->filter(fn ($event) => is_subclass_of($event, SendScheduleConstraint::class)) 54 | ->filter(fn (SendScheduleConstraint $event) => $event->canSend( 55 | $this, 56 | $this->logs 57 | ))->count() === collect($this->constraints)->count(); 58 | } 59 | 60 | public function constraintsDescriptions(): array 61 | { 62 | try { 63 | return collect($this->constraints) 64 | ->map(fn (string $event) => unserialize($event)) 65 | ->filter(fn ($event) => is_subclass_of($event, Descriptionable::class)) 66 | ->reduce(function ($base, Descriptionable $descriable) { 67 | return array_merge($base, $descriable::conditions()); 68 | }, []); 69 | } catch (Throwable $e) { 70 | $this->markAsFailed($e->getMessage()); 71 | 72 | return []; 73 | } 74 | } 75 | 76 | public function constraintsNotSatisfiedDescriptions(): array 77 | { 78 | try { 79 | return collect($this->constraints) 80 | ->map(fn (string $event) => unserialize($event)) 81 | ->filter(fn ($event) => is_subclass_of($event, Descriptionable::class)) 82 | ->filter(fn ($event) => is_subclass_of($event, SendScheduleConstraint::class)) 83 | ->filter(fn ($event) => ! $event->canSend($this, $this->logs)) 84 | ->reduce(function ($base, Descriptionable $descriable) { 85 | return array_merge($base, $descriable::conditions()); 86 | }, []); 87 | } catch (Throwable $e) { 88 | $this->markAsFailed($e->getMessage()); 89 | 90 | return []; 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /database/migrations/create_mailator_tables.php.stub: -------------------------------------------------------------------------------- 1 | bigIncrements('id'); 15 | 16 | $table->string('name', 100)->nullable(); 17 | $table->boolean('stopable')->default(false); 18 | $table->boolean('unique')->default(false); 19 | $table->string('tags', 100)->nullable(); 20 | $table->text('mailable_class')->nullable(); 21 | $table->nullableMorphs('targetable'); 22 | $table->text('action')->nullable(); 23 | $table->unsignedInteger('delay_minutes')->nullable()->comment('Number of hours/days.'); 24 | $table->enum('time_frame_origin', [ 25 | MailatorSchedule::TIME_FRAME_ORIGIN_BEFORE, 26 | MailatorSchedule::TIME_FRAME_ORIGIN_AFTER, 27 | ])->nullable()->comment('Before or after event.'); 28 | $table->timestamp('timestamp_target')->nullable(); 29 | $table->json('constraints')->nullable()->comment('Offset target.'); 30 | $table->json('recipients')->nullable(); 31 | $table->text('when')->nullable(); 32 | $table->string('frequency_option')->default(MailatorSchedule::FREQUENCY_OPTIONS_ONCE)->comment('How often send email notification.'); 33 | $table->json('schedule_at_hours')->nullable(); 34 | $table->timestamp('last_sent_at')->nullable(); 35 | $table->timestamp('last_failed_at')->nullable(); 36 | $table->timestamp('completed_at')->nullable(); 37 | $table->text('failure_reason')->nullable(); 38 | $table->timestamps(); 39 | }); 40 | 41 | Schema::create(config('mailator.logs_table', 'mailator_logs'), function (Blueprint $table) { 42 | $table->bigIncrements('id'); 43 | $table->string('name')->nullable(); 44 | $table->json('recipients')->nullable(); 45 | $table->foreignId('mailator_schedule_id')->nullable(); 46 | $table->enum('status', [ 47 | MailatorLog::STATUS_FAILED, 48 | MailatorLog::STATUS_SENT, 49 | ]); 50 | $table->dateTime('action_at')->nullable(); 51 | $table->text('exception')->nullable(); 52 | $table->timestamps(); 53 | 54 | /** 55 | * Foreign keys 56 | */ 57 | $table->foreign('mailator_schedule_id') 58 | ->references('id') 59 | ->on(config('mailator.schedulers_table_name', 'mailator_schedulers')); 60 | }); 61 | 62 | Schema::create('mail_templates', function (Blueprint $table) { 63 | $table->id(); 64 | $table->uuid('uuid'); 65 | 66 | $table->string('name')->nullable(); 67 | $table->string('from_email')->nullable(); 68 | $table->string('from_name')->nullable(); 69 | $table->string('subject')->nullable(); 70 | 71 | $table->longText('html')->nullable(); 72 | $table->longText('email_html')->nullable(); 73 | $table->longText('webview_html')->nullable(); 74 | 75 | $table->string('mailable_class')->nullable(); 76 | $table->timestamps(); 77 | }); 78 | 79 | Schema::create('mail_template_placeholders', function (Blueprint $table) { 80 | $table->id(); 81 | $table->foreignId('mail_template_id')->constrained('mail_templates')->cascadeOnDelete(); 82 | $table->string('name'); 83 | $table->string('description'); 84 | $table->json('meta')->nullable(); 85 | $table->timestamps(); 86 | 87 | /** * Indexes */ 88 | $table->index('mail_template_id'); 89 | }); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/LaravelMailatorServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->bind(MailatorSchedule::class, config('mailator.model')); 24 | } 25 | 26 | if (config('mailator.log_model')) { 27 | $this->app->bind(MailatorLog::class, config('mailator.log_model')); 28 | } 29 | 30 | if (config('mailator.templates.template_model')) { 31 | $this->app->bind(MailTemplate::class, config('mailator.templates.template_model')); 32 | } 33 | 34 | if (config('mailator.templates.placeholder_model')) { 35 | $this->app->bind(MailTemplatePlaceholder::class, config('mailator.templates.placeholder_model')); 36 | } 37 | 38 | /* 39 | * Optional methods to load your package assets 40 | */ 41 | // $this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'laravel-mailator'); 42 | $this->loadViewsFrom(__DIR__.'/../resources/views/publish', 'laravel-mailator'); 43 | // $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); 44 | // $this->loadRoutesFrom(__DIR__.'/routes.php'); 45 | 46 | if ($this->app->runningInConsole()) { 47 | $this->publishes([ 48 | __DIR__.'/../config/mailator.php' => config_path('mailator.php'), 49 | ], 'mailator-config'); 50 | 51 | if (! class_exists('CreateMailatorTables')) { 52 | $this->publishes([ 53 | __DIR__ . '/../database/migrations/create_mailator_tables.php.stub' => database_path('migrations/' . date('Y_m_d_His', now()->subMinute()->timestamp) . '_create_mailator_tables.php'), 54 | ], 'mailator-migrations'); 55 | } 56 | 57 | if (! class_exists('AlterMailLogsTableAddCascadeDelete')) { 58 | $this->publishes([ 59 | __DIR__ . '/../database/migrations/alter_mail_logs_table_add_cascade_delete.php.stub' => database_path('migrations/' . date('Y_m_d_His', now()->timestamp) . '_alter_mail_logs_table_add_cascade_delete.php'), 60 | ], 'mailator-migrations'); 61 | } 62 | 63 | // Publishing the views. 64 | $this->publishes([ 65 | __DIR__.'/../resources/views/publish' => resource_path('views/vendor/laravel-mailator'), 66 | ], 'mailator-views'); 67 | 68 | // Publishing assets. 69 | /*$this->publishes([ 70 | __DIR__.'/../resources/assets' => public_path('vendor/laravel-mailator'), 71 | ], 'assets');*/ 72 | 73 | // Publishing the translation files. 74 | /*$this->publishes([ 75 | __DIR__.'/../resources/lang' => resource_path('lang/vendor/laravel-mailator'), 76 | ], 'lang');*/ 77 | 78 | // Registering package commands. 79 | $this->commands([ 80 | GarbageCollectorCommand::class, 81 | MailatorSchedulerCommand::class, 82 | PruneMailatorScheduleCommand::class, 83 | PruneMailatorLogsCommand::class, 84 | ]); 85 | } 86 | } 87 | 88 | /** 89 | * Register the application services. 90 | */ 91 | public function register() 92 | { 93 | // Automatically apply the package configuration 94 | $this->mergeConfigFrom(__DIR__.'/../config/mailator.php', 'mailator'); 95 | 96 | // Register the main class to use with the facade 97 | $this->app->singleton('mailator', function () { 98 | return new MailatorManager(); 99 | }); 100 | 101 | $this->app->singleton('mailator-scheduler', function () { 102 | return new SchedulerManager(); 103 | }); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Build Status 5 | Latest Stable Version. 6 | Total Downloads 7 | License 8 |

9 | 10 | Laravel Mailator provides a featherweight system for configure email scheduler and email templates based on application 11 | events. 12 | 13 | ## Installation 14 | 15 | You can install the package via composer: 16 | 17 | ```bash 18 | composer require binarcode/laravel-mailator 19 | ``` 20 | 21 | ## Publish 22 | 23 | Publish migrations: `php artisan vendor:publish --tag=mailator-migrations` 24 | 25 | Publish config: `php artisan vendor:publish --tag=mailator-config` 26 | 27 | ## Usage 28 | 29 | It has mainly 2 directions of usage: 30 | 31 | 1. Schedule emails sending (or actions triggering) 32 | 33 | 2. Email Templates & Placeholders 34 | 35 | ## Scheduler 36 | 37 | To set up a mail to be sent after or before an event, you can do this by using the `Scheduler` facade. 38 | 39 | Here is an example of how to send the `invoice reminder email` `3 days` before the `$invoice->due_date`: 40 | 41 | ```php 42 | use Binarcode\LaravelMailator\Tests\Fixtures\InvoiceReminderMailable; 43 | use Binarcode\LaravelMailator\Tests\Fixtures\SerializedConditionCondition; 44 | 45 | Binarcode\LaravelMailator\Scheduler::init('Invoice reminder.') 46 | ->mailable(new InvoiceReminderMailable($invoice)) 47 | ->recipients('foo@binarcode.com', 'baz@binarcode.com') 48 | ->constraint(new SerializedConditionCondition($invoice)) 49 | ->days(3) 50 | ->before($invoice->due_date) 51 | ->save(); 52 | ``` 53 | 54 | Let's explain what each line means. 55 | 56 | ### Mailable 57 | 58 | This should be an instance of laravel `Mailable`. 59 | 60 | ### Recipients 61 | 62 | This should be a list or valid emails where the email will be sent. 63 | 64 | It could be an array of emails as well. 65 | 66 | ### Weeks 67 | 68 | This should be a number of weeks the email should be delayed. 69 | 70 | ### Days 71 | 72 | This should be a number of days the email should be delayed. 73 | 74 | ### Hours 75 | 76 | Instead of `days()` you can use `hours()` as well. 77 | 78 | ### Minutes 79 | 80 | If your scheduler run by minute, you can also use `minutes()` to delay the email. 81 | 82 | ### Before 83 | 84 | The `before` constraint accept a `CarbonInterface` and indicates from when scheduler should start run the mail or action. For instance: 85 | 86 | ```php 87 | ->days(1) 88 | ->before(Carbon::make('2021-02-06')) 89 | ``` 90 | 91 | says, send this email `1 day before 02 June 2021`, so basically the email will be scheduled for `01 June 2021`. 92 | 93 | ### After 94 | 95 | The `after` constraint accept a `CarbonInterface` as well. The difference, is that it inform scheduler to send it `after` the specified timestamp. Say we want to send a survey email `1 week` after the order is placed: 96 | 97 | ```php 98 | ->weeks(1) 99 | ->after($order->created_at) 100 | ``` 101 | 102 | ### Precision 103 | Hour Precision 104 | 105 | The `precision` method provides fine-grained control over when emails are sent using MailatorSchedule. It allows you to specify specific hours or intervals within a 24-hour period. Here's an example of how to use the precision method: 106 | ```php 107 | ->many() 108 | ->precision([3-4]) 109 | ``` 110 | This will schedule the email dispatch between '03:00:00' AM and '04:59:59' AM. 111 | 112 | or 113 | ```php 114 | ->once() 115 | ->precision([1]) 116 | ``` 117 | This will schedule the email dispatch between '01:00:00' AM and '01:59:59'. 118 | 119 | You can continue this pattern to specify the desired hour(s) within the range of 1 to 24. 120 | 121 | **Important: When using the precision feature in the Mailator scheduler, it is recommended to set the scheduler to run at intervals that are less than an hour. You can choose intervals such as every 5 minutes, 10 minutes, 30 minutes, or any other desired duration.** 122 | ### Constraint 123 | 124 | The `constraint()` method accept an instance of `Binarcode\LaravelMailator\Constraints\SendScheduleConstraint`. Each constraint will be called when the scheduler will try to send the email. If all constraints return true, the email will be sent. 125 | 126 | The `constraint()` method could be called many times, and each constraint will be stored. 127 | 128 | Since each constraint will be serialized, it's very indicated to use `Illuminate\Queue\SerializesModels` trait, so the serialized models will be loaded properly, and the data stored in your storage system will be much less. 129 | 130 | Let's assume we have this `BeforeInvoiceExpiresConstraint` constraint: 131 | 132 | ```php 133 | class BeforeInvoiceExpiresConstraint implements SendScheduleConstraint 134 | { 135 | public function canSend(MailatorSchedule $mailatorSchedule, Collection $log): bool 136 | { 137 | // your conditions 138 | return true; 139 | } 140 | } 141 | ``` 142 | 143 | ### Constraintable 144 | 145 | Instead of defining the `constraint` from the mail definition, sometimes it could be more readable if you define it directly into the `mailable` class: 146 | 147 | ```php 148 | use Binarcode\LaravelMailator\Constraints\Constraintable; 149 | 150 | class InvoiceReminderMailable extends Mailable implements Constraintable 151 | { 152 | public function constraints(): array 153 | { 154 | return [ 155 | new DynamicContraint 156 | ]; 157 | } 158 | } 159 | 160 | ``` 161 | 162 | ### Action 163 | 164 | Using `Scheduler` you can even define your custom action: 165 | 166 | ```php 167 | $scheduler = Scheduler::init('Invoice reminder.') 168 | ->days(1) 169 | ->before(now()->addWeek()) 170 | ->actionClass(CustomAction::class) 171 | ->save(); 172 | ``` 173 | 174 | The `CustomAction` should implement the `Binarcode\LaravelMailator\Actions\Action` class. 175 | 176 | ### Target 177 | 178 | You can link the scheduler with any entity like this: 179 | 180 | ```php 181 | Scheduler::init('Invoice reminder.') 182 | ->mailable(new InvoiceReminderMailable()) 183 | ->days(1) 184 | ->target($invoice) 185 | ->save(); 186 | ``` 187 | 188 | and then in the `Invoice` model you can get all emails related to it: 189 | 190 | ```php 191 | // app/Models/Invoice.php 192 | public function schedulers() 193 | { 194 | return $this->morphMany(Binarcode\LaravelMailator\Models\MailatorSchedule::class, 'targetable'); 195 | } 196 | ... 197 | ``` 198 | 199 | Mailator provides the `Binarcode\LaravelMailator\Models\Concerns\HasMailatorSchedulers` trait you can put in your Invoice model, so the relations will be loaded. 200 | 201 | ### Daily 202 | 203 | By default, scheduler run the action, or send the email only once. You can change that, and use a daily reminder till the constraint returns a truth condition: 204 | 205 | ```php 206 | use Binarcode\LaravelMailator\Scheduler; 207 | 208 | // 2021-20-06 - 20 June 2021 209 | $expirationDate = $invoice->expire_at; 210 | 211 | Scheduler::init('Invoice reminder') 212 | ->mailable(new InvoiceReminderMailable()) 213 | ->daily() 214 | ->weeks(1) 215 | ->before($expirationDate) 216 | ``` 217 | 218 | This scheduler will send the `InvoiceReminderMailable` email daily starting with `13 June 2021` (one week before the expiration date). 219 | 220 | How to stop the email sending if the invoice was paid meanwhile? Simply adding a constraint that will do not send it: 221 | 222 | ```php 223 | ->constraint(new InvoicePaidConstraint($invoice)) 224 | ``` 225 | 226 | and the constraint handle method could be something like this: 227 | 228 | ```php 229 | class InvoicePaidConstraint implements SendScheduleConstraint 230 | { 231 | use SerializesModels; 232 | 233 | public function __construct( 234 | private Invoice $invoice 235 | ) { } 236 | 237 | public function canSend(MailatorSchedule $schedule, Collection $logs): bool 238 | { 239 | return is_null($this->invoice->paid_at); 240 | } 241 | } 242 | ``` 243 | 244 | ## Stop conditions 245 | 246 | There are few ways email stop to be sent. 247 | 248 | The first condition, is that if for some reason sending email fails 3 times, the `MailatorSchedule` will be marked as `completed_at`. Number of times could be configured in the config file `mailator.scheduler.mark_complete_after_fails_count`. 249 | 250 | Any successfully sent mail, that should be sent only once, will be marked as `completed_at`. 251 | 252 | 253 | ### Stopable 254 | 255 | You can configure your scheduler to be marked as `completed_at` if in the you custom constraint returns a falsy condition. Back to our `InvoiceReminderMailable`, say the invoice expires on `20 June`, we send the first reminder on `13 June`, then the second reminder on `14 June`, if the client pay the invoice on `14 June` the `InvoicePaidConstraint` will return a falsy value, so there is no reason to try to send the invoice reminder on `15 June` again. So the system could mark this scheduler as `completed_at`. 256 | 257 | 258 | To do so, you can use the `stopable()` method. 259 | 260 | ### Unique 261 | 262 | You can configure your scheduler to store a unique relationship with the target class for mailable by specifying: 263 | 264 | ```php 265 | ->unique() 266 | ``` 267 | 268 | ie: 269 | 270 | ```php 271 | Scheduler::init() 272 | ->mailable(new InvoiceReminderMailable()) 273 | ->target($user) 274 | ->unique() 275 | ->save(); 276 | 277 | Scheduler::init() 278 | ->mailable(new InvoiceReminderMailable()) 279 | ->target($user) 280 | ->unique() 281 | ->save(); 282 | ``` 283 | 284 | This will store a single scheduler for the `$user`. 285 | 286 | ## Events 287 | 288 | Mailator has few events you can use. 289 | 290 | If your mailable class extends the `Binarcode\LaravelMailator\Contracts\Beforable`, you will be able to inject the `before` method, that will be called right before the sending the email. 291 | 292 | If your mailable class extends the `Binarcode\LaravelMailator\Contracts\Afterable`, you will be able to inject the `after` method, that will be called right after the mail has being sent. 293 | 294 | 295 | And latest, after each mail has being sent, mailator will fire the `Binarcode\LaravelMailator\Events\ScheduleMailSentEvent` event, so you can listen for it. 296 | 297 | ## Run 298 | 299 | Now you have to run a scheduler command in your Kernel, and call: 300 | 301 | ```php 302 | Binarcode\LaravelMailator\Scheduler::run(); 303 | ``` 304 | 305 | Package provides the `Binarcode\LaravelMailator\Console\MailatorSchedulerCommand` command you can put in your Console Kernel: 306 | 307 | ```php 308 | $schedule->command(MailatorSchedulerCommand::class)->everyThirtyMinutes(); 309 | ``` 310 | 311 | 312 | ## Templating 313 | 314 | To create an email template: 315 | 316 | ``` php 317 | $template = Binarcode\LaravelMailator\Models\MailTemplate::create([ 318 | 'name' => 'Welcome Email.', 319 | 'from_email' => 'from@bar.com', 320 | 'from_name' => 'From Bar', 321 | 'subject' => 'Welcome to Mailator.', 322 | 'html' => '

Welcome to the party!

', 323 | ]); 324 | ``` 325 | 326 | Adding some placeholders with description to this template: 327 | 328 | ```php 329 | $template->placeholders()->create( 330 | [ 331 | 'name' => '::name::', 332 | 'description' => 'Name', 333 | ], 334 | ); 335 | ``` 336 | 337 | To use the template, you simply have to add the `WithMailTemplate` trait to your mailable. 338 | 339 | This will enforce you to implement the `getReplacers` method, this should return an array of replacers to your template. 340 | The array may contain instances of `Binarcode\LaravelMailator\Replacers\Replacer` or even `Closure` instances. 341 | 342 | Mailator shipes with a builtin replacer `ModelAttributesReplacer`, it will automaticaly replace attributes from the 343 | model you provide to placeholders. 344 | 345 | The last step is how to say to your mailable what template to use. This could be done into the build method as shown 346 | bellow: 347 | 348 | ```php 349 | class WelcomeMailatorMailable extends Mailable 350 | { 351 | use Binarcode\LaravelMailator\Support\WithMailTemplate; 352 | 353 | private Model $user; 354 | 355 | public function __construct(Model $user) 356 | { 357 | $this->user = $user; 358 | } 359 | 360 | public function build() 361 | { 362 | return $this->template(MailTemplate::firstWhere('name', 'Welcome Email.')); 363 | } 364 | 365 | public function getReplacers(): array 366 | { 367 | return [ 368 | Binarcode\LaravelMailator\Replacers\ModelAttributesReplacer::makeWithModel($this->user), 369 | 370 | function($html) { 371 | // 372 | } 373 | ]; 374 | } 375 | } 376 | ``` 377 | 378 | ### Testing 379 | 380 | ``` bash 381 | composer test 382 | ``` 383 | 384 | ### Changelog 385 | 386 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 387 | 388 | ## Contributing 389 | 390 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 391 | 392 | ### Security 393 | 394 | If you discover any security related issues, please email eduard.lupacescu@binarcode.com or [message me on twitter](https://twitter.com/LupacescuEuard) instead of using the issue tracker. 395 | 396 | ## Credits 397 | 398 | - [Eduard Lupacescu](https://github.com/binaryk) 399 | - [All Contributors](../../contributors) 400 | 401 | ## License 402 | 403 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 404 | -------------------------------------------------------------------------------- /src/Models/MailatorSchedule.php: -------------------------------------------------------------------------------- 1 | $constraints 51 | * @property Carbon $timestamp_target 52 | * @property array $recipients 53 | * @property string $action 54 | * @property Closure|string $when 55 | * @property Carbon $last_failed_at 56 | * @property string $failure_reason 57 | * @property Carbon $last_sent_at 58 | * @property array|null $schedule_at_hours 59 | * @property Carbon $completed_at 60 | * @property string $frequency_option 61 | * @property-read Collection $logs 62 | * 63 | * @method static MailatorSchedulerBuilder query() 64 | */ 65 | class MailatorSchedule extends Model 66 | { 67 | use ConstraintsResolver; 68 | use HasTarget; 69 | use HasFuture; 70 | use ClassResolver; 71 | use WithPrune; 72 | 73 | public function getTable() 74 | { 75 | return config('mailator.schedulers_table_name', 'mailator_schedulers'); 76 | } 77 | 78 | public const TIME_FRAME_ORIGIN_BEFORE = 'before'; 79 | public const TIME_FRAME_ORIGIN_AFTER = 'after'; 80 | 81 | public const FREQUENCY_OPTIONS_MANY = 'many'; 82 | public const FREQUENCY_OPTIONS_ONCE = 'once'; 83 | public const FREQUENCY_OPTIONS_HOURLY = 'hourly'; 84 | public const FREQUENCY_OPTIONS_DAILY = 'daily'; 85 | public const FREQUENCY_OPTIONS_WEEKLY = 'weekly'; 86 | public const FREQUENCY_OPTIONS_NEVER = 'never'; 87 | public const FREQUENCY_OPTIONS_MANUAL = 'manual'; 88 | 89 | protected $guarded = []; 90 | 91 | protected $casts = [ 92 | 'constraints' => 'array', 93 | 'recipients' => 'array', 94 | 'schedule_at_hours' => 'array', 95 | 'timestamp_target' => 'datetime', 96 | 'last_failed_at' => 'datetime', 97 | 'last_sent_at' => 'datetime', 98 | 'created_at' => 'datetime', 99 | 'updated_at' => 'datetime', 100 | 'start_at' => 'datetime', 101 | 'end_at' => 'datetime', 102 | 'completed_at' => 'datetime', 103 | 'stopable' => 'boolean', 104 | 'unique' => 'boolean', 105 | ]; 106 | 107 | protected $attributes = [ 108 | 'frequency_option' => self::FREQUENCY_OPTIONS_ONCE, 109 | ]; 110 | 111 | public static function init(string $name): self 112 | { 113 | return new static(['name' => $name]); 114 | } 115 | 116 | public function mailable(Mailable $mailable): self 117 | { 118 | if (config('mailator.serialization.enforce_public_properties') && $this->hasNonPublicConstructorProps($mailable)) { 119 | throw new RuntimeException('Mailable contains non-public constructor properties which cannot be safely serialized'); 120 | } 121 | 122 | if ($mailable instanceof Constraintable) { 123 | collect($mailable->constraints()) 124 | ->filter(fn ($constraint) => $constraint instanceof SendScheduleConstraint) 125 | ->each(fn (SendScheduleConstraint $constraint) => $this->constraint($constraint)); 126 | } 127 | 128 | $this->mailable_class = serialize($mailable); 129 | 130 | return $this; 131 | } 132 | 133 | public function times(int $count): self 134 | { 135 | // todo 136 | return $this; 137 | } 138 | 139 | public function once(): self 140 | { 141 | $this->frequency_option = static::FREQUENCY_OPTIONS_ONCE; 142 | 143 | return $this; 144 | } 145 | 146 | public function manual(): self 147 | { 148 | $this->frequency_option = static::FREQUENCY_OPTIONS_MANUAL; 149 | 150 | $this->markComplete(); 151 | 152 | return $this; 153 | } 154 | 155 | public function never(): self 156 | { 157 | $this->frequency_option = static::FREQUENCY_OPTIONS_NEVER; 158 | 159 | $this->markComplete(); 160 | 161 | return $this; 162 | } 163 | 164 | public function many(): self 165 | { 166 | $this->frequency_option = static::FREQUENCY_OPTIONS_MANY; 167 | 168 | return $this; 169 | } 170 | 171 | public function hourly(): self 172 | { 173 | $this->frequency_option = static::FREQUENCY_OPTIONS_HOURLY; 174 | 175 | return $this; 176 | } 177 | 178 | public function daily(): static 179 | { 180 | $this->frequency_option = static::FREQUENCY_OPTIONS_DAILY; 181 | 182 | return $this; 183 | } 184 | 185 | public function weekly(): static 186 | { 187 | $this->frequency_option = static::FREQUENCY_OPTIONS_WEEKLY; 188 | 189 | return $this; 190 | } 191 | 192 | public function stopable(bool $stopable = true): self 193 | { 194 | $this->stopable = $stopable; 195 | 196 | return $this; 197 | } 198 | 199 | public function isStopable(): bool 200 | { 201 | return (bool) $this->stopable; 202 | } 203 | 204 | public function unique(): self 205 | { 206 | $this->unique = true; 207 | 208 | return $this; 209 | } 210 | 211 | public function isUnique(): bool 212 | { 213 | return (bool) $this->unique; 214 | } 215 | 216 | public function after(CarbonInterface $date = null): self 217 | { 218 | $this->time_frame_origin = static::TIME_FRAME_ORIGIN_AFTER; 219 | 220 | if ($date) { 221 | $this->timestamp_target = $date; 222 | } 223 | 224 | return $this; 225 | } 226 | 227 | public function contrained(SendScheduleConstraint $constraint): self 228 | { 229 | $this->constraint($constraint); 230 | 231 | return $this; 232 | } 233 | 234 | public function before(CarbonInterface $date = null): self 235 | { 236 | $this->time_frame_origin = static::TIME_FRAME_ORIGIN_BEFORE; 237 | 238 | if ($date) { 239 | $this->timestamp_target = $date; 240 | } 241 | 242 | return $this; 243 | } 244 | 245 | public function isDaily(): bool 246 | { 247 | return $this->frequency_option === static::FREQUENCY_OPTIONS_DAILY; 248 | } 249 | 250 | public function isWeekly(): bool 251 | { 252 | return $this->frequency_option === static::FREQUENCY_OPTIONS_WEEKLY; 253 | } 254 | 255 | public function hasPrecision(): bool 256 | { 257 | return (bool) $this->schedule_at_hours; 258 | } 259 | 260 | public function isAfter(): bool 261 | { 262 | return $this->time_frame_origin === static::TIME_FRAME_ORIGIN_AFTER; 263 | } 264 | 265 | public function isBefore(): bool 266 | { 267 | return $this->time_frame_origin === static::TIME_FRAME_ORIGIN_BEFORE; 268 | } 269 | 270 | public function isOnce(): bool 271 | { 272 | return $this->frequency_option === static::FREQUENCY_OPTIONS_ONCE; 273 | } 274 | 275 | public function isNever(): bool 276 | { 277 | return $this->frequency_option === static::FREQUENCY_OPTIONS_NEVER; 278 | } 279 | 280 | public function isManual(): bool 281 | { 282 | return $this->frequency_option === static::FREQUENCY_OPTIONS_MANUAL; 283 | } 284 | 285 | public function isMany(): bool 286 | { 287 | return $this->frequency_option === static::FREQUENCY_OPTIONS_MANY; 288 | } 289 | 290 | public function toDays(): int 291 | { 292 | //let's say we have 1 day and 2 hours till day job ends 293 | //so we will floor it to 1, and will send the reminder in time 294 | return (int) floor($this->delay_minutes / ConverterEnum::MINUTES_IN_DAY); 295 | } 296 | 297 | public function toHours(): int 298 | { 299 | return (int) floor($this->delay_minutes / ConverterEnum::MINUTES_IN_HOUR); 300 | } 301 | 302 | public function minutes(int $number): self 303 | { 304 | $this->delay_minutes = $number; 305 | 306 | return $this; 307 | } 308 | 309 | public function hours(int $number): self 310 | { 311 | $this->delay_minutes = $number * ConverterEnum::MINUTES_IN_HOUR; 312 | 313 | return $this; 314 | } 315 | 316 | public function days(int $number): self 317 | { 318 | $this->delay_minutes = $number * ConverterEnum::MINUTES_IN_DAY; 319 | 320 | return $this; 321 | } 322 | 323 | public function precision(array $scheduleAtHours): self 324 | { 325 | $this->schedule_at_hours = $scheduleAtHours; 326 | 327 | return $this; 328 | } 329 | 330 | public function weeks(int $number): static 331 | { 332 | $this->delay_minutes = $number * ConverterEnum::MINUTES_IN_WEEK; 333 | 334 | return $this; 335 | } 336 | 337 | public function constraint(SendScheduleConstraint $constraint): self 338 | { 339 | $this->constraints = array_merge(Arr::wrap($this->constraints), [serialize($constraint)]); 340 | 341 | return $this; 342 | } 343 | 344 | public function recipients(...$recipients): self 345 | { 346 | $this->recipients = array_merge(collect($recipients) 347 | ->flatten() 348 | ->filter(fn ($email) => $this->ensureValidEmail($email)) 349 | ->unique() 350 | ->toArray(), $this->recipients ?? []); 351 | 352 | return $this; 353 | } 354 | 355 | public function when(Closure $closure): self 356 | { 357 | $this->when = serialize( 358 | new SerializableClosure($closure) 359 | ); 360 | 361 | return $this; 362 | } 363 | 364 | public function logs(): HasMany 365 | { 366 | return $this->hasMany(MailatorLog::class, 'mailator_schedule_id'); 367 | } 368 | 369 | public function shouldSend(): bool 370 | { 371 | try { 372 | $this->loadMissing('logs'); 373 | 374 | if (! $this->configurationsPasses()) { 375 | return false; 376 | } 377 | 378 | if (! $this->whenPasses()) { 379 | return false; 380 | } 381 | 382 | if (! $this->eventsPasses()) { 383 | if ($this->isStopable()) { 384 | $this->markComplete(); 385 | } 386 | 387 | return false; 388 | } 389 | 390 | return true; 391 | } catch (Exception|Throwable $e) { 392 | $this->markAsFailed($e->getMessage()); 393 | 394 | app(ResolveGarbageAction::class)->handle($this); 395 | 396 | return false; 397 | } 398 | } 399 | 400 | public function executeWhenPasses(bool $now = false): void 401 | { 402 | if (! $this->save()) { 403 | return; 404 | } 405 | 406 | if ($this->shouldSend()) { 407 | $this->execute($now); 408 | } 409 | } 410 | 411 | public function execute(bool $now = false): void 412 | { 413 | if (! $this->save()) { 414 | return; 415 | } 416 | 417 | try { 418 | if ($this->hasCustomAction()) { 419 | unserialize($this->action)->handle($this); 420 | 421 | $this->markAsSent(); 422 | 423 | static::garbageResolver()->handle($this); 424 | } else { 425 | if ($now) { 426 | dispatch_sync(new SendMailJob($this)); 427 | } else { 428 | dispatch(new SendMailJob($this)); 429 | } 430 | } 431 | } catch (Exception|Throwable $e) { 432 | $this->markAsFailed($e->getMessage()); 433 | } 434 | } 435 | 436 | public static function run(): void 437 | { 438 | app(RunSchedulersAction::class)(); 439 | } 440 | 441 | public function hasCustomAction(): bool 442 | { 443 | return ! is_null($this->action); 444 | } 445 | 446 | public function getMailable(): ?Mailable 447 | { 448 | try { 449 | return unserialize($this->mailable_class); 450 | } catch (Throwable|TypeError $e) { 451 | $this->markAsFailed($e->getMessage()); 452 | } 453 | 454 | return null; 455 | } 456 | 457 | public function markAsSent(): self 458 | { 459 | $this->logs() 460 | ->create([ 461 | 'recipients' => $this->getRecipients(), 462 | 'name' => $this->name, 463 | 'status' => MailatorLog::STATUS_SENT, 464 | 'action_at' => now(), 465 | 'created_at' => now(), 466 | 'updated_at' => now(), 467 | ]); 468 | 469 | $this->last_sent_at = now(); 470 | $this->save(); 471 | 472 | return $this; 473 | } 474 | 475 | public function markAsFailed(string $failureReason): self 476 | { 477 | $this->logs()->create([ 478 | 'recipients' => $this->getRecipients(), 479 | 'name' => $this->name, 480 | 'status' => MailatorLog::STATUS_FAILED, 481 | 'action_at' => now(), 482 | 'created_at' => now(), 483 | 'updated_at' => now(), 484 | 'exception' => $failureReason, 485 | ]); 486 | 487 | $this->update([ 488 | 'last_failed_at' => now(), 489 | 'failure_reason' => Str::limit($failureReason, 250), 490 | ]); 491 | 492 | return $this; 493 | } 494 | 495 | public function getRecipients(): array 496 | { 497 | return collect($this->recipients) 498 | ->filter(fn ($email) => $this->ensureValidEmail($email)) 499 | ->toArray(); 500 | } 501 | 502 | protected function ensureValidEmail(string $email): bool 503 | { 504 | return ! Validator::make( 505 | compact('email'), 506 | ['email' => 'required|email'] 507 | )->fails(); 508 | } 509 | 510 | public function actionClass(Action $action): self 511 | { 512 | $this->action = serialize($action); 513 | 514 | return $this; 515 | } 516 | 517 | public function tag(string|array $tag): self 518 | { 519 | if (is_array($tag)) { 520 | $tag = implode(',', $tag); 521 | } 522 | 523 | $this->tags = $tag; 524 | 525 | return $this; 526 | } 527 | 528 | public function getReadableConditionAttribute(): string 529 | { 530 | if ($this->isManual()) { 531 | return (string) __('manual'); 532 | } 533 | 534 | $condition = $this->toDays().' day(s)'; 535 | 536 | if ($this->toDays() < 1) { 537 | $condition = $this->toHours().' hour(s) '; 538 | } 539 | 540 | if ($this->toHours() < 1) { 541 | $condition = $this->delay_minutes.' minute(s) '; 542 | } 543 | 544 | if ($this->delay_minutes < 1) { 545 | return (string) __('immediate'); 546 | } 547 | 548 | $condition .= $this->time_frame_origin." ".$this->timestamp_target?->copy()->format('m/d/Y h:i A'); 549 | 550 | return $condition; 551 | } 552 | 553 | public function newEloquentBuilder($query): MailatorSchedulerBuilder 554 | { 555 | return new MailatorSchedulerBuilder($query); 556 | } 557 | 558 | public function markComplete(): self 559 | { 560 | $this->completed_at = now(); 561 | $this->save(); 562 | 563 | return $this; 564 | } 565 | 566 | public function isCompleted(): bool 567 | { 568 | return ! is_null($this->completed_at); 569 | } 570 | 571 | public function failedLastTimes(int $times): bool 572 | { 573 | return $this 574 | ->logs() 575 | ->latest() 576 | ->take($times) 577 | ->get() 578 | ->filter 579 | ->isFailed() 580 | ->count() === $times; 581 | } 582 | 583 | public function timestampTarget(): ?CarbonInterface 584 | { 585 | return $this->timestamp_target?->clone(); 586 | } 587 | 588 | public function isRepetitive(): bool 589 | { 590 | return ! $this->isOnce(); 591 | } 592 | 593 | public function wasSentOnce(): bool 594 | { 595 | return ! is_null($this->last_sent_at); 596 | } 597 | 598 | public function getConstraints(): ConstraintsCollection 599 | { 600 | return ConstraintsCollection::make($this->constraints); 601 | } 602 | 603 | public function save(array $options = []) 604 | { 605 | if (! $this->isUnique()) { 606 | return parent::save($options); 607 | } 608 | 609 | $mailable = get_class(unserialize($this->mailable_class)); 610 | 611 | $exists = static::targetableType($this->targetable_type) 612 | ->targetableId($this->targetable_id) 613 | ->mailableClass($mailable) 614 | ->where('name', $this->name) 615 | ->when($this->getKey(), function (Builder $q) { 616 | $q->where($this->getKeyName(), '!=', $this->getKey()); 617 | }) 618 | ->exists(); 619 | 620 | if ($exists) { 621 | return false; 622 | } 623 | 624 | return parent::save($options); 625 | } 626 | 627 | private function hasNonPublicConstructorProps(Mailable $mailable): bool 628 | { 629 | $reflection = new ReflectionClass($mailable); 630 | $constructor = $reflection->getConstructor(); 631 | 632 | if (! $constructor) { 633 | return false; 634 | } 635 | 636 | return collect($constructor->getParameters()) 637 | ->filter(fn ($param) => $reflection->getProperty($param->getName())->isPrivate() 638 | || $reflection->getProperty($param->getName())->isProtected()) 639 | ->isNotEmpty(); 640 | } 641 | } 642 | --------------------------------------------------------------------------------