Completed
Push — master ( e8e2e6...967609 )
by Davide
08:58
created

PostController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 317
Duplicated Lines 0 %

Test Coverage

Coverage 70.2%

Importance

Changes 0
Metric Value
eloc 91
dl 0
loc 317
ccs 66
cts 94
cp 0.702
rs 10
c 0
b 0
f 0
wmc 15

11 Methods

Rating   Name   Duplication   Size   Complexity  
A saveOnDb() 0 30 2
A destroy() 0 6 1
A store() 0 21 2
A update() 0 15 1
A postBySlug() 0 9 1
A show() 0 66 1
A __construct() 0 5 1
A edit() 0 7 1
A postdata() 0 5 1
A index() 0 46 3
A create() 0 6 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
159
        // JumbotronImages
160 1
        $post->body = LaravelJumbotronImages::replaceJumbotronSnippetsWithTemplate($post->body);
161 1
        $post->before_content = LaravelJumbotronImages::replaceJumbotronSnippetsWithTemplate($post->before_content);
162 1
        $post->after_content = LaravelJumbotronImages::replaceJumbotronSnippetsWithTemplate($post->after_content);
163
        
164
        
165
        /*       
166
                // Card
167
                $cardClass = new CardClass();
168
                $post->body = $cardClass->getCard($post->body);
169
                $post->before_content = $cardClass->getCard($post->before_content);
170
                $post->after_content = $cardClass->getCard($post->after_content);
171
172
                // Category Columns
173
                $cardsCarouselClass = new CardsCarouselClass();
174
                $post->body = $cardsCarouselClass->getColumns($post->body);
175
                $post->before_content = $cardsCarouselClass->getColumns($post->before_content);
176
                $post->after_content = $cardsCarouselClass->getColumns($post->after_content);
177
178
                // Category Columns
179
                $columnClass = new ColumnsClass();
180
                $post->body = $columnClass->getColumns($post->body);
181
                $post->before_content = $columnClass->getColumns($post->before_content);
182
                $post->after_content = $columnClass->getColumns($post->after_content);
183
184
                // Stats Donate
185
                $statsDonateClass = new StatsDonateClass();
186
                $post->body = $statsDonateClass->getStatsDonate($post->body);
187
                $post->before_content = $statsDonateClass->getStatsDonate($post->before_content);
188
                $post->after_content = $statsDonateClass->getStatsDonate($post->after_content);
189
190
                // Stats Donate
191
                $communityGoalsClass = new CommunityGoalsClass();
192
                $post->body = $communityGoalsClass->getCommunityGoals($post->body);
193
194
                // Paypal Button
195
                $paypalButton = new PaypalButtonClass();
196
                $post->body = $paypalButton->getPaypalButton($post->body);
197
198
                // Gallery
199
                $storagePath = storage_path('app/public');
200
                $publicPath = public_path();
201
                //dump($storagePath,$publicPath);
202
                $galleryClass = new GalleryClass();
203
                //dump($post->body);
204
                $post->body = $galleryClass->getGallery($post->body, $storagePath, $publicPath);
205
                $post->before_content = $galleryClass->getGallery($post->before_content, $storagePath, $publicPath);
206
                $post->after_content = $galleryClass->getGallery($post->after_content, $storagePath, $publicPath);
207
        */
208
209 1
        return view('laravel-smart-blog::posts.show', compact('post'));
210
    }
211
212
    /***************************************************************************/
213
214
    /**
215
     * Show the form for editing the specified resource.
216
     *
217
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
218
     * @return \Illuminate\Http\Response
219
     */
220 1
    public function edit(Post $post)
221
    {
222
        //$categories = Category::getCategoriesArray();
223 1
        $categories = Category::listsTranslations('name')->pluck('name', 'id');
224
        //$categories = Category::getCategoriesArray();
225
226 1
        return view('laravel-smart-blog::posts.edit', compact('post'))->with('categories', $categories);
227
    }
228
229
    /***************************************************************************/
230
231
    /**
232
     * Update the specified resource in storage.
233
     *
234
     * @param  \Illuminate\Http\Request  $request
235
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
236
     * @return \Illuminate\Http\Response
237
     */
238 2
    public function update(Request $request, Post $post)
239
    {
240 2
        request()->validate([
241 2
            'title' => 'required',
242
            'body' => 'required',
243
            'category_id' => 'required',
244
        ]);
245
246
        // Set the default language to edit the post for the admin to English (to avoid bug with null titles)
247
        //App::setLocale('en');
248
249 1
        $this->saveOnDb($request, $post);
250
251 1
        return redirect()->route('posts.index')
252 1
                        ->with('success', __('laravel-smart-blog::messages.article_updated_successfully'));
253
    }
254
255
    /***************************************************************************/
256
257
    /**
258
     * Remove the specified resource from storage.
259
     *
260
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
261
     * @return \Illuminate\Http\Response
262
     */
263 1
    public function destroy(Post $post)
264
    {
265 1
        $post->delete();
266
267 1
        return redirect()->route('posts.index')
268 1
                        ->with('success', __('laravel-smart-blog::messages.article_deleted_successfully'));
269
    }
270
271
    /***************************************************************************/
272
273
    /**
274
     * Return the single post datas by post id [title, body, image].
275
     *
276
     * @param  int $post_id
277
     * @return \DavideCasiraghi\LaravelSmartBlog\Models\Post
278
     */
279
    public function postdata($post_id)
280
    {
281
        $ret = Post::where('id', $post_id)->first();
282
283
        return $ret;
284
    }
285
286
    /***************************************************************************/
287
288
    /**
289
     * Return the post by SLUG. (eg. http://websitename.com/post/xxxxx).
290
     *
291
     * @param  string $slug
292
     * @return \Illuminate\Http\Response
293
     */
294
    public function postBySlug($slug)
295
    {
296
        $post = Post::
297
                where('post_translations.slug', $slug)
298
                ->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
299
                ->select('posts.*', 'post_translations.title', 'post_translations.intro_text', 'post_translations.body', 'post_translations.before_content', 'post_translations.after_content')
300
                ->first();
301
302
        return $this->show($post);
303
    }
304
305
    /***************************************************************************/
306
307
    /**
308
     * Save the record on DB.
309
     * @param  \Illuminate\Http\Request  $request
310
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
311
     * @return void
312
     */
313 2
    public function saveOnDb($request, $post)
314
    {
315 2
        $post->translateOrNew('en')->title = $request->get('title');
316 2
        $post->translateOrNew('en')->body = clean($request->get('body'));
317 2
        $post->translateOrNew('en')->intro_text = $request->get('intro_text');
318 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...
319 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...
320 2
        $post->category_id = $request->get('category_id');
321
322 2
        $post->status = $request->get('status');
323 2
        $post->featured = $request->get('featured');
324
325
        // Intro image  picture upload
326 2
        if ($request->file('introimage')) {
327
            $imageFile = $request->file('introimage');
328
            $imageName = $imageFile->hashName();
329
            $imageSubdir = 'posts_intro_images';
330
            $imageWidth = '968';
331
            $thumbWidth = '300';
332
333
            $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

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