Kaynağa Gözat

refactor: traits

3.x
wallo 2 yıl önce
ebeveyn
işleme
e67b079162

+ 7
- 5
app/Traits/Blamable.php Dosyayı Görüntüle

@@ -8,13 +8,15 @@ trait Blamable
8 8
 {
9 9
     public static function bootBlamable(): void
10 10
     {
11
-        static::creating(static function ($model) {
12
-            $model->created_by = Auth::check() ? Auth::id() : null;
13
-            $model->updated_by = Auth::check() ? Auth::id() : null;
11
+        $auth = Auth::check() ? Auth::id() : null;
12
+
13
+        static::creating(static function ($model) use ($auth) {
14
+            $model->created_by = $auth;
15
+            $model->updated_by = $auth;
14 16
         });
15 17
 
16
-        static::updating(static function ($model) {
17
-            $model->updated_by = Auth::check() ? Auth::id() : null;
18
+        static::updating(static function ($model) use ($auth) {
19
+            $model->updated_by = $auth;
18 20
         });
19 21
     }
20 22
 }

+ 0
- 56
app/Traits/HandlesCompanyDefaultUpdate.php Dosyayı Görüntüle

@@ -1,56 +0,0 @@
1
-<?php
2
-
3
-namespace App\Traits;
4
-
5
-use Illuminate\Database\Eloquent\Model;
6
-use Illuminate\Support\Facades\Auth;
7
-
8
-trait HandlesCompanyDefaultUpdate
9
-{
10
-    abstract protected function getRelatedEntities(): array;
11
-
12
-    protected function handleRecordUpdate(Model $record, array $data): Model
13
-    {
14
-        $relatedEntities = $this->getRelatedEntities();
15
-
16
-        $existingRecord = $record::query()->where('company_id', Auth::user()->currentCompany->id)
17
-            ->latest()
18
-            ->first();
19
-
20
-        foreach ($relatedEntities as $field => $params) {
21
-            [$modelClass, $key, $type] = array_pad($params, 3, null);
22
-
23
-            if ($existingRecord === null || ! isset($existingRecord->{$field})) {
24
-                continue;
25
-            }
26
-
27
-            if (isset($data[$field]) && $data[$field] !== $existingRecord->{$field}) {
28
-                $this->updateEnabledRecord(new $modelClass, $key, $existingRecord->{$field}, $type, false);
29
-                $this->updateEnabledRecord(new $modelClass, $key, $data[$field], $type);
30
-            }
31
-        }
32
-
33
-        $defaults = $record::query()->where('company_id', Auth::user()->currentCompany->id)->first();
34
-
35
-        if ($defaults === null) {
36
-            $defaults = $record::query()->create($data);
37
-        } else {
38
-            $defaults->update($data);
39
-        }
40
-
41
-        return $defaults;
42
-    }
43
-
44
-    protected function updateEnabledRecord(Model $record, string $key, mixed $value, ?string $type = null, bool $enabled = true): void
45
-    {
46
-        $query = $record::query()->where('company_id', Auth::user()->currentCompany->id)
47
-            ->where('enabled', ! $enabled);
48
-
49
-        if ($type !== null) {
50
-            $query = $query->where('type', $type);
51
-        }
52
-
53
-        $query->where($key, $value)
54
-            ->update(compact('enabled'));
55
-    }
56
-}

+ 20
- 54
app/Traits/HandlesResourceRecordCreation.php Dosyayı Görüntüle

@@ -3,73 +3,39 @@
3 3
 namespace App\Traits;
4 4
 
5 5
 use App\Models\User;
6
-use Filament\Support\Exceptions\Halt;
7
-use Illuminate\Auth\Access\AuthorizationException;
8
-use Illuminate\Database\Eloquent\Model;
9
-use Illuminate\Support\Facades\DB;
10
-use Illuminate\Validation\ValidationException;
11
-use Throwable;
6
+use Illuminate\Database\Eloquent\{Builder, Model};
12 7
 
13 8
 trait HandlesResourceRecordCreation
14 9
 {
15
-    /**
16
-     * @throws Halt
17
-     */
18
-    protected function handleRecordCreationWithUniqueField(array $data, Model $model, User $user, ?string $uniqueField = null, ?string $uniqueFieldValue = null): Model
10
+    protected function handleRecordCreationWithUniqueField(array $data, Model $model, User $user, ?string $uniqueField = null): Model
19 11
     {
20
-        try {
21
-            return DB::transaction(function () use ($data, $user, $model, $uniqueField, $uniqueFieldValue) {
22
-                $enabled = (bool) ($data['enabled'] ?? false);
12
+        $companyId = $user->currentCompany->id;
13
+        $shouldBeEnabled = (bool) ($data['enabled'] ?? false);
23 14
 
24
-                if ($enabled === true) {
25
-                    $this->disableExistingRecord($user->currentCompany->id, $model, $uniqueField, $uniqueFieldValue);
26
-                } else {
27
-                    $this->ensureAtLeastOneEnabled($user->currentCompany->id, $model, $enabled, $uniqueField, $uniqueFieldValue);
28
-                }
29
-
30
-                $data['enabled'] = $enabled;
31
-
32
-                return $model::create($data);
33
-            });
34
-        } catch (ValidationException) {
35
-            throw new Halt('Invalid data provided. Please check the form and try again.');
36
-        } catch (AuthorizationException) {
37
-            throw new Halt('You are not authorized to perform this action.');
38
-        } catch (Throwable) {
39
-            throw new Halt('An unexpected error occurred. Please try again.');
40
-        }
41
-    }
42
-
43
-    protected function disableExistingRecord(int $companyId, Model $model, ?string $uniqueField = null, ?string $uniqueFieldValue = null): void
44
-    {
45
-        $query = $model::query()->where('company_id', $companyId)
15
+        $query = $model::query()
16
+            ->where('company_id', $companyId)
46 17
             ->where('enabled', true);
47 18
 
48
-        if ($uniqueField && $uniqueFieldValue) {
49
-            $query->where($uniqueField, $uniqueFieldValue);
19
+        if ($uniqueField && array_key_exists($uniqueField, $data)) {
20
+            $query->where($uniqueField, $data[$uniqueField]);
50 21
         }
51 22
 
52
-        $existingEnabledRecord = $query->first();
23
+        $this->toggleRecords($query, $shouldBeEnabled);
53 24
 
54
-        if ($existingEnabledRecord !== null) {
55
-            $existingEnabledRecord->enabled = false;
56
-            $existingEnabledRecord->save();
57
-        }
25
+        $data['enabled'] = $shouldBeEnabled;
26
+        $instance = $model->newInstance($data);
27
+        $instance->save();
28
+
29
+        return $instance;
58 30
     }
59 31
 
60
-    protected function ensureAtLeastOneEnabled(int $companyId, Model $model, bool &$enabled, ?string $uniqueField = null, ?string $uniqueFieldValue = null): void
32
+    private function toggleRecords(Builder $query, bool &$shouldBeEnabled): void
61 33
     {
62
-        $query = $model::query()->where('company_id', $companyId)
63
-            ->where('enabled', true);
64
-
65
-        if ($uniqueField && $uniqueFieldValue) {
66
-            $query->where($uniqueField, $uniqueFieldValue);
67
-        }
68
-
69
-        $otherEnabledRecord = $query->first();
70
-
71
-        if ($otherEnabledRecord === null) {
72
-            $enabled = true;
34
+        if ($shouldBeEnabled) {
35
+            $existingEnabledRecord = $query->first();
36
+            $existingEnabledRecord?->update(['enabled' => false]);
37
+        } elseif ($query->doesntExist()) {
38
+            $shouldBeEnabled = true;
73 39
         }
74 40
     }
75 41
 }

+ 22
- 53
app/Traits/HandlesResourceRecordUpdate.php Dosyayı Görüntüle

@@ -3,61 +3,38 @@
3 3
 namespace App\Traits;
4 4
 
5 5
 use App\Models\User;
6
-use Filament\Support\Exceptions\Halt;
7
-use Illuminate\Auth\Access\AuthorizationException;
8 6
 use Illuminate\Database\Eloquent\{Builder, Model};
9
-use Illuminate\Support\Facades\DB;
10
-use Illuminate\Validation\ValidationException;
11
-use Throwable;
12 7
 
13 8
 trait HandlesResourceRecordUpdate
14 9
 {
15
-    /**
16
-     * @throws Halt
17
-     */
18 10
     protected function handleRecordUpdateWithUniqueField(Model $record, array $data, User $user, ?string $uniqueField = null): Model
19 11
     {
20
-        try {
21
-            return DB::transaction(function () use ($user, $uniqueField, $record, $data) {
22
-                $companyId = $user->currentCompany->id;
23
-                $oldValue = $uniqueField ? $record->{$uniqueField} : null;
24
-                $newValue = $uniqueField ? $data[$uniqueField] : null;
25
-                $enabled = (bool) ($data['enabled'] ?? false);
12
+        $companyId = $user->currentCompany->id;
13
+        $oldValue = $uniqueField ? $record->{$uniqueField} : null;
14
+        $newValue = $uniqueField ? $data[$uniqueField] : null;
15
+        $enabled = (bool) ($data['enabled'] ?? false);
26 16
 
27
-                if ($oldValue !== $newValue && $record->enabled) {
28
-                    $this->toggleRecord($companyId, $record, $uniqueField, $oldValue, false, true);
29
-                }
17
+        if ($oldValue !== $newValue && $record->getAttribute('enabled')) {
18
+            $this->toggleRecord($companyId, $record, $uniqueField, $oldValue, false, true);
19
+        }
30 20
 
31
-                if ($enabled === true) {
32
-                    $this->toggleRecord($companyId, $record, $uniqueField, $newValue, true, false);
33
-                } elseif ($enabled === false) {
34
-                    $this->ensureAtLeastOneEnabled($companyId, $record, $uniqueField, $newValue, $enabled);
35
-                }
21
+        if ($enabled === true) {
22
+            $this->toggleRecord($companyId, $record, $uniqueField, $newValue, true, false);
23
+        } elseif ($enabled === false) {
24
+            $this->ensureAtLeastOneEnabled($companyId, $record, $uniqueField, $newValue, $enabled);
25
+        }
36 26
 
37
-                $data['enabled'] = $enabled;
27
+        $data['enabled'] = $enabled;
38 28
 
39
-                return tap($record)->update($data);
40
-            });
41
-        } catch (ValidationException) {
42
-            throw new Halt('Invalid data provided. Please check the form and try again.');
43
-        } catch (AuthorizationException) {
44
-            throw new Halt('You are not authorized to perform this action.');
45
-        } catch (Throwable) {
46
-            throw new Halt('An unexpected error occurred. Please try again.');
47
-        }
29
+        return tap($record)->update($data);
48 30
     }
49 31
 
50 32
     protected function toggleRecord(int $companyId, Model $record, ?string $uniqueField, $value, bool $enabled, bool $newStatus): void
51 33
     {
52 34
         $query = $this->buildQuery($companyId, $record, $uniqueField, $value, $enabled);
53 35
 
54
-        if ($newStatus) {
55
-            $otherRecord = $query->first();
56
-
57
-            if ($otherRecord) {
58
-                $otherRecord->enabled = true;
59
-                $otherRecord->save();
60
-            }
36
+        if ($newStatus && ($otherRecord = $query->first())) {
37
+            $otherRecord->update(['enabled' => true]);
61 38
         } else {
62 39
             $query->update(['enabled' => false]);
63 40
         }
@@ -65,24 +42,16 @@ trait HandlesResourceRecordUpdate
65 42
 
66 43
     protected function buildQuery(int $companyId, Model $record, ?string $uniqueField, $value, bool $enabled): Builder
67 44
     {
68
-        $query = $record::query()->where('company_id', $companyId)
69
-            ->where('id', '!=', $record->id)
70
-            ->where('enabled', $enabled);
71
-
72
-        if ($uniqueField) {
73
-            $query->where($uniqueField, $value);
74
-        }
75
-
76
-        return $query;
45
+        return $record::query()
46
+            ->where('company_id', $companyId)
47
+            ->where('id', '!=', $record->getKey())
48
+            ->where('enabled', $enabled)
49
+            ->when($uniqueField, static fn ($q) => $q->where($uniqueField, $value));
77 50
     }
78 51
 
79 52
     protected function ensureAtLeastOneEnabled(int $companyId, Model $record, ?string $uniqueField, $value, bool &$enabled): void
80 53
     {
81 54
         $query = $this->buildQuery($companyId, $record, $uniqueField, $value, true);
82
-        $enabledCount = $query->count();
83
-
84
-        if ($enabledCount === 0) {
85
-            $enabled = true;
86
-        }
55
+        $enabled = $query->exists() ? $enabled : true;
87 56
     }
88 57
 }

Loading…
İptal
Kaydet