3 namespace BookStack\Console\Commands;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Sorting\BookSorter;
7 use BookStack\Sorting\SortSet;
8 use Illuminate\Console\Command;
10 class AssignSortSetCommand extends Command
13 * The name and signature of the console command.
17 protected $signature = 'bookstack:assign-sort-set
18 {sort-set=0: ID of the sort set to apply}
19 {--all-books : Apply to all books in the system}
20 {--books-without-sort : Apply to only books without a sort set already assigned}
21 {--books-with-sort= : Apply to only books with the sort of given id}';
24 * The console command description.
28 protected $description = 'Assign a sort set to content in the system';
31 * Execute the console command.
33 public function handle(BookSorter $sorter): int
35 $sortSetId = intval($this->argument('sort-set')) ?? 0;
36 if ($sortSetId === 0) {
37 return $this->listSortSets();
40 $set = SortSet::query()->find($sortSetId);
41 if ($this->option('all-books')) {
42 $query = Book::query();
43 } else if ($this->option('books-without-sort')) {
44 $query = Book::query()->whereNull('sort_set_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_set_id', $sortId);
53 $this->error("Either the --all-books or --books-without-sort option must be provided!");
58 $this->error("Sort set of provided id {$sortSetId} not found!");
62 $count = $query->clone()->count();
63 $this->warn("This will apply sort set [{$set->id}: {$set->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 ($set, $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_set_id = $set->id;
77 $sorter->runBookAutoSort($book);
82 $this->info("Sort applied to {$processed} books!");
87 protected function listSortSets(): int
90 $sets = SortSet::query()->orderBy('id', 'asc')->get();
91 $this->error("Sort set ID required!");
92 $this->warn("\nAvailable sort sets:");
93 foreach ($sets as $set) {
94 $this->info("{$set->id}: {$set->name}");