]> git.localhorst.tv Git - alttp.git/blobdiff - app/Http/Controllers/TechniqueController.php
basic content editing
[alttp.git] / app / Http / Controllers / TechniqueController.php
index 7173f1edce28ad515b364e79d2eeb98a454dead1..59559a94a1883edb46c50c7f71e33cd33f87b072 100644 (file)
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
 
 use App\Models\Technique;
 use App\Models\TechniqueMap;
+use App\Models\TechniqueTranslation;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Http\Request;
 
@@ -41,6 +42,52 @@ class TechniqueController extends Controller
                return $tech->toJson();
        }
 
+       public function update(Request $request, Technique $content) {
+               $this->authorize('update', $content);
+
+               $validatedData = $request->validate([
+                       'attribution' => 'string',
+                       'description' => 'string',
+                       'language' => 'string|in:de,en',
+                       'parent_id' => 'integer|exists:App\\Models\\Technique,id',
+                       'short' => 'string',
+                       'title' => 'string',
+               ]);
+
+               if ($validatedData['language'] == 'en') {
+                       $this->applyLocalizedValues($validatedData, $content);
+                       $content->save();
+               } else {
+                       $translation = $this->getTranslation($content, $validatedData['language']);
+                       $this->applyLocalizedValues($validatedData, $translation);
+                       $translation->save();
+               }
+
+               $result = isset($validatedData['parent_id']) ? Technique::findOrFail($validatedData['parent_id']) : $content->fresh();
+               $result->load(['chapters', 'relations']);
+               return $result->toJson();
+       }
+
+       private function applyLocalizedValues($validatedData, $content) {
+               foreach (['attribution', 'description', 'short', 'title'] as $name) {
+                       if (isset($validatedData[$name])) {
+                               $content->{$name} = $validatedData[$name];
+                       }
+               }
+       }
+
+       private function getTranslation(Technique $content, $language) {
+               foreach ($content->translations as $translation) {
+                       if ($translation->locale == $language) {
+                               return $translation;
+                       }
+               }
+               $translation = new TechniqueTranslation();
+               $translation->technique_id = $content->id;
+               $translation->locale = $language;
+               return $translation;
+       }
+
        protected function applyFilter(Request $request, Builder $query) {
                $validatedData = $request->validate([
                        'phrase' => 'string|nullable',