5 use Illuminate\Database\Eloquent\Model;
7 abstract class Entity extends Model
13 * Compares this entity to another given entity.
14 * Matches by comparing class and id.
18 public function matches($entity)
20 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
24 * Checks if an entity matches or contains another given entity.
25 * @param Entity $entity
28 public function matchesOrContains(Entity $entity)
30 $matches = [get_class($this), $this->id] === [get_class($entity), $entity->id];
32 if ($matches) return true;
34 if ($entity->isA('chapter') && $this->isA('book')) {
35 return $entity->book_id === $this->id;
38 if ($entity->isA('page') && $this->isA('book')) {
39 return $entity->book_id === $this->id;
42 if ($entity->isA('page') && $this->isA('chapter')) {
43 return $entity->chapter_id === $this->id;
50 * Gets the activity objects for this entity.
51 * @return \Illuminate\Database\Eloquent\Relations\MorphMany
53 public function activity()
55 return $this->morphMany('BookStack\Activity', 'entity')->orderBy('created_at', 'desc');
59 * Get View objects for this entity.
62 public function views()
64 return $this->morphMany('BookStack\View', 'viewable');
68 * Get just the views for the current user.
71 public function userViews()
73 return $this->views()->where('user_id', '=', auth()->user()->id);
77 * Allows checking of the exact class, Used to check entity type.
78 * Cleaner method for is_a.
82 public static function isA($type)
84 return static::getClassName() === strtolower($type);
88 * Gets the class name.
91 public static function getClassName()
93 return strtolower(array_slice(explode('\\', static::class), -1, 1)[0]);
97 *Gets a limited-length version of the entities name.
101 public function getShortName($length = 25)
103 if(strlen($this->name) <= $length) return $this->name;
104 return substr($this->name, 0, $length-3) . '...';
108 * Perform a full-text search on this entity.
109 * @param string[] $fieldsToSearch
110 * @param string[] $terms
111 * @param string[] array $wheres
114 public static function fullTextSearch($fieldsToSearch, $terms, $wheres = [])
117 foreach ($terms as $term) {
118 $termString .= htmlentities($term) . '* ';
120 $fields = implode(',', $fieldsToSearch);
121 $termStringEscaped = \DB::connection()->getPdo()->quote($termString);
122 $search = static::addSelect(\DB::raw('*, MATCH(name) AGAINST('.$termStringEscaped.' IN BOOLEAN MODE) AS title_relevance'));
123 $search = $search->whereRaw('MATCH(' . $fields . ') AGAINST(? IN BOOLEAN MODE)', [$termStringEscaped]);
125 // Add additional where terms
126 foreach ($wheres as $whereTerm) {
127 $search->where($whereTerm[0], $whereTerm[1], $whereTerm[2]);
131 if (!static::isA('book')) $search = $search->with('book');
132 if (static::isA('page')) $search = $search->with('chapter');
134 return $search->orderBy('title_relevance', 'desc')->get();
138 * Get the url for this item.
141 abstract public function getUrl();