]> BookStack Code Mirror - bookstack/blobdiff - app/Api/ApiEntityListFormatter.php
Added include func for search api
[bookstack] / app / Api / ApiEntityListFormatter.php
index 436d66d598e8f2fb86fc27622f9016900b2a7c8e..23fa8e6ea7249274759e5b4fa98cf49b27a50a8a 100644 (file)
@@ -3,6 +3,7 @@
 namespace BookStack\Api;
 
 use BookStack\Entities\Models\Entity;
+use BookStack\Entities\Models\Page;
 
 class ApiEntityListFormatter
 {
@@ -12,6 +13,11 @@ class ApiEntityListFormatter
      */
     protected array $list = [];
 
+    /**
+     * Whether to include related titles in the response.
+     */
+    protected bool $includeRelatedTitles = false;
+
     /**
      * The fields to show in the formatted data.
      * Can be a plain string array item for a direct model field (If existing on model).
@@ -20,8 +26,16 @@ class ApiEntityListFormatter
      * @var array<string|int, string|callable>
      */
     protected array $fields = [
-        'id', 'name', 'slug', 'book_id', 'chapter_id', 'draft',
-        'template', 'priority', 'created_at', 'updated_at',
+        'id',
+        'name',
+        'slug',
+        'book_id',
+        'chapter_id',
+        'draft',
+        'template',
+        'priority',
+        'created_at',
+        'updated_at',
     ];
 
     public function __construct(array $list)
@@ -62,6 +76,30 @@ class ApiEntityListFormatter
         return $this;
     }
 
+    /**
+     * Enable the inclusion of related book and chapter titles in the response.
+     */
+    public function withRelatedTitles(): self
+    {
+        $this->includeRelatedTitles = true;
+
+        $this->withField('book_title', function (Entity $entity) {
+            if (method_exists($entity, 'book')) {
+                return $entity->book?->name;
+            }
+            return null;
+        });
+
+        $this->withField('chapter_title', function (Entity $entity) {
+            if ($entity instanceof Page && $entity->chapter_id) {
+                return optional($entity->getAttribute('chapter'))->name;
+            }
+            return null;
+        });
+
+        return $this;
+    }
+
     /**
      * Format the data and return an array of formatted content.
      * @return array[]