Passed
Push — master ( c35458...7dcfdb )
by Darko
10:35
created

AdminContentController::updateContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 18
rs 9.7998
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace App\Http\Controllers\Admin;
4
5
use App\Http\Controllers\BasePageController;
6
use App\Models\Content;
7
use App\Models\User;
8
use Illuminate\Http\RedirectResponse;
9
use Illuminate\Http\Request;
10
11
class AdminContentController extends BasePageController
12
{
13
    /**
14
     * Display list of all content.
15
     *
16
     * @throws \Exception
17
     */
18
    public function index()
19
    {
20
        $this->setAdminPrefs();
21
22
        $contentList = Content::query()
23
            ->orderByRaw('contenttype, COALESCE(ordinal, 1000000)')
24
            ->get();
25
26
        $this->viewData = array_merge($this->viewData, [
27
            'contentlist' => $contentList,
28
            'meta_title' => 'Content List',
29
            'title' => 'Content List',
30
        ]);
31
32
        return view('admin.content.index', $this->viewData);
33
    }
34
35
    /**
36
     * Show form to create or edit content.
37
     *
38
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
39
     * @throws \Exception
40
     */
41
    public function create(Request $request)
42
    {
43
        $this->setAdminPrefs();
44
        $meta_title = 'Content Add';
45
46
        // Set the current action.
47
        $action = $request->input('action') ?? 'view';
48
49
        $content = [
50
            'id' => '',
51
            'title' => '',
52
            'url' => '',
53
            'body' => '',
54
            'metadescription' => '',
55
            'metakeywords' => '',
56
            'contenttype' => '',
57
            'status' => '',
58
            'ordinal' => '',
59
            'created_at' => '',
60
            'role' => '',
61
        ];
62
63
        switch ($action) {
64
            case 'add':
65
                $meta_title = 'Content Add';
66
                $content['status'] = Content::STATUS_ENABLED;
67
                $content['contenttype'] = Content::TYPE_ARTICLE;
68
                break;
69
70
            case 'submit':
71
                // Validate and add or update content
72
                if ($request->missing('id') || empty($request->input('id'))) {
73
                    $returnid = $this->addContent($request->all());
74
                } else {
75
                    $this->updateContent($request->all());
76
                    $returnid = $request->input('id');
77
                }
78
79
                return redirect('admin/content-add?id='.$returnid);
80
81
            case 'view':
82
            default:
83
                if ($request->has('id')) {
84
                    $meta_title = 'Content Edit';
85
                    $id = $request->input('id');
86
                    $content = $this->getContentById($id);
87
                }
88
                break;
89
        }
90
91
        $contenttypelist = [
92
            Content::TYPE_USEFUL => 'Useful Link',
93
            Content::TYPE_ARTICLE => 'Article',
94
            Content::TYPE_INDEX => 'Homepage'
95
        ];
96
97
        $rolelist = [
98
            Content::ROLE_EVERYONE => 'Everyone',
99
            Content::ROLE_LOGGED_IN => 'Logged in Users',
100
            Content::ROLE_ADMIN => 'Admins'
101
        ];
102
103
        $this->viewData = array_merge($this->viewData, [
104
            'status_ids' => [Content::STATUS_ENABLED, Content::STATUS_DISABLED],
105
            'status_names' => ['Enabled', 'Disabled'],
106
            'yesno_ids' => [1, 0],
107
            'yesno_names' => ['Yes', 'No'],
108
            'contenttypelist' => $contenttypelist,
109
            'content' => $content,
110
            'rolelist' => $rolelist,
111
            'meta_title' => $meta_title,
112
            'title' => $meta_title,
113
        ]);
114
115
        return view('admin.content.add', $this->viewData);
116
    }
117
118
    /**
119
     * Delete content by ID.
120
     */
121
    public function destroy(Request $request): \Illuminate\Routing\Redirector|RedirectResponse|\Illuminate\Contracts\Foundation\Application
122
    {
123
        if ($request->has('id')) {
124
            Content::query()->where('id', $request->input('id'))->delete();
125
        }
126
127
        $referrer = $request->server('HTTP_REFERER');
128
129
        return redirect()->to($referrer);
0 ignored issues
show
Bug introduced by
It seems like $referrer can also be of type array; however, parameter $path of Illuminate\Routing\Redirector::to() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

129
        return redirect()->to(/** @scrutinizer ignore-type */ $referrer);
Loading history...
130
    }
131
132
    /**
133
     * Add new content.
134
     */
135
    protected function addContent(array $data): int
136
    {
137
        // Normalize URL
138
        $data = $this->normalizeContentUrl($data);
139
140
        // If ordinal is 1, increment all existing ordinals
141
        if (($data['ordinal'] ?? 0) === 1) {
142
            Content::query()->where('ordinal', '>', 0)->increment('ordinal');
143
        }
144
145
        return Content::query()->insertGetId([
0 ignored issues
show
Bug Best Practice introduced by
The expression return App\Models\Conten...'updated_at' => now())) could return the type Illuminate\Database\Eloquent\Builder which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
146
            'role' => $data['role'] ?? Content::ROLE_EVERYONE,
147
            'title' => $data['title'] ?? '',
148
            'url' => $data['url'] ?? '/',
149
            'body' => $data['body'] ?? '',
150
            'metadescription' => $data['metadescription'] ?? '',
151
            'metakeywords' => $data['metakeywords'] ?? '',
152
            'contenttype' => $data['contenttype'] ?? Content::TYPE_ARTICLE,
153
            'status' => $data['status'] ?? Content::STATUS_ENABLED,
154
            'ordinal' => $data['ordinal'] ?? 0,
155
            'created_at' => now(),
156
            'updated_at' => now(),
157
        ]);
158
    }
159
160
    /**
161
     * Update existing content.
162
     */
163
    protected function updateContent(array $data): int
164
    {
165
        // Normalize URL
166
        $data = $this->normalizeContentUrl($data);
167
168
        return Content::query()
169
            ->where('id', $data['id'])
170
            ->update([
171
                'role' => $data['role'] ?? Content::ROLE_EVERYONE,
172
                'title' => $data['title'] ?? '',
173
                'url' => $data['url'] ?? '/',
174
                'body' => $data['body'] ?? '',
175
                'metadescription' => $data['metadescription'] ?? '',
176
                'metakeywords' => $data['metakeywords'] ?? '',
177
                'contenttype' => $data['contenttype'] ?? Content::TYPE_ARTICLE,
178
                'status' => $data['status'] ?? Content::STATUS_ENABLED,
179
                'ordinal' => $data['ordinal'] ?? 0,
180
                'updated_at' => now(),
181
            ]);
182
    }
183
184
    /**
185
     * Get content by ID for admin viewing.
186
     */
187
    protected function getContentById(int $id): ?Content
188
    {
189
        return Content::query()->find($id);
190
    }
191
192
    /**
193
     * Normalize content URL to ensure proper formatting.
194
     */
195
    protected function normalizeContentUrl(array $data): array
196
    {
197
        if (isset($data['url'])) {
198
            // Ensure URL starts with /
199
            if ($data['url'] !== '/' && !str_starts_with($data['url'], '/')) {
200
                $data['url'] = '/'.$data['url'];
201
            }
202
203
            // Ensure URL ends with /
204
            if (!str_ends_with($data['url'], '/')) {
205
                $data['url'] .= '/';
206
            }
207
        }
208
209
        return $data;
210
    }
211
}
212