1 <?php namespace BookStack\Repos;
3 use BookStack\Attribute;
5 use BookStack\Services\PermissionService;
9 * @package BookStack\Repos
16 protected $permissionService;
19 * AttributeRepo constructor.
20 * @param Attribute $attr
22 * @param PermissionService $ps
24 public function __construct(Attribute $attr, Entity $ent, PermissionService $ps)
26 $this->attribute = $attr;
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('attributes');
41 $searchQuery = $this->permissionService->enforceEntityRestrictions($searchQuery, $action);
42 return $searchQuery->first();
46 * Get all attributes 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();
56 return $entity->attributes;
60 * Get attribute name suggestions from scanning existing attribute names.
64 public function getNameSuggestions($searchTerm)
66 if ($searchTerm === '') return [];
67 $query = $this->attribute->where('name', 'LIKE', $searchTerm . '%')->groupBy('name')->orderBy('name', 'desc');
68 $query = $this->permissionService->filterRestrictedEntityRelations($query, 'attributes', 'entity_id', 'entity_type');
69 return $query->get(['name'])->pluck('name');
73 * Save an array of attributes to an entity
74 * @param Entity $entity
75 * @param array $attributes
76 * @return array|\Illuminate\Database\Eloquent\Collection
78 public function saveAttributesToEntity(Entity $entity, $attributes = [])
80 $entity->attributes()->delete();
82 foreach ($attributes as $attribute) {
83 $newAttributes[] = $this->newInstanceFromInput($attribute);
86 return $entity->attributes()->saveMany($newAttributes);
90 * Create a new Attribute instance from user input.
94 protected function newInstanceFromInput($input)
96 $name = trim($input['name']);
97 $value = isset($input['value']) ? trim($input['value']) : '';
98 // Any other modification or cleanup required can go here
99 $values = ['name' => $name, 'value' => $value];
100 return $this->attribute->newInstance($values);