]> BookStack Code Mirror - bookstack/blob - app/Repos/BookRepo.php
Improved empty lists. Fixes #10.
[bookstack] / app / Repos / BookRepo.php
1 <?php namespace Oxbow\Repos;
2
3 use Illuminate\Support\Str;
4 use Oxbow\Book;
5
6 class BookRepo
7 {
8
9     protected $book;
10     protected $pageRepo;
11
12     /**
13      * BookRepo constructor.
14      * @param Book $book
15      * @param PageRepo $pageRepo
16      */
17     public function __construct(Book $book, PageRepo $pageRepo)
18     {
19         $this->book = $book;
20         $this->pageRepo = $pageRepo;
21     }
22
23     public function getById($id)
24     {
25         return $this->book->findOrFail($id);
26     }
27
28     public function getAll()
29     {
30         return $this->book->all();
31     }
32
33     public function getBySlug($slug)
34     {
35         return $this->book->where('slug', '=', $slug)->first();
36     }
37
38     public function newFromInput($input)
39     {
40         return $this->book->fill($input);
41     }
42
43     public function countBySlug($slug)
44     {
45         return $this->book->where('slug', '=', $slug)->count();
46     }
47
48     public function destroyBySlug($bookSlug)
49     {
50         $book = $this->getBySlug($bookSlug);
51         foreach($book->pages as $page) {
52             $page->delete();
53         }
54         foreach($book->chapters as $chapter) {
55             $chapter->delete();
56         }
57         $book->delete();
58     }
59
60     public function getNewPriority($book)
61     {
62         $lastElem = $book->children()->pop();
63         return $lastElem ? $lastElem->priority + 1 : 0;
64     }
65
66     public function doesSlugExist($slug, $currentId = false)
67     {
68         $query = $this->book->where('slug', '=', $slug);
69         if($currentId) {
70             $query = $query->where('id', '!=', $currentId);
71         }
72         return $query->count() > 0;
73     }
74
75     public function findSuitableSlug($name, $currentId = false)
76     {
77         $slug = Str::slug($name);
78         while($this->doesSlugExist($slug, $currentId)) {
79             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
80         }
81         return $slug;
82     }
83
84 }