Completed
Push — dev ( dafd8a...7a3759 )
by Darko
08:41
created

Category::getForApi()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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