3 namespace BookStack\Console\Commands;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Sorting\BookSorter;
7 use BookStack\Sorting\SortRule;
8 use Illuminate\Console\Command;
10 class AssignSortRuleCommand extends Command
13 * The name and signature of the console command.
17 protected $signature = 'bookstack:assign-sort-rule
18 {sort-rule=0: ID of the sort rule to apply}
19 {--all-books : Apply to all books in the system}
20 {--books-without-sort : Apply to only books without a sort rule already assigned}
21 {--books-with-sort= : Apply to only books with the sort rule of given id}';
24 * The console command description.
28 protected $description = 'Assign a sort rule to content in the system';
31 * Execute the console command.
33 public function handle(BookSorter $sorter): int
35 $sortRuleId = intval($this->argument('sort-rule')) ?? 0;
36 if ($sortRuleId === 0) {
37 return $this->listSortRules();
40 $rule = SortRule::query()->find($sortRuleId);
41 if ($this->option('all-books')) {
42 $query = Book::query();
43 } else if ($this->option('books-without-sort')) {
44 $query = Book::query()->whereNull('sort_rule_id');
45 } else if ($this->option('books-with-sort')) {
46 $sortId = intval($this->option('books-with-sort')) ?: 0;
48 $this->error("Provided --books-with-sort option value is invalid");
51 $query = Book::query()->where('sort_rule_id', $sortId);
53 $this->error("No option provided to specify target. Run with the -h option to see all available options.");
58 $this->error("Sort rule of provided id {$sortRuleId} not found!");
62 $count = $query->clone()->count();
63 $this->warn("This will apply sort rule [{$rule->id}: {$rule->name}] to {$count} book(s) and run the sort on each.");
64 $confirmed = $this->confirm("Are you sure you want to continue?");
71 $query->chunkById(10, function ($books) use ($rule, $sorter, $count, &$processed) {
72 $max = min($count, ($processed + 10));
73 $this->info("Applying to {$processed}-{$max} of {$count} books");
74 foreach ($books as $book) {
75 $book->sort_rule_id = $rule->id;
77 $sorter->runBookAutoSort($book);
82 $this->info("Sort applied to {$processed} book(s)!");
87 protected function listSortRules(): int
90 $rules = SortRule::query()->orderBy('id', 'asc')->get();
91 $this->error("Sort rule ID required!");
92 $this->warn("\nAvailable sort rules:");
93 foreach ($rules as $rule) {
94 $this->info("{$rule->id}: {$rule->name}");