3 namespace BookStack\Activity\Tools;
5 use BookStack\Activity\Models\Tag;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
10 class TagClassGenerator
12 public function __construct(
13 protected Entity $entity
20 public function generate(): array
23 $tags = $this->entity->tags->all();
25 foreach ($tags as $tag) {
26 array_push($classes, ...$this->generateClassesForTag($tag));
29 if ($this->entity instanceof BookChild && userCan('view', $this->entity->book)) {
30 $bookTags = $this->entity->book->tags;
31 foreach ($bookTags as $bookTag) {
32 array_push($classes, ...$this->generateClassesForTag($bookTag, 'book-'));
36 if ($this->entity instanceof Page && $this->entity->chapter && userCan('view', $this->entity->chapter)) {
37 $chapterTags = $this->entity->chapter->tags;
38 foreach ($chapterTags as $chapterTag) {
39 array_push($classes, ...$this->generateClassesForTag($chapterTag, 'chapter-'));
43 return array_unique($classes);
46 public function generateAsString(): string
48 return implode(' ', $this->generate());
54 protected function generateClassesForTag(Tag $tag, string $prefix = ''): array
57 $name = $this->normalizeTagClassString($tag->name);
58 $value = $this->normalizeTagClassString($tag->value);
59 $classes[] = "{$prefix}tag-name-{$name}";
61 $classes[] = "{$prefix}tag-value-{$value}";
62 $classes[] = "{$prefix}tag-pair-{$name}-{$value}";
67 protected function normalizeTagClassString(string $value): string
69 $value = str_replace(' ', '', strtolower($value));
70 $value = str_replace('-', '', strtolower($value));