3 namespace BookStack\Actions;
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Entities\Models\Entity;
8 use Illuminate\Support\Collection;
13 protected $permissionService;
16 * TagRepo constructor.
18 public function __construct(Tag $tag, PermissionService $ps)
21 $this->permissionService = $ps;
25 * Get tag name suggestions from scanning existing tag names.
26 * If no search term is given the 50 most popular tag names are provided.
28 public function getNameSuggestions(?string $searchTerm): Collection
30 $query = $this->tag->newQuery()
31 ->select('*', DB::raw('count(*) as count'))
35 $query = $query->where('name', 'LIKE', $searchTerm . '%')->orderBy('name', 'desc');
37 $query = $query->orderBy('count', 'desc')->take(50);
40 $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
42 return $query->get(['name'])->pluck('name');
46 * Get tag value suggestions from scanning existing tag values.
47 * If no search is given the 50 most popular values are provided.
48 * Passing a tagName will only find values for a tags with a particular name.
50 public function getValueSuggestions(?string $searchTerm, ?string $tagName): Collection
52 $query = $this->tag->newQuery()
53 ->select('*', DB::raw('count(*) as count'))
57 $query = $query->where('value', 'LIKE', $searchTerm . '%')->orderBy('value', 'desc');
59 $query = $query->orderBy('count', 'desc')->take(50);
63 $query = $query->where('name', '=', $tagName);
66 $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
68 return $query->get(['value'])->pluck('value');
72 * Save an array of tags to an entity.
74 public function saveTagsToEntity(Entity $entity, array $tags = []): iterable
76 $entity->tags()->delete();
78 $newTags = collect($tags)->filter(function ($tag) {
79 return boolval(trim($tag['name']));
80 })->map(function ($tag) {
81 return $this->newInstanceFromInput($tag);
84 return $entity->tags()->saveMany($newTags);
88 * Create a new Tag instance from user input.
89 * Input must be an array with a 'name' and an optional 'value' key.
91 protected function newInstanceFromInput(array $input): Tag
93 $name = trim($input['name']);
94 $value = isset($input['value']) ? trim($input['value']) : '';
96 return $this->tag->newInstance(['name' => $name, 'value' => $value]);