├── .github └── SECURITY.md ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json └── src ├── CacheGarbageCollector.php ├── ClearExpiredCommand.php ├── Events ├── GarbageCollectionEnded.php ├── GarbageCollectionFailed.php └── GarbageCollectionStarting.php ├── ServiceProvider.php └── Support ├── FileRegister.php └── Formatter.php /.github/SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | If you discover any security related issues, please email hello@arif.me instead of using the issue tracker. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor 2 | composer.lock -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### 1.0.0 - 2023-10-01 2 | - feat: dry run with --dry-run. https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/7 by @arifhp86 3 | - feat: disable directory delete with --disable-directory-delete https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/7 by @arifhp86 4 | - feat: trigger events during command execution https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/7 by @arifhp86 5 | - chore: add license, security policy and contribution guideline https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/7 by @arifhp86 6 | - docs: add documentation https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/7 by @arifhp86 7 | 8 | ### 0.0.5 9 | - Only read part of the file to check if it's expired. https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/6 by @jmdz 10 | 11 | ### 0.0.4 12 | - Fix typo in readme. https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/3 by @attogram 13 | 14 | ### 0.0.3 15 | - Compatibility with Laravel 6. https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/2 by @zaxxo 16 | 17 | ### 0.0.2 18 | - Fix wrong config syntax. https://github.com/arifhp86/laravel-clear-expired-cache-file/pull/1 by @barryp -------------------------------------------------------------------------------- /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**! -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) arifhp86 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 13 | all 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 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Clear Expired Cache Files 2 | 3 | [![Latest Stable Version](https://img.shields.io/github/release/arifhp86/laravel-clear-expired-cache-file.svg?style=flat-square)](https://github.com/arifhp86/laravel-clear-expired-cache-file/releases) 4 | [![MIT Licensed](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) 5 | [![Total Downloads](https://img.shields.io/packagist/dt/arifhp86/laravel-clear-expired-cache-file.svg?style=flat-square)](https://packagist.org/packages/arifhp86/laravel-clear-expired-cache-file) 6 | 7 | When you use the `file` cache driver, you may have noticed that the cache files are never deleted automatically. They are overwritten when the cache is refreshed which is good, but if there is some randomness in you cache keys, or for some other reason some of your cache files are never touched again, they will stay on your server forever. This package helps you to get rid of these lingering files. 8 | 9 | This package only adds one artisan command: `php artisan cache:clear-expired` and it will delete all cache files that has already been expired. 10 | 11 | ## Installation 12 | 13 | You can install the package via composer: 14 | 15 | ```bash 16 | composer require arifhp86/laravel-clear-expired-cache-file 17 | ``` 18 | 19 | ## Usage 20 | 21 | Run the following command 22 | ```bash 23 | php artisan cache:clear-expired 24 | ``` 25 | ### Run on schedule 26 | You can also schedule the command to run automatically. For example, if you want to run the command every day at 1 AM, you can add the following to your `app/Console/Kernel.php` file: 27 | 28 | ```php 29 | protected function schedule(Schedule $schedule) 30 | { 31 | $schedule->command('cache:clear-expired')->dailyAt('01:00'); 32 | } 33 | ``` 34 | 35 | ### Dry run 36 | You can run the command in dry run mode. In this mode, the command will not delete any files. It will only show you the files that will be deleted if you run the command without the `--dry-run` option. 37 | 38 | ```bash 39 | php artisan cache:clear-expired --dry-run 40 | ``` 41 | 42 | ### Disable directory deletion 43 | By default, the command will delete all empty directories after deleting the expired files. You can disable this behavior by using the `--disable-directory-delete` option. 44 | 45 | ```bash 46 | php artisan cache:clear-expired --disable-directory-delete 47 | ``` 48 | 49 | ### Events 50 | The command triggers three events: 51 | - `Arifhp86\ClearExpiredCacheFile\Events\GarbageCollectionStarting`: Before the command runs. 52 | - `Arifhp86\ClearExpiredCacheFile\Events\GarbageCollectionEnded`: After the command runs. 53 | - `Arifhp86\ClearExpiredCacheFile\Events\GarbageCollectionFailed`: If the command fails. 54 | 55 | You can use these events to run your own code before or after the command runs. 56 | #### Send email notification after the command runs 57 | 58 | ```php 59 | // app/Providers/EventServiceProvider.php boot method 60 | 61 | use Arifhp86\ClearExpiredCacheFile\Events\GarbageCollectionEnded; 62 | 63 | Event::listen(function (GarbageCollectionEnded $event) { 64 | $timeTaken = $event->time; // in seconds 65 | $memory = $event->memory; // in bytes 66 | $numberOfFilesDeleted = $event->expiredFiles->getCount(); 67 | $diskCleared = $event->expiredFiles->getFormattedSize(); 68 | $remainingFiles = $event->activeFiles->getCount(); 69 | $remainingDisk = $event->activeFiles->getFormattedSize(); 70 | $numberOfDeletedDirectories = $event->deletedDirectories; 71 | 72 | // Send email notification 73 | //... 74 | }); 75 | ``` 76 | 77 | #### Send email notification if the command fails 78 | 79 | ```php 80 | // app/Providers/EventServiceProvider.php boot method 81 | 82 | use Arifhp86\ClearExpiredCacheFile\Events\GarbageCollectionFailed; 83 | 84 | Event::listen(function (GarbageCollectionFailed $event) { 85 | $exception = $event->exception; 86 | $message = $exception->getMessage(); 87 | $stackTrace = $exception->getTraceAsString(); 88 | 89 | // Send email notification 90 | //... 91 | }); 92 | ``` 93 | 94 | ## Changelog 95 | 96 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 97 | 98 | ## Contributing 99 | 100 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 101 | 102 | ## Security Vulnerabilities 103 | 104 | Please review [our security policy](../../security/policy) on how to report security vulnerabilities. 105 | 106 | ## Credits 107 | 108 | - [Arifur Rahman](https://github.com/arifhp86) 109 | - [All Contributors](../../contributors) 110 | 111 | ## License 112 | 113 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 114 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "arifhp86/laravel-clear-expired-cache-file", 3 | "description": "Remove laravel expired cache file/folder", 4 | "keywords": ["laravel", "cache", "expired", "clear"], 5 | "license": "MIT", 6 | "authors": [{ 7 | "name": "Arifur Rahman", 8 | "email": "arifhp86@gmail.com" 9 | }], 10 | "require": { 11 | "php": "^7.0|^8.0", 12 | "laravel/framework": ">=5.5", 13 | "wilderborn/partyline": "^1.0" 14 | }, 15 | "autoload": { 16 | "psr-4": { 17 | "Arifhp86\\ClearExpiredCacheFile\\": "src/" 18 | } 19 | }, 20 | "extra": { 21 | "laravel": { 22 | "providers": [ 23 | "Arifhp86\\ClearExpiredCacheFile\\ServiceProvider" 24 | ] 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/CacheGarbageCollector.php: -------------------------------------------------------------------------------- 1 | filesystem = $filesystem; 25 | $this->expiredFiles = new FileRegister(); 26 | $this->activeFiles = new FileRegister(); 27 | } 28 | 29 | public function collectGarbage() 30 | { 31 | GarbageCollectionStarting::dispatch(); 32 | 33 | $start = microtime(true); 34 | $this->deleteExpiredFiles()->deleteEmptyDirectories(); 35 | 36 | $timeInSeconds = microtime(true) - $start; 37 | $memoryInBytes = memory_get_peak_usage(true); 38 | 39 | $time = Formatter::formatDuration($timeInSeconds); 40 | $memory = Formatter::formatSpace($memoryInBytes); 41 | 42 | Partyline::line("Duration: {$time}, Memory: {$memory}"); 43 | 44 | GarbageCollectionEnded::dispatch( 45 | $timeInSeconds, 46 | $memoryInBytes, 47 | $this->expiredFiles, 48 | $this->activeFiles, 49 | $this->deletedDirectories 50 | ); 51 | } 52 | 53 | public function setDisableDirectoryDelete(bool $disableDirectoryDelete): self 54 | { 55 | $this->disableDirectoryDelete = $disableDirectoryDelete; 56 | 57 | return $this; 58 | } 59 | 60 | public function setIsDryRun(bool $isDryRun): self 61 | { 62 | $this->isDryRun = $isDryRun; 63 | 64 | return $this; 65 | } 66 | 67 | protected function deleteExpiredFiles(): self 68 | { 69 | Partyline::line('Scanning cache files...'); 70 | 71 | foreach ($this->filesystem->allFiles() as $file) { 72 | if($this->notACacheFile($file)) { 73 | continue; 74 | } 75 | 76 | // Check if the file has not been already deleted by the app itself 77 | if (! $this->filesystem->exists($file)) { 78 | Partyline::alert("File {$file} not found!"); 79 | continue; 80 | } 81 | 82 | $size = $this->filesystem->size($file); 83 | if($this->fileIsExpired($file)) { 84 | $this->expiredFiles->add($size); 85 | if (! $this->isDryRun) { 86 | $this->filesystem->delete($file); 87 | } 88 | } else { 89 | $this->activeFiles->add($size); 90 | } 91 | } 92 | 93 | 94 | if (! $this->expiredFiles->getCount()) { 95 | Partyline::line('No expired cache file found!'); 96 | } else { 97 | $count = $this->expiredFiles->getCount(); 98 | $size = $this->expiredFiles->getFormattedSize(); 99 | Partyline::info("{$count} ({$size}) expired cache files deleted."); 100 | } 101 | 102 | if (! $this->activeFiles->getCount()) { 103 | Partyline::line('0 cache file remaining.'); 104 | } else { 105 | $count = $this->activeFiles->getCount(); 106 | $size = $this->activeFiles->getFormattedSize(); 107 | Partyline::info("{$count} ({$size}) cache file remaining."); 108 | } 109 | Partyline::line("\n"); 110 | 111 | return $this; 112 | } 113 | 114 | protected function deleteEmptyDirectories(): self 115 | { 116 | if ($this->disableDirectoryDelete || $this->isDryRun) { 117 | return $this; 118 | } 119 | 120 | Partyline::line('Scanning directories...'); 121 | 122 | foreach(array_reverse($this->filesystem->allDirectories()) as $dir) { 123 | if (! $this->directoryIsEmpty($dir)) { 124 | continue; 125 | } 126 | 127 | $this->filesystem->deleteDirectory($dir); 128 | $this->deletedDirectories += 1; 129 | } 130 | 131 | if (! $this->deletedDirectories) { 132 | Partyline::line('No empty directory found!'); 133 | } else { 134 | Partyline::info("{$this->deletedDirectories} empty directories deleted."); 135 | } 136 | 137 | Partyline::line("\n"); 138 | 139 | return $this; 140 | } 141 | 142 | protected function directoryIsEmpty(string $dir): bool 143 | { 144 | return count(scandir($this->filesystem->path($dir))) === 2; 145 | } 146 | 147 | protected function fileIsExpired(string $file): bool 148 | { 149 | return Carbon::now()->timestamp >= $this->getExpireDate($file); 150 | } 151 | 152 | protected function getExpireDate(string $file): int 153 | { 154 | $handle = fopen($this->filesystem->path($file), 'r'); 155 | $expire = fread($handle, 10); 156 | fclose($handle); 157 | 158 | // if the file is empty for some reason, we get an empty string 159 | if ($expire === '') { 160 | return 0; 161 | } 162 | 163 | return (int) $expire; 164 | } 165 | 166 | protected function notACacheFile(string $name): bool 167 | { 168 | return substr($name, 0, 1) === '.'; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/ClearExpiredCommand.php: -------------------------------------------------------------------------------- 1 | garbageCollector = $garbageCollector; 41 | } 42 | 43 | /** 44 | * Execute the console command. 45 | * 46 | * @return int 47 | */ 48 | public function handle(): int 49 | { 50 | Partyline::bind($this); 51 | 52 | try { 53 | $this->garbageCollector 54 | ->setIsDryRun($this->option('dry-run')) 55 | ->setDisableDirectoryDelete($this->option('disable-directory-delete')) 56 | ->collectGarbage(); 57 | } catch (Exception $e) { 58 | GarbageCollectionFailed::dispatch($e); 59 | 60 | $this->error($e->getMessage()); 61 | 62 | return self::FAILURE; 63 | } 64 | 65 | return self::SUCCESS; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Events/GarbageCollectionEnded.php: -------------------------------------------------------------------------------- 1 | time = $time; 26 | $this->memory = $memory; 27 | $this->expiredFiles = $expiredFiles; 28 | $this->activeFiles = $activeFiles; 29 | $this->deletedDirectories = $deletedDirectories; 30 | } 31 | } -------------------------------------------------------------------------------- /src/Events/GarbageCollectionFailed.php: -------------------------------------------------------------------------------- 1 | exception = $exception; 17 | } 18 | } -------------------------------------------------------------------------------- /src/Events/GarbageCollectionStarting.php: -------------------------------------------------------------------------------- 1 | app->when(CacheGarbageCollector::class) 20 | ->needs(Filesystem::class) 21 | ->give(function () { 22 | config(['filesystems.disks.cache-folder' => [ 23 | 'driver' => 'local', 24 | 'root' => config('cache.stores.file.path') 25 | ]]); 26 | 27 | return Storage::disk('cache-folder'); 28 | }); 29 | } 30 | 31 | 32 | /** 33 | * Perform post-registration booting of services. 34 | * 35 | * @return void 36 | */ 37 | public function boot() 38 | { 39 | if ($this->app->runningInConsole()) { 40 | $this->commands([ 41 | ClearExpiredCommand::class, 42 | ]); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/Support/FileRegister.php: -------------------------------------------------------------------------------- 1 | count += 1; 13 | $this->size += $size; 14 | } 15 | 16 | public function getSize(): int 17 | { 18 | return $this->size; 19 | } 20 | 21 | public function getFormattedSize(): string 22 | { 23 | return Formatter::formatSpace($this->size); 24 | } 25 | 26 | public function getCount(): int 27 | { 28 | return $this->count; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Support/Formatter.php: -------------------------------------------------------------------------------- 1 |