Completed
Push — dev ( 8486bf...fdc38b )
by Darko
08:23
created

Console::fetchAmazonProperties()   B

Complexity

Conditions 9
Paths 20

Size

Total Lines 51
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
eloc 34
dl 0
loc 51
ccs 0
cts 31
cp 0
rs 8.0555
c 0
b 0
f 0
cc 9
nc 20
nop 2
crap 90

How to fix   Long Method   

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 Blacklight;
4
5
use App\Models\Genre;
6
use GuzzleHttp\Client;
7
use App\Models\Release;
8
use App\Models\Category;
9
use App\Models\Settings;
10
use App\Models\ConsoleInfo;
11
use Illuminate\Support\Carbon;
12
use Messerli90\IGDB\Facades\IGDB;
13
use Illuminate\Support\Facades\DB;
14
use Illuminate\Support\Facades\Cache;
15
use GuzzleHttp\Exception\ClientException;
16
17
/**
18
 * Class Console.
19
 */
20
class Console
21
{
22
    public const CONS_UPROC = 0; // Release has not been processed.
23
    public const CONS_NTFND = -2;
24
25
    protected const MATCH_PERCENT = 60;
26
27
    /**
28
     * @var
29
     */
30
    protected $igdbSleep;
31
32
    /**
33
     * @var bool
34
     */
35
    public $echooutput;
36
37
    /**
38
     * @var null|string
39
     */
40
    public $pubkey;
41
42
    /**
43
     * @var null|string
44
     */
45
    public $privkey;
46
47
    /**
48
     * @var null|string
49
     */
50
    public $asstag;
51
52
    /**
53
     * @var int|null|string
54
     */
55
    public $gameqty;
56
57
    /**
58
     * @var int|null|string
59
     */
60
    public $sleeptime;
61
62
    /**
63
     * @var string
64
     */
65
    public $imgSavePath;
66
67
    /**
68
     * @var string
69
     */
70
    public $renamed;
71
72
    /**
73
     * @var string
74
     */
75
    public $catWhere;
76
77
    /**
78
     * Store names of failed Amazon lookup items.
79
     * @var array
80
     */
81
    public $failCache;
82
83
    /**
84
     * @var \Blacklight\ColorCLI
85
     */
86
    protected $colorCli;
87
88
    /**
89
     * @param array $options Class instances / Echo to cli.
90
     * @throws \Exception
91
     */
92
    public function __construct(array $options = [])
93
    {
94
        $defaults = [
95
            'Echo'     => false,
96
            'Settings' => null,
97
        ];
98
        $options += $defaults;
99
100
        $this->echooutput = ($options['Echo'] && config('nntmux.echocli'));
101
102
        $this->colorCli = new ColorCLI();
103
104
        $this->pubkey = Settings::settingValue('APIs..amazonpubkey');
105
        $this->privkey = Settings::settingValue('APIs..amazonprivkey');
106
        $this->asstag = Settings::settingValue('APIs..amazonassociatetag');
107
        $this->gameqty = (Settings::settingValue('..maxgamesprocessed') !== '') ? (int) Settings::settingValue('..maxgamesprocessed') : 150;
0 ignored issues
show
introduced by
The condition App\Models\Settings::set...gamesprocessed') !== '' is always true.
Loading history...
108
        $this->sleeptime = (Settings::settingValue('..amazonsleep') !== '') ? (int) Settings::settingValue('..amazonsleep') : 1000;
0 ignored issues
show
introduced by
The condition App\Models\Settings::set...'..amazonsleep') !== '' is always true.
Loading history...
109
        $this->imgSavePath = NN_COVERS.'console'.DS;
110
        $this->renamed = (int) Settings::settingValue('..lookupgames') === 2;
0 ignored issues
show
Documentation Bug introduced by
The property $renamed was declared of type string, but (int)App\Models\Settings...('..lookupgames') === 2 is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
111
112
        $this->failCache = [];
113
    }
114
115
    /**
116
     * @param $id
117
     * @return \Illuminate\Database\Eloquent\Model|null|static
118
     */
119
    public function getConsoleInfo($id)
120
    {
121
        return ConsoleInfo::query()->where('consoleinfo.id', $id)->select('consoleinfo.*', 'genres.title as genres')->leftJoin('genres', 'genres.id', '=', 'consoleinfo.genres_id')->first();
122
    }
123
124
    /**
125
     * @param string $title
126
     * @param string $platform
127
     *
128
     * @return false|\Illuminate\Database\Eloquent\Model
129
     */
130
    public function getConsoleInfoByName($title, $platform)
131
    {
132
        //only used to get a count of words
133
        $searchWords = '';
134
135
        $title = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $title);
136
        $title = preg_replace('/[^\w ]+/', '', $title);
137
        $title = trim(trim(preg_replace('/\s\s+/i', ' ', $title)));
138
        foreach (explode(' ', $title) as $word) {
139
            $word = trim(rtrim(trim($word), '-'));
140
            if ($word !== '' && $word !== '-') {
141
                $word = '+'.$word;
142
                $searchWords .= sprintf('%s ', $word);
143
            }
144
        }
145
        $searchWords = trim($searchWords.'+'.$platform);
146
147
        return ConsoleInfo::search($searchWords)->first() ?? false;
148
    }
149
150
    /**
151
     * @param       $page
152
     * @param       $cat
153
     * @param       $start
154
     * @param       $num
155
     * @param       $orderBy
156
     * @param array $excludedCats
157
     *
158
     * @return array
159
     * @throws \Exception
160
     */
161
    public function getConsoleRange($page, $cat, $start, $num, $orderBy, array $excludedCats = []): array
162
    {
163
        $browseBy = $this->getBrowseBy();
164
        $catsrch = '';
165
        if (\count($cat) > 0 && (int) $cat[0] !== -1) {
166
            $catsrch = Category::getCategorySearch($cat);
167
        }
168
        $exccatlist = '';
169
        if (\count($excludedCats) > 0) {
170
            $exccatlist = ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')';
171
        }
172
        $order = $this->getConsoleOrder($orderBy);
173
        $calcSql = sprintf(
174
            "
175
					SELECT SQL_CALC_FOUND_ROWS
176
						con.id,
177
						GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id
178
					FROM consoleinfo con
179
					LEFT JOIN releases r ON con.id = r.consoleinfo_id
180
					WHERE r.nzbstatus = 1
181
					AND con.title != ''
182
					AND con.cover = 1
183
					AND r.passwordstatus %s
184
					%s %s %s
185
					GROUP BY con.id
186
					ORDER BY %s %s %s",
187
            (new Releases())->showPasswords(),
188
            $browseBy,
189
            $catsrch,
190
            $exccatlist,
191
            $order[0],
192
            $order[1],
193
            ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start)
194
        );
195
        $cached = Cache::get(md5($calcSql.$page));
196
        if ($cached !== null) {
197
            $consoles = $cached;
198
        } else {
199
            $data = DB::select($calcSql);
200
            $consoles = ['total' => DB::select('SELECT FOUND_ROWS() AS total'), 'result' => $data];
201
            $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_medium'));
202
            Cache::put(md5($calcSql.$page), $consoles, $expiresAt);
203
        }
204
        $consoleIDs = $releaseIDs = false;
205
        if (\is_array($consoles['result'])) {
206
            foreach ($consoles['result'] as $console => $id) {
207
                $consoleIDs[] = $id->id;
208
                $releaseIDs[] = $id->grp_release_id;
209
            }
210
        }
211
        $sql = sprintf(
212
            '
213
				SELECT
214
					r.id, r.rarinnerfilecount, r.grabs, r.comments, r.totalpart, r.size, r.postdate, r.searchname, r.haspreview, r.passwordstatus, r.guid, rn.releases_id, g.name AS group_name, df.failed AS failed,
215
				con.*,
216
				r.consoleinfo_id,
217
				g.name AS group_name,
218
				genres.title AS genre,
219
				rn.releases_id AS nfoid
220
				FROM releases r
221
				LEFT OUTER JOIN groups g ON g.id = r.groups_id
222
				LEFT OUTER JOIN release_nfos rn ON rn.releases_id = r.id
223
				LEFT OUTER JOIN dnzb_failures df ON df.release_id = r.id
224
				INNER JOIN consoleinfo con ON con.id = r.consoleinfo_id
225
				INNER JOIN genres ON con.genres_id = genres.id
226
				WHERE con.id IN (%s)
227
				AND r.id IN (%s)
228
				%s
229
				GROUP BY con.id
230
				ORDER BY %s %s',
231
            (\is_array($consoleIDs) ? implode(',', $consoleIDs) : -1),
0 ignored issues
show
introduced by
The condition is_array($consoleIDs) is always false.
Loading history...
232
            (\is_array($releaseIDs) ? implode(',', $releaseIDs) : -1),
0 ignored issues
show
introduced by
The condition is_array($releaseIDs) is always false.
Loading history...
233
            $catsrch,
234
            $order[0],
235
            $order[1]
236
        );
237
        $return = Cache::get(md5($sql.$page));
238
        if ($return !== null) {
239
            return $return;
240
        }
241
        $return = DB::select($sql);
242
        if (\count($return) > 0) {
243
            $return[0]->_totalcount = $consoles['total'][0]->total ?? 0;
244
        }
245
        $expiresAt = now()->addMinutes(config('nntmux.cache_expiry_long'));
246
        Cache::put(md5($sql.$page), $return, $expiresAt);
247
248
        return $return;
249
    }
250
251
    /**
252
     * @param $orderBy
253
     * @return array
254
     */
255
    public function getConsoleOrder($orderBy): array
256
    {
257
        $order = ($orderBy === '') ? 'r.postdate' : $orderBy;
258
        $orderArr = explode('_', $order);
259
        switch ($orderArr[0]) {
260
            case 'title':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
261
                $orderfield = 'con.title';
262
                break;
263
            case 'platform':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
264
                $orderfield = 'con.platform';
265
                break;
266
            case 'releasedate':
267
                $orderfield = 'con.releasedate';
268
                break;
269
            case 'genre':
270
                $orderfield = 'con.genres_id';
271
                break;
272
            case 'size':
273
                $orderfield = 'r.size';
274
                break;
275
            case 'files':
276
                $orderfield = 'r.totalpart';
277
                break;
278
            case 'stats':
279
                $orderfield = 'r.grabs';
280
                break;
281
            case 'posted':
282
            default:
283
                $orderfield = 'r.postdate';
284
                break;
285
        }
286
        $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc';
287
288
        return [$orderfield, $ordersort];
289
    }
290
291
    /**
292
     * @return array
293
     */
294
    public function getConsoleOrdering(): array
295
    {
296
        return ['title_asc', 'title_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'platform_asc', 'platform_desc', 'releasedate_asc', 'releasedate_desc', 'genre_asc', 'genre_desc'];
297
    }
298
299
    /**
300
     * @return array
301
     */
302
    public function getBrowseByOptions(): array
303
    {
304
        return ['platform' => 'platform', 'title' => 'title', 'genre' => 'genres_id'];
305
    }
306
307
    /**
308
     * @return string
309
     */
310
    public function getBrowseBy(): string
311
    {
312
        $browseBy = ' ';
313
        foreach ($this->getBrowseByOptions() as $bbk => $bbv) {
314
            if (isset($_REQUEST[$bbk]) && ! empty($_REQUEST[$bbk])) {
315
                $bbs = stripslashes($_REQUEST[$bbk]);
316
                $browseBy .= 'AND con.'.$bbv.' LIKE '.escapeString('%'.$bbs.'%');
317
            }
318
        }
319
320
        return $browseBy;
321
    }
322
323
    /**
324
     * @param $id
325
     * @param $title
326
     * @param $asin
327
     * @param $url
328
     * @param $salesrank
329
     * @param $platform
330
     * @param $publisher
331
     * @param $releasedate
332
     * @param $esrb
333
     * @param $cover
334
     * @param $genres_id
335
     * @param string $review
336
     */
337
    public function update($id, $title, $asin, $url, $salesrank, $platform, $publisher, $releasedate, $esrb, $cover, $genres_id, $review = 'review'): void
338
    {
339
        $releasedate = $releasedate !== '' ? $releasedate : 'null';
340
        $review = $review === 'review' ? $review : substr($review, 0, 3000);
341
        ConsoleInfo::query()
342
            ->where('id', $id)
343
            ->update(compact('title', 'asin', 'url', 'salesrank', 'platform', 'publisher', 'releasedate', 'esrb', 'cover', 'genres_id', 'review'));
344
    }
345
346
    /**
347
     * @param $gameInfo
348
     * @return int|mixed
349
     * @throws \Exception
350
     */
351
    public function updateConsoleInfo($gameInfo)
352
    {
353
        $consoleId = self::CONS_NTFND;
354
355
        $igdb = $this->fetchIGDBProperties($gameInfo['title'], $gameInfo['node']);
356
        if ($igdb !== false) {
0 ignored issues
show
introduced by
The condition $igdb !== false is always true.
Loading history...
357
            if ($igdb['coverurl'] !== '') {
358
                $igdb['cover'] = 1;
359
            } else {
360
                $igdb['cover'] = 0;
361
            }
362
363
            $consoleId = $this->_updateConsoleTable($igdb);
364
365
            if ($this->echooutput && $consoleId !== -2) {
366
                $this->colorCli->header('Added/updated game: ').$this->colorCli->alternateOver('   Title:    ').$this->colorCli->primary($igdb['title']).$this->colorCli->alternateOver('   Platform: ').$this->colorCli->primary($igdb['platform']).$this->colorCli->alternateOver('   Genre: ').$this->colorCli->primary($igdb['consolegenre']);
0 ignored issues
show
Bug introduced by
Are you sure $this->colorCli->header('Added/updated game: ') of type void can be used in concatenation? ( Ignorable by Annotation )

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

366
                /** @scrutinizer ignore-type */ $this->colorCli->header('Added/updated game: ').$this->colorCli->alternateOver('   Title:    ').$this->colorCli->primary($igdb['title']).$this->colorCli->alternateOver('   Platform: ').$this->colorCli->primary($igdb['platform']).$this->colorCli->alternateOver('   Genre: ').$this->colorCli->primary($igdb['consolegenre']);
Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->primary($igdb['platform']) targeting Blacklight\ColorCLI::primary() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure $this->colorCli->alternateOver(' Platform: ') of type void can be used in concatenation? ( Ignorable by Annotation )

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

366
                $this->colorCli->header('Added/updated game: ').$this->colorCli->alternateOver('   Title:    ').$this->colorCli->primary($igdb['title'])./** @scrutinizer ignore-type */ $this->colorCli->alternateOver('   Platform: ').$this->colorCli->primary($igdb['platform']).$this->colorCli->alternateOver('   Genre: ').$this->colorCli->primary($igdb['consolegenre']);
Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->header('Added/updated game: ') targeting Blacklight\ColorCLI::header() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->alternateOver(' Genre: ') targeting Blacklight\ColorCLI::alternateOver() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure $this->colorCli->primary($igdb['platform']) of type void can be used in concatenation? ( Ignorable by Annotation )

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

366
                $this->colorCli->header('Added/updated game: ').$this->colorCli->alternateOver('   Title:    ').$this->colorCli->primary($igdb['title']).$this->colorCli->alternateOver('   Platform: ')./** @scrutinizer ignore-type */ $this->colorCli->primary($igdb['platform']).$this->colorCli->alternateOver('   Genre: ').$this->colorCli->primary($igdb['consolegenre']);
Loading history...
Bug introduced by
Are you sure $this->colorCli->primary($igdb['consolegenre']) of type void can be used in concatenation? ( Ignorable by Annotation )

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

366
                $this->colorCli->header('Added/updated game: ').$this->colorCli->alternateOver('   Title:    ').$this->colorCli->primary($igdb['title']).$this->colorCli->alternateOver('   Platform: ').$this->colorCli->primary($igdb['platform']).$this->colorCli->alternateOver('   Genre: ')./** @scrutinizer ignore-type */ $this->colorCli->primary($igdb['consolegenre']);
Loading history...
Bug introduced by
Are you sure $this->colorCli->primary($igdb['title']) of type void can be used in concatenation? ( Ignorable by Annotation )

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

366
                $this->colorCli->header('Added/updated game: ').$this->colorCli->alternateOver('   Title:    ')./** @scrutinizer ignore-type */ $this->colorCli->primary($igdb['title']).$this->colorCli->alternateOver('   Platform: ').$this->colorCli->primary($igdb['platform']).$this->colorCli->alternateOver('   Genre: ').$this->colorCli->primary($igdb['consolegenre']);
Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->primary($igdb['consolegenre']) targeting Blacklight\ColorCLI::primary() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure $this->colorCli->alternateOver(' Genre: ') of type void can be used in concatenation? ( Ignorable by Annotation )

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

366
                $this->colorCli->header('Added/updated game: ').$this->colorCli->alternateOver('   Title:    ').$this->colorCli->primary($igdb['title']).$this->colorCli->alternateOver('   Platform: ').$this->colorCli->primary($igdb['platform'])./** @scrutinizer ignore-type */ $this->colorCli->alternateOver('   Genre: ').$this->colorCli->primary($igdb['consolegenre']);
Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->primary($igdb['title']) targeting Blacklight\ColorCLI::primary() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->alternateOver(' Platform: ') targeting Blacklight\ColorCLI::alternateOver() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->alternateOver(' Title: ') targeting Blacklight\ColorCLI::alternateOver() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
367
            }
368
        }
369
370
        return $consoleId;
371
    }
372
373
    /**
374
     * @param array $gameInfo
375
     * @param array $con
376
     * @return bool
377
     */
378
    protected function _matchConToGameInfo(array $gameInfo = [], array $con = []): bool
379
    {
380
        $matched = false;
381
382
        // This actual compares the two strings and outputs a percentage value.
383
        $titlepercent = $platformpercent = '';
384
385
        //Remove import tags from console title for match
386
        $con['title'] = trim(preg_replace('/([\[|\(]).{2,} import([\]|\)])$/i', '', $con['title']));
387
388
        similar_text(strtolower($gameInfo['title']), strtolower($con['title']), $titlepercent);
0 ignored issues
show
Bug introduced by
$titlepercent of type string is incompatible with the type double expected by parameter $percent of similar_text(). ( Ignorable by Annotation )

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

388
        similar_text(strtolower($gameInfo['title']), strtolower($con['title']), /** @scrutinizer ignore-type */ $titlepercent);
Loading history...
389
        similar_text(strtolower($gameInfo['platform']), strtolower($con['platform']), $platformpercent);
390
391
        // Since Wii Ware games and XBLA have inconsistent original platforms, as long as title is 50% its ok.
392
        if ($titlepercent >= 50 && preg_match('/wiiware|xbla/i', trim($gameInfo['platform']))) {
393
            $titlepercent = 100;
394
            $platformpercent = 100;
395
        }
396
397
        // If the release is DLC matching will be difficult, so assume anything over 50% is legit.
398
        if ($titlepercent >= 50 && isset($gameInfo['dlc']) && (int) $gameInfo['dlc'] === 1) {
399
            $titlepercent = 100;
400
            $platformpercent = 100;
401
        }
402
403
        if ($titlepercent < 70) {
404
            $gameInfo['title'] .= ' - '.$gameInfo['platform'];
405
            similar_text(strtolower($gameInfo['title']), strtolower($con['title']), $titlepercent);
406
        }
407
408
        // Platform must equal 100%.
409
410
        if ((int) $platformpercent === 100 && (int) $titlepercent >= 70) {
411
            $matched = true;
412
        }
413
414
        return $matched;
415
    }
416
417
    /**
418
     * @param $amaz
419
     * @param $gameInfo
420
     * @return array
421
     */
422
    protected function _setConBeforeMatch($amaz, $gameInfo): array
423
    {
424
        $con = [];
425
        $con['platform'] = (string) $amaz->ItemAttributes->Platform;
426
        if (empty($con['platform'])) {
427
            $con['platform'] = $gameInfo['platform'];
428
        }
429
430
        if (stripos('Super', $con['platform']) !== false) {
431
            $con['platform'] = 'SNES';
432
        }
433
434
        $con['title'] = (string) $amaz->ItemAttributes->Title;
435
        if (empty($con['title'])) {
436
            $con['title'] = $gameInfo['title'];
437
        }
438
439
        // Remove Download strings
440
        $dlStrings = [' [Online Game Code]', ' [Download]', ' [Digital Code]', ' [Digital Download]'];
441
        $con['title'] = str_ireplace($dlStrings, '', $con['title']);
442
443
        return $con;
444
    }
445
446
    /**
447
     * @param $amaz
448
     * @return array
449
     */
450
    protected function _setConAfterMatch($amaz): array
451
    {
452
        $con = [];
453
        $con['asin'] = (string) $amaz->ASIN;
454
455
        $con['url'] = (string) $amaz->DetailPageURL;
456
        $con['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $con['url']);
457
458
        $con['salesrank'] = (string) $amaz->SalesRank;
459
        if ($con['salesrank'] === '') {
460
            $con['salesrank'] = 'null';
461
        }
462
463
        $con['publisher'] = (string) $amaz->ItemAttributes->Publisher;
464
        $con['esrb'] = (string) $amaz->ItemAttributes->ESRBAgeRating;
465
        $con['releasedate'] = (string) $amaz->ItemAttributes->ReleaseDate;
466
467
        if (! isset($con['releasedate'])) {
468
            $con['releasedate'] = '';
469
        }
470
471
        if ($con['releasedate'] === "''") {
472
            $con['releasedate'] = '';
473
        }
474
475
        $con['review'] = '';
476
        if (isset($amaz->EditorialReviews)) {
477
            $con['review'] = trim(strip_tags((string) $amaz->EditorialReviews->EditorialReview->Content));
478
        }
479
480
        return $con;
481
    }
482
483
    /**
484
     * @param $amaz
485
     *
486
     * @return array
487
     * @throws \Exception
488
     */
489
    protected function _matchGenre($amaz): array
490
    {
491
        $genreName = '';
492
493
        if (isset($amaz->BrowseNodes)) {
494
            //had issues getting this out of the browsenodes obj
495
            //workaround is to get the xml and load that into its own obj
496
            $amazGenresXml = $amaz->BrowseNodes->asXml();
497
            $amazGenresObj = simplexml_load_string($amazGenresXml);
498
            $amazGenres = $amazGenresObj->xpath('//Name');
499
500
            foreach ($amazGenres as $amazGenre) {
501
                $currName = trim($amazGenre[0]);
502
                if (empty($genreName)) {
503
                    $genreMatch = $this->matchBrowseNode($currName);
504
                    if ($genreMatch !== false) {
505
                        $genreName = $genreMatch;
506
                        break;
507
                    }
508
                }
509
            }
510
        }
511
512
        if ($genreName === '' && isset($amaz->ItemAttributes->Genre)) {
513
            $a = (string) $amaz->ItemAttributes->Genre;
514
            $b = str_replace('-', ' ', $a);
515
            $tmpGenre = explode(' ', $b);
516
517
            foreach ($tmpGenre as $tg) {
518
                $genreMatch = $this->matchBrowseNode(ucwords($tg));
519
                if ($genreMatch !== false) {
520
                    $genreName = $genreMatch;
521
                    break;
522
                }
523
            }
524
        }
525
526
        if (empty($genreName)) {
527
            $genreName = 'Unknown';
528
        }
529
530
        $genreKey = $this->_getGenreKey($genreName);
531
532
        return ['consolegenre' => $genreName, 'consolegenreid' => $genreKey];
533
    }
534
535
    /**
536
     * @param $genreName
537
     *
538
     * @return false|int|string
539
     * @throws \Exception
540
     */
541
    protected function _getGenreKey($genreName)
542
    {
543
        $genreassoc = $this->_loadGenres();
544
545
        if (\in_array(strtolower($genreName), $genreassoc, false)) {
546
            $genreKey = array_search(strtolower($genreName), $genreassoc, false);
547
        } else {
548
            $genreKey = Genre::query()->insertGetId(['title' => $genreName, 'type' => Genres::CONSOLE_TYPE]);
549
        }
550
551
        return $genreKey;
552
    }
553
554
    /**
555
     * @return array
556
     * @throws \Exception
557
     */
558
    protected function _loadGenres(): array
559
    {
560
        $gen = new Genres(['Settings' => null]);
561
562
        return $gen->loadGenres(Genres::CONSOLE_TYPE);
563
    }
564
565
    /** This function sets the platform retrieved
566
     *  from the release to the Amazon equivalent.
567
     *
568
     * @param string $platform
569
     *
570
     *
571
     * @return string
572
     */
573
    protected function _replacePlatform($platform): string
574
    {
575
        switch (strtoupper($platform)) {
576
577
            case 'X360':
578
            case 'XBOX360':
579
                $platform = 'Xbox 360';
580
                break;
581
            case 'XBOXONE':
582
            case 'XBOX ONE':
583
                $platform = 'Xbox One';
584
                break;
585
            case 'DSi':
586
            case 'NDS':
587
                $platform = 'Nintendo DS';
588
                break;
589
            case '3DS':
590
                $platform = 'Nintendo 3DS';
591
                break;
592
            case 'PS2':
593
                $platform = 'PlayStation2';
594
                break;
595
            case 'PS3':
596
                $platform = 'PlayStation 3';
597
                break;
598
            case 'PS4':
599
                $platform = 'PlayStation 4';
600
                break;
601
            case 'PSP':
602
                $platform = 'Sony PSP';
603
                break;
604
            case 'PSVITA':
605
                $platform = 'PlayStation Vita';
606
                break;
607
            case 'PSX':
608
            case 'PSX2PSP':
609
                $platform = 'PlayStation';
610
                break;
611
            case 'WIIU':
612
                $platform = 'Nintendo Wii U';
613
                break;
614
            case 'WII':
615
                $platform = 'Nintendo Wii';
616
                break;
617
            case 'NGC':
618
                $platform = 'GameCube';
619
                break;
620
            case 'N64':
621
                $platform = 'Nintendo 64';
622
                break;
623
            case 'NES':
624
                $platform = 'Nintendo NES';
625
                break;
626
            case 'SUPER NINTENDO':
627
            case 'NINTENDO SUPER NES':
628
            case 'SNES':
629
                $platform = 'SNES';
630
                break;
631
        }
632
633
        return $platform;
634
    }
635
636
    /**
637
     * @param array $con
638
     * @return int|mixed
639
     */
640
    protected function _updateConsoleTable(array $con = [])
641
    {
642
        $ri = new ReleaseImage();
643
644
        $check = ConsoleInfo::query()->where('asin', $con['asin'])->first();
645
646
        if ($check === null) {
647
            $consoleId = ConsoleInfo::query()
648
                ->insertGetId(
649
                    [
650
                        'title' => $con['title'],
651
                        'asin' => $con['asin'],
652
                        'url' => $con['url'],
653
                        'salesrank' => $con['salesrank'],
654
                        'platform' => $con['platform'],
655
                        'publisher' => $con['publisher'],
656
                        'genres_id' => (int) $con['consolegenreid'] === -1 ? 'null' : $con['consolegenreid'],
657
                        'esrb' => $con['esrb'],
658
                        'releasedate' => $con['releasedate'] !== '' ? $con['releasedate'] : 'null',
659
                        'review' => substr($con['review'], 0, 3000),
660
                        'created_at' => now(),
661
                        'updated_at' => now(),
662
                    ]
663
                );
664
            if ($con['cover'] === 1) {
665
                $con['cover'] = $ri->saveImage($consoleId, $con['coverurl'], $this->imgSavePath, 250, 250);
0 ignored issues
show
Bug introduced by
It seems like $consoleId can also be of type Illuminate\Database\Eloquent\Builder; however, parameter $imgName of Blacklight\ReleaseImage::saveImage() does only seem to accept string, 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

665
                $con['cover'] = $ri->saveImage(/** @scrutinizer ignore-type */ $consoleId, $con['coverurl'], $this->imgSavePath, 250, 250);
Loading history...
666
            }
667
        } else {
668
            $consoleId = $check['id'];
669
670
            if ($con['cover'] === 1) {
671
                $con['cover'] = $ri->saveImage($consoleId, $con['coverurl'], $this->imgSavePath, 250, 250);
0 ignored issues
show
Bug introduced by
It seems like $consoleId can also be of type Illuminate\Database\Eloq...uent\Relations\Relation and Illuminate\Database\Eloquent\Relations\Relation; however, parameter $imgName of Blacklight\ReleaseImage::saveImage() does only seem to accept string, 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

671
                $con['cover'] = $ri->saveImage(/** @scrutinizer ignore-type */ $consoleId, $con['coverurl'], $this->imgSavePath, 250, 250);
Loading history...
672
            }
673
674
            $this->update(
675
                $consoleId,
676
                $con['title'],
677
                $con['asin'],
678
                $con['url'],
679
                $con['salesrank'],
680
                $con['platform'],
681
                $con['publisher'],
682
                $con['releasedate'] ?? null,
683
                $con['esrb'],
684
                $con['cover'],
685
                $con['consolegenreid'],
686
                $con['review'] ?? null
687
            );
688
        }
689
690
        return $consoleId;
691
    }
692
693
    /**
694
     * @param $gameInfo
695
     * @param $gamePlatform
696
     *
697
     * @return array|bool|\StdClass
698
     * @throws \Exception
699
     */
700
    public function fetchIGDBProperties($gameInfo, $gamePlatform)
701
    {
702
        $bestMatch = false;
703
704
        $gamePlatform = $this->_replacePlatform($gamePlatform);
705
        if (now() > $this->igdbSleep) {
706
            $this->igdbSleep = null;
707
        }
708
        if ($this->igdbSleep === null && config('services.igdb.key') !== '') {
709
            try {
710
                $result = IGDB::searchGames($gameInfo);
711
                if (! empty($result)) {
712
                    foreach ($result as $res) {
713
                        similar_text(strtolower($gameInfo), strtolower($res->name), $percent);
714
                        if ($percent >= 90) {
715
                            $bestMatch = $res->id;
716
                        }
717
                    }
718
                    if ($bestMatch !== false) {
719
                        $game = IGDB::getGame($bestMatch, [
720
                            'id',
721
                            'name',
722
                            'first_release_date',
723
                            'aggregated_rating',
724
                            'summary',
725
                            'cover',
726
                            'url',
727
                            'screenshots',
728
                            'publishers.name',
729
                            'themes.name',
730
                            'platforms.name',
731
                        ]);
732
733
                        $publishers = [];
734
                        if (! empty($game->publishers)) {
735
                            foreach ($game->publishers as $publisher) {
736
                                $publishers[] = IGDB::getCompany($publisher)->name;
737
                            }
738
                        }
739
740
                        $genres = [];
741
742
                        if (! empty($game->themes)) {
743
                            foreach ($game->themes as $theme) {
744
                                $genres[] = IGDB::getTheme($theme)->name;
745
                            }
746
                        }
747
748
                        $genreKey = $this->_getGenreKey(implode(',', $genres));
749
750
                        $platform = '';
751
752
                        if (! empty($game->platforms)) {
753
                            foreach ($game->platforms as $platforms) {
754
                                $platforms = IGDB::getPlatform($platforms);
755
                                similar_text($platforms->name, $gamePlatform, $percent);
756
                                if ($percent >= 85) {
757
                                    $platform = $platforms->name;
758
                                    break;
759
                                }
760
                            }
761
                        }
762
763
                        $game = [
764
                            'title' => $game->name,
765
                            'asin' => $game->id,
766
                            'review' => $game->summary ?? '',
767
                            'coverurl' => ! empty($game->cover->url) ? 'https:'.$game->cover->url : '',
768
                            'releasedate' => ! empty($game->first_release_date) ? Carbon::createFromTimestamp(substr($game->first_release_date, 0, -3))->format('Y-m-d') : now()->format('Y-m-d'),
0 ignored issues
show
Bug introduced by
substr($game->first_release_date, 0, -3) of type string is incompatible with the type integer expected by parameter $timestamp of Carbon\Carbon::createFromTimestamp(). ( Ignorable by Annotation )

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

768
                            'releasedate' => ! empty($game->first_release_date) ? Carbon::createFromTimestamp(/** @scrutinizer ignore-type */ substr($game->first_release_date, 0, -3))->format('Y-m-d') : now()->format('Y-m-d'),
Loading history...
769
                            'esrb' => ! empty($game->aggregated_rating) ? round($game->aggregated_rating).'%' : 'Not Rated',
770
                            'url' => $game->url ?? '',
771
                            'publisher' => ! empty($publishers) ? implode(',', $publishers) : 'Unknown',
772
                            'platform' => $platform ?? '',
773
                            'consolegenre' => ! empty($genres) ? implode(',', $genres) : 'Unknown',
774
                            'consolegenreid' => $genreKey ?? '',
775
                            'salesrank' => '',
776
                        ];
777
778
                        return $game;
779
                    }
780
781
                    $this->colorCli->notice('IGDB returned no valid results');
782
783
                    return false;
784
                }
785
786
                $this->colorCli->notice('IGDB found no valid results');
787
788
                return false;
789
            } catch (ClientException $e) {
790
                if ($e->getCode() === 429) {
791
                    $this->igdbSleep = now()->endOfMonth();
792
                }
793
            }
794
        }
795
796
        return false;
797
    }
798
799
    /**
800
     * @throws \Exception
801
     */
802
    public function processConsoleReleases(): void
803
    {
804
        $query = Release::query()->select(['searchname', 'id'])->whereBetween('categories_id', [Category::GAME_ROOT, Category::GAME_OTHER])->where('nzbstatus', '=', NZB::NZB_ADDED)->whereNull('consoleinfo_id');
805
        if ($this->renamed === true) {
0 ignored issues
show
introduced by
The condition $this->renamed === true is always false.
Loading history...
806
            $query->where('isrenamed', '=', 1);
807
        }
808
        $res = $query->limit($this->gameqty)->orderBy('postdate')->get();
0 ignored issues
show
Bug introduced by
It seems like $this->gameqty can also be of type string; however, parameter $value of Illuminate\Database\Query\Builder::limit() does only seem to accept integer, 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

808
        $res = $query->limit(/** @scrutinizer ignore-type */ $this->gameqty)->orderBy('postdate')->get();
Loading history...
809
810
        $releaseCount = $res->count();
811
        if ($res instanceof \Traversable && $releaseCount > 0) {
812
            if ($this->echooutput) {
813
                $this->colorCli->header('Processing '.$releaseCount.' console release(s).');
814
            }
815
816
            foreach ($res as $arr) {
817
                $startTime = now()->timestamp;
818
                $usedAmazon = false;
819
                $gameId = self::CONS_NTFND;
820
                $gameInfo = $this->parseTitle($arr['searchname']);
821
822
                if ($gameInfo !== false) {
823
                    if ($this->echooutput) {
824
                        $this->colorCli->headerOver('Looking up: ').
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->colorCli->headerOver('Looking up: ') targeting Blacklight\ColorCLI::headerOver() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure $this->colorCli->headerOver('Looking up: ') of type void can be used in concatenation? ( Ignorable by Annotation )

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

824
                        /** @scrutinizer ignore-type */ $this->colorCli->headerOver('Looking up: ').
Loading history...
825
                            $this->colorCli->primary(
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->colorCli->primary...Info['platform'] . ')') targeting Blacklight\ColorCLI::primary() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
826
                                $gameInfo['title'].
827
                                ' ('.
828
                                $gameInfo['platform'].')'
829
                            );
830
                    }
831
832
                    // Check for existing console entry.
833
                    $gameCheck = $this->getConsoleInfoByName($gameInfo['title'], $gameInfo['platform']);
834
835
                    if ($gameCheck === false && \in_array($gameInfo['title'].$gameInfo['platform'], $this->failCache, false)) {
836
                        // Lookup recently failed, no point trying again
837
                        if ($this->echooutput) {
838
                            $this->colorCli->headerOver('Cached previous failure. Skipping.');
839
                        }
840
                        $gameId = -2;
841
                    } elseif ($gameCheck === false) {
842
                        $gameId = $this->updateConsoleInfo($gameInfo);
843
                        $usedAmazon = true;
844
                        if ($gameId === null) {
845
                            $gameId = -2;
846
                            $this->failCache[] = $gameInfo['title'].$gameInfo['platform'];
847
                        }
848
                    } else {
849
                        if ($this->echooutput) {
850
                            $this->colorCli->headerOver('Found Local: ').
0 ignored issues
show
Bug introduced by
Are you sure $this->colorCli->headerOver('Found Local: ') of type void can be used in concatenation? ( Ignorable by Annotation )

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

850
                            /** @scrutinizer ignore-type */ $this->colorCli->headerOver('Found Local: ').
Loading history...
Bug introduced by
Are you sure the usage of $this->colorCli->headerOver('Found Local: ') targeting Blacklight\ColorCLI::headerOver() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
851
                                $this->colorCli->primary("{$gameCheck['title']} - {$gameCheck['platform']}");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->colorCli->primary...$gameCheck['platform']) targeting Blacklight\ColorCLI::primary() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
852
                        }
853
                        $gameId = $gameCheck['id'];
854
                    }
855
                } elseif ($this->echooutput) {
856
                    echo '.';
857
                }
858
859
                // Update release.
860
                Release::query()->where('id', $arr['id'])->update(['consoleinfo_id'=> $gameId]);
861
862
                // Sleep to not flood amazon.
863
                $diff = floor((now()->timestamp - $startTime) * 1000000);
864
                if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) {
865
                    usleep($this->sleeptime * 1000 - $diff);
0 ignored issues
show
Bug introduced by
$this->sleeptime * 1000 - $diff of type double is incompatible with the type integer expected by parameter $micro_seconds of usleep(). ( Ignorable by Annotation )

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

865
                    usleep(/** @scrutinizer ignore-type */ $this->sleeptime * 1000 - $diff);
Loading history...
866
                }
867
            }
868
        } elseif ($this->echooutput) {
869
            $this->colorCli->header('No console releases to process.');
870
        }
871
    }
872
873
    /**
874
     * @param $releaseName
875
     *
876
     * @return array|false
877
     */
878
    public function parseTitle($releaseName)
879
    {
880
        $releaseName = preg_replace('/\sMulti\d?\s/i', '', $releaseName);
881
        $result = [];
882
883
        // Get name of the game from name of release.
884
        if (preg_match('/^(.+((abgx360EFNet|EFNet\sFULL|FULL\sabgxEFNet|abgx\sFULL|abgxbox360EFNet)\s|illuminatenboard\sorg|Place2(hom|us)e.net|united-forums? co uk|\(\d+\)))?(?P<title>.*?)[\.\-_ ](v\.?\d\.\d|PAL|NTSC|EUR|USA|JP|ASIA|JAP|JPN|AUS|MULTI(\.?\d{1,2})?|PATCHED|FULLDVD|DVD5|DVD9|DVDRIP|PROPER|REPACK|RETAIL|DEMO|DISTRIBUTION|REGIONFREE|[\. ]RF[\. ]?|READ\.?NFO|NFOFIX|PSX(2PSP)?|PS[2-4]|PSP|PSVITA|WIIU|WII|X\-?BOX|XBLA|X360|3DS|NDS|N64|NGC)/i', $releaseName, $matches)) {
885
            $title = $matches['title'];
886
887
            // Replace dots, underscores, or brackets with spaces.
888
            $result['title'] = str_replace(['.', '_', '%20', '[', ']'], ' ', $title);
889
            $result['title'] = str_replace([' RF ', '.RF.', '-RF-', '_RF_'], ' ', $result['title']);
890
            //Remove format tags from release title for match
891
            $result['title'] = trim(preg_replace('/PAL|MULTI(\d)?|NTSC-?J?|\(JAPAN\)/i', '', $result['title']));
892
            //Remove disc tags from release title for match
893
            $result['title'] = trim(preg_replace('/Dis[ck] \d.*$/i', '', $result['title']));
894
895
            // Needed to add code to handle DLC Properly.
896
            if (stripos('dlc', $result['title']) !== false) {
897
                $result['dlc'] = '1';
898
                if (stripos('Rock Band Network', $result['title']) !== false) {
899
                    $result['title'] = 'Rock Band';
900
                } elseif (strpos('-', $result['title']) !== false) {
901
                    $dlc = explode('-', $result['title']);
902
                    $result['title'] = $dlc[0];
903
                } elseif (preg_match('/(.*? .*?) /i', $result['title'], $dlc)) {
904
                    $result['title'] = $dlc[0];
905
                }
906
            }
907
        } else {
908
            $title = '';
909
        }
910
911
        // Get the platform of the release.
912
        if (preg_match('/[\.\-_ ](?P<platform>XBLA|WiiWARE|N64|SNES|NES|PS[2-4]|PS 3|PSX(2PSP)?|PSP|WIIU|WII|XBOX360|XBOXONE|X\-?BOX|X360|3DS|NDS|N?GC)/i', $releaseName, $matches)) {
913
            $platform = $matches['platform'];
914
915
            if (preg_match('/^N?GC$/i', $platform)) {
916
                $platform = 'NGC';
917
            }
918
919
            if (stripos('PSX2PSP', $platform) === 0) {
920
                $platform = 'PSX';
921
            }
922
923
            if (! empty($title) && stripos('XBLA', $platform) === 0 && stripos('dlc', $title) !== false) {
924
                $platform = 'XBOX360';
925
            }
926
927
            $browseNode = $this->getBrowseNode($platform);
928
            $result['platform'] = $platform;
929
            $result['node'] = $browseNode;
930
        }
931
        $result['release'] = $releaseName;
932
        array_map('trim', $result);
933
934
        /* Make sure we got a title and platform otherwise the resulting lookup will probably be shit.
935
           Other option is to pass the $release->categories_id here if we don't find a platform but that
936
           would require an extra lookup to determine the name. In either case we should have a title at the minimum. */
937
938
        return (isset($result['title'], $result['platform']) && ! empty($result['title'])) ? $result : false;
939
    }
940
941
    /**
942
     * @param $platform
943
     *
944
     * @return string
945
     */
946
    public function getBrowseNode($platform): string
947
    {
948
        switch ($platform) {
949
            case 'PS2':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
950
                $nodeId = '301712';
951
                break;
952
            case 'PS3':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
953
                $nodeId = '14210751';
954
                break;
955
            case 'PS4':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
956
                $nodeId = '6427814011';
957
                break;
958
            case 'PSP':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
959
                $nodeId = '11075221';
960
                break;
961
            case 'PSVITA':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
962
                $nodeId = '3010556011';
963
                break;
964
            case 'PSX':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
965
                $nodeId = '294940';
966
                break;
967
            case 'WII':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
968
            case 'Wii':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
969
                $nodeId = '14218901';
970
                break;
971
            case 'WIIU':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
972
            case 'WiiU':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
973
                $nodeId = '3075112011';
974
                break;
975
            case 'XBOX360':
976
            case 'X360':
977
                $nodeId = '14220161';
978
                break;
979
            case 'XBOXONE':
980
                $nodeId = '6469269011';
981
                break;
982
            case 'XBOX':
983
            case 'X-BOX':
984
                $nodeId = '537504';
985
                break;
986
            case 'NDS':
987
                $nodeId = '11075831';
988
                break;
989
            case '3DS':
990
                $nodeId = '2622269011';
991
                break;
992
            case 'GC':
993
            case 'NGC':
994
                $nodeId = '541022';
995
                break;
996
            case 'N64':
997
                $nodeId = '229763';
998
                break;
999
            case 'SNES':
1000
                $nodeId = '294945';
1001
                break;
1002
            case 'NES':
1003
                $nodeId = '566458';
1004
                break;
1005
            default:
1006
                $nodeId = '468642';
1007
                break;
1008
        }
1009
1010
        return $nodeId;
1011
    }
1012
1013
    /**
1014
     * @param $nodeName
1015
     *
1016
     * @return bool|string
1017
     */
1018
    public function matchBrowseNode($nodeName)
1019
    {
1020
        $str = '';
1021
1022
        //music nodes above mp3 download nodes
1023
        switch ($nodeName) {
1024
            case 'Action_shooter':
1025
            case 'Action_Games':
1026
            case 'Action_games':
1027
                $str = 'Action';
1028
                break;
1029
            case 'Action/Adventure':
1030
            case 'Action\Adventure':
1031
            case 'Adventure_games':
1032
                $str = 'Adventure';
1033
                break;
1034
            case 'Boxing_games':
1035
            case 'Sports_games':
1036
                $str = 'Sports';
1037
                break;
1038
            case 'Fantasy_action_games':
1039
                $str = 'Fantasy';
1040
                break;
1041
            case 'Fighting_action_games':
1042
                $str = 'Fighting';
1043
                break;
1044
            case 'Flying_simulation_games':
1045
                $str = 'Flying';
1046
                break;
1047
            case 'Horror_action_games':
1048
                $str = 'Horror';
1049
                break;
1050
            case 'Kids & Family':
1051
                $str = 'Family';
1052
                break;
1053
            case 'Role_playing_games':
1054
                $str = 'Role-Playing';
1055
                break;
1056
            case 'Shooter_action_games':
1057
                $str = 'Shooter';
1058
                break;
1059
            case 'Singing_games':
1060
                $str = 'Music';
1061
                break;
1062
            case 'Action':
1063
            case 'Adventure':
1064
            case 'Arcade':
1065
            case 'Board Games':
1066
            case 'Cards':
1067
            case 'Casino':
1068
            case 'Collections':
1069
            case 'Family':
1070
            case 'Fantasy':
1071
            case 'Fighting':
1072
            case 'Flying':
1073
            case 'Horror':
1074
            case 'Music':
1075
            case 'Puzzle':
1076
            case 'Racing':
1077
            case 'Rhythm':
1078
            case 'Role-Playing':
1079
            case 'Simulation':
1080
            case 'Shooter':
1081
            case 'Shooting':
1082
            case 'Sports':
1083
            case 'Strategy':
1084
            case 'Trivia':
1085
                $str = $nodeName;
1086
                break;
1087
        }
1088
1089
        return ($str !== '') ? $str : false;
1090
    }
1091
}
1092