Passed
Push — master ( 3035dc...bff6d0 )
by Darko
11:09
created

Category::getForMenu()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 17
rs 9.9332
c 0
b 0
f 0
cc 4
nc 3
nop 1
1
<?php
2
3
namespace App\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
use Illuminate\Database\Eloquent\Relations\HasMany;
8
use Illuminate\Support\Facades\Cache;
9
use Illuminate\Support\Facades\DB;
10
11
/**
12
 * App\Models\Category.
13
 *
14
 * @property int $id
15
 * @property string $title
16
 * @property int|null $parentid
17
 * @property int $status
18
 * @property string|null $description
19
 * @property bool $disablepreview
20
 * @property int $minsizetoformrelease
21
 * @property int $maxsizetoformrelease
22
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Category[] $children
23
 * @property-read Category|null $parent
24
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Release[] $releases
25
 *
26
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereDescription($value)
27
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereDisablepreview($value)
28
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereId($value)
29
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereMaxsizetoformrelease($value)
30
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereMinsizetoformrelease($value)
31
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereParentid($value)
32
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereStatus($value)
33
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereTitle($value)
34
 *
35
 * @mixin \Eloquent
36
 *
37
 * @property int|null $root_categories_id
38
 *
39
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category newModelQuery()
40
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category newQuery()
41
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category query()
42
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Category whereRootCategoriesId($value)
43
 */
44
class Category extends Model
45
{
46
    /**
47
     * Category constants.
48
     * Do NOT use the values, as they may change, always use the constant - that's what it's for.
49
     */
50
    public const int OTHER_MISC = 10;
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting '=' on line 50 at column 21
Loading history...
51
52
    public const int OTHER_HASHED = 20;
53
54
    public const int GAME_NDS = 1010;
55
56
    public const int GAME_PSP = 1020;
57
58
    public const int GAME_WII = 1030;
59
60
    public const int GAME_XBOX = 1040;
61
62
    public const int GAME_XBOX360 = 1050;
63
64
    public const int GAME_WIIWARE = 1060;
65
66
    public const int GAME_XBOX360DLC = 1070;
67
68
    public const int GAME_PS3 = 1080;
69
70
    public const int GAME_OTHER = 1999;
71
72
    public const int GAME_3DS = 1110;
73
74
    public const int GAME_PSVITA = 1120;
75
76
    public const int GAME_WIIU = 1130;
77
78
    public const int GAME_XBOXONE = 1140;
79
80
    public const int GAME_PS4 = 1180;
81
82
    public const int MOVIE_FOREIGN = 2010;
83
84
    public const int MOVIE_OTHER = 2999;
85
86
    public const int MOVIE_SD = 2030;
87
88
    public const int MOVIE_HD = 2040;
89
90
    public const int MOVIE_UHD = 2045;
91
92
    public const int MOVIE_3D = 2050;
93
94
    public const int MOVIE_BLURAY = 2060;
95
96
    public const int MOVIE_DVD = 2070;
97
98
    public const int MOVIE_WEBDL = 2080;
99
100
    public const int MOVIE_X265 = 2090;
101
102
    public const int MUSIC_MP3 = 3010;
103
104
    public const int MUSIC_VIDEO = 3020;
105
106
    public const int MUSIC_AUDIOBOOK = 3030;
107
108
    public const int MUSIC_LOSSLESS = 3040;
109
110
    public const int MUSIC_PODCAST = 3050;
111
112
    public const int MUSIC_OTHER = 3999;
113
114
    public const int MUSIC_FOREIGN = 3060;
115
116
    public const int PC_0DAY = 4010;
117
118
    public const int PC_ISO = 4020;
119
120
    public const int PC_MAC = 4030;
121
122
    public const int PC_PHONE_OTHER = 4040;
123
124
    public const int PC_GAMES = 4050;
125
126
    public const int PC_PHONE_IOS = 4060;
127
128
    public const int PC_PHONE_ANDROID = 4070;
129
130
    public const int TV_WEBDL = 5010;
131
132
    public const int TV_FOREIGN = 5020;
133
134
    public const int TV_SD = 5030;
135
136
    public const int TV_HD = 5040;
137
138
    public const int TV_UHD = 5045;
139
140
    public const int TV_OTHER = 5999;
141
142
    public const int TV_SPORT = 5060;
143
144
    public const int TV_ANIME = 5070;
145
146
    public const int TV_DOCU = 5080;
147
148
    public const int TV_X265 = 5090;
149
150
    public const int XXX_DVD = 6010;
151
152
    public const int XXX_WMV = 6020;
153
154
    public const int XXX_XVID = 6030;
155
156
    public const int XXX_X264 = 6040;
157
158
    public const int XXX_CLIPHD = 6041;
159
160
    public const int XXX_CLIPSD = 6042;
161
162
    public const int XXX_UHD = 6045;
163
164
    public const int XXX_VR = 6046;
165
166
    public const int XXX_ONLYFANS = 6047;
167
168
    public const int XXX_PACK = 6050;
169
170
    public const int XXX_IMAGESET = 6060;
171
172
    public const int XXX_OTHER = 6999;
173
174
    public const int XXX_SD = 6080;
175
176
    public const int XXX_WEBDL = 6090;
177
178
    public const int BOOKS_MAGAZINES = 7010;
179
180
    public const int BOOKS_EBOOK = 7020;
181
182
    public const int BOOKS_COMICS = 7030;
183
184
    public const int BOOKS_TECHNICAL = 7040;
185
186
    public const int BOOKS_FOREIGN = 7060;
187
188
    public const int BOOKS_UNKNOWN = 7999;
189
190
    public const int OTHER_ROOT = 1;
191
192
    public const int GAME_ROOT = 1000;
193
194
    public const int MOVIE_ROOT = 2000;
195
196
    public const int MUSIC_ROOT = 3000;
197
198
    public const int PC_ROOT = 4000;
199
200
    public const int TV_ROOT = 5000;
201
202
    public const int XXX_ROOT = 6000;
203
204
    public const int BOOKS_ROOT = 7000;
205
206
    public const int STATUS_INACTIVE = 0;
207
208
    public const int STATUS_ACTIVE = 1;
209
210
    public const int STATUS_DISABLED = 2;
211
212
    public const array OTHERS_GROUP =
213
        [
214
            self::BOOKS_UNKNOWN,
215
            self::GAME_OTHER,
216
            self::MOVIE_OTHER,
217
            self::MUSIC_OTHER,
218
            self::PC_PHONE_OTHER,
219
            self::TV_OTHER,
220
            self::OTHER_HASHED,
221
            self::XXX_OTHER,
222
            self::OTHER_MISC,
223
        ];
224
225
    public const array MOVIES_GROUP =
226
        [
227
            self::MOVIE_FOREIGN,
228
            self::MOVIE_ROOT,
229
            self::MOVIE_OTHER,
230
            self::MOVIE_SD,
231
            self::MOVIE_HD,
232
            self::MOVIE_UHD,
233
            self::MOVIE_3D,
234
            self::MOVIE_BLURAY,
235
            self::MOVIE_DVD,
236
            self::MOVIE_WEBDL,
237
            self::MOVIE_X265,
238
        ];
239
240
    public const array TV_GROUP =
241
        [
242
            self::TV_FOREIGN,
243
            self::TV_ROOT,
244
            self::TV_OTHER,
245
            self::TV_SD,
246
            self::TV_HD,
247
            self::TV_UHD,
248
            self::TV_ANIME,
249
            self::TV_DOCU,
250
            self::TV_SPORT,
251
            self::TV_WEBDL,
252
            self::TV_X265,
253
        ];
254
255
    /**
256
     * @var string
257
     */
258
259
    /**
260
     * @var bool
261
     */
262
    public $timestamps = false;
263
264
    /**
265
     * @var bool
266
     */
267
    protected $dateFormat = false;
268
269
    /**
270
     * @var array
271
     */
272
    protected $guarded = [];
273
274
    public function releases(): HasMany
275
    {
276
        return $this->hasMany(Release::class, 'categories_id');
277
    }
278
279
    public function parent(): BelongsTo
280
    {
281
        return $this->belongsTo(RootCategory::class, 'root_categories_id');
282
    }
283
284
    /**
285
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|static[]
286
     */
287
    public static function getRecentlyAdded()
288
    {
289
        $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_long'));
290
        $result = Cache::get(md5('RecentlyAdded'));
291
        if ($result !== null) {
292
            return $result;
293
        }
294
295
        $result = self::query()
296
            ->with('parent')
297
            ->where('r.adddate', '>', now()->subWeek())
298
            ->select(['root_categories_id', DB::raw('COUNT(r.id) as count'), 'title'])
299
            ->join('releases as r', 'r.categories_id', '=', 'categories.id')
300
            ->groupBy('title')
301
            ->orderByDesc('count')
302
            ->get();
303
304
        Cache::put(md5('RecentlyAdded'), $result, $expiresAt);
305
306
        return $result;
307
    }
308
309
    public static function getCategorySearch(array $cat = [], ?string $searchType = null, $builder = false): string|array|null
310
    {
311
        $categories = [];
312
313
        // if searchType is tv return TV categories
314
        if ($searchType === 'tv') {
315
            $cat = self::TV_GROUP;
316
        }
317
318
        // is searchType is movies return MOVIES categories
319
        if ($searchType === 'movies') {
320
            $cat = self::MOVIES_GROUP;
321
        }
322
323
        // If multiple categories were sent in a single array position, slice and add them
324
        if (str_contains($cat[0], ',')) {
325
            $tmpcats = explode(',', $cat[0]);
326
            // Reset the category to the first comma separated value in the string
327
            $cat[0] = $tmpcats[0];
328
            // Add the remaining categories in the string to the original array
329
            foreach (array_slice($tmpcats, 1) as $tmpcat) {
330
                $cat[] = $tmpcat;
331
            }
332
        }
333
334
        foreach ($cat as $category) {
335
            if (is_numeric($category) && $category !== -1 && self::isParent($category)) {
336
                $children = RootCategory::find($category)->categories->pluck('id')->toArray();
337
                $categories = array_merge($categories, $children);
338
            } elseif (is_numeric($category) && $category > 0) {
339
                $categories[] = $category;
340
            }
341
        }
342
343
        $catCount = count($categories);
344
345
        if ($builder) {
346
            return match ($catCount) {
347
                0 => null,
348
                1 => $categories[0] !== -1 ? $categories : null,
349
                default => $categories,
350
            };
351
        }
352
353
        return match ($catCount) {
354
            0 => 'AND 1=1',
355
            1 => $categories[0] !== -1 ? ' AND r.categories_id = '.$categories[0] : '',
356
            default => ' AND r.categories_id IN ('.implode(', ', $categories).') ',
357
        };
358
    }
359
360
    /**
361
     * Returns a concatenated list of other categories.
362
     */
363
    public static function getCategoryOthersGroup(): string
364
    {
365
        return implode(
366
            ',',
367
            self::OTHERS_GROUP
368
        );
369
    }
370
371
    /**
372
     * @return mixed
373
     */
374
    public static function getCategoryValue($category)
375
    {
376
        return \constant('self::'.$category);
377
    }
378
379
    /**
380
     * Check if category is parent.
381
     */
382
    public static function isParent($cid): bool
383
    {
384
        $ret = RootCategory::query()->where(['id' => $cid])->first();
385
386
        return $ret !== null;
387
    }
388
389
    /**
390
     * @return \Illuminate\Database\Eloquent\Collection|static[]
391
     */
392
    public static function getFlat()
393
    {
394
        return self::query()->get();
395
    }
396
397
    /**
398
     * Get children of a parent category.
399
     *
400
     *
401
     * @return mixed
402
     */
403
    public static function getChildren($categoryId)
404
    {
405
        $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_long'));
406
        $result = Cache::get(md5($categoryId));
407
        if ($result !== null) {
408
            return $result;
409
        }
410
411
        $result = RootCategory::find($categoryId)->categories;
412
        Cache::put(md5($categoryId), $result, $expiresAt);
413
414
        return $result;
415
    }
416
417
    /**
418
     * Get names of enabled parent categories.
419
     *
420
     * @return \Illuminate\Database\Eloquent\Collection|static[]
421
     */
422
    public static function getEnabledParentNames()
423
    {
424
        return RootCategory::query()->where('status', '=', 1)->get(['title']);
425
    }
426
427
    /**
428
     * Returns category ID's for site disabled categories.
429
     *
430
     *
431
     * @return \Illuminate\Database\Eloquent\Collection|static[]
432
     */
433
    public static function getDisabledIDs()
434
    {
435
        return self::query()
436
            ->where('status', '=', 2)
437
            ->get(['id']);
438
    }
439
440
    /**
441
     * Get multiple categories.
442
     *
443
     * @return bool|\Illuminate\Database\Eloquent\Collection|static[]
444
     */
445
    public static function getByIds($ids)
446
    {
447
        if (\count($ids) > 0) {
448
            $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_long'));
449
            $result = Cache::get(md5(implode(',', $ids)));
450
            if ($result !== null) {
451
                return $result;
452
            }
453
            $result = self::query()->whereIn('id', $ids)->get();
454
455
            Cache::put(md5(md5(implode(',', $ids))), $result, $expiresAt);
456
457
            return $result;
458
        }
459
460
        return false;
461
    }
462
463
    /**
464
     * Return the parent and category name from the supplied categoryID.
465
     */
466
    public static function getNameByID($categoryId): string
467
    {
468
        $cat = self::query()->where('id', $categoryId)->first();
469
470
        return $cat !== null ? $cat->parent->title.' -> '.$cat->title : '';
471
    }
472
473
    /**
474
     * @return bool|mixed
475
     */
476
    public static function getIdByName($title, $parent)
477
    {
478
        $cat = self::query()->where('title', $title)->with('parent.'.$parent)->first(['id']);
479
480
        return $cat !== null ? $cat->id : false;
481
    }
482
483
    /**
484
     * Update a category.
485
     */
486
    public static function updateCategory($id, $status, $desc, $disablepreview, $minsize, $maxsize): int
487
    {
488
        return self::query()->where('id', $id)->update(
489
            [
490
                'disablepreview' => $disablepreview,
491
                'status' => $status,
492
                'minsizetoformrelease' => $minsize,
493
                'maxsizetoformrelease' => $maxsize,
494
                'description' => $desc,
495
            ]
496
        );
497
    }
498
499
    public static function getForMenu(array $excludedCats = []): array
500
    {
501
        $categoriesResult = [];
502
        $categoriesArray = RootCategory::query()->with(['categories' => function ($query) use ($excludedCats) {
503
            if (! empty($excludedCats)) {
504
                $query->whereNotIn('id', $excludedCats);
505
            }
506
            $query->select(['id', 'title', 'root_categories_id', 'description']);
507
        }])->select(['id', 'title'])->get()->toArray();
508
509
        foreach ($categoriesArray as $category) {
510
            if (! empty($category['categories'])) {
511
                $categoriesResult[] = $category;
512
            }
513
        }
514
515
        return $categoriesResult;
516
    }
517
518
    /**
519
     * @return mixed
520
     */
521
    public static function getForApi()
522
    {
523
        $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_long'));
524
        $result = Cache::get(md5('ForApi'));
525
        if ($result !== null) {
526
            return $result;
527
        }
528
529
        $result = RootCategory::query()->select(['id', 'title'])->where('status', '=', self::STATUS_ACTIVE)->get();
530
531
        Cache::put(md5('ForApi'), $result, $expiresAt);
532
533
        return $result;
534
    }
535
536
    /**
537
     * Return a list of categories for use in a dropdown.
538
     */
539
    public static function getForSelect(bool $blnIncludeNoneSelected = true): array
540
    {
541
        $categories = self::getCategories();
542
        $temp_array = [];
543
544
        if ($blnIncludeNoneSelected) {
545
            $temp_array[-1] = '--Please Select--';
546
        }
547
        foreach ($categories as $category) {
548
            $temp_array[$category->id] = $category->parent->title.' > '.$category->title;
549
        }
550
551
        return $temp_array;
552
    }
553
554
    /**
555
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
556
     */
557
    public static function getCategories(bool $activeOnly = false, array $excludedCats = []): \Illuminate\Database\Eloquent\Collection|array
558
    {
559
        $sql = self::query()
560
            ->with('parent')
561
            ->select(['id', 'status', 'title', 'root_categories_id'])
562
            ->orderBy('id');
563
564
        if ($activeOnly) {
565
            $sql->where('status', '=', self::STATUS_ACTIVE);
566
        }
567
568
        if (! empty($excludedCats)) {
569
            $sql->whereNotIn('id', $excludedCats);
570
        }
571
572
        return $sql->get();
573
    }
574
}
575