1+ <?php
2+ /**
3+ * laravel
4+ *
5+ * @author Jérémy GAULIN <[email protected] > 6+ * @copyright 2017 - B&B Web Expertise
7+ */
8+
9+ namespace Bnb \Laravel \Attachments \Console \Commands ;
10+
11+ use Bnb \Laravel \Attachments \Attachment ;
12+ use Carbon \Carbon ;
13+ use Illuminate \Console \Command ;
14+ use Illuminate \Support \Collection ;
15+ use Lang ;
16+ use Symfony \Component \Console \Input \InputOption ;
17+
18+ class CleanupAttachments extends Command
19+ {
20+
21+ protected $ signature = 'attachments:cleanup ' ;
22+
23+
24+ public function __construct ()
25+ {
26+ $ this ->description = Lang::get ('attachments::messages.console.cleanup_description ' );
27+
28+ parent ::__construct ();
29+
30+ $ this ->getDefinition ()->addOption (new InputOption ('since ' , '-s ' , InputOption::VALUE_OPTIONAL ,
31+ Lang::get ('attachments::messages.console.cleanup_option_since ' ), 1440 ));
32+ }
33+
34+
35+ public function handle ()
36+ {
37+ if ($ this ->confirm (Lang::get ('attachments::messages.console.cleanup_confirm ' ))) {
38+ $ query = Attachment::query ()
39+ ->whereNull ('model_type ' )
40+ ->whereNull ('model_id ' )
41+ ->where ('updated_at ' , '<= ' , Carbon::now ()->addMinutes (-1 * $ this ->option ('since ' )));
42+
43+ $ progress = $ this ->output ->createProgressBar ($ count = $ query ->count ());
44+
45+ if ($ count ) {
46+ $ query ->chunk (100 , function ($ attachements ) use ($ progress ) {
47+ /** @var Collection $attachements */
48+ $ attachements ->each (function ($ attachement ) use ($ progress ) {
49+ /** @var Attachment $attachement */
50+ $ attachement ->delete ();
51+
52+ $ progress ->advance ();
53+ });
54+ });
55+
56+ $ this ->info (Lang::get ('attachments::messages.console.done ' ));
57+ } else {
58+ $ this ->comment (Lang::get ('attachments::messages.console.cleanup_no_data ' ));
59+ }
60+ }
61+ }
62+ }
0 commit comments