]> BookStack Code Mirror - bookstack/blob - app/References/ReferenceService.php
Added reference storage system, and command to re-index
[bookstack] / app / References / ReferenceService.php
1 <?php
2
3 namespace BookStack\References;
4
5 use BookStack\Entities\Models\Page;
6 use Illuminate\Database\Eloquent\Collection;
7
8 class ReferenceService
9 {
10
11     /**
12      * Update the outgoing references for the given page.
13      */
14     public function updateForPage(Page $page): void
15     {
16         $this->updateForPages([$page]);
17     }
18
19     /**
20      * Update the outgoing references for all pages in the system.
21      */
22     public function updateForAllPages(): void
23     {
24         Reference::query()
25             ->where('from_type', '=', (new Page())->getMorphClass())
26             ->truncate();
27
28         Page::query()->select(['id', 'html'])->chunk(100, function(Collection $pages) {
29             $this->updateForPages($pages->all());
30         });
31     }
32
33     /**
34      * Update the outgoing references for the pages in the given array.
35      *
36      * @param Page[] $pages
37      */
38     protected function updateForPages(array $pages): void
39     {
40         if (count($pages) === 0) {
41             return;
42         }
43
44         $parser = CrossLinkParser::createWithEntityResolvers();
45         $references = [];
46
47         $pageIds = array_map(fn(Page $page) => $page->id, $pages);
48         Reference::query()
49             ->where('from_type', '=', $pages[0]->getMorphClass())
50             ->whereIn('from_id', $pageIds)
51             ->delete();
52
53         foreach ($pages as $page) {
54             $models = $parser->extractLinkedModels($page->html);
55
56             foreach ($models as $model) {
57                 $references[] = [
58                     'from_id' => $page->id,
59                     'from_type' => $page->getMorphClass(),
60                     'to_id' => $model->id,
61                     'to_type' => $model->getMorphClass(),
62                 ];
63             }
64         }
65
66         foreach (array_chunk($references, 1000) as $referenceDataChunk) {
67             Reference::query()->insert($referenceDataChunk);
68         }
69     }
70
71 }