Completed
Push — master ( 1e1a94...fe204c )
by Valentyn
05:23
created

Megogo::getUrlByTitle()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 0
cts 17
cp 0
rs 9.0968
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 30
1
<?php
2
3
namespace App\Movies\Parser;
4
5
use Symfony\Component\DomCrawler\Crawler;
6
7
class Megogo
8
{
9
    private const ENDPOINT = 'https://megogo.net/ua/films/main?q={title}&view_type=list&ajax=true&widget=widget_7';
10
11
    public function getUrlByTitle(string $originalTitle): string
12
    {
13
        $endpoint = strtr(self::ENDPOINT, [
14
            '{title}' => urlencode($originalTitle)
15
        ]);
16
17
        $html = $this->getHtml($endpoint);
18
19
        if (!$html) {
20
            throw new \ErrorException('Html cant be loaded');
21
        }
22
23
        $crawler = new Crawler($html);
24
        $searchTitle = trim($crawler->filter('.search-results-title')->first()->text());
25
26
        if (!$searchTitle) {
27
            throw new \ErrorException('Cant find search title');
28
        }
29
30
        $firstWord = current(explode(' ', $searchTitle));
31
        if (mb_strtolower($firstWord) !== 'найдено') {
32
            throw new \ErrorException('This movie not found on megogo');
33
        }
34
35
        $url = $crawler->filter('a.invisible-overlay')->first()->attr('href');
36
37
        if (!$url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
38
            throw new \ErrorException('Url of movie not found');
39
        }
40
41
        return 'https://megogo.net' . $url;
42
    }
43
44
    private function getHtml(string $endpoint): string
45
    {
46
        $c = curl_init($endpoint);
47
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
48
        $json = curl_exec($c);
49
        curl_close($c);
50
51
        if (!$json) {
52
            //todo write to log curl_error()
53
            return '';
54
        }
55
56
        $response = json_decode($json, true);
57
58
        return $response['data']['widgets']['widget_7']['html'];
59
    }
60
}