Predb::checkPre()   B
last analyzed

Complexity

Conditions 10
Paths 52

Size

Total Lines 39
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 39
rs 7.6666
c 0
b 0
f 0
cc 10
nc 52
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Models;
4
5
use Blacklight\ColorCLI;
6
use Blacklight\ConsoleTools;
7
use Blacklight\ElasticSearchSiteSearch;
8
use Blacklight\ManticoreSearch;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Database\Eloquent\Relations\HasMany;
11
use Illuminate\Support\Arr;
12
use Illuminate\Support\Facades\Cache;
13
use Laravel\Scout\Searchable;
14
15
/**
16
 * App\Models\Predb.
17
 *
18
 * @property mixed $release
19
 * @property mixed $hash
20
 * @property int $id Primary key
21
 * @property string $title
22
 * @property string|null $nfo
23
 * @property string|null $size
24
 * @property string|null $category
25
 * @property string|null $predate
26
 * @property string $source
27
 * @property int $requestid
28
 * @property int $groups_id FK to groups
29
 * @property bool $nuked Is this pre nuked? 0 no 2 yes 1 un nuked 3 mod nuked
30
 * @property string|null $nukereason If this pre is nuked, what is the reason?
31
 * @property string|null $files How many files does this pre have ?
32
 * @property string $filename
33
 * @property bool $searched
34
 *
35
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereCategory($value)
36
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereFilename($value)
37
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereFiles($value)
38
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereGroupsId($value)
39
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereId($value)
40
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereNfo($value)
41
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereNuked($value)
42
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereNukereason($value)
43
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb wherePredate($value)
44
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereRequestid($value)
45
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereSearched($value)
46
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereSize($value)
47
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereSource($value)
48
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb whereTitle($value)
49
 *
50
 * @mixin \Eloquent
51
 *
52
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb newModelQuery()
53
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb newQuery()
54
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Predb query()
55
 */
56
class Predb extends Model
57
{
58
    use Searchable;
0 ignored issues
show
Bug introduced by
The trait Laravel\Scout\Searchable requires the property $queryCallback which is not provided by App\Models\Predb.
Loading history...
59
60
    // Nuke status.
61
    public const PRE_NONUKE = 0; // Pre is not nuked.
62
63
    public const PRE_UNNUKED = 1; // Pre was un nuked.
64
65
    public const PRE_NUKED = 2; // Pre is nuked.
66
67
    public const PRE_MODNUKE = 3; // Nuke reason was modified.
68
69
    public const PRE_RENUKED = 4; // Pre was re nuked.
70
71
    public const PRE_OLDNUKE = 5; // Pre is nuked for being old.
72
73
    /**
74
     * @var string
75
     */
76
    protected $table = 'predb';
77
78
    /**
79
     * @var bool
80
     */
81
    public $timestamps = false;
82
83
    /**
84
     * @var bool
85
     */
86
    protected $dateFormat = false;
87
88
    /**
89
     * @var array
90
     */
91
    protected $guarded = [];
92
93
    public function hash(): HasMany
94
    {
95
        return $this->hasMany(PredbHash::class, 'predb_id');
96
    }
97
98
    public function release(): HasMany
99
    {
100
        return $this->hasMany(Release::class, 'predb_id');
101
    }
102
103
    /**
104
     * Attempts to match PreDB titles to releases.
105
     *
106
     *
107
     * @throws \RuntimeException
108
     */
109
    public static function checkPre(bool|int|string $dateLimit = false): void
110
    {
111
        $consoleTools = new ConsoleTools;
112
        $updated = 0;
113
114
        if (config('nntmux.echocli')) {
115
            (new ColorCLI)->header('Querying DB for release search names not matched with PreDB titles.');
116
        }
117
118
        $query = self::query()
119
            ->where('releases.predb_id', '<', 1)
120
            ->join('releases', 'predb.title', '=', 'releases.searchname')
121
            ->select(['predb.id as predb_id', 'releases.id as releases_id']);
122
        if ($dateLimit !== false && (int) $dateLimit > 0) {
123
            $query->where('adddate', '>', now()->subDays((int) $dateLimit));
124
        }
125
126
        $res = $query->get();
127
128
        if ($res !== null) {
129
            $total = \count($res);
130
            (new ColorCLI)->primary(number_format($total).' releases to match.');
131
132
            foreach ($res as $row) {
133
                Release::query()->where('id', $row['releases_id'])->update(['predb_id' => $row['predb_id']]);
134
135
                if (config('nntmux.echocli')) {
136
                    $consoleTools->overWritePrimary(
137
                        'Matching up preDB titles with release searchnames: '.$consoleTools->percentString(++$updated, $total)
138
                    );
139
                }
140
            }
141
            if (config('nntmux.echocli')) {
142
                echo PHP_EOL;
143
            }
144
145
            if (config('nntmux.echocli')) {
146
                (new ColorCLI)->header(
147
                    'Matched '.number_format(($updated > 0) ? $updated : 0).' PreDB titles to release search names.'
148
                );
149
            }
150
        }
151
    }
152
153
    /**
154
     * Try to match a single release to a PreDB title when the release is created.
155
     *
156
     * @return array|false Array with title/id from PreDB if found, false if not found.
157
     */
158
    public static function matchPre(string $cleanerName)
159
    {
160
        if (empty($cleanerName)) {
161
            return false;
162
        }
163
164
        $titleCheck = self::query()->where('title', $cleanerName)->first(['id']);
165
166
        if ($titleCheck !== null) {
167
            return [
168
                'title' => $cleanerName,
169
                'predb_id' => $titleCheck['id'],
170
            ];
171
        }
172
173
        // Check if clean name matches a PreDB filename.
174
        $fileCheck = self::query()->where('filename', $cleanerName)->first(['id', 'title']);
175
176
        if ($fileCheck !== null) {
177
            return [
178
                'title' => $fileCheck['title'],
179
                'predb_id' => $fileCheck['id'],
180
            ];
181
        }
182
183
        return false;
184
    }
185
186
    /**
187
     * @return mixed
188
     *
189
     * @throws \Exception
190
     */
191
    public static function getAll(string $search = '')
192
    {
193
        $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_medium'));
194
        $predb = Cache::get(md5($search));
195
        if ($predb !== null) {
196
            return $predb;
197
        }
198
        $sql = self::query()->leftJoin('releases', 'releases.predb_id', '=', 'predb.id')->orderByDesc('predb.predate');
0 ignored issues
show
Bug introduced by
'predb.predate' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $column of Illuminate\Database\Query\Builder::orderByDesc(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

198
        $sql = self::query()->leftJoin('releases', 'releases.predb_id', '=', 'predb.id')->orderByDesc(/** @scrutinizer ignore-type */ 'predb.predate');
Loading history...
199
        if (! empty($search)) {
200
            if (config('nntmux.elasticsearch_enabled') === true) {
201
                $ids = (new ElasticSearchSiteSearch)->predbIndexSearch($search);
202
            } else {
203
                $manticore = new ManticoreSearch;
204
                $ids = Arr::get($manticore->searchIndexes('predb_rt', $search, ['title']), 'id');
205
            }
206
            $sql->whereIn('predb.id', $ids);
207
        }
208
209
        $predb = $sql->paginate(config('nntmux.items_per_page'));
210
        Cache::put(md5($search), $predb, $expiresAt);
211
212
        return $predb;
213
    }
214
215
    /**
216
     * Get all PRE's for a release.
217
     *
218
     *
219
     * @return \Illuminate\Database\Eloquent\Collection|static[]
220
     */
221
    public static function getForRelease($preID)
222
    {
223
        return self::query()->where('id', $preID)->get();
224
    }
225
226
    /**
227
     * Return a single PRE for a release.
228
     *
229
     *
230
     * @return Model|null|static
231
     */
232
    public static function getOne($preID)
233
    {
234
        return self::query()->where('id', $preID)->first();
235
    }
236
237
    public function searchableAs(): string
238
    {
239
        return 'ft_predb_filename';
240
    }
241
242
    public function toSearchableArray(): array
243
    {
244
        return [
245
            'filename' => $this->filename,
246
        ];
247
    }
248
}
249