-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResourceEditsController.php
More file actions
182 lines (150 loc) · 6.85 KB
/
ResourceEditsController.php
File metadata and controls
182 lines (150 loc) · 6.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreResourceEdit;
use App\Models\ComputerScienceResource;
use App\Models\ResourceEdits;
use App\Services\DataNormalizationService;
use App\Services\ResourceEditsService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Str;
use Throwable;
class ResourceEditsController extends Controller
{
public function __construct(
private DataNormalizationService $dataNormalizationService
) {}
/**
* Return the form to create a edit.
*/
public function create(string $slug)
{
$computerScienceResource = ComputerScienceResource::where('slug', $slug)->firstOrFail();
$computerScienceResource->load('user');
return Inertia::render('ResourceEdits/Create', [
'resource' => fn () => $computerScienceResource,
]);
}
/**
* Store the edits request.
*/
public function store(ComputerScienceResource $computerScienceResource, StoreResourceEdit $request)
{
$validatedData = $request->validated();
$proposedChanges = $validatedData['proposed_changes'] ?? [];
$actualChanges = $this->calculateChanges($computerScienceResource, $proposedChanges);
// Add image path to the actual changes
if (array_key_exists('image_file', $proposedChanges)) {
$actualChanges['image_path'] = null;
if (isset($proposedChanges['image_file'])) {
$path = $proposedChanges['image_file']->store('resource-edits', 'public');
$actualChanges['image_path'] = $path;
}
unset($actualChanges['image_file']);
}
if (empty($actualChanges)) {
Log::warning("Resource edit was submitted without any changes for resource ID: {$computerScienceResource->id}");
return redirect()->back()->with('warning', 'Cannot submit an edit with no changes made.');
}
$resourceEdit = ResourceEdits::create([
'user_id' => Auth::id(),
'computer_science_resource_id' => $computerScienceResource->id,
'edit_title' => $validatedData['edit_title'],
'edit_description' => $validatedData['edit_description'],
'proposed_changes' => $actualChanges,
]);
return redirect()->route('resource_edits.show', ['slug' => $resourceEdit->slug])
->with('success', 'Edits Created!');
}
/**
* Calculate the actual differences between the proposed changes and the original resource.
*/
private function calculateChanges(ComputerScienceResource $resource, array $proposedChanges): array
{
$actualChanges = [];
$normalizedProposed = $this->dataNormalizationService->normalize($proposedChanges);
$normalizedOriginal = $this->dataNormalizationService->normalize($resource->toArray());
foreach ($normalizedProposed as $key => $value) {
if (! array_key_exists($key, $normalizedOriginal) || $normalizedOriginal[$key] !== $value) {
// Use the original value from the request, not the normalized one, for file uploads.
$actualChanges[$key] = $proposedChanges[$key];
}
}
return $actualChanges;
}
public function show(string $slug)
{
$resourceEdits = ResourceEdits::where('slug', $slug)->firstOrFail();
$resourceEdits->load('computerScienceResource');
$resourceEdits->load('user');
return Inertia::render('ResourceEdits/Show', [
'editedResource' => fn () => $resourceEdits,
]);
}
public function merge(ResourceEditsService $editsService, ResourceEdits $resourceEdits)
{
if (! $editsService->canMergeEdits($resourceEdits)) {
return redirect()->back()->with('warning', 'Not enough approvals');
}
DB::beginTransaction();
try {
$resource = ComputerScienceResource::findOrFail($resourceEdits->computer_science_resource_id);
// Go through each property in proposed_changes, and if it exists. then set the value
$changes = $resourceEdits->proposed_changes;
$proposedFields = ['name', 'description', 'page_url', 'platforms', 'difficulty', 'pricing'];
foreach ($proposedFields as $field) {
if (array_key_exists($field, $changes)) {
$resource->$field = $changes[$field];
}
}
if (array_key_exists('image_path', $changes)) {
// TODO: Remove the old photo resource photo, will be handled in a cron job,
//
// photo image_url history can be viewed via activity log.
//
$destPath = null;
if (isset($changes['image_path'])) {
// Copy the new file from 'resource-edits' to 'resource' (do not delete the old one)
$sourcePath = $changes['image_path'];
$fileExtension = pathinfo($sourcePath, PATHINFO_EXTENSION);
$newFileName = Str::random(40).'.'.$fileExtension;
$destPath = 'resource/'.$newFileName;
// TODO: FIGURE OUT WHAT TO DO IN CASE OF EXCEPTION IN CODE FROM LATER STEPS
Storage::disk('public')->move($sourcePath, $destPath);
}
// Update image_path in DB
$resource->image_path = $destPath;
}
$resource->save();
$proposedTagFields = ['topic_tags', 'programming_language_tags', 'general_tags'];
foreach ($proposedTagFields as $field) {
if (array_key_exists($field, $changes)) {
$resource->$field = $changes[$field];
}
}
// Delete the edit since we successfully merged the changes
$resourceEdits->delete();
DB::commit();
Log::info('Resource edit merged', [
'resource_id' => $resource->id,
'resource_edit_id' => $resourceEdits->id,
'user_id' => Auth::id(),
'edit_title' => $resourceEdits->edit_title,
'edit_description' => $resourceEdits->edit_description,
]);
return redirect(route('resources.show', ['slug' => $resource->slug]))
->with('success', 'Successfully Merged Changes!');
} catch (Throwable $e) {
DB::rollBack();
Log::critical('Failed to merge resource edits', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'resource_edit_id' => $resourceEdits->id,
]);
return redirect()->back()->withErrors(['error' => 'Failed to merge resource edits. Please try again.']);
}
}
}