Completed
Push — master ( f2030c...73a9c5 )
by Davide
08:06 queued 03:51
created

PostController::postdata()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

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