]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/PageRevision.php
Images: Added nulling of image page relation on page delete
[bookstack] / app / Entities / Models / PageRevision.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use BookStack\Activity\Models\Loggable;
6 use BookStack\App\Model;
7 use BookStack\Users\Models\User;
8 use Carbon\Carbon;
9 use Illuminate\Database\Eloquent\Factories\HasFactory;
10 use Illuminate\Database\Eloquent\Relations\BelongsTo;
11
12 /**
13  * Class PageRevision.
14  *
15  * @property mixed  $id
16  * @property int    $page_id
17  * @property string $name
18  * @property string $slug
19  * @property string $book_slug
20  * @property int    $created_by
21  * @property Carbon $created_at
22  * @property Carbon $updated_at
23  * @property string $type
24  * @property string $summary
25  * @property string $markdown
26  * @property string $html
27  * @property string $text
28  * @property int    $revision_number
29  * @property Page   $page
30  * @property-read ?User $createdBy
31  */
32 class PageRevision extends Model implements Loggable
33 {
34     use HasFactory;
35
36     protected $fillable = ['name', 'text', 'summary'];
37     protected $hidden = ['html', 'markdown', 'text'];
38
39     /**
40      * Get the user that created the page revision.
41      */
42     public function createdBy(): BelongsTo
43     {
44         return $this->belongsTo(User::class, 'created_by');
45     }
46
47     /**
48      * Get the page this revision originates from.
49      */
50     public function page(): BelongsTo
51     {
52         return $this->belongsTo(Page::class);
53     }
54
55     /**
56      * Get the url for this revision.
57      */
58     public function getUrl(string $path = ''): string
59     {
60         return $this->page->getUrl('/revisions/' . $this->id . '/' . ltrim($path, '/'));
61     }
62
63     /**
64      * Get the previous revision for the same page if existing.
65      */
66     public function getPreviousRevision(): ?PageRevision
67     {
68         $id = static::newQuery()->where('page_id', '=', $this->page_id)
69             ->where('id', '<', $this->id)
70             ->max('id');
71
72         if ($id) {
73             return static::query()->find($id);
74         }
75
76         return null;
77     }
78
79     /**
80      * Allows checking of the exact class, Used to check entity type.
81      * Included here to align with entities in similar use cases.
82      * (Yup, Bit of an awkward hack).
83      *
84      * @deprecated Use instanceof instead.
85      */
86     public static function isA(string $type): bool
87     {
88         return $type === 'revision';
89     }
90
91     public function logDescriptor(): string
92     {
93         return "Revision #{$this->revision_number} (ID: {$this->id}) for page ID {$this->page_id}";
94     }
95 }