]> BookStack Code Mirror - bookstack/blob - app/Repos/ChapterRepo.php
Expanded chapters interface and improved book/page deletion
[bookstack] / app / Repos / ChapterRepo.php
1 <?php namespace Oxbow\Repos;
2
3
4 use Illuminate\Support\Str;
5 use Oxbow\Chapter;
6
7 class ChapterRepo
8 {
9
10     protected $chapter;
11
12     /**
13      * ChapterRepo constructor.
14      * @param $chapter
15      */
16     public function __construct(Chapter $chapter)
17     {
18         $this->chapter = $chapter;
19     }
20
21     public function getById($id)
22     {
23         return $this->chapter->findOrFail($id);
24     }
25
26     public function getAll()
27     {
28         return $this->chapter->all();
29     }
30
31     public function getBySlug($slug, $bookId)
32     {
33         return $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
34     }
35
36     public function newFromInput($input)
37     {
38         return $this->chapter->fill($input);
39     }
40
41     public function destroyById($id)
42     {
43         $page = $this->getById($id);
44         $page->delete();
45     }
46
47     public function doesSlugExist($slug, $bookId, $currentId = false)
48     {
49         $query = $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId);
50         if($currentId) {
51             $query = $query->where('id', '!=', $currentId);
52         }
53         return $query->count() > 0;
54     }
55
56     public function findSuitableSlug($name, $bookId, $currentId = false)
57     {
58         $slug = Str::slug($name);
59         while($this->doesSlugExist($slug, $bookId, $currentId)) {
60             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
61         }
62         return $slug;
63     }
64
65 }