├── .github
├── CONTRIBUTING.md
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ └── config.yml
├── SECURITY.md
├── dependabot.yml
└── workflows
│ ├── dependabot-auto-merge.yml
│ ├── php-cs-fixer.yml
│ ├── phpstan.yml
│ ├── run-tests.yml
│ └── update-changelog.yml
├── .php_cs.dist.php
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── phpstan-baseline.neon
├── phpstan.neon.dist
├── resources
└── views
│ ├── html.blade.php
│ ├── mail
│ ├── html
│ │ └── message.blade.php
│ └── text
│ │ └── message.blade.php
│ └── text.blade.php
├── src
├── Channels
│ └── SubscriberMailChannel.php
├── Contracts
│ ├── AppliesToMailingList.php
│ ├── CanUnsubscribe.php
│ ├── CheckNotifiableSubscriptionStatus.php
│ └── CheckSubscriptionStatusBeforeSendingNotifications.php
├── Controllers
│ └── UnsubscribeController.php
├── Events
│ ├── UserUnsubscribed.php
│ └── UserUnsubscribing.php
├── Facades
│ └── Subscriber.php
├── MailSubscriber.php
├── SubscribableApplicationServiceProvider.php
├── SubscribableServiceProvider.php
└── Subscriber.php
└── stubs
└── SubscribableServiceProvider.stub
/.github/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 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: peterfox
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: Ask a question
4 | url: https://github.com/ylsideas/subscribable-notifications/discussions/new?category=q-a
5 | about: Ask the community for help
6 | - name: Request a feature
7 | url: https://github.com/ylsideas/subscribable-notifications/discussions/new?category=ideas
8 | about: Share ideas for new features
9 | - name: Report a security issue
10 | url: https://github.com/ylsideas/subscribable-notifications/security/policy
11 | about: Learn how to notify us for sensitive bugs
12 | - name: Report a bug
13 | url: https://github.com/ylsideas/subscribable-notifications/issues/new
14 | about: Report a reproducable bug
15 |
--------------------------------------------------------------------------------
/.github/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | If you discover any security related issues, please email peter.fox@ylsideas.co instead of using the issue tracker.
4 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # Please see the documentation for all configuration options:
2 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
3 |
4 | version: 2
5 | updates:
6 |
7 | - package-ecosystem: "github-actions"
8 | directory: "/"
9 | schedule:
10 | interval: "weekly"
11 | labels:
12 | - "dependencies"
--------------------------------------------------------------------------------
/.github/workflows/dependabot-auto-merge.yml:
--------------------------------------------------------------------------------
1 | name: dependabot-auto-merge
2 | on: pull_request_target
3 |
4 | permissions:
5 | pull-requests: write
6 | contents: write
7 |
8 | jobs:
9 | dependabot:
10 | runs-on: ubuntu-latest
11 | if: ${{ github.actor == 'dependabot[bot]' }}
12 | steps:
13 |
14 | - name: Dependabot metadata
15 | id: metadata
16 | uses: dependabot/fetch-metadata@v2.4.0
17 | with:
18 | github-token: "${{ secrets.GITHUB_TOKEN }}"
19 |
20 | - name: Auto-merge Dependabot PRs for semver-minor updates
21 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}}
22 | run: gh pr merge --auto --merge "$PR_URL"
23 | env:
24 | PR_URL: ${{github.event.pull_request.html_url}}
25 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
26 |
27 | - name: Auto-merge Dependabot PRs for semver-patch updates
28 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}}
29 | run: gh pr merge --auto --merge "$PR_URL"
30 | env:
31 | PR_URL: ${{github.event.pull_request.html_url}}
32 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
33 |
--------------------------------------------------------------------------------
/.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@v5
22 | with:
23 | commit_message: Fix styling
24 |
--------------------------------------------------------------------------------
/.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.3'
20 | coverage: none
21 |
22 | - name: Install composer dependencies
23 | uses: ramsey/composer-install@v3
24 |
25 | - name: Run PHPStan
26 | run: ./vendor/bin/phpstan --error-format=github
27 |
--------------------------------------------------------------------------------
/.github/workflows/run-tests.yml:
--------------------------------------------------------------------------------
1 | name: run-tests
2 |
3 | on:
4 | push:
5 | pull_request:
6 | branches:
7 | - main
8 |
9 | jobs:
10 | test:
11 | runs-on: ${{ matrix.os }}
12 |
13 | strategy:
14 | fail-fast: false
15 | matrix:
16 | os: [ubuntu-latest]
17 | php: [8.4, 8.3, 8.2]
18 | laravel: ['12.*', '11.*', '10.*']
19 | stability: [prefer-lowest, prefer-stable]
20 | include:
21 | - laravel: 10.*
22 | testbench: 8.*
23 | - laravel: 11.*
24 | testbench: 9.*
25 | - laravel: 12.*
26 | testbench: 10.*
27 |
28 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }}
29 |
30 | steps:
31 | - name: Checkout code
32 | uses: actions/checkout@v4
33 |
34 | - name: Setup PHP
35 | uses: shivammathur/setup-php@v2
36 | with:
37 | php-version: ${{ matrix.php }}
38 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo
39 | coverage: none
40 |
41 | - name: Setup problem matchers
42 | run: |
43 | echo "::add-matcher::${{ runner.tool_cache }}/php.json"
44 | echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
45 |
46 | - name: Install dependencies
47 | run: |
48 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
49 | composer update --${{ matrix.stability }} --prefer-dist --no-interaction
50 |
51 | - name: Execute tests
52 | run: vendor/bin/phpunit
53 |
--------------------------------------------------------------------------------
/.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@v5
25 | with:
26 | branch: main
27 | commit_message: Update CHANGELOG
28 | file_pattern: CHANGELOG.md
29 |
--------------------------------------------------------------------------------
/.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 | '@PSR12' => 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 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to `unsubscribable-notification` will be documented in this file
4 |
5 | ## 1.1.0 - 2019-11-03
6 |
7 | ### Altered
8 |
9 | - Changes the view namespace to `subscriber` from `unsubscribe`. This was done to avoid confusion. This
10 | would have potentially caused problems if you wanted to customise how the unsubscribe links worked visually.
11 | If you update to this version and have previously published the vendor folder and then renamed the folder to
12 | `unsubscribe` you will need to rename it to `subscriber`.
13 |
14 | ## 1.0.2 - 2019-09-05
15 |
16 | ### Added
17 |
18 | - Updated for Laravel 6
19 | - Updated TestBench to work with Laravel 6
20 | - Updated PHPUnit to version 8 to work with TestBench
21 |
22 | ## 1.0.0 - 2019-06-27
23 |
24 | ### Added
25 |
26 | - MailChannel to block notifications for emails if the user has unsubscribed.
27 | - Can generate signed URLs for a user unsubscribing from a mailing list or all mail notifications.
28 | - Handles the unsubscribing process.
29 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Peter Fox
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.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Subscribable Notifications for Laravel
2 |
3 | [](https://packagist.org/packages/ylsideas/subscribable-notifications)
4 | [](https://github.com/ylsideas/subscribable-notifications/actions?query=workflow%3Arun-tests+branch%3Amain)
5 | [](https://github.com/ylsideas/subscribable-notifications/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amain)
6 | [](https://packagist.org/packages/ylsideas/subscribable-notifications)
7 |
8 | This package has been designed to help you handle email unsubscribes with as little as 5 minutes setup. After installing
9 | your notifications sent over email should now be delivered with unsubscribe links in the footer and as a mail header
10 | which email clients can present to the user for quicker unsubscribing. It can also handle resolving the unsubscribing
11 | of the user through a signed route/controller.
12 |
13 | ## Installation
14 |
15 | You can install the package via composer:
16 |
17 | ```bash
18 | composer require ylsideas/subscribable-notifications
19 | ```
20 |
21 | Optionally to make use of the built in unsubscribing handler you can publish the application service
22 | provider. If you wish to implement your own unsubscribing process and only insert unsubscribe links into
23 | your notifications, you can forgo doing this.
24 |
25 | ```bash
26 | php artisan vendor:publish --tag=subscriber-provider
27 | ```
28 |
29 | This will create a `\App\Providers\SubscriberServiceProvider` class which you will need to register
30 | in `config/app.php`.
31 |
32 | ```php
33 | 'providers' => [
34 | ...
35 |
36 | /*
37 | * Package Service Providers...
38 | */
39 | \App\Providers\SubscribableServiceProvider::class,
40 |
41 | ...
42 | ]
43 | ```
44 |
45 | After this you can configure your unsubscribe handlers quickly as methods within the service provider that return the closures.
46 |
47 | The package itself does not determine how you store or evaluate your users' subscribed state. Instead
48 | it provides hooks in which to handle that.
49 |
50 | ## Usage
51 |
52 | First off you must implement the `YlsIdeas\SubscribableNotifications\Contracts\CanUnsubscribe` interface
53 | on your notifiable User model. You can also apply the `YlsIdeas\SubscribableNotifications\MailSubscriber` trait
54 | which will implement this for you to automatically provide signed urls for the unsubscribe controller provided
55 | by this library.
56 |
57 | ``` php
58 | use YlsIdeas\SubscribableNotifications\MailSubscriber;
59 | use YlsIdeas\SubscribableNotifications\Contracts\CanUnsubscribe;
60 |
61 | class User implements CanUnsubscribe
62 | {
63 | use Notifiable, MailSubscriber;
64 | }
65 | ```
66 |
67 | ### Implementing your own unsubscribe links
68 |
69 | If you wish to implement your own completely different `unsubscribeLink()` method you can.
70 |
71 | ``` php
72 | use YlsIdeas\SubscribableNotifications\Contracts\CanUnsubscribe;
73 |
74 | class User implements CanUnsubscribe
75 | {
76 | use Notifiable;
77 |
78 | public function unsubscribeLink(?string $mailingList = ''): string
79 | {
80 | return URL::signedRoute(
81 | 'sorry-to-see-you-go',
82 | ['subscriber' => $this, 'mailingList' => $mailingList],
83 | now()->addDays(1)
84 | );
85 | }
86 | }
87 | ```
88 |
89 | ### Implementing notifications as part of a mailing list
90 |
91 | If you wish to apply specific mailing lists to notifications you need to implement the
92 | `YlsIdeas\SubscribableNotifications\Contracts\AppliesToMailingList` on those notifications.
93 | This will put two unsubscribe links into your emails generated from those notifications.
94 | One for all emails and one for only that type of email.
95 |
96 | ``` php
97 | use YlsIdeas\SubscribableNotifications\Contracts\AppliesToMailingList;
98 |
99 | class Welcome extends Notification implements AppliesToMailingList
100 | {
101 | ...
102 |
103 | public function usesMailingList(): string
104 | {
105 | return 'weekly-updates';
106 | }
107 |
108 | ...
109 | }
110 | ```
111 |
112 | ### Using the full unsubscribing workflow
113 |
114 | Using the `App\Providers\SubscriberServiceProvider` you can set up simple hooks to handle
115 | unsubscribing the user from all future emails. This package doesn't determine how you should
116 | store that record of opting out of future emails. Instead you provide functions in the provider
117 | which will be called. The following are just examples of what you can do.
118 |
119 | #### Implementing an unsubscribe hook for a specific mailing list
120 |
121 | This handler will be called if a user links a link through to unsubscribe for a specific mailing list.
122 |
123 | ``` php
124 | public class SubscriberServiceProvider
125 | {
126 | ...
127 |
128 | public function onUnsubscribeFromMailingList()
129 | {
130 | return function ($user, $mailingList) {
131 | $user->mailing_lists = $user->mailing_lists->put($mailingList, false);
132 | $user->save();
133 | };
134 | }
135 |
136 | ...
137 | }
138 | ```
139 |
140 | #### Implementing an unsubscribe hook for all emails
141 |
142 | This handler will be called if the user has clicked through to the link to unsubscribe from all future emails.
143 |
144 | ``` php
145 | public class SubscriberServiceProvider
146 | {
147 | ...
148 |
149 | public function onUnsubscribeFromAllMailingLists()
150 | {
151 | return function ($user) {
152 | $user->unsubscribed_at = now();
153 | $user->save();
154 | };
155 | }
156 |
157 | ...
158 | }
159 | ```
160 |
161 | #### Implementing an unsubscribe response
162 |
163 | The completion handler will be called after a user is unsubscribed, allowing you to customise where the user is
164 | redirected to or if you want to maybe show a further form even.
165 |
166 | ``` php
167 | public class SubscriberServiceProvider
168 | {
169 | ...
170 |
171 | public function onCompletion()
172 | {
173 | return function ($user, $mailingList) {
174 | return view('confirmation')
175 | ->with('alert', 'You\'re not unsubscribed');
176 | };
177 | }
178 |
179 | ...
180 | }
181 | ```
182 |
183 | ### Dedicated handler
184 |
185 | You may also provide a string in the format of `class@method` that the subscriber class will use to grab the class
186 | from the service container and then call the specified method on if you want to do something more custom.
187 |
188 | ```php
189 | public class SubscriberServiceProvider
190 | {
191 | ...
192 |
193 | public function onUnsubscribeFromAllMailingLists()
194 | {
195 | return '\App\UnsubscribeHandler@handleUnsubscribing';
196 | }
197 |
198 | ...
199 | }
200 | ```
201 |
202 | ### Checking if a notification should be sent per the subscription
203 |
204 | You can also add hooks to check if a user should receive notifications for a mailing
205 | list or for all mail notifications.
206 |
207 | To do this you need to make sure your user has the
208 | `YlsIdeas\SubscribableNotifications\Contracts\CheckSubscriptionStatusBeforeSendingNotifications` interface
209 | implemented. The `YlsIdeas\SubscribableNotifications\MailSubscriber` trait will implement this for you to use the
210 | built in Subscriber handlers.
211 |
212 | If you want to implement a method yourself to check the subscription you could also just implement the method yourself
213 | like in the example below.
214 |
215 | ``` php
216 | use YlsIdeas\SubscribableNotifications\Contracts\CanUnsubscribe;
217 | use YlsIdeas\SubscribableNotifications\Contracts\CheckSubscriptionStatusBeforeSendingNotifications;
218 | use YlsIdeas\SubscribableNotifications\Facades\Subscriber;
219 |
220 | class User implements CanUnsubscribe, CheckSubscriptionStatusBeforeSendingNotifications
221 | {
222 | use Notifiable;
223 |
224 |
225 | public function mailSubscriptionStatus(Notification $notification) : bool
226 | {
227 | return Subscriber::checkSubscriptionStatus(
228 | $this,
229 | $notification instanceof AppliesToMailingList
230 | ? $notification->usesMailingList()
231 | : null
232 | );
233 | }
234 | }
235 | ```
236 |
237 | Then you need to implement the
238 | `YlsIdeas\SubscribableNotifications\Contracts\CheckNotifiableSubscriptionStatus` interface on the notifications
239 | that should trigger a check of the subscription status of the user it's being sent to. Then you just need to return
240 | `true` if the subscription status should be checked.
241 |
242 | ``` php
243 | use YlsIdeas\SubscribableNotifications\Contracts\CheckNotifiableSubscriptionStatus;
244 |
245 | class Welcome extends Notification implements CheckNotifiableSubscriptionStatus
246 | {
247 | ...
248 |
249 | public function checkMailSubscriptionStatus() : bool
250 | {
251 | return true;
252 | }
253 |
254 | ...
255 | }
256 | ```
257 |
258 | To use the functionality you then need to add your own Subscription check hooks. These hooks can be implemented
259 | as you see fit.
260 |
261 | ``` php
262 | public class SubscriberServiceProvider
263 | {
264 | ...
265 |
266 | public function onCheckSubscriptionStatusOfMailingList()
267 | {
268 | return function ($user, $mailingList) {
269 | return $user->mailing_lists->get($mailingList, false);
270 | };
271 | }
272 |
273 | public function onCheckSubscriptionStatusOfAllMailingLists()
274 | {
275 | return function ($user) {
276 | return $user->unsubscribed_at === null;
277 | };
278 | }
279 |
280 | ...
281 | }
282 | ```
283 |
284 | ### Customising the email templates
285 |
286 | Out of the box the emails generated use the same templates except that they
287 | inject a small bit of text into the footer of the emails. If you wish you customise
288 | the templates further you may publish the views.
289 |
290 | ```bash
291 | php artisan vendor:publish --tag=subscriber-views
292 | ```
293 |
294 | This will create a `resources/views/vendor/subscriber` folder containing both `html.blade.php`
295 | and `text.blade.php` which can be customised. These will then be the defaults used by the
296 | notification mail channel.
297 |
298 | ### Customising the User Model
299 |
300 | If you are using a different User model than the one found in `app/Models/User.php` or
301 | `app/Users.php` for Laravel 7 and earlier you can change this by calling. It's suggested you
302 | do this in the boot method of the `SubscriberServiceProvider`.
303 |
304 | ```php
305 | Subscriber::userModel('App\Models\User');
306 | ```
307 |
308 | ### Testing
309 |
310 | ``` bash
311 | composer test
312 | ```
313 |
314 | ### Changelog
315 |
316 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.
317 |
318 | ## Contributing
319 |
320 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
321 |
322 | ### Security
323 |
324 | If you discover any security related issues, please email peter.fox@ylsideas.co instead of using the issue tracker.
325 |
326 | ## Credits
327 |
328 | - [Peter Fox](https://github.com/peterfox)
329 | - [All Contributors](../../contributors)
330 |
331 | ## License
332 |
333 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
334 |
335 | ## Laravel Package Boilerplate
336 |
337 | This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).
338 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ylsideas/subscribable-notifications",
3 | "description": "A Laravel package for adding unsubscribe links to notifications",
4 | "keywords": [
5 | "ylsideas",
6 | "unsubscribable-notification",
7 | "laravel"
8 | ],
9 | "homepage": "https://github.com/ylsideas/subscribable-notifications",
10 | "license": "MIT",
11 | "type": "library",
12 | "authors": [
13 | {
14 | "name": "Peter Fox",
15 | "email": "peter.fox@ylsideas.co",
16 | "role": "Developer"
17 | }
18 | ],
19 | "require": {
20 | "php": "^8.2",
21 | "illuminate/contracts": "12.*|11.*|10.*"
22 | },
23 | "require-dev": {
24 | "orchestra/testbench": "^8.0|^9.0|^10.0",
25 | "nunomaduro/collision": "^8.0|^7.8|^6.0",
26 | "larastan/larastan": "^2.0|^3.0",
27 | "pestphp/pest": "^2.34|^3.0",
28 | "pestphp/pest-plugin-laravel": "^2.3|^3.0",
29 | "phpstan/extension-installer": "^1.1",
30 | "phpstan/phpstan-deprecation-rules": "^1.0|^2.0",
31 | "phpstan/phpstan-phpunit": "^1.0|^2.0",
32 | "spatie/laravel-ray": "^1.26"
33 | },
34 | "autoload": {
35 | "psr-4": {
36 | "YlsIdeas\\SubscribableNotifications\\": "src"
37 | }
38 | },
39 | "autoload-dev": {
40 | "psr-4": {
41 | "YlsIdeas\\SubscribableNotifications\\Tests\\": "tests"
42 | }
43 | },
44 | "scripts": {
45 | "analyse": "vendor/bin/phpstan analyse",
46 | "test": "vendor/bin/pest",
47 | "test-coverage": "vendor/bin/pest coverage"
48 | },
49 | "config": {
50 | "sort-packages": true,
51 | "allow-plugins": {
52 | "phpstan/extension-installer": true,
53 | "pestphp/pest-plugin": true
54 | }
55 | },
56 | "extra": {
57 | "laravel": {
58 | "providers": [
59 | "YlsIdeas\\SubscribableNotifications\\SubscribableServiceProvider"
60 | ],
61 | "aliases": {
62 | "Subscriber": "YlsIdeas\\Facades\\Subscriber"
63 | }
64 | }
65 | },
66 | "minimum-stability": "dev",
67 | "prefer-stable": true
68 | }
69 |
--------------------------------------------------------------------------------
/phpstan-baseline.neon:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ylsideas/subscribable-notifications/bd8ed7ad0074bfa4411fc988420437c9cf3b75a4/phpstan-baseline.neon
--------------------------------------------------------------------------------
/phpstan.neon.dist:
--------------------------------------------------------------------------------
1 | includes:
2 | - phpstan-baseline.neon
3 |
4 | parameters:
5 | level: 4
6 | paths:
7 | - src
8 | tmpDir: build/phpstan
9 | checkOctaneCompatibility: true
10 | checkModelProperties: true
11 | checkMissingIterableValueType: false
12 |
13 |
--------------------------------------------------------------------------------
/resources/views/html.blade.php:
--------------------------------------------------------------------------------
1 | @component('subscriber::mail.html.message')
2 | {{-- Greeting --}}
3 | @if (! empty($greeting))
4 | # {{ $greeting }}
5 | @else
6 | @if ($level === 'error')
7 | # @lang('Whoops!')
8 | @else
9 | # @lang('Hello!')
10 | @endif
11 | @endif
12 |
13 | {{-- Intro Lines --}}
14 | @foreach ($introLines as $line)
15 | {{ $line }}
16 |
17 | @endforeach
18 |
19 | {{-- Action Button --}}
20 | @isset($actionText)
21 |
31 | @component('mail::button', ['url' => $actionUrl, 'color' => $color])
32 | {{ $actionText }}
33 | @endcomponent
34 | @endisset
35 |
36 | {{-- Outro Lines --}}
37 | @foreach ($outroLines as $line)
38 | {{ $line }}
39 |
40 | @endforeach
41 |
42 | {{-- Salutation --}}
43 | @if (! empty($salutation))
44 | {{ $salutation }}
45 | @else
46 | @lang('Regards'),
{{ config('app.name') }}
47 | @endif
48 |
49 | {{-- Subcopy --}}
50 | @isset($actionText)
51 | @slot('subcopy')
52 | @lang(
53 | "If you’re having trouble clicking the \":actionText\" button, copy and paste the URL below\n".
54 | 'into your web browser: [:actionURL](:actionURL).',
55 | [
56 | 'actionText' => $actionText,
57 | 'actionURL' => $actionUrl,
58 | ]
59 | )
60 | @endslot
61 | @endisset
62 |
63 | @slot('unsubscribe')
64 | @if($unsubscribeLink ?? false)
65 | @lang(
66 | 'If you no longer want to receive this type of email in the future use this [link](:link).',
67 | ['link' => $unsubscribeLink]
68 | )
69 | @endif
70 | @if($unsubscribeLinkForAll ?? false)
71 | @lang(
72 | 'To no longer receive any future emails use this [link](:link).',
73 | ['link' => $unsubscribeLinkForAll]
74 | )
75 | @endif
76 | @endslot
77 |
78 | @endcomponent
79 |
--------------------------------------------------------------------------------
/resources/views/mail/html/message.blade.php:
--------------------------------------------------------------------------------
1 | @component('mail::layout')
2 | {{-- Header --}}
3 | @slot('header')
4 | @component('mail::header', ['url' => config('app.url')])
5 | {{ config('app.name') }}
6 | @endcomponent
7 | @endslot
8 |
9 | {{-- Body --}}
10 | {{ $slot }}
11 |
12 | {{-- Subcopy --}}
13 | @isset($subcopy)
14 | @slot('subcopy')
15 | @component('mail::subcopy')
16 | {{ $subcopy }}
17 | @endcomponent
18 | @endslot
19 | @endisset
20 |
21 | {{-- Footer --}}
22 | @slot('footer')
23 | @component('mail::footer')
24 | © {{ date('Y') }} {{ config('app.name') }}. @lang('All rights reserved.')
25 | @isset($unsubscribe)
26 |
27 | {{ $unsubscribe }}
28 | @endisset
29 | @endcomponent
30 | @endslot
31 | @endcomponent
32 |
--------------------------------------------------------------------------------
/resources/views/mail/text/message.blade.php:
--------------------------------------------------------------------------------
1 | @component('mail::layout')
2 | {{-- Header --}}
3 | @slot('header')
4 | @component('mail::header', ['url' => config('app.url')])
5 | {{ config('app.name') }}
6 | @endcomponent
7 | @endslot
8 |
9 | {{-- Body --}}
10 | {{ $slot }}
11 |
12 | {{-- Subcopy --}}
13 | @isset($subcopy)
14 | @slot('subcopy')
15 | @component('mail::subcopy')
16 | {{ $subcopy }}
17 | @endcomponent
18 | @endslot
19 | @endisset
20 |
21 | {{-- Footer --}}
22 | @slot('footer')
23 | @component('mail::footer')
24 | © {{ date('Y') }} {{ config('app.name') }}. @lang("All rights reserved.\n")
25 | @isset($unsubscribe)
26 | {{ $unsubscribe }}
27 | @endisset
28 | @endcomponent
29 | @endslot
30 | @endcomponent
31 |
--------------------------------------------------------------------------------
/resources/views/text.blade.php:
--------------------------------------------------------------------------------
1 | @component('subscriber::mail.text.message')
2 | {{-- Greeting --}}
3 | @if (! empty($greeting))
4 | # {{ $greeting }}
5 | @else
6 | @if ($level === 'error')
7 | # @lang('Whoops!')
8 | @else
9 | # @lang('Hello!')
10 | @endif
11 | @endif
12 |
13 | {{-- Intro Lines --}}
14 | @foreach ($introLines as $line)
15 | {{ $line }}
16 |
17 | @endforeach
18 |
19 | {{-- Action Button --}}
20 | @isset($actionText)
21 |
31 | @component('mail::button', ['url' => $actionUrl, 'color' => $color])
32 | {{ $actionText }}
33 | @endcomponent
34 | @endisset
35 |
36 | {{-- Outro Lines --}}
37 | @foreach ($outroLines as $line)
38 | {{ $line }}
39 |
40 | @endforeach
41 |
42 | {{-- Salutation --}}
43 | @if (! empty($salutation))
44 | {{ $salutation }}
45 | @else
46 | @lang('Regards'),
{{ config('app.name') }}
47 | @endif
48 |
49 | {{-- Subcopy --}}
50 | @isset($actionText)
51 | @slot('subcopy')
52 | @lang(
53 | "If you’re having trouble clicking the \":actionText\" button, copy and paste the URL below\n".
54 | 'into your web browser: [:actionURL](:actionURL).',
55 | [
56 | 'actionText' => $actionText,
57 | 'actionURL' => $actionUrl,
58 | ]
59 | )
60 | @endslot
61 | @endisset
62 |
63 | @slot('unsubscribe')
64 | @if($unsubscribeLink ?? false)
65 | @lang(
66 | "If you no longer want to receive this type of email in the future go to :link.\n",
67 | ['link' => $unsubscribeLink]
68 | )
69 | @endif
70 | @if($unsubscribeLinkForAll ?? false)
71 | @lang(
72 | "To no longer receive any future emails go to :link.\n",
73 | ['link' => $unsubscribeLinkForAll]
74 | )
75 | @endif
76 | @endslot
77 |
78 | @endcomponent
79 |
--------------------------------------------------------------------------------
/src/Channels/SubscriberMailChannel.php:
--------------------------------------------------------------------------------
1 | checkMailSubscriptionStatus() &&
36 | ! $notifiable->mailSubscriptionStatus($notification)) {
37 | return null;
38 | }
39 |
40 | if (method_exists($notification, 'toMail')) {
41 | $message = $notification->toMail($notifiable);
42 | } else {
43 | throw new \RuntimeException('Notification does not support sending mail');
44 | }
45 |
46 | // Inject unsubscribe links for rendering in the view
47 | if ($notifiable instanceof CanUnsubscribe && $message instanceof MailMessage) {
48 | if ($notification instanceof AppliesToMailingList) {
49 | $message->viewData['unsubscribeLink'] = $notifiable->unsubscribeLink(
50 | $notification->usesMailingList()
51 | );
52 | }
53 | $message->viewData['unsubscribeLinkForAll'] = $notifiable->unsubscribeLink();
54 | }
55 |
56 | if (! $notifiable->routeNotificationFor('mail', $notification) &&
57 | ! $message instanceof Mailable) {
58 | return null;
59 | }
60 |
61 | if ($message instanceof Mailable) {
62 | $message->send($this->mailer);
63 |
64 | return null;
65 | }
66 |
67 | return $this->mailer->mailer($message->mailer ?? null)->send(
68 | $this->buildView($message),
69 | array_merge($message->data(), $this->additionalMessageData($notification)),
70 | $this->messageBuilder($notifiable, $notification, $message)
71 | );
72 | }
73 |
74 | /**
75 | * Build the mail message.
76 | *
77 | * @param \Illuminate\Mail\Message $mailMessage
78 | * @param mixed $notifiable
79 | * @param \Illuminate\Notifications\Notification $notification
80 | * @param \Illuminate\Notifications\Messages\MailMessage $message
81 | *
82 | * @return void
83 | */
84 | protected function buildMessage($mailMessage, $notifiable, $notification, $message)
85 | {
86 | parent::buildMessage($mailMessage, $notifiable, $notification, $message);
87 |
88 | if ($notifiable instanceof CanUnsubscribe) {
89 | $mailMessage->getHeaders()->addTextHeader(
90 | 'List-Unsubscribe',
91 | sprintf('<%s>', $notifiable->unsubscribeLink(
92 | $notification instanceof AppliesToMailingList
93 | ? $notification->usesMailingList()
94 | : null
95 | ))
96 | );
97 | }
98 | }
99 |
100 | /**
101 | * Build the notification's view.
102 | *
103 | * @param \Illuminate\Notifications\Messages\MailMessage $message
104 | * @return string|array
105 | */
106 | protected function buildView($message)
107 | {
108 | if ($message->view) {
109 | return $message->view;
110 | }
111 |
112 | return [
113 | 'html' => $this->markdown->render('subscriber::html', $message->data()),
114 | 'text' => $this->markdown->renderText('subscriber::text', $message->data()),
115 | ];
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/Contracts/AppliesToMailingList.php:
--------------------------------------------------------------------------------
1 | middleware('signed');
29 | $this->subscriber = $subscriber;
30 | }
31 |
32 | /**
33 | * Handle the incoming request.
34 | *
35 | * @param Request $request
36 | * @param mixed $subscriber
37 | * @param string|null $mailingList
38 | * @return Response
39 | */
40 | public function __invoke(Request $request, $subscriber, ?string $mailingList = null)
41 | {
42 | $model = new $this->subscriber->userModel();
43 |
44 | $subscriber = $model
45 | ->where($model->getRouteKeyName(), $subscriber)
46 | ->first();
47 |
48 | if (! $subscriber) {
49 | abort(403, __('Could not process unsubscribe request'));
50 | }
51 |
52 | event(new UserUnsubscribing($subscriber, $mailingList));
53 |
54 | if ($mailingList) {
55 | $this->subscriber->unsubscribeFromMailingList($subscriber, $mailingList);
56 | } else {
57 | $this->subscriber->unsubscribeFromAllMailingLists($subscriber);
58 | }
59 |
60 | event(new UserUnsubscribed($subscriber, $mailingList));
61 |
62 | return $this->subscriber->complete($subscriber, $mailingList);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/Events/UserUnsubscribed.php:
--------------------------------------------------------------------------------
1 | user = $user;
21 | $this->mailingList = $mailingList;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/Events/UserUnsubscribing.php:
--------------------------------------------------------------------------------
1 | user = $user;
21 | $this->mailingList = $mailingList;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/Facades/Subscriber.php:
--------------------------------------------------------------------------------
1 | $this, 'mailingList' => $mailingList]
21 | );
22 | }
23 |
24 | /**
25 | * @param Notification $notification
26 | * @return bool
27 | */
28 | public function mailSubscriptionStatus(Notification $notification): bool
29 | {
30 | return Subscriber::checkSubscriptionStatus(
31 | $this,
32 | $notification instanceof AppliesToMailingList
33 | ? $notification->usesMailingList()
34 | : null
35 | );
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/SubscribableApplicationServiceProvider.php:
--------------------------------------------------------------------------------
1 | loadRoutes === true) {
22 | $this->loadRoutes();
23 | }
24 |
25 | \YlsIdeas\SubscribableNotifications\Facades\Subscriber::userModel(
26 | $this->userModel()
27 | );
28 |
29 | \YlsIdeas\SubscribableNotifications\Facades\Subscriber::onUnsubscribeFromMailingList(
30 | $this->onUnsubscribeFromMailingList()
31 | );
32 | \YlsIdeas\SubscribableNotifications\Facades\Subscriber::onUnsubscribeFromAllMailingLists(
33 | $this->onUnsubscribeFromAllMailingLists()
34 | );
35 | \YlsIdeas\SubscribableNotifications\Facades\Subscriber::onCompletion(
36 | $this->onCompletion()
37 | );
38 | \YlsIdeas\SubscribableNotifications\Facades\Subscriber::onCheckSubscriptionStatusOfMailingList(
39 | $this->onCheckSubscriptionStatusOfMailingList()
40 | );
41 | \YlsIdeas\SubscribableNotifications\Facades\Subscriber::onCheckSubscriptionStatusOfAllMailingLists(
42 | $this->onCheckSubscriptionStatusOfAllMailingLists()
43 | );
44 | }
45 |
46 | protected function userModel()
47 | {
48 | if ($this->model != null) {
49 | return $this->model;
50 | }
51 |
52 | if (version_compare($this->app->version(), '8.0.0', '>=')) {
53 | return '\App\Models\User';
54 | }
55 |
56 | return '\App\User';
57 | }
58 |
59 | public function loadRoutes()
60 | {
61 | \YlsIdeas\SubscribableNotifications\Facades\Subscriber::routes();
62 | }
63 |
64 | /**
65 | * @return callable|string
66 | */
67 | abstract public function onUnsubscribeFromMailingList();
68 |
69 | /**
70 | * @return callable|string
71 | */
72 | abstract public function onUnsubscribeFromAllMailingLists();
73 |
74 | /**
75 | * @return callable|string
76 | */
77 | abstract public function onCompletion();
78 |
79 | /**
80 | * @return callable|string
81 | */
82 | abstract public function onCheckSubscriptionStatusOfMailingList();
83 |
84 | /**
85 | * @return callable|string
86 | */
87 | abstract public function onCheckSubscriptionStatusOfAllMailingLists();
88 | }
89 |
--------------------------------------------------------------------------------
/src/SubscribableServiceProvider.php:
--------------------------------------------------------------------------------
1 | loadViewsFrom(__DIR__.'/../resources/views', 'subscriber');
18 |
19 | if ($this->app->runningInConsole()) {
20 | $this->publishes([
21 | __DIR__.'/../resources/views' => resource_path('views/vendor/subscriber'),
22 | ], 'subscriber-views');
23 |
24 | $this->publishes([
25 | __DIR__.'/../stubs/SubscribableServiceProvider.stub' => app_path('Providers/SubscribableServiceProvider.php'),
26 | ], 'subscriber-provider');
27 | }
28 | }
29 |
30 | /**
31 | * Register the application services.
32 | */
33 | public function register()
34 | {
35 | $this->app->bind(MailChannel::class, SubscriberMailChannel::class);
36 | $this->app->singleton(Subscriber::class, function (Application $app) {
37 | /** @phpstan-ignore-next-line */
38 | return new Subscriber($app);
39 | });
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Subscriber.php:
--------------------------------------------------------------------------------
1 | app = $app;
56 | }
57 |
58 | public function routes($router = null)
59 | {
60 | $router = $router ?? $this->app->make('router');
61 | $router->get(
62 | $this->uri,
63 | $this->hander
64 | )
65 | ->name($this->routeName);
66 | }
67 |
68 | /**
69 | * @return string
70 | */
71 | public function routeName()
72 | {
73 | return $this->routeName;
74 | }
75 |
76 | /**
77 | * @param string|null $model
78 | * @return string|null
79 | */
80 | public function userModel(?string $model = null)
81 | {
82 | if ($model) {
83 | $this->userModel = $model;
84 |
85 | return null;
86 | }
87 |
88 | return $this->userModel;
89 | }
90 |
91 | /**
92 | * @param string|callable $handler
93 | * @throws \Illuminate\Contracts\Container\BindingResolutionException
94 | */
95 | public function onUnsubscribeFromMailingList($handler)
96 | {
97 | $this->onUnsubscribeFromMailingList = $this->parseHandler($handler);
98 | }
99 |
100 | /**
101 | * @param string|callable $handler
102 | * @throws \Illuminate\Contracts\Container\BindingResolutionException
103 | */
104 | public function onUnsubscribeFromAllMailingLists($handler)
105 | {
106 | $this->onUnsubscribeFromAllMailingLists = $this->parseHandler($handler);
107 | }
108 |
109 | /**
110 | * @param string|callable $handler
111 | * @throws \Illuminate\Contracts\Container\BindingResolutionException
112 | */
113 | public function onCompletion($handler)
114 | {
115 | $this->onCompletion = $this->parseHandler($handler);
116 | }
117 |
118 | /**
119 | * @param string|callable $handler
120 | * @throws \Illuminate\Contracts\Container\BindingResolutionException
121 | */
122 | public function onCheckSubscriptionStatusOfAllMailingLists($handler)
123 | {
124 | $this->onCheckSubscriptionStatusForAllMailingLists = $this->parseHandler($handler);
125 | }
126 |
127 | /**
128 | * @param string|callable $handler
129 | * @throws \Illuminate\Contracts\Container\BindingResolutionException
130 | */
131 | public function onCheckSubscriptionStatusOfMailingList($handler)
132 | {
133 | $this->onCheckSubscriptionStatusForMailingLists = $this->parseHandler($handler);
134 | }
135 |
136 | /**
137 | * @param mixed $user
138 | * @param string $mailingList
139 | */
140 | public function unsubscribeFromMailingList($user, string $mailingList)
141 | {
142 | call_user_func($this->onUnsubscribeFromMailingList, $user, $mailingList);
143 | }
144 |
145 | /**
146 | * @param mixed $user
147 | */
148 | public function unsubscribeFromAllMailingLists($user)
149 | {
150 | call_user_func($this->onUnsubscribeFromAllMailingLists, $user);
151 | }
152 |
153 | /**
154 | * @param mixed $user
155 | * @param string|null $mailingList
156 | * @return Response
157 | */
158 | public function complete($user, ?string $mailingList = null)
159 | {
160 | return call_user_func($this->onCompletion, $user, $mailingList);
161 | }
162 |
163 | /**
164 | * @param mixed $user
165 | * @param string|null $mailingList
166 | * @return bool
167 | */
168 | public function checkSubscriptionStatus($user, ?string $mailingList = null)
169 | {
170 | if ($mailingList !== null) {
171 | return (bool) call_user_func($this->onCheckSubscriptionStatusForAllMailingLists, $user) &&
172 | (bool) call_user_func($this->onCheckSubscriptionStatusForMailingLists, $user, $mailingList);
173 | }
174 |
175 | return (bool) call_user_func($this->onCheckSubscriptionStatusForAllMailingLists, $user);
176 | }
177 |
178 | protected function parseHandler(string|callable$handler): callable
179 | {
180 | if (is_string($handler)) {
181 | $parsed = Str::parseCallback($handler);
182 | $parsed[0] = $this->app->make($parsed[0]);
183 |
184 | return $parsed;
185 | }
186 |
187 | return $handler;
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/stubs/SubscribableServiceProvider.stub:
--------------------------------------------------------------------------------
1 | redirectTo('/');
42 | };
43 | }
44 |
45 | /**
46 | * @return callable|string
47 | */
48 | public function onCheckSubscriptionStatusOfMailingList()
49 | {
50 | return function ($user, $mailingList) {
51 | return true;
52 | };
53 | }
54 |
55 | /**
56 | * @return callable|string
57 | */
58 | public function onCheckSubscriptionStatusOfAllMailingLists()
59 | {
60 | return function ($user) {
61 | return true;
62 | };
63 | }
64 | }
65 |
--------------------------------------------------------------------------------