]> BookStack Code Mirror - bookstack/commitdiff
Applied another set of static analysis improvements
authorDan Brown <redacted>
Sat, 20 Nov 2021 14:03:56 +0000 (14:03 +0000)
committerDan Brown <redacted>
Sat, 20 Nov 2021 14:03:56 +0000 (14:03 +0000)
18 files changed:
app/Actions/ActivityService.php
app/Auth/Access/ExternalBaseUserProvider.php
app/Auth/Permissions/RolePermission.php
app/Console/Commands/RegenerateSearch.php
app/Entities/Models/Deletion.php
app/Entities/Models/Entity.php
app/Entities/Models/PageRevision.php
app/Entities/Repos/BaseRepo.php
app/Entities/Repos/PageRepo.php
app/Entities/Tools/BookContents.php
app/Entities/Tools/NextPreviousContentLocator.php
app/Entities/Tools/PageContent.php
app/Entities/Tools/SearchIndex.php
app/Entities/Tools/SearchRunner.php
app/Entities/Tools/SiblingFetcher.php
app/Entities/Tools/TrashCan.php
app/Http/Controllers/RecycleBinController.php
app/Interfaces/Deletable.php [new file with mode: 0644]

index bc7a6b6b7c3353f39384ae73d88eaca284d5ed41..33ed44b32efa0dd64715af5a227e90a642cc0574 100644 (file)
@@ -4,6 +4,7 @@ namespace BookStack\Actions;
 
 use BookStack\Auth\Permissions\PermissionService;
 use BookStack\Auth\User;
+use BookStack\Entities\Models\Book;
 use BookStack\Entities\Models\Chapter;
 use BookStack\Entities\Models\Entity;
 use BookStack\Entities\Models\Page;
@@ -100,13 +101,13 @@ class ActivityService
      */
     public function entityActivity(Entity $entity, int $count = 20, int $page = 1): array
     {
-        /** @var [string => int[]] $queryIds */
+        /** @var array<string, int[]> $queryIds */
         $queryIds = [$entity->getMorphClass() => [$entity->id]];
 
-        if ($entity->isA('book')) {
+        if ($entity instanceof Book) {
             $queryIds[(new Chapter())->getMorphClass()] = $entity->chapters()->visible()->pluck('id');
         }
-        if ($entity->isA('book') || $entity->isA('chapter')) {
+        if ($entity instanceof Book || $entity instanceof Chapter) {
             $queryIds[(new Page())->getMorphClass()] = $entity->pages()->visible()->pluck('id');
         }
 
index fde610c3e18746f33b616c4b309a91327eb77d91..dc765ddc53a587dd399f70f7cf27ac12eae386c7 100644 (file)
@@ -4,6 +4,7 @@ namespace BookStack\Auth\Access;
 
 use Illuminate\Contracts\Auth\Authenticatable;
 use Illuminate\Contracts\Auth\UserProvider;
+use Illuminate\Database\Eloquent\Model;
 
 class ExternalBaseUserProvider implements UserProvider
 {
@@ -16,8 +17,6 @@ class ExternalBaseUserProvider implements UserProvider
 
     /**
      * LdapUserProvider constructor.
-     *
-     * @param $model
      */
     public function __construct(string $model)
     {
@@ -27,7 +26,7 @@ class ExternalBaseUserProvider implements UserProvider
     /**
      * Create a new instance of the model.
      *
-     * @return \Illuminate\Database\Eloquent\Model
+     * @return Model
      */
     public function createModel()
     {
@@ -41,7 +40,7 @@ class ExternalBaseUserProvider implements UserProvider
      *
      * @param mixed $identifier
      *
-     * @return \Illuminate\Contracts\Auth\Authenticatable|null
+     * @return Authenticatable|null
      */
     public function retrieveById($identifier)
     {
@@ -54,7 +53,7 @@ class ExternalBaseUserProvider implements UserProvider
      * @param mixed  $identifier
      * @param string $token
      *
-     * @return \Illuminate\Contracts\Auth\Authenticatable|null
+     * @return Authenticatable|null
      */
     public function retrieveByToken($identifier, $token)
     {
@@ -64,7 +63,7 @@ class ExternalBaseUserProvider implements UserProvider
     /**
      * Update the "remember me" token for the given user in storage.
      *
-     * @param \Illuminate\Contracts\Auth\Authenticatable $user
+     * @param Authenticatable $user
      * @param string                                     $token
      *
      * @return void
@@ -79,7 +78,7 @@ class ExternalBaseUserProvider implements UserProvider
      *
      * @param array $credentials
      *
-     * @return \Illuminate\Contracts\Auth\Authenticatable|null
+     * @return Authenticatable|null
      */
     public function retrieveByCredentials(array $credentials)
     {
@@ -94,7 +93,7 @@ class ExternalBaseUserProvider implements UserProvider
     /**
      * Validate a user against the given credentials.
      *
-     * @param \Illuminate\Contracts\Auth\Authenticatable $user
+     * @param Authenticatable $user
      * @param array                                      $credentials
      *
      * @return bool
index 0a0e6ff17f531a3d16b3fab542716a84487dbc94..f34de917c07a425e7bf689c728d2edbe8ed2bfab 100644 (file)
@@ -4,6 +4,7 @@ namespace BookStack\Auth\Permissions;
 
 use BookStack\Auth\Role;
 use BookStack\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 
 /**
  * @property int $id
@@ -13,19 +14,15 @@ class RolePermission extends Model
     /**
      * The roles that belong to the permission.
      */
-    public function roles()
+    public function roles(): BelongsToMany
     {
         return $this->belongsToMany(Role::class, 'permission_role', 'permission_id', 'role_id');
     }
 
     /**
      * Get the permission object by name.
-     *
-     * @param $name
-     *
-     * @return mixed
      */
-    public static function getByName($name)
+    public static function getByName(string $name): ?RolePermission
     {
         return static::where('name', '=', $name)->first();
     }
index 62ee88fc0f10fe237b0b8d2c08663bc6de72040a..20e3fc7983f8bd7ff472758d20f3693841864ec5 100644 (file)
@@ -49,7 +49,7 @@ class RegenerateSearch extends Command
             DB::setDefaultConnection($this->option('database'));
         }
 
-        $this->searchIndex->indexAllEntities(function (Entity $model, int $processed, int $total) {
+        $this->searchIndex->indexAllEntities(function (Entity $model, int $processed, int $total): void {
             $this->info('Indexed ' . class_basename($model) . ' entries (' . $processed . '/' . $total . ')');
         });
 
index 3face841b1890cdafc398c3374ec7d217b50675e..97abb87ffc5ea83c7b5773d35ede202cd396e5fa 100644 (file)
@@ -3,13 +3,14 @@
 namespace BookStack\Entities\Models;
 
 use BookStack\Auth\User;
+use BookStack\Interfaces\Deletable;
 use BookStack\Interfaces\Loggable;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
 use Illuminate\Database\Eloquent\Relations\MorphTo;
 
 /**
- * @property Model $deletable
+ * @property Deletable $deletable
  */
 class Deletion extends Model implements Loggable
 {
index 4c4e55bb83f29319962e0797538b3c7bc58af143..eccec40b592e829f0573756c7de06cff50e2dbc1 100644 (file)
@@ -12,6 +12,7 @@ use BookStack\Auth\Permissions\JointPermission;
 use BookStack\Entities\Tools\SearchIndex;
 use BookStack\Entities\Tools\SlugGenerator;
 use BookStack\Facades\Permissions;
+use BookStack\Interfaces\Deletable;
 use BookStack\Interfaces\Favouritable;
 use BookStack\Interfaces\Sluggable;
 use BookStack\Interfaces\Viewable;
@@ -44,7 +45,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
  * @method static Builder withLastView()
  * @method static Builder withViewCount()
  */
-abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
+abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable
 {
     use SoftDeletes;
     use HasCreatorAndUpdater;
@@ -210,6 +211,7 @@ abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
     /**
      * Check if this instance or class is a certain type of entity.
      * Examples of $type are 'page', 'book', 'chapter'.
+     * @deprecated Use instanceof instead.
      */
     public static function isA(string $type): bool
     {
index 6856c23e1674ee27cb939fbea32c07fe69435a08..a3c4379a6a68bb3e0cc2af94a02c354f94bcee33 100644 (file)
@@ -84,11 +84,9 @@ class PageRevision extends Model
      * Included here to align with entities in similar use cases.
      * (Yup, Bit of an awkward hack).
      *
-     * @param $type
-     *
-     * @return bool
+     * @deprecated Use instanceof instead.
      */
-    public static function isA($type)
+    public static function isA(string $type): bool
     {
         return $type === 'revision';
     }
index 5699185031b12129de12f622c375f4a48980b4ac..6b29dad7b547623058aef4b84760cfc56ef7302f 100644 (file)
@@ -67,10 +67,12 @@ class BaseRepo
     /**
      * Update the given items' cover image, or clear it.
      *
+     * @param Entity&HasCoverImage $entity
+     *
      * @throws ImageUploadException
      * @throws \Exception
      */
-    public function updateCoverImage(HasCoverImage $entity, ?UploadedFile $coverImage, bool $removeImage = false)
+    public function updateCoverImage($entity, ?UploadedFile $coverImage, bool $removeImage = false)
     {
         if ($coverImage) {
             $this->imageRepo->destroyImage($entity->cover);
index f66f2beb8ce16d9930b904c2e9c5e969d27fc7ae..ed5534f082073677415db00b6a225f87b76bbe57 100644 (file)
@@ -290,6 +290,8 @@ class PageRepo
     public function restoreRevision(Page $page, int $revisionId): Page
     {
         $page->revision_count++;
+
+        /** @var PageRevision $revision */
         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
 
         $page->fill($revision->toArray());
@@ -334,7 +336,8 @@ class PageRepo
         }
 
         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
-        $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
+        $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
+        $page->changeBook($newBookId);
         $page->rebuildPermissions();
 
         Activity::addForEntity($page, ActivityType::PAGE_MOVE);
@@ -406,7 +409,7 @@ class PageRepo
      */
     protected function changeParent(Page $page, Entity $parent)
     {
-        $book = ($parent instanceof Book) ? $parent : $parent->book;
+        $book = ($parent instanceof Chapter) ? $parent->book : $parent;
         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
         $page->save();
 
@@ -467,6 +470,7 @@ class PageRepo
     {
         $parent = $page->getParent();
         if ($parent instanceof Chapter) {
+            /** @var ?Page $lastPage */
             $lastPage = $parent->pages('desc')->first();
 
             return $lastPage ? $lastPage->priority + 1 : 0;
index 8622d5e129486f78112e1b23867de77a4a4b7c0c..9b2190ca23e89b1e4b439106e8e58240dd2dedac 100644 (file)
@@ -67,7 +67,7 @@ class BookContents
         $all->each(function (Entity $entity) use ($renderPages) {
             $entity->setRelation('book', $this->book);
 
-            if ($renderPages && $entity->isA('page')) {
+            if ($renderPages && $entity instanceof Page) {
                 $entity->html = (new PageContent($entity))->render();
             }
         });
@@ -151,7 +151,7 @@ class BookContents
 
         $priorityChanged = intval($model->priority) !== intval($sortMapItem->sort);
         $bookChanged = intval($model->book_id) !== intval($sortMapItem->book);
-        $chapterChanged = ($sortMapItem->type === 'page') && intval($model->chapter_id) !== $sortMapItem->parentChapter;
+        $chapterChanged = ($model instanceof Page) && intval($model->chapter_id) !== $sortMapItem->parentChapter;
 
         if ($bookChanged) {
             $model->changeBook($sortMapItem->book);
index f70abd9b6fb37b40d4522300d32b90b9d3ac3a83..54b575935be790fc382cb84d136b1bf27c1eb06f 100644 (file)
@@ -64,7 +64,7 @@ class NextPreviousContentLocator
         /** @var Entity $item */
         foreach ($bookTree->all() as $item) {
             $flatOrdered->push($item);
-            $childPages = $item->visible_pages ?? [];
+            $childPages = $item->getAttribute('visible_pages') ?? [];
             $flatOrdered = $flatOrdered->concat($childPages);
         }
 
index 45bfe8fa1740bf0c9c33cbd2432967a74cd73547..a6ba352a834c0f5f9709c03ec79fe42f326d2138 100644 (file)
@@ -156,7 +156,7 @@ class PageContent
     /**
      * Parse a base64 image URI into the data and extension.
      *
-     * @return array{extension: array, data: string}
+     * @return array{extension: string, data: string}
      */
     protected function parseBase64ImageUri(string $uri): array
     {
@@ -230,7 +230,7 @@ class PageContent
      */
     protected function setUniqueId(\DOMNode $element, array &$idMap): array
     {
-        if (get_class($element) !== 'DOMElement') {
+        if (!$element instanceof \DOMElement) {
             return ['', ''];
         }
 
@@ -242,7 +242,7 @@ class PageContent
             return [$existingId, $existingId];
         }
 
-        // Create an unique id for the element
+        // Create a unique id for the element
         // Uses the content as a basis to ensure output is the same every time
         // the same content is passed through.
         $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
index d748c1695d46369c314eb6f6f121b0bc9dce3649..79139ec24062433ed136bebd77cd57fd130bfd30 100644 (file)
@@ -67,7 +67,7 @@ class SearchIndex
      * - The number that have been processed so far.
      * - The total number of that model to be processed.
      *
-     * @param callable(Entity, int, int)|null $progressCallback
+     * @param callable(Entity, int, int):void|null $progressCallback
      */
     public function indexAllEntities(?callable $progressCallback = null)
     {
index 04f4c57681a88e29b38bed639362a68127b8381e..a4f1314820d1d39abc9f62d20f715a67901845d4 100644 (file)
@@ -9,6 +9,7 @@ use BookStack\Entities\Models\BookChild;
 use BookStack\Entities\Models\Entity;
 use BookStack\Entities\Models\Page;
 use BookStack\Entities\Models\SearchTerm;
+use Illuminate\Database\Connection;
 use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
 use Illuminate\Database\Eloquent\Collection as EloquentCollection;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -356,7 +357,9 @@ class SearchRunner
                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
                     // search the value as a string which prevents being able to do number-based operations
                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
-                    $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
+                    /** @var Connection $connection */
+                    $connection = $query->getConnection();
+                    $tagValue = (float) trim($connection->getPdo()->quote($tagValue), "'");
                     $query->whereRaw("value ${tagOperator} ${tagValue}");
                 } else {
                     $query->where('value', $tagOperator, $tagValue);
index 249e0038eeb8d086c25b3c308a973c265d1c628d..617ef4a620df810f9369e8fd8f6e49abed461304 100644 (file)
@@ -5,6 +5,7 @@ namespace BookStack\Entities\Tools;
 use BookStack\Entities\EntityProvider;
 use BookStack\Entities\Models\Book;
 use BookStack\Entities\Models\Bookshelf;
+use BookStack\Entities\Models\Chapter;
 use BookStack\Entities\Models\Page;
 use Illuminate\Support\Collection;
 
@@ -24,7 +25,7 @@ class SiblingFetcher
         }
 
         // Page in book or chapter
-        if (($entity instanceof Page && !$entity->chapter) || $entity->isA('chapter')) {
+        if (($entity instanceof Page && !$entity->chapter) || $entity instanceof Chapter) {
             $entities = $entity->book->getDirectChildren();
         }
 
index 8327c948931b5567e80fc3d6ca5728c82533fa87..fcf933726d2e0b6d8320ef0e9b72ab07b989dbc3 100644 (file)
@@ -235,13 +235,15 @@ class TrashCan
     {
         $shouldRestore = true;
         $restoreCount = 0;
-        $parent = $deletion->deletable->getParent();
 
-        if ($parent && $parent->trashed()) {
-            $shouldRestore = false;
+        if ($deletion->deletable instanceof Entity) {
+            $parent = $deletion->deletable->getParent();
+            if ($parent && $parent->trashed()) {
+                $shouldRestore = false;
+            }
         }
 
-        if ($shouldRestore) {
+        if ($deletion->deletable instanceof Entity && $shouldRestore) {
             $restoreCount = $this->restoreEntity($deletion->deletable);
         }
 
index 1736023a5047db5d7ed9049ac7fd50d855f805f5..1cffb161cc8a3f94e68d8d6eaeb72ab2e10d7730 100644 (file)
@@ -58,6 +58,7 @@ class RecycleBinController extends Controller
                 $searching = false;
             }
         }
+
         /** @var ?Deletion $parentDeletion */
         $parentDeletion = ($currentDeletable === $deletion->deletable) ? null : $currentDeletable->deletions()->first();
 
diff --git a/app/Interfaces/Deletable.php b/app/Interfaces/Deletable.php
new file mode 100644 (file)
index 0000000..ca59e04
--- /dev/null
@@ -0,0 +1,14 @@
+<?php
+
+namespace BookStack\Interfaces;
+
+use Illuminate\Database\Eloquent\Relations\MorphMany;
+
+/**
+ * A model that can be deleted in a manner that deletions
+ * are tracked to be part of the recycle bin system.
+ */
+interface Deletable
+{
+    public function deletions(): MorphMany;
+}
\ No newline at end of file