1 <?php namespace BookStack\Actions;
3 use BookStack\Auth\Permissions\PermissionService;
4 use BookStack\Entities\Models\Entity;
6 use Illuminate\Support\Collection;
12 protected $permissionService;
15 * TagRepo constructor.
17 public function __construct(Tag $tag, PermissionService $ps)
20 $this->permissionService = $ps;
24 * Get tag name suggestions from scanning existing tag names.
25 * If no search term is given the 50 most popular tag names are provided.
27 public function getNameSuggestions(?string $searchTerm): Collection
29 $query = $this->tag->newQuery()
30 ->select('*', DB::raw('count(*) as count'))
34 $query = $query->where('name', 'LIKE', $searchTerm . '%')->orderBy('name', 'desc');
36 $query = $query->orderBy('count', 'desc')->take(50);
39 $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
40 return $query->get(['name'])->pluck('name');
44 * Get tag value suggestions from scanning existing tag values.
45 * If no search is given the 50 most popular values are provided.
46 * Passing a tagName will only find values for a tags with a particular name.
48 public function getValueSuggestions(?string $searchTerm, ?string $tagName): Collection
50 $query = $this->tag->newQuery()
51 ->select('*', DB::raw('count(*) as count'))
55 $query = $query->where('value', 'LIKE', $searchTerm . '%')->orderBy('value', 'desc');
57 $query = $query->orderBy('count', 'desc')->take(50);
61 $query = $query->where('name', '=', $tagName);
64 $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
65 return $query->get(['value'])->pluck('value');
69 * Save an array of tags to an entity
71 public function saveTagsToEntity(Entity $entity, array $tags = []): iterable
73 $entity->tags()->delete();
75 $newTags = collect($tags)->filter(function ($tag) {
76 return boolval(trim($tag['name']));
77 })->map(function ($tag) {
78 return $this->newInstanceFromInput($tag);
81 return $entity->tags()->saveMany($newTags);
85 * Create a new Tag instance from user input.
86 * Input must be an array with a 'name' and an optional 'value' key.
88 protected function newInstanceFromInput(array $input): Tag
90 $name = trim($input['name']);
91 $value = isset($input['value']) ? trim($input['value']) : '';
92 return $this->tag->newInstance(['name' => $name, 'value' => $value]);