3 namespace BookStack\Api;
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Entities\Models\Page;
8 class ApiEntityListFormatter
11 * The list to be formatted.
14 protected array $list = [];
17 * The fields to show in the formatted data.
18 * Can be a plain string array item for a direct model field (If existing on model).
19 * If the key is a string, with a callable value, the return value of the callable
20 * will be used for the resultant value. A null return value will omit the property.
21 * @var array<string|int, string|callable>
23 protected array $fields = [
36 public function __construct(array $list)
40 // Default dynamic fields
41 $this->withField('url', fn(Entity $entity) => $entity->getUrl());
45 * Add a field to be used in the formatter, with the property using the given
46 * name and value being the return type of the given callback.
48 public function withField(string $property, callable $callback): self
50 $this->fields[$property] = $callback;
55 * Show the 'type' property in the response reflecting the entity type.
56 * EG: page, chapter, bookshelf, book
57 * To be included in results with non-pre-determined types.
59 public function withType(): self
61 $this->withField('type', fn(Entity $entity) => $entity->getType());
66 * Include tags in the formatted data.
68 public function withTags(): self
70 $this->withField('tags', fn(Entity $entity) => $entity->tags);
75 * Enable the inclusion of related book and chapter titles in the response.
77 public function withRelatedData(): self
79 $this->withField('book', function (Entity $entity) {
80 if (method_exists($entity, 'book')) {
81 return $entity->book()->select(['id', 'name', 'slug'])->first();
86 $this->withField('chapter', function (Entity $entity) {
87 if ($entity instanceof Page && $entity->chapter_id) {
88 return $entity->chapter()->select(['id', 'name', 'slug'])->first();
97 * Format the data and return an array of formatted content.
100 public function format(): array
102 $this->loadRelatedData();
106 foreach ($this->list as $item) {
107 $results[] = $this->formatSingle($item);
114 * Eager load the related book and chapter data when needed.
116 protected function loadRelatedData(): void
118 $pages = collect($this->list)->filter(fn($item) => $item instanceof Page);
120 foreach ($this->list as $entity) {
121 if (method_exists($entity, 'book')) {
122 $entity->load('book');
124 if ($entity instanceof Page && $entity->chapter_id) {
125 $entity->load('chapter');
131 * Format a single entity item to a plain array.
133 protected function formatSingle(Entity $entity): array
136 $values = (clone $entity)->toArray();
138 foreach ($this->fields as $field => $callback) {
139 if (is_string($callback)) {
141 if (!isset($values[$field])) {
144 $value = $values[$field];
146 $value = $callback($entity);
147 if (is_null($value)) {
152 $result[$field] = $value;