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') || $entity->isA('page')) && $this->isA('book')) {
35 return $entity->book_id === $this->id;
38 if ($entity->isA('page') && $this->isA('chapter')) {
39 return $entity->chapter_id === $this->id;
46 * Gets the activity objects for this entity.
47 * @return \Illuminate\Database\Eloquent\Relations\MorphMany
49 public function activity()
51 return $this->morphMany('BookStack\Activity', 'entity')->orderBy('created_at', 'desc');
55 * Get View objects for this entity.
58 public function views()
60 return $this->morphMany('BookStack\View', 'viewable');
64 * Allows checking of the exact class, Used to check entity type.
65 * Cleaner method for is_a.
69 public static function isA($type)
71 return static::getClassName() === strtolower($type);
75 * Gets the class name.
78 public static function getClassName()
80 return strtolower(array_slice(explode('\\', static::class), -1, 1)[0]);
84 *Gets a limited-length version of the entities name.
88 public function getShortName($length = 25)
90 if(strlen($this->name) <= $length) return $this->name;
91 return substr($this->name, 0, $length-3) . '...';
95 * Perform a full-text search on this entity.
96 * @param string[] $fieldsToSearch
97 * @param string[] $terms
98 * @param string[] array $wheres
101 public static function fullTextSearchQuery($fieldsToSearch, $terms, $wheres = [])
104 foreach ($terms as $term) {
105 $termString .= htmlentities($term) . '* ';
107 $fields = implode(',', $fieldsToSearch);
108 $termStringEscaped = \DB::connection()->getPdo()->quote($termString);
109 $search = static::addSelect(\DB::raw('*, MATCH(name) AGAINST('.$termStringEscaped.' IN BOOLEAN MODE) AS title_relevance'));
110 $search = $search->whereRaw('MATCH(' . $fields . ') AGAINST(? IN BOOLEAN MODE)', [$termString]);
112 // Add additional where terms
113 foreach ($wheres as $whereTerm) {
114 $search->where($whereTerm[0], $whereTerm[1], $whereTerm[2]);
118 if (static::isA('page')) {
119 $search = $search->with('book', 'chapter', 'createdBy', 'updatedBy');
120 } else if (static::isA('chapter')) {
121 $search = $search->with('book');
124 return $search->orderBy('title_relevance', 'desc');
128 * Get the url for this item.
131 abstract public function getUrl();