Completed
Push — master ( 3c954f...4e1888 )
by Davide
05:38
created

PostController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 319
Duplicated Lines 0 %

Test Coverage

Coverage 70.83%

Importance

Changes 0
Metric Value
eloc 93
dl 0
loc 319
ccs 68
cts 96
cp 0.7083
rs 10
c 0
b 0
f 0
wmc 15

11 Methods

Rating   Name   Duplication   Size   Complexity  
A store() 0 21 2
A __construct() 0 5 1
A index() 0 46 3
A create() 0 6 1
A saveOnDb() 0 30 2
A destroy() 0 6 1
A update() 0 15 1
A postBySlug() 0 9 1
A show() 0 68 1
A edit() 0 7 1
A postdata() 0 5 1
1
<?php
2
3
namespace DavideCasiraghi\LaravelSmartBlog\Http\Controllers;
4
5
use Validator;
6
use Illuminate\Support\Str;
7
use Illuminate\Http\Request;
8
// use App\Classes\CardClass;
9
use Illuminate\Support\Facades\DB;
10
use Illuminate\Support\Facades\App;
11
// use App\Classes\ColumnsClass;
12
// use App\Classes\GalleryClass;
13
// use App\Classes\AccordionClass;
14
// use App\Classes\StatsDonateClass;
15
// use App\Classes\PaypalButtonClass;
16
use DavideCasiraghi\LaravelSmartBlog\Models\Post;
17
// use App\Classes\CardsCarouselClass;
18
use DavideCasiraghi\LaravelSmartBlog\Models\Category;
19
// use App\Classes\CommunityGoalsClass;
20
use DavideCasiraghi\LaravelCards\Facades\LaravelCards;
21
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
22
use DavideCasiraghi\ResponsiveGallery\Facades\ResponsiveGallery;
23
use DavideCasiraghi\BootstrapAccordion\Facades\BootstrapAccordion;
24
use DavideCasiraghi\LaravelJumbotronImages\Facades\LaravelJumbotronImages;
25
26
class PostController extends Controller
27
{
28 11
    public function __construct()
29
    {
30
31
        //Restrict the access to this resource just to logged in users except show view
32 11
        $this->middleware('admin', ['except' => ['show', 'postBySlug']]);
33 11
    }
34
35
    /***************************************************************************/
36
37
    /**
38
     * Display a listing of the resource.
39
     * @param  \Illuminate\Http\Request  $request
40
     * @return \Illuminate\Http\Response
41
     */
42 5
    public function index(Request $request)
43
    {
44
        //$categories = Category::getCategoriesArray();
45 5
        $categories = Category::listsTranslations('name')->pluck('name', 'id');
46
47 5
        $searchKeywords = $request->input('keywords');
48 5
        $searchCategory = $request->input('category_id');
49
50
        // Returns all countries having translations
51
        //dd(Post::translated()->get());
52
53
        // Countries available for translations
54 5
        $countriesAvailableForTranslations = LaravelLocalization::getSupportedLocales();
55
        //DB::enableQueryLog();
56
57 5
        if ($searchKeywords || $searchCategory) {
58
            $posts = Post::
59
                select('post_translations.post_id AS id', 'post_translations.title AS title', 'status', 'featured', 'introimage', 'introimage_alt', 'category_id', 'locale')
60
                ->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
61
62
                ->when($searchKeywords, function ($query, $searchKeywords) {
63
                    return $query->where('post_translations.locale', '=', 'en')
64
                                 ->where(function ($query) use ($searchKeywords) {
65
                                     $query->where('post_translations.title', $searchKeywords)
66
                                                  ->orWhere('post_translations.title', 'like', '%'.$searchKeywords.'%');
67
                                 });
68
                })
69
                ->when($searchCategory, function ($query, $searchCategory) {
70
                    return $query->where('post_translations.locale', '=', 'en')
71
                                 ->where(function ($query) use ($searchCategory) {
72
                                     $query->where('category_id', '=', $searchCategory);
73
                                 });
74
                })
75
                ->paginate(20);
76
        } else {
77 5
            $posts = Post::listsTranslations('title')->select('posts.id', 'title', 'category_id', 'status', 'featured', 'introimage', 'introimage_alt')->orderBy('title')->paginate(20);
78
        }
79
80
        //dd(DB::getQueryLog());
81
82 5
        return view('laravel-smart-blog::posts.index', compact('posts'))
83 5
            ->with('i', (request()->input('page', 1) - 1) * 20)
84 5
            ->with('categories', $categories)
85 5
            ->with('searchKeywords', $searchKeywords)
86 5
            ->with('searchCategory', $searchCategory)
87 5
            ->with('countriesAvailableForTranslations', $countriesAvailableForTranslations);
88
    }
89
90
    /***************************************************************************/
91
92
    /**
93
     * Show the form for creating a new resource.
94
     *
95
     * @return \Illuminate\Http\Response
96
     */
97 1
    public function create()
98
    {
99
        //$categories = Category::getCategoriesArray();
100 1
        $categories = Category::listsTranslations('name')->pluck('name', 'id');
101
102 1
        return view('laravel-smart-blog::posts.create')->with('categories', $categories);
103
    }
104
105
    /***************************************************************************/
106
107
    /**
108
     * Store a newly created resource in storage.
109
     *
110
     * @param  \Illuminate\Http\Request  $request
111
     * @return \Illuminate\Http\Response
112
     */
113 2
    public function store(Request $request)
114
    {
115
        // Validate form datas
116 2
        $validator = Validator::make($request->all(), [
117 2
                'title' => 'required',
118
                'body' => 'required',
119
                'category_id' => 'required',
120
            ]);
121 2
        if ($validator->fails()) {
122 1
            return back()->withErrors($validator)->withInput();
123
        }
124
125 1
        $post = new Post();
126
127
        // Set the default language to edit the post for the admin to English (to avoid bug with null titles)
128
        //App::setLocale('en'); //removed for the package!!! maybe we still need it!!!
129
130 1
        $this->saveOnDb($request, $post);
131
132 1
        return redirect()->route('posts.index')
133 1
                        ->with('success', __('laravel-smart-blog::messages.article_added_successfully'));
134
    }
135
136
    /***************************************************************************/
137
138
    /**
139
     * Display the specified resource.
140
     *
141
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
142
     * @return \Illuminate\Http\Response
143
     */
144 1
    public function show(Post $post)
145
    {
146
147
        // Accordion
148 1
        $post->body = BootstrapAccordion::getAccordions($post->body, 'plus-minus-circle');
0 ignored issues
show
Bug introduced by
The property body does not seem to exist on DavideCasiraghi\LaravelSmartBlog\Models\Post. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
149
150
        // Gallery
151 1
        $publicPath = public_path('storage');
152 1
        $post->body = ResponsiveGallery::getGallery($post->body, $publicPath);
153 1
        $post->before_content = ResponsiveGallery::getGallery($post->before_content, $publicPath);
0 ignored issues
show
Bug introduced by
The property before_content does not seem to exist on DavideCasiraghi\LaravelSmartBlog\Models\Post. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
154 1
        $post->after_content = ResponsiveGallery::getGallery($post->after_content, $publicPath);
0 ignored issues
show
Bug introduced by
The property after_content does not seem to exist on DavideCasiraghi\LaravelSmartBlog\Models\Post. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
155
156
        // Cards
157 1
        $post->body = LaravelCards::replace_card_snippets_with_template($post->body);
158 1
        $post->before_content = LaravelCards::replace_card_snippets_with_template($post->before_content);
159 1
        $post->after_content = LaravelCards::replace_card_snippets_with_template($post->after_content);
160
161
162
        // JumbotronImages
163 1
        $post->body = LaravelJumbotronImages::replaceJumbotronSnippetsWithTemplate($post->body);
164 1
        $post->before_content = LaravelJumbotronImages::replaceJumbotronSnippetsWithTemplate($post->before_content);
165 1
        $post->after_content = LaravelJumbotronImages::replaceJumbotronSnippetsWithTemplate($post->after_content);
166
167
        /*
168
                // Card
169
                $cardClass = new CardClass();
170
                $post->body = $cardClass->getCard($post->body);
171
                $post->before_content = $cardClass->getCard($post->before_content);
172
                $post->after_content = $cardClass->getCard($post->after_content);
173
174
                // Category Columns
175
                $cardsCarouselClass = new CardsCarouselClass();
176
                $post->body = $cardsCarouselClass->getColumns($post->body);
177
                $post->before_content = $cardsCarouselClass->getColumns($post->before_content);
178
                $post->after_content = $cardsCarouselClass->getColumns($post->after_content);
179
180
                // Category Columns
181
                $columnClass = new ColumnsClass();
182
                $post->body = $columnClass->getColumns($post->body);
183
                $post->before_content = $columnClass->getColumns($post->before_content);
184
                $post->after_content = $columnClass->getColumns($post->after_content);
185
186
                // Stats Donate
187
                $statsDonateClass = new StatsDonateClass();
188
                $post->body = $statsDonateClass->getStatsDonate($post->body);
189
                $post->before_content = $statsDonateClass->getStatsDonate($post->before_content);
190
                $post->after_content = $statsDonateClass->getStatsDonate($post->after_content);
191
192
                // Stats Donate
193
                $communityGoalsClass = new CommunityGoalsClass();
194
                $post->body = $communityGoalsClass->getCommunityGoals($post->body);
195
196
                // Paypal Button
197
                $paypalButton = new PaypalButtonClass();
198
                $post->body = $paypalButton->getPaypalButton($post->body);
199
200
                // Gallery
201
                $storagePath = storage_path('app/public');
202
                $publicPath = public_path();
203
                //dump($storagePath,$publicPath);
204
                $galleryClass = new GalleryClass();
205
                //dump($post->body);
206
                $post->body = $galleryClass->getGallery($post->body, $storagePath, $publicPath);
207
                $post->before_content = $galleryClass->getGallery($post->before_content, $storagePath, $publicPath);
208
                $post->after_content = $galleryClass->getGallery($post->after_content, $storagePath, $publicPath);
209
        */
210
211 1
        return view('laravel-smart-blog::posts.show', compact('post'));
212
    }
213
214
    /***************************************************************************/
215
216
    /**
217
     * Show the form for editing the specified resource.
218
     *
219
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
220
     * @return \Illuminate\Http\Response
221
     */
222 1
    public function edit(Post $post)
223
    {
224
        //$categories = Category::getCategoriesArray();
225 1
        $categories = Category::listsTranslations('name')->pluck('name', 'id');
226
        //$categories = Category::getCategoriesArray();
227
228 1
        return view('laravel-smart-blog::posts.edit', compact('post'))->with('categories', $categories);
229
    }
230
231
    /***************************************************************************/
232
233
    /**
234
     * Update the specified resource in storage.
235
     *
236
     * @param  \Illuminate\Http\Request  $request
237
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
238
     * @return \Illuminate\Http\Response
239
     */
240 2
    public function update(Request $request, Post $post)
241
    {
242 2
        request()->validate([
243 2
            'title' => 'required',
244
            'body' => 'required',
245
            'category_id' => 'required',
246
        ]);
247
248
        // Set the default language to edit the post for the admin to English (to avoid bug with null titles)
249
        //App::setLocale('en');
250
251 1
        $this->saveOnDb($request, $post);
252
253 1
        return redirect()->route('posts.index')
254 1
                        ->with('success', __('laravel-smart-blog::messages.article_updated_successfully'));
255
    }
256
257
    /***************************************************************************/
258
259
    /**
260
     * Remove the specified resource from storage.
261
     *
262
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
263
     * @return \Illuminate\Http\Response
264
     */
265 1
    public function destroy(Post $post)
266
    {
267 1
        $post->delete();
268
269 1
        return redirect()->route('posts.index')
270 1
                        ->with('success', __('laravel-smart-blog::messages.article_deleted_successfully'));
271
    }
272
273
    /***************************************************************************/
274
275
    /**
276
     * Return the single post datas by post id [title, body, image].
277
     *
278
     * @param  int $post_id
279
     * @return \DavideCasiraghi\LaravelSmartBlog\Models\Post
280
     */
281
    public function postdata($post_id)
282
    {
283
        $ret = Post::where('id', $post_id)->first();
284
285
        return $ret;
286
    }
287
288
    /***************************************************************************/
289
290
    /**
291
     * Return the post by SLUG. (eg. http://websitename.com/post/xxxxx).
292
     *
293
     * @param  string $slug
294
     * @return \Illuminate\Http\Response
295
     */
296
    public function postBySlug($slug)
297
    {
298
        $post = Post::
299
                where('post_translations.slug', $slug)
300
                ->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
301
                ->select('posts.*', 'post_translations.title', 'post_translations.intro_text', 'post_translations.body', 'post_translations.before_content', 'post_translations.after_content')
302
                ->first();
303
304
        return $this->show($post);
305
    }
306
307
    /***************************************************************************/
308
309
    /**
310
     * Save the record on DB.
311
     * @param  \Illuminate\Http\Request  $request
312
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
313
     * @return void
314
     */
315 2
    public function saveOnDb($request, $post)
316
    {
317 2
        $post->translateOrNew('en')->title = $request->get('title');
318 2
        $post->translateOrNew('en')->body = clean($request->get('body'));
319 2
        $post->translateOrNew('en')->intro_text = $request->get('intro_text');
320 2
        $post->created_by = \Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
321 2
        $post->translateOrNew('en')->slug = Str::slug($post->title, '-');
0 ignored issues
show
Bug introduced by
The property title does not seem to exist on DavideCasiraghi\LaravelSmartBlog\Models\Post. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
322 2
        $post->category_id = $request->get('category_id');
323
324 2
        $post->status = $request->get('status');
325 2
        $post->featured = $request->get('featured');
326
327
        // Intro image  picture upload
328 2
        if ($request->file('introimage')) {
329
            $imageFile = $request->file('introimage');
330
            $imageName = $imageFile->hashName();
331
            $imageSubdir = 'posts_intro_images';
332
            $imageWidth = '968';
333
            $thumbWidth = '300';
334
335
            $this->uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
0 ignored issues
show
Bug introduced by
It seems like $imageFile can also be of type Illuminate\Http\UploadedFile; however, parameter $imageFile of DavideCasiraghi\LaravelS...::uploadImageOnServer() does only seem to accept array, 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

335
            $this->uploadImageOnServer(/** @scrutinizer ignore-type */ $imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
Loading history...
336
            $post->introimage = $imageName;
337
        } else {
338 2
            $post->introimage = $request->introimage;
339
        }
340
341 2
        $post->translateOrNew('en')->before_content = $request->get('before_content');
342 2
        $post->translateOrNew('en')->after_content = $request->get('after_content');
343
344 2
        $post->save();
345 2
    }
346
}
347