├── .all-contributorsrc ├── .github ├── icon.png ├── kurozora-open-source-badge.svg └── workflows │ └── run-tests.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── phpunit.xml.dist ├── src ├── CooldownServiceProvider.php ├── HasCooldowns.php ├── Migrations │ └── 2020_04_26_0000_create_cooldowns_table.php ├── Models │ └── Cooldown.php ├── Support │ └── PendingCooldown.php └── helpers.php └── tests ├── Feature ├── AutomaticCleanUpTest.php ├── GlobalCooldownTest.php └── ModelCooldownTest.php ├── Support ├── Migrations │ └── 2020_04_27_0000_create_users_test_table.php └── User.php └── TestCase.php /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "README.md" 4 | ], 5 | "imageSize": 100, 6 | "commit": false, 7 | "contributors": [ 8 | { 9 | "login": "musa11971", 10 | "name": "Musa", 11 | "avatar_url": "https://avatars1.githubusercontent.com/u/21341801?v=4", 12 | "profile": "http://musa11971.me", 13 | "contributions": [ 14 | "code", 15 | "doc" 16 | ] 17 | }, 18 | { 19 | "login": "kiritokatklian", 20 | "name": "Kirito", 21 | "avatar_url": "https://avatars0.githubusercontent.com/u/6556281?v=4", 22 | "profile": "https://www.linkedin.com/in/katklian/", 23 | "contributions": [ 24 | "ideas", 25 | "design" 26 | ] 27 | } 28 | ], 29 | "contributorsPerLine": 7, 30 | "projectName": "laravel-cooldown", 31 | "projectOwner": "Kurozora", 32 | "repoType": "github", 33 | "repoHost": "https://github.com", 34 | "skipCi": true 35 | } 36 | -------------------------------------------------------------------------------- /.github/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kurozora/laravel-cooldown/dacf073da9a80b9596cdfe00d3619ad2314a61a8/.github/icon.png -------------------------------------------------------------------------------- /.github/kurozora-open-source-badge.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | Kurozora Open Source 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | Kurozora 27 | 28 | 29 | 30 | 31 | 32 | 33 | Open Source 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: true 11 | matrix: 12 | php: [7.3] 13 | laravel: [6.*] 14 | dependency-version: [prefer-lowest, prefer-stable] 15 | include: 16 | - laravel: 6.* 17 | testbench: 4.* 18 | 19 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} 20 | 21 | steps: 22 | - name: Checkout code 23 | uses: actions/checkout@v1 24 | 25 | - name: Cache dependencies 26 | uses: actions/cache@v1 27 | with: 28 | path: ~/.composer/cache/files 29 | key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} 30 | 31 | - name: Setup PHP 32 | uses: shivammathur/setup-php@v1 33 | with: 34 | php-version: ${{ matrix.php }} 35 | extension-csv: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick 36 | coverage: none 37 | 38 | - name: Install dependencies 39 | run: | 40 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 41 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest 42 | 43 | - name: Execute tests 44 | run: vendor/bin/phpunit -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | vendor 3 | tests/Support/temp 4 | tests/temp 5 | composer.lock 6 | phpunit.xml 7 | .env 8 | .phpunit.result.cache 9 | .idea -------------------------------------------------------------------------------- /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 | The MIT License (MIT) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Latest version on packagist 5 | GitHub Tests Action Status 6 | Quality score 7 | Total downloads 8 | Kurozora Open Source 9 |

10 | 11 |

12 | plug-and-play global and model-specific cooldowns 13 |

14 | 15 | # Laravel Cooldowns 16 | 17 | This Laravel package makes it easier to implement cooldowns into your app. 18 | Consider the following example: 19 | ```php 20 | // The user will be able to post again 5 minutes from now 21 | $user->cooldown('create-post')->for('5 minutes'); 22 | ``` 23 | 24 | ## Installation 25 | 26 | You can install the package via composer: 27 | 28 | ```bash 29 | composer require kurozora/laravel-cooldown 30 | ``` 31 | 32 | ## Usage 33 | ### Global cooldowns 34 | Global cooldowns aren't tied to any model and are the same throughout your entire app. 35 | Use the `cooldown` helper to create one: 36 | 37 | ```php 38 | cooldown('registration')->for('1 hour'); 39 | ``` 40 | 41 | Here's an example of how you could limit registration to once per hour: 42 | 43 | ```php 44 | if(cooldown('registration')->notPassed()) 45 | return 'Registration is currently unavailable.'; 46 | 47 | // ... perform account registration ... 48 | 49 | cooldown('registration')->for('1 hour'); 50 | ``` 51 | 52 | ### Model-specific cooldowns 53 | Of course, a more useful use-case would be to tie cooldowns to models. In order to make use of this, you'll need to add the trait to your model: 54 | 55 | ```php 56 | use Illuminate\Database\Eloquent\Model; 57 | use Kurozora\Cooldown\HasCooldowns; 58 | 59 | class User extends Model 60 | { 61 | use HasCooldowns; 62 | } 63 | ``` 64 | 65 | The API used to interact with model-specific cooldowns is the exact same as global cooldowns, however you use the `cooldown` method on the model itself: 66 | 67 | ```php 68 | if($user->cooldown('create-post')->notPassed()) 69 | return 'You cannot create a post right now.'; 70 | 71 | // ... create the post ... 72 | 73 | $user->cooldown('create-post')->for('5 minutes'); 74 | ```` 75 | 76 | ### All cooldown methods 77 | These methods are available for both global and model-specific cooldowns. 78 | 79 | `for()` **Cooldown for a timespan** 80 | Pass along a string with the desired timespan. 81 | ```php 82 | cooldown('create-post')->for('1 day 3 hours'); 83 | ``` 84 | 85 | `until()` **Cooldown for a given datetime** 86 | Pass along a Carbon object with the desired datetime. 87 | ```php 88 | $tomorrow = now()->addDay(); 89 | 90 | cooldown('create-post')->until($tomorrow); 91 | ``` 92 | 93 | `reset()` **Reset the cooldown** 94 | The cooldown will be reset, and the action will be available immediately. 95 | ```php 96 | cooldown('create-post')->reset(); 97 | ``` 98 | 99 | `passed()` 100 | Checks whether the cooldown has passed. Returns true if the cooldown hasn't ever been initiated. 101 | ```php 102 | cooldown('create-post')->passed(); // true/false 103 | ``` 104 | 105 | `notPassed()` 106 | Checks whether the cooldown is still active, and thus hasn't passed yet. 107 | ```php 108 | cooldown('create-post')->notPassed(); // true/false 109 | ``` 110 | 111 | `expiresAt()` **Get the expiration date** 112 | Returns the datetime at which the cooldown will pass. 113 | ```php 114 | cooldown('create-post')->expiresAt(); // Illuminate\Support\Carbon object 115 | ```` 116 | 117 | `get()` 118 | Returns the underlying Cooldown model. 119 | ```php 120 | cooldown('create-post')->get(); // Kurozora\Cooldown\Models\Cooldown object 121 | ```` 122 | 123 | ### Testing 124 | 125 | ``` bash 126 | composer test 127 | ``` 128 | 129 | ## Contributing 130 | 131 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 132 | 133 | ### Security 134 | 135 | If you discover any security related issues, please email kurozoraapp@gmail.com instead of using the issue tracker. 136 | 137 | ## Contributors ✨ 138 | 139 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 |

Musa

💻 📖

Kirito

🤔 🎨
150 | 151 | 152 | 153 | 154 | 155 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! 156 | 157 | ## License 158 | 159 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kurozora/laravel-cooldown", 3 | "description": "Easily implement global or model-specific cooldowns into your Laravel app.", 4 | "keywords": [ 5 | "laravel-cooldown" 6 | ], 7 | "homepage": "https://github.com/Kurozora/laravel-cooldown", 8 | "license": "MIT", 9 | "authors": [ 10 | { 11 | "name": "musa11971", 12 | "email": "mussesemou99@gmail.com", 13 | "role": "Developer" 14 | } 15 | ], 16 | "require": { 17 | "php": "^7.3" 18 | }, 19 | "require-dev": { 20 | "orchestra/testbench": "^4.0", 21 | "phpunit/phpunit": "^8.2", 22 | "symfony/var-dumper": "^4.3" 23 | }, 24 | "autoload": { 25 | "psr-4": { 26 | "Kurozora\\Cooldown\\": "src" 27 | } 28 | }, 29 | "autoload-dev": { 30 | "psr-4": { 31 | "Kurozora\\Cooldown\\Tests\\": "tests" 32 | } 33 | }, 34 | "scripts": { 35 | "test": "vendor/bin/phpunit", 36 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 37 | }, 38 | "config": { 39 | "sort-packages": true 40 | }, 41 | "extra": { 42 | "laravel": { 43 | "providers": [ 44 | "Kurozora\\Cooldown\\CooldownServiceProvider" 45 | ] 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | src/ 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/CooldownServiceProvider.php: -------------------------------------------------------------------------------- 1 | loadMigrationsFrom(__DIR__ . '/Migrations'); 19 | $this->cleanUpExpiredCooldowns(); 20 | } 21 | 22 | /** 23 | * Register the application services. 24 | */ 25 | public function register() 26 | { 27 | require 'helpers.php'; 28 | } 29 | 30 | /** 31 | * Deletes all expired cooldowns. Only runs once per day. 32 | */ 33 | public function cleanUpExpiredCooldowns() 34 | { 35 | // Get the datetime at which the cooldowns were last cleaned up 36 | /** @var Carbon $lastDeletedAt */ 37 | $lastDeletedAt = Cache::get('kurozora_cooldown_last_cleaned_up_at', null); 38 | $hoursAgo = $lastDeletedAt == null ? null : $lastDeletedAt->diffInHours(now()); 39 | 40 | // Delete the cooldowns if the last run was 24 hours ago or more 41 | if($hoursAgo >= 24 || $hoursAgo == null) { 42 | try { 43 | Cooldown::expired()->delete(); 44 | } 45 | catch(Exception $e) { } 46 | 47 | Cache::forever('kurozora_cooldown_last_cleaned_up_at', now()); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /src/HasCooldowns.php: -------------------------------------------------------------------------------- 1 | bigIncrements('id'); 18 | $table->string('name'); 19 | $table->nullableMorphs('model'); 20 | $table->timestamp('expires_at'); 21 | $table->timestamps(); 22 | }); 23 | } 24 | 25 | /** 26 | * Reverse the migrations. 27 | * 28 | * @return void 29 | */ 30 | public function down() 31 | { 32 | Schema::drop('kurozora_cooldowns'); 33 | } 34 | } -------------------------------------------------------------------------------- /src/Models/Cooldown.php: -------------------------------------------------------------------------------- 1 | morphTo(); 29 | } 30 | 31 | /** 32 | * Scope a query to only include expired cooldowns. 33 | * 34 | * @param \Illuminate\Database\Eloquent\Builder $query 35 | * @return \Illuminate\Database\Eloquent\Builder 36 | */ 37 | public function scopeExpired($query) 38 | { 39 | return $query->where('expires_at', '<', now()); 40 | } 41 | } -------------------------------------------------------------------------------- /src/Support/PendingCooldown.php: -------------------------------------------------------------------------------- 1 | name = $name; 25 | $this->model = $model; 26 | 27 | return $this; 28 | } 29 | 30 | /** 31 | * Sets the cooldown for the given time period string. 32 | * e.g.: '5 minutes', '10 days' etc. 33 | * 34 | * @param string $time 35 | * @return Cooldown 36 | */ 37 | public function for($time) 38 | { 39 | $date = now()->add($time); 40 | 41 | return $this->createOrUpdateCooldownWithDate($date); 42 | } 43 | 44 | /** 45 | * Sets the cooldown to the given date. 46 | * 47 | * @param Carbon $date 48 | * @return Cooldown 49 | */ 50 | public function until($date) 51 | { 52 | return $this->createOrUpdateCooldownWithDate($date); 53 | } 54 | 55 | /** 56 | * Deletes the cooldown instance to reset it. 57 | */ 58 | public function reset() 59 | { 60 | $cooldown = $this->findCooldownWithName($this->name); 61 | 62 | if(!$cooldown) return; 63 | 64 | try { 65 | $cooldown->delete(); 66 | } 67 | catch(Exception $e) { } 68 | } 69 | 70 | /** 71 | * Checks whether the cooldown period has passed. 72 | * 73 | * @return bool 74 | */ 75 | public function passed() 76 | { 77 | $cooldown = $this->findCooldownWithName($this->name); 78 | 79 | if(!$cooldown) 80 | return true; 81 | 82 | if(now() < $cooldown->expires_at) 83 | return false; 84 | 85 | try { 86 | $cooldown->delete(); 87 | } 88 | catch(Exception $e) { } 89 | 90 | return true; 91 | } 92 | 93 | /** 94 | * Checks whether the cooldown period hasn't passed yet. 95 | * 96 | * @return bool 97 | */ 98 | public function notPassed() 99 | { 100 | $cooldown = $this->findCooldownWithName($this->name); 101 | 102 | if(!$cooldown) 103 | return false; 104 | 105 | if(now() < $cooldown->expires_at) 106 | return true; 107 | 108 | try { 109 | $cooldown->delete(); 110 | } 111 | catch(Exception $e) { } 112 | 113 | return false; 114 | } 115 | 116 | /** 117 | * Returns the datetime at which the cooldown expires. 118 | * 119 | * @return Carbon|null 120 | */ 121 | public function expiresAt() 122 | { 123 | if($this->passed()) return null; 124 | 125 | $cooldown = $this->findCooldownWithName($this->name); 126 | 127 | return $cooldown->expires_at; 128 | } 129 | 130 | /** 131 | * Returns the underlying Cooldown model, if any. 132 | * 133 | * @return Cooldown|null 134 | */ 135 | public function get() 136 | { 137 | return $this->findCooldownWithName($this->name); 138 | } 139 | 140 | /** 141 | * Returns the first cooldown instance with the given name. 142 | * 143 | * @param string $name 144 | * @return null|Cooldown 145 | */ 146 | private function findCooldownWithName($name) 147 | { 148 | return Cooldown::where('name', $name) 149 | ->where('model_type', $this->modelType()) 150 | ->where('model_id', $this->modelId()) 151 | ->first(); 152 | } 153 | 154 | /** 155 | * Creates a cooldown instance with the given date. 156 | * 157 | * @param Carbon $date 158 | * @return Cooldown 159 | */ 160 | private function createOrUpdateCooldownWithDate($date) 161 | { 162 | // Update existing cooldown 163 | if($cooldown = $this->findCooldownWithName($this->name)) 164 | { 165 | $cooldown->expires_at = $date; 166 | $cooldown->save(); 167 | 168 | return $cooldown; 169 | } 170 | 171 | // Create a new cooldown 172 | return Cooldown::create([ 173 | 'name' => $this->name, 174 | 'expires_at' => $date, 175 | 'model_type' => $this->modelType(), 176 | 'model_id' => $this->modelId() 177 | ]); 178 | } 179 | 180 | /** 181 | * Returns the model's type. 182 | * 183 | * @return string|null 184 | */ 185 | private function modelType() 186 | { 187 | if($this->model === null) return null; 188 | 189 | return get_class($this->model); 190 | } 191 | 192 | /** 193 | * Returns the model's ID. 194 | * 195 | * @return int|null 196 | */ 197 | private function modelId() 198 | { 199 | if($this->model === null) return null; 200 | 201 | return (int) $this->model->id; 202 | } 203 | } -------------------------------------------------------------------------------- /src/helpers.php: -------------------------------------------------------------------------------- 1 | for('25 minutes'); 19 | 20 | Carbon::setTestNow(now()->addDay()); 21 | 22 | (new CooldownServiceProvider(app()))->cleanUpExpiredCooldowns(); 23 | 24 | $this->assertEquals(0, Cooldown::count()); 25 | } 26 | 27 | /** @test */ 28 | public function valid_cooldowns_survive_the_clean_up() 29 | { 30 | cooldown('registration')->for('1 day 2 hours'); 31 | 32 | Carbon::setTestNow(now()->addDay()); 33 | 34 | (new CooldownServiceProvider(app()))->cleanUpExpiredCooldowns(); 35 | 36 | $this->assertEquals(1, Cooldown::count()); 37 | } 38 | } -------------------------------------------------------------------------------- /tests/Feature/GlobalCooldownTest.php: -------------------------------------------------------------------------------- 1 | assertTrue(function_exists('cooldown')); 18 | } 19 | 20 | /** @test */ 21 | public function cooldown_helper_can_register_cooldowns_with_for_method() 22 | { 23 | cooldown('registration')->for('1 hour'); 24 | 25 | $this->assertEquals(1, Cooldown::count()); 26 | } 27 | 28 | /** @test */ 29 | public function cooldown_helper_can_register_cooldowns_with_until_method() 30 | { 31 | cooldown('registration')->until(now()->addHour()); 32 | 33 | $this->assertEquals(1, Cooldown::count()); 34 | } 35 | 36 | /** @test */ 37 | public function cooldown_helper_can_check_if_cooldowns_passed() 38 | { 39 | Carbon::setTestNow(now()); 40 | 41 | $this->assertTrue(cooldown('registration')->passed()); 42 | 43 | Cooldown::create([ 44 | 'name' => 'registration', 45 | 'expires_at' => now()->addHour() 46 | ]); 47 | 48 | $this->assertFalse(cooldown('registration')->passed()); 49 | 50 | Carbon::setTestNow(now()->addMinutes(59)); 51 | 52 | $this->assertFalse(cooldown('registration')->passed()); 53 | 54 | Carbon::setTestNow(now()->addMinutes(1)); 55 | 56 | $this->assertTrue(cooldown('registration')->passed()); 57 | } 58 | 59 | /** @test */ 60 | public function cooldowns_are_deleted_when_they_are_expired() 61 | { 62 | cooldown('registration')->for('1 hour'); 63 | 64 | Carbon::setTestNow(now()->addHour()); 65 | 66 | $this->assertTrue(cooldown('registration')->passed()); 67 | $this->assertEquals(0, Cooldown::count()); 68 | } 69 | 70 | /** @test */ 71 | public function a_cooldown_expiration_date_can_be_retrieved() 72 | { 73 | Carbon::setTestNow(now()); 74 | 75 | cooldown('registration')->for('1 hour'); 76 | 77 | $this->assertInstanceOf(Carbon::class, cooldown('registration')->expiresAt()); 78 | } 79 | 80 | /** @test */ 81 | public function global_cooldowns_are_updated_if_they_already_exist() 82 | { 83 | cooldown('registration')->for('1 hour'); 84 | 85 | $this->assertEquals(1, Cooldown::count()); 86 | 87 | cooldown('registration')->for('24 hours'); 88 | 89 | $this->assertEquals(1, Cooldown::count()); 90 | } 91 | 92 | /** @test */ 93 | public function a_global_cooldown_can_be_reset() 94 | { 95 | cooldown('registration')->for('1 hour'); 96 | 97 | $this->assertEquals(1, Cooldown::count()); 98 | 99 | cooldown('registration')->reset(); 100 | 101 | $this->assertEquals(0, Cooldown::count()); 102 | } 103 | } -------------------------------------------------------------------------------- /tests/Feature/ModelCooldownTest.php: -------------------------------------------------------------------------------- 1 | user = User::create(['name' => 'Kurozora']); 23 | } 24 | 25 | /** @test */ 26 | public function cooldown_function_exists_on_model() 27 | { 28 | $this->assertTrue(method_exists($this->user, 'cooldown')); 29 | } 30 | 31 | /** @test */ 32 | public function a_cooldown_can_be_registered_with_for_method() 33 | { 34 | $this->user->cooldown('create-post')->for('10 minutes'); 35 | 36 | $this->assertEquals(1, Cooldown::count()); 37 | } 38 | 39 | /** @test */ 40 | public function a_cooldown_can_be_registered_with_until_method() 41 | { 42 | $this->user->cooldown('create-post')->until(now()->addMinutes(10)); 43 | 44 | $this->assertEquals(1, Cooldown::count()); 45 | } 46 | 47 | /** @test */ 48 | public function model_cooldowns_are_updated_if_they_already_exist() 49 | { 50 | $this->user->cooldown('create-post')->for('1 hour'); 51 | 52 | $this->assertEquals(1, Cooldown::count()); 53 | 54 | $this->user->cooldown('create-post')->for('24 hours'); 55 | 56 | $this->assertEquals(1, Cooldown::count()); 57 | } 58 | 59 | /** @test */ 60 | public function a_model_cooldown_can_be_reset() 61 | { 62 | $this->user->cooldown('create-post')->for('1 hour'); 63 | 64 | $this->assertEquals(1, Cooldown::count()); 65 | 66 | $this->user->cooldown('create-post')->reset(); 67 | 68 | $this->assertEquals(0, Cooldown::count()); 69 | } 70 | } -------------------------------------------------------------------------------- /tests/Support/Migrations/2020_04_27_0000_create_users_test_table.php: -------------------------------------------------------------------------------- 1 | bigIncrements('id'); 18 | $table->string('name'); 19 | $table->timestamps(); 20 | }); 21 | } 22 | 23 | /** 24 | * Reverse the migrations. 25 | * 26 | * @return void 27 | */ 28 | public function down() 29 | { 30 | Schema::drop('users'); 31 | } 32 | } -------------------------------------------------------------------------------- /tests/Support/User.php: -------------------------------------------------------------------------------- 1 | loadMigrationsFrom(__DIR__ . '/Support/Migrations'); 16 | } 17 | 18 | /** 19 | * Register the provider. 20 | * 21 | * @param \Illuminate\Foundation\Application $app 22 | * 23 | * @return array 24 | */ 25 | protected function getPackageProviders($app) 26 | { 27 | return [ 28 | CooldownServiceProvider::class 29 | ]; 30 | } 31 | 32 | /** 33 | * Set up the test environment. 34 | * 35 | * @param \Illuminate\Foundation\Application $app 36 | */ 37 | protected function getEnvironmentSetUp($app) 38 | { 39 | // Enable debug mode 40 | $app['config']->set('app.debug', true); 41 | 42 | // Configure database 43 | $app['config']->set('database.default', 'sqlite'); 44 | $app['config']->set('database.connections.sqlite', [ 45 | 'driver' => 'sqlite', 46 | 'database' => ':memory:', 47 | 'prefix' => '', 48 | ]); 49 | 50 | // Configure cache 51 | $app['config']->set('cache.default', 'testing'); 52 | $app['config']->set('cache.stores.testing', [ 53 | 'driver' => 'array' 54 | ]); 55 | } 56 | } --------------------------------------------------------------------------------