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',
28 public function __construct(array $list)
32 // Default dynamic fields
33 $this->withField('url', fn(Entity $entity) => $entity->getUrl());
37 * Add a field to be used in the formatter, with the property using the given
38 * name and value being the return type of the given callback.
40 public function withField(string $property, callable $callback): self
42 $this->fields[$property] = $callback;
47 * Show the 'type' property in the response reflecting the entity type.
48 * EG: page, chapter, bookshelf, book
49 * To be included in results with non-pre-determined types.
51 public function withType(): self
53 $this->withField('type', fn(Entity $entity) => $entity->getType());
58 * Include tags in the formatted data.
60 public function withTags(): self
62 $this->withField('tags', fn(Entity $entity) => $entity->tags);
67 * Format the data and return an array of formatted content.
70 public function format(): array
74 foreach ($this->list as $item) {
75 $results[] = $this->formatSingle($item);
82 * Format a single entity item to a plain array.
84 protected function formatSingle(Entity $entity): array
87 $values = (clone $entity)->toArray();
89 foreach ($this->fields as $field => $callback) {
90 if (is_string($callback)) {
92 if (!isset($values[$field])) {
95 $value = $values[$field];
97 $value = $callback($entity);
98 if (is_null($value)) {
103 $result[$field] = $value;