]> BookStack Code Mirror - bookstack/blob - app/Repos/BookRepo.php
7f7517e92243b050a9c8567a25063f274d8f94ed
[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     /**
39      * Get a new book instance from request input.
40      * @param $input
41      * @return Book
42      */
43     public function newFromInput($input)
44     {
45         return $this->book->fill($input);
46     }
47
48     public function countBySlug($slug)
49     {
50         return $this->book->where('slug', '=', $slug)->count();
51     }
52
53     public function destroyBySlug($bookSlug)
54     {
55         $book = $this->getBySlug($bookSlug);
56         foreach($book->pages as $page) {
57             $page->delete();
58         }
59         foreach($book->chapters as $chapter) {
60             $chapter->delete();
61         }
62         $book->delete();
63     }
64
65     public function getNewPriority($book)
66     {
67         $lastElem = $book->children()->pop();
68         return $lastElem ? $lastElem->priority + 1 : 0;
69     }
70
71     public function doesSlugExist($slug, $currentId = false)
72     {
73         $query = $this->book->where('slug', '=', $slug);
74         if($currentId) {
75             $query = $query->where('id', '!=', $currentId);
76         }
77         return $query->count() > 0;
78     }
79
80     public function findSuitableSlug($name, $currentId = false)
81     {
82         $slug = Str::slug($name);
83         while($this->doesSlugExist($slug, $currentId)) {
84             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
85         }
86         return $slug;
87     }
88
89     public function getBySearch($term)
90     {
91         $terms = explode(' ', preg_quote(trim($term)));
92         $books = $this->book->fullTextSearch(['name', 'description'], $terms);
93         $words = join('|', $terms);
94         foreach ($books as $book) {
95             //highlight
96             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $book->getExcerpt(100));
97             $book->searchSnippet = $result;
98         }
99         return $books;
100     }
101
102 }