1 <?php namespace BookStack\Repos;
5 use BookStack\Services\PermissionService;
9 * @package BookStack\Repos
16 protected $permissionService;
19 * TagRepo constructor.
22 * @param PermissionService $ps
24 public function __construct(Tag $attr, Entity $ent, PermissionService $ps)
28 $this->permissionService = $ps;
32 * Get an entity instance of its particular type.
35 * @param string $action
37 public function getEntity($entityType, $entityId, $action = 'view')
39 $entityInstance = $this->entity->getEntityInstance($entityType);
40 $searchQuery = $entityInstance->where('id', '=', $entityId)->with('tags');
41 $searchQuery = $this->permissionService->enforceEntityRestrictions($searchQuery, $action);
42 return $searchQuery->first();
46 * Get all tags for a particular entity.
47 * @param string $entityType
48 * @param int $entityId
51 public function getForEntity($entityType, $entityId)
53 $entity = $this->getEntity($entityType, $entityId);
54 if ($entity === null) return collect();
60 * Get tag name suggestions from scanning existing tag names.
64 public function getNameSuggestions($searchTerm)
66 if ($searchTerm === '') return [];
67 $query = $this->tag->where('name', 'LIKE', $searchTerm . '%')->groupBy('name')->orderBy('name', 'desc');
68 $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
69 return $query->get(['name'])->pluck('name');
73 * Get tag value suggestions from scanning existing tag values.
78 public function getValueSuggestions($searchTerm, $tagName = false)
80 if ($searchTerm === '') return [];
81 $query = $this->tag->where('value', 'LIKE', $searchTerm . '%')->groupBy('value')->orderBy('value', 'desc');
82 if ($tagName !== false) {
83 $query = $query->where('name', '=', $tagName);
85 $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
86 return $query->get(['value'])->pluck('value');
90 * Save an array of tags to an entity
91 * @param Entity $entity
93 * @return array|\Illuminate\Database\Eloquent\Collection
95 public function saveTagsToEntity(Entity $entity, $tags = [])
97 $entity->tags()->delete();
99 foreach ($tags as $tag) {
100 if (trim($tag['name']) === '') continue;
101 $newTags[] = $this->newInstanceFromInput($tag);
104 return $entity->tags()->saveMany($newTags);
108 * Create a new Tag instance from user input.
112 protected function newInstanceFromInput($input)
114 $name = trim($input['name']);
115 $value = isset($input['value']) ? trim($input['value']) : '';
116 // Any other modification or cleanup required can go here
117 $values = ['name' => $name, 'value' => $value];
118 return $this->tag->newInstance($values);