3 namespace BookStack\Api;
5 use BookStack\Entities\Models\Entity;
7 class ApiEntityListFormatter
10 * The list to be formatted.
16 * The fields to show in the formatted data.
17 * Can be a plain string array item for a direct model field (If existing on model).
18 * If the key is a string, with a callable value, the return value of the callable
19 * will be used for the resultant value. A null return value will omit the property.
20 * @var array<string|int, string|callable>
23 'id', 'name', 'slug', 'book_id', 'chapter_id',
24 'draft', 'template', 'created_at', 'updated_at',
27 public function __construct(array $list)
31 // Default dynamic fields
32 $this->withField('url', fn(Entity $entity) => $entity->getUrl());
36 * Add a field to be used in the formatter, with the property using the given
37 * name and value being the return type of the given callback.
39 public function withField(string $property, callable $callback): self
41 $this->fields[$property] = $callback;
46 * Show the 'type' property in the response reflecting the entity type.
47 * EG: page, chapter, bookshelf, book
48 * To be included in results with non-pre-determined types.
50 public function withType(): self
52 $this->withField('type', fn(Entity $entity) => $entity->getType());
57 * Include tags in the formatted data.
59 public function withTags(): self
61 $this->withField('tags', fn(Entity $entity) => $entity->tags);
66 * Format the data and return an array of formatted content.
69 public function format(): array
73 foreach ($this->list as $item) {
74 $results[] = $this->formatSingle($item);
81 * Format a single entity item to a plain array.
83 protected function formatSingle(Entity $entity): array
86 $values = (clone $entity)->toArray();
88 foreach ($this->fields as $field => $callback) {
89 if (is_string($callback)) {
91 if (!isset($values[$field])) {
94 $value = $values[$field];
96 $value = $callback($entity);
97 if (is_null($value)) {
102 $result[$field] = $value;