Passed
Push — master ( a79f35...85b490 )
by Darko
11:19
created

ReleaseManagementService::deleteSingle()   B

Complexity

Conditions 10
Paths 30

Size

Total Lines 45
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 45
rs 7.6666
cc 10
nc 30
nop 3

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\Services\Releases;
4
5
use App\Models\Release;
6
use App\Services\Search\ManticoreSearchService;
7
use Blacklight\NZB;
8
use Blacklight\ReleaseImage;
9
use Elasticsearch;
10
use Elasticsearch\Common\Exceptions\Missing404Exception;
11
use Illuminate\Support\Facades\DB;
12
use Illuminate\Support\Facades\File;
13
14
/**
15
 * Service for managing releases (delete, update, export).
16
 */
17
class ReleaseManagementService
18
{
19
    private ManticoreSearchService $manticoreSearch;
20
21
    public function __construct(
22
        ManticoreSearchService $manticoreSearch
23
    ) {
24
        $this->manticoreSearch = $manticoreSearch;
25
    }
26
27
    /**
28
     * @throws \Exception
29
     */
30
    public function deleteMultiple(int|array|string $list): void
31
    {
32
        $list = (array) $list;
33
34
        $nzb = new NZB;
35
        $releaseImage = new ReleaseImage;
36
37
        foreach ($list as $identifier) {
38
            $this->deleteSingle(['g' => $identifier, 'i' => false], $nzb, $releaseImage);
39
        }
40
    }
41
42
    /**
43
     * Deletes a single release by GUID, and all the corresponding files.
44
     *
45
     * @param  array  $identifiers  ['g' => Release GUID(mandatory), 'id => ReleaseID(optional, pass
46
     *                              false)]
47
     *
48
     * @throws \Exception
49
     */
50
    public function deleteSingle(array $identifiers, NZB $nzb, ReleaseImage $releaseImage): void
51
    {
52
        // Delete NZB from disk.
53
        $nzbPath = $nzb->NZBPath($identifiers['g']);
54
        if (! empty($nzbPath)) {
55
            File::delete($nzbPath);
56
        }
57
58
        // Delete images.
59
        $releaseImage->delete($identifiers['g']);
60
61
        if (config('nntmux.elasticsearch_enabled') === true) {
62
            if ($identifiers['i'] === false) {
63
                $identifiers['i'] = Release::query()->where('guid', $identifiers['g'])->first(['id']);
64
                if ($identifiers['i'] !== null) {
65
                    $identifiers['i'] = $identifiers['i']['id'];
66
                }
67
            }
68
            if ($identifiers['i'] !== null) {
69
                $params = [
70
                    'index' => 'releases',
71
                    'id' => $identifiers['i'],
72
                ];
73
74
                try {
75
                    Elasticsearch::delete($params);
76
                } catch (Missing404Exception $e) {
77
                    // we do nothing here just catch the error, we don't care if release is missing from ES, we are deleting it anyway
78
                }
79
            }
80
        } else {
81
            // Delete from Manticore
82
            if ($identifiers['i'] === false) {
83
                $release = Release::query()->where('guid', $identifiers['g'])->first(['id']);
84
                if ($release !== null) {
85
                    $identifiers['i'] = $release->id;
86
                }
87
            }
88
            if (!empty($identifiers['i'])) {
89
                $this->manticoreSearch->deleteRelease((int) $identifiers['i']);
90
            }
91
        }
92
93
        // Delete from DB.
94
        Release::whereGuid($identifiers['g'])->delete();
95
    }
96
97
    /**
98
     * @return bool|int
99
     */
100
    public function updateMulti($guids, $category, $grabs, $videoId, $episodeId, $anidbId, $imdbId)
101
    {
102
        if (! \is_array($guids) || \count($guids) < 1) {
103
            return false;
104
        }
105
106
        $update = [
107
            'categories_id' => $category === -1 ? 'categories_id' : $category,
108
            'grabs' => $grabs,
109
            'videos_id' => $videoId,
110
            'tv_episodes_id' => $episodeId,
111
            'anidbid' => $anidbId,
112
            'imdbid' => $imdbId,
113
        ];
114
115
        return Release::query()->whereIn('guid', $guids)->update($update);
116
    }
117
118
    /**
119
     * @return Release[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Query\Builder[]|\Illuminate\Support\Collection
120
     */
121
    public function getForExport(string $postFrom = '', string $postTo = '', string $groupID = '')
122
    {
123
        $query = Release::query()
124
            ->select(['r.searchname', 'r.guid', 'g.name as gname', DB::raw("CONCAT(cp.title,'_',c.title) AS catName")])
125
            ->from('releases as r')
0 ignored issues
show
Bug introduced by
'releases as r' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $table of Illuminate\Database\Query\Builder::from(). ( Ignorable by Annotation )

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

125
            ->from(/** @scrutinizer ignore-type */ 'releases as r')
Loading history...
126
            ->leftJoin('categories as c', 'c.id', '=', 'r.categories_id')
127
            ->leftJoin('root_categories as cp', 'cp.id', '=', 'c.root_categories_id')
128
            ->leftJoin('usenet_groups as g', 'g.id', '=', 'r.groups_id');
129
130
        if ($groupID !== '') {
131
            $query->where('r.groups_id', $groupID);
132
        }
133
134
        if ($postFrom !== '') {
135
            $dateParts = explode('/', $postFrom);
136
            if (\count($dateParts) === 3) {
137
                $query->where('r.postdate', '>', $dateParts[2].'-'.$dateParts[1].'-'.$dateParts[0].'00:00:00');
138
            }
139
        }
140
141
        if ($postTo !== '') {
142
            $dateParts = explode('/', $postTo);
143
            if (\count($dateParts) === 3) {
144
                $query->where('r.postdate', '<', $dateParts[2].'-'.$dateParts[1].'-'.$dateParts[0].'23:59:59');
145
            }
146
        }
147
148
        return $query->get();
149
    }
150
151
    /**
152
     * @return mixed|string
153
     */
154
    public function getEarliestUsenetPostDate(): mixed
155
    {
156
        $row = Release::query()->selectRaw("DATE_FORMAT(min(postdate), '%d/%m/%Y') AS postdate")->first();
157
158
        return $row === null ? '01/01/2014' : $row['postdate'];
159
    }
160
161
    /**
162
     * @return mixed|string
163
     */
164
    public function getLatestUsenetPostDate(): mixed
165
    {
166
        $row = Release::query()->selectRaw("DATE_FORMAT(max(postdate), '%d/%m/%Y') AS postdate")->first();
167
168
        return $row === null ? '01/01/2014' : $row['postdate'];
169
    }
170
171
    public function getReleasedGroupsForSelect(bool $blnIncludeAll = true): array
172
    {
173
        $groups = Release::query()
174
            ->selectRaw('DISTINCT g.id, g.name')
175
            ->leftJoin('usenet_groups as g', 'g.id', '=', 'releases.groups_id')
176
            ->get();
177
        $temp_array = [];
178
179
        if ($blnIncludeAll) {
180
            $temp_array[-1] = '--All Groups--';
181
        }
182
183
        foreach ($groups as $group) {
184
            $temp_array[$group['id']] = $group['name'];
185
        }
186
187
        return $temp_array;
188
    }
189
}
190
191