Completed
Push — master ( 99e198...6a1969 )
by Davide
04:16
created

PostController::index()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 46
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3.9953

Importance

Changes 0
Metric Value
cc 3
eloc 26
nc 2
nop 1
dl 0
loc 46
ccs 13
cts 25
cp 0.52
crap 3.9953
rs 9.504
c 0
b 0
f 0
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 Mcamara\LaravelLocalization\Facades\LaravelLocalization;
21
use DavideCasiraghi\BootstrapAccordion\Facades\BootstrapAccordion;
22
use DavideCasiraghi\ResponsiveGallery\Facades\ResponsiveGallery;
23
24
class PostController extends Controller
25
{
26 11
    public function __construct()
27
    {
28
29
        //Restrict the access to this resource just to logged in users except show view
30 11
        $this->middleware('admin', ['except' => ['show', 'postBySlug']]);
31 11
    }
32
33
    /***************************************************************************/
34
35
    /**
36
     * Display a listing of the resource.
37
     * @param  \Illuminate\Http\Request  $request
38
     * @return \Illuminate\Http\Response
39
     */
40 5
    public function index(Request $request)
41
    {
42
        //$categories = Category::getCategoriesArray();
43 5
        $categories = Category::listsTranslations('name')->pluck('name', 'id');
44
45 5
        $searchKeywords = $request->input('keywords');
46 5
        $searchCategory = $request->input('category_id');
47
48
        // Returns all countries having translations
49
        //dd(Post::translated()->get());
50
51
        // Countries available for translations
52 5
        $countriesAvailableForTranslations = LaravelLocalization::getSupportedLocales();
53
        //DB::enableQueryLog();
54
55 5
        if ($searchKeywords || $searchCategory) {
56
            $posts = Post::
57
                select('post_translations.post_id AS id', 'post_translations.title AS title', 'status', 'featured', 'introimage', 'introimage_alt', 'category_id', 'locale')
58
                ->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
59
60
                ->when($searchKeywords, function ($query, $searchKeywords) {
61
                    return $query->where('post_translations.locale', '=', 'en')
62
                                 ->where(function ($query) use ($searchKeywords) {
63
                                     $query->where('post_translations.title', $searchKeywords)
64
                                                  ->orWhere('post_translations.title', 'like', '%'.$searchKeywords.'%');
65
                                 });
66
                })
67
                ->when($searchCategory, function ($query, $searchCategory) {
68
                    return $query->where('post_translations.locale', '=', 'en')
69
                                 ->where(function ($query) use ($searchCategory) {
70
                                     $query->where('category_id', '=', $searchCategory);
71
                                 });
72
                })
73
                ->paginate(20);
74
        } else {
75 5
            $posts = Post::listsTranslations('title')->select('posts.id', 'title', 'category_id', 'status', 'featured', 'introimage', 'introimage_alt')->orderBy('title')->paginate(20);
76
        }
77
78
        //dd(DB::getQueryLog());
79
80 5
        return view('laravel-smart-blog::posts.index', compact('posts'))
81 5
            ->with('i', (request()->input('page', 1) - 1) * 20)
82 5
            ->with('categories', $categories)
83 5
            ->with('searchKeywords', $searchKeywords)
84 5
            ->with('searchCategory', $searchCategory)
85 5
            ->with('countriesAvailableForTranslations', $countriesAvailableForTranslations);
86
    }
87
88
    /***************************************************************************/
89
90
    /**
91
     * Show the form for creating a new resource.
92
     *
93
     * @return \Illuminate\Http\Response
94
     */
95 1
    public function create()
96
    {
97
        //$categories = Category::getCategoriesArray();
98 1
        $categories = Category::listsTranslations('name')->pluck('name', 'id');
99
100 1
        return view('laravel-smart-blog::posts.create')->with('categories', $categories);
101
    }
102
103
    /***************************************************************************/
104
105
    /**
106
     * Store a newly created resource in storage.
107
     *
108
     * @param  \Illuminate\Http\Request  $request
109
     * @return \Illuminate\Http\Response
110
     */
111 2
    public function store(Request $request)
112
    {
113
        // Validate form datas
114 2
        $validator = Validator::make($request->all(), [
115 2
                'title' => 'required',
116
                'body' => 'required',
117
                'category_id' => 'required',
118
            ]);
119 2
        if ($validator->fails()) {
120 1
            return back()->withErrors($validator)->withInput();
121
        }
122
123 1
        $post = new Post();
124
125
        // Set the default language to edit the post for the admin to English (to avoid bug with null titles)
126
        //App::setLocale('en'); //removed for the package!!! maybe we still need it!!!
127
128 1
        $this->saveOnDb($request, $post);
129
130 1
        return redirect()->route('posts.index')
131 1
                        ->with('success', __('laravel-smart-blog::messages.article_added_successfully'));
132
    }
133
134
    /***************************************************************************/
135
136
    /**
137
     * Display the specified resource.
138
     *
139
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
140
     * @return \Illuminate\Http\Response
141
     */
142 1
    public function show(Post $post)
143
    {
144
145
        // Accordion
146 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...
147
148
        // Gallery
149 1
        $publicPath = public_path("storage");
150 1
        $post->body = ResponsiveGallery::getGallery($post->body, $publicPath);
151
152
        /*        $accordionClass = new AccordionClass();
153
                $post->body = $accordionClass->getAccordion($post->body);
154
                $post->before_content = $accordionClass->getAccordion($post->before_content);
155
                $post->after_content = $accordionClass->getAccordion($post->after_content);
156
157
                // Card
158
                $cardClass = new CardClass();
159
                $post->body = $cardClass->getCard($post->body);
160
                $post->before_content = $cardClass->getCard($post->before_content);
161
                $post->after_content = $cardClass->getCard($post->after_content);
162
163
                // Category Columns
164
                $cardsCarouselClass = new CardsCarouselClass();
165
                $post->body = $cardsCarouselClass->getColumns($post->body);
166
                $post->before_content = $cardsCarouselClass->getColumns($post->before_content);
167
                $post->after_content = $cardsCarouselClass->getColumns($post->after_content);
168
169
                // Category Columns
170
                $columnClass = new ColumnsClass();
171
                $post->body = $columnClass->getColumns($post->body);
172
                $post->before_content = $columnClass->getColumns($post->before_content);
173
                $post->after_content = $columnClass->getColumns($post->after_content);
174
175
                // Stats Donate
176
                $statsDonateClass = new StatsDonateClass();
177
                $post->body = $statsDonateClass->getStatsDonate($post->body);
178
                $post->before_content = $statsDonateClass->getStatsDonate($post->before_content);
179
                $post->after_content = $statsDonateClass->getStatsDonate($post->after_content);
180
181
                // Stats Donate
182
                $communityGoalsClass = new CommunityGoalsClass();
183
                $post->body = $communityGoalsClass->getCommunityGoals($post->body);
184
185
                // Paypal Button
186
                $paypalButton = new PaypalButtonClass();
187
                $post->body = $paypalButton->getPaypalButton($post->body);
188
189
                // Gallery
190
                $storagePath = storage_path('app/public');
191
                $publicPath = public_path();
192
                //dump($storagePath,$publicPath);
193
                $galleryClass = new GalleryClass();
194
                //dump($post->body);
195
                $post->body = $galleryClass->getGallery($post->body, $storagePath, $publicPath);
196
                $post->before_content = $galleryClass->getGallery($post->before_content, $storagePath, $publicPath);
197
                $post->after_content = $galleryClass->getGallery($post->after_content, $storagePath, $publicPath);
198
        */
199
200 1
        return view('laravel-smart-blog::posts.show', compact('post'));
201
    }
202
203
    /***************************************************************************/
204
205
    /**
206
     * Show the form for editing the specified resource.
207
     *
208
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
209
     * @return \Illuminate\Http\Response
210
     */
211 1
    public function edit(Post $post)
212
    {
213
        //$categories = Category::getCategoriesArray();
214 1
        $categories = Category::listsTranslations('name')->pluck('name', 'id');
215
        //$categories = Category::getCategoriesArray();
216
217 1
        return view('laravel-smart-blog::posts.edit', compact('post'))->with('categories', $categories);
218
    }
219
220
    /***************************************************************************/
221
222
    /**
223
     * Update the specified resource in storage.
224
     *
225
     * @param  \Illuminate\Http\Request  $request
226
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
227
     * @return \Illuminate\Http\Response
228
     */
229 2
    public function update(Request $request, Post $post)
230
    {
231 2
        request()->validate([
232 2
            'title' => 'required',
233
            'body' => 'required',
234
            'category_id' => 'required',
235
        ]);
236
237
        // Set the default language to edit the post for the admin to English (to avoid bug with null titles)
238
        //App::setLocale('en');
239
240 1
        $this->saveOnDb($request, $post);
241
242 1
        return redirect()->route('posts.index')
243 1
                        ->with('success', __('laravel-smart-blog::messages.article_updated_successfully'));
244
    }
245
246
    /***************************************************************************/
247
248
    /**
249
     * Remove the specified resource from storage.
250
     *
251
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
252
     * @return \Illuminate\Http\Response
253
     */
254 1
    public function destroy(Post $post)
255
    {
256 1
        $post->delete();
257
258 1
        return redirect()->route('posts.index')
259 1
                        ->with('success', __('laravel-smart-blog::messages.article_deleted_successfully'));
260
    }
261
262
    /***************************************************************************/
263
264
    /**
265
     * Return the single post datas by post id [title, body, image].
266
     *
267
     * @param  int $post_id
268
     * @return \DavideCasiraghi\LaravelSmartBlog\Models\Post
269
     */
270
    public function postdata($post_id)
271
    {
272
        $ret = Post::where('id', $post_id)->first();
273
274
        return $ret;
275
    }
276
277
    /***************************************************************************/
278
279
    /**
280
     * Return the post by SLUG. (eg. http://websitename.com/post/xxxxx).
281
     *
282
     * @param  string $slug
283
     * @return \Illuminate\Http\Response
284
     */
285
    public function postBySlug($slug)
286
    {
287
        $post = Post::
288
                where('post_translations.slug', $slug)
289
                ->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
290
                ->select('posts.*', 'post_translations.title', 'post_translations.intro_text', 'post_translations.body', 'post_translations.before_content', 'post_translations.after_content')
291
                ->first();
292
293
        return $this->show($post);
294
    }
295
296
    /***************************************************************************/
297
298
    /**
299
     * Save the record on DB.
300
     * @param  \Illuminate\Http\Request  $request
301
     * @param  \DavideCasiraghi\LaravelSmartBlog\Models\Post  $post
302
     * @return void
303
     */
304 2
    public function saveOnDb($request, $post)
305
    {
306 2
        $post->translateOrNew('en')->title = $request->get('title');
307 2
        $post->translateOrNew('en')->body = clean($request->get('body'));
308 2
        $post->translateOrNew('en')->intro_text = $request->get('intro_text');
309 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...
310 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...
311 2
        $post->category_id = $request->get('category_id');
312
313 2
        $post->status = $request->get('status');
314 2
        $post->featured = $request->get('featured');
315
316
        // Intro image  picture upload
317 2
        if ($request->file('introimage')) {
318
            $imageFile = $request->file('introimage');
319
            $imageName = $imageFile->hashName();
320
            $imageSubdir = 'posts_intro_images';
321
            $imageWidth = '968';
322
            $thumbWidth = '300';
323
324
            $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

324
            $this->uploadImageOnServer(/** @scrutinizer ignore-type */ $imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
Loading history...
325
            $post->introimage = $imageName;
326
        } else {
327 2
            $post->introimage = $request->introimage;
328
        }
329
330 2
        $post->translateOrNew('en')->before_content = $request->get('before_content');
331 2
        $post->translateOrNew('en')->after_content = $request->get('after_content');
332
333 2
        $post->save();
334 2
    }
335
}
336