Completed
Push — master ( 29166d...6b1c5d )
by Davide
12:35
created

PostController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 306
Duplicated Lines 0 %

Test Coverage

Coverage 67.44%

Importance

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

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