]> BookStack Code Mirror - bookstack/blobdiff - app/Api/ApiEntityListFormatter.php
Updated translations with latest Crowdin changes (#5695)
[bookstack] / app / Api / ApiEntityListFormatter.php
index 7d00834e5d1040c47eb56abe9c123674f4e683eb..3c94d96ee600789ce212296b1ba31bb49059f8cb 100644 (file)
@@ -2,7 +2,9 @@
 
 namespace BookStack\Api;
 
+use BookStack\Entities\Models\BookChild;
 use BookStack\Entities\Models\Entity;
+use BookStack\Entities\Models\Page;
 
 class ApiEntityListFormatter
 {
@@ -10,7 +12,7 @@ class ApiEntityListFormatter
      * The list to be formatted.
      * @var Entity[]
      */
-    protected $list = [];
+    protected array $list = [];
 
     /**
      * The fields to show in the formatted data.
@@ -19,10 +21,17 @@ class ApiEntityListFormatter
      * will be used for the resultant value. A null return value will omit the property.
      * @var array<string|int, string|callable>
      */
-    protected $fields = [
-        'id', 'name', 'slug', 'book_id', 'chapter_id',
-        'draft', 'template', 'created_at', 'updated_at',
-        'priority'
+    protected array $fields = [
+        'id',
+        'name',
+        'slug',
+        'book_id',
+        'chapter_id',
+        'draft',
+        'template',
+        'priority',
+        'created_at',
+        'updated_at',
     ];
 
     public function __construct(array $list)
@@ -63,6 +72,28 @@ class ApiEntityListFormatter
         return $this;
     }
 
+    /**
+     * Include parent book/chapter info in the formatted data.
+     */
+    public function withParents(): self
+    {
+        $this->withField('book', function (Entity $entity) {
+            if ($entity instanceof BookChild && $entity->book) {
+                return $entity->book->only(['id', 'name', 'slug']);
+            }
+            return null;
+        });
+
+        $this->withField('chapter', function (Entity $entity) {
+            if ($entity instanceof Page && $entity->chapter) {
+                return $entity->chapter->only(['id', 'name', 'slug']);
+            }
+            return null;
+        });
+
+        return $this;
+    }
+
     /**
      * Format the data and return an array of formatted content.
      * @return array[]