Failed Conditions
Push — master ( 0132b0...4515f8 )
by Adrien
02:55
created

Movie::getImdbUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace mQueue\Model;
4
5
use DOMDocument;
6
use DOMXPath;
7
use Exception;
8
use Zend_Date;
9
10
/**
11
 * A movie
12
 */
13
class Movie extends AbstractModel
14
{
15
    /**
16
     * Extract IMDb id from URL
17
     *
18
     * @param string $string
19
     *
20
     * @return null|string the id extracted
21
     */
22 2
    public static function extractId($string)
23
    {
24 2
        preg_match_all("/(\d{7,})/", $string, $r);
25 2
        if (isset($r[1][0])) {
26 1
            return $r[1][0];
27
        }
28
29 2
        return null;
30
    }
31
32
    /**
33
     * Returns the title, if needed fetch the title from IMDb
34
     *
35
     * @return string
36
     */
37 1
    public function getTitle()
38
    {
39
        // If we didn't get the title yet, fetch it and save in our database
40 1
        if (!($this->title)) {
41
            $this->fetchData();
42
        }
43
44 1
        return $this->title;
45
    }
46
47
    /**
48
     * Fetch data from IMDb and store in database (possibly overwriting)
49
     */
50
    public function fetchData(): void
51
    {
52
        $ch = curl_init($this->getImdbUrl());
53
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept-Language: en-US,en;q=0.8']);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_setopt() does only seem to accept resource, 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

53
        curl_setopt(/** @scrutinizer ignore-type */ $ch, CURLOPT_HTTPHEADER, ['Accept-Language: en-US,en;q=0.8']);
Loading history...
54
        curl_setopt($ch, CURLOPT_HEADER, false);
55
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
56
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
57
58
        $file = curl_exec($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, 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

58
        $file = curl_exec(/** @scrutinizer ignore-type */ $ch);
Loading history...
59
        curl_close($ch);
0 ignored issues
show
Bug introduced by
It seems like $ch can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, 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

59
        curl_close(/** @scrutinizer ignore-type */ $ch);
Loading history...
60
61
        $document = new DOMDocument();
62
        @$document->loadHTML($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for loadHTML(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

62
        /** @scrutinizer ignore-unhandled */ @$document->loadHTML($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
63
        $xpath = new DOMXPath($document);
64
65
        // Extract title
66
        $titleEntries = $xpath->evaluate('//meta[contains(@property, "og:title")]/@content');
67
        if ($titleEntries->length == 1) {
68
            $rawTitle = $titleEntries->item(0)->value;
69
            $this->title = preg_replace('~ - IMDb$~', '', $rawTitle);
0 ignored issues
show
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
70
        } else {
71
            $this->title = '[title not available, could not fetch from IMDb]';
72
73
            return; // If there is not even title give up everything
74
        }
75
76
        // Extract release date
77
        $jsonLd = $xpath->evaluate('//script[@type="application/ld+json"]/text()');
78
        if ($jsonLd->length == 1) {
79
            $json = json_decode($jsonLd->item(0)->data, true);
80
            $this->dateRelease = $json['datePublished'] ?? null;
0 ignored issues
show
Bug Best Practice introduced by
The property dateRelease does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
81
        } else {
82
            $this->dateRelease = null;
83
        }
84
85
        $this->dateUpdate = Zend_Date::now()->get(Zend_Date::ISO_8601);
0 ignored issues
show
Bug Best Practice introduced by
The property dateUpdate does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
86
        $this->setReadOnly(false); // If the movie is coming from a joined query, we need to set non-readonly before saving
87
        $this->save();
88
    }
89
90
    /**
91
     * Sets the ID for the movie from any string containing a valid ID
92
     *
93
     * @param string $id
94
     *
95
     * @return \mQueue\Model\Movie
96
     */
97
    public function setId($id)
98
    {
99
        $extractedId = self::extractId($id);
100
        if (!$extractedId) {
101
            throw new Exception(sprintf('Invalid Id for movie. Given "%1$s", extracted "%2$s"', $id, $extractedId));
102
        }
103
104
        $this->id = $extractedId;
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
105
106
        return $this;
107
    }
108
109
    /**
110
     * Returns the IMDb url for the movie
111
     *
112
     * @return string
113
     */
114
    public function getImdbUrl()
115
    {
116
        return 'https://www.imdb.com/title/tt' . str_pad($this->id, 7, '0', STR_PAD_LEFT) . '/';
117
    }
118
119
    /**
120
     * Returns the status for this movie and the specified user
121
     *
122
     * @param \mQueue\Model\User $user
123
     *
124
     * @return \mQueue\Model\Status
125
     */
126
    public function getStatus(User $user = null)
127
    {
128
        return StatusMapper::find($this->id, $user);
129
    }
130
131
    /**
132
     * Set the status for the specified user
133
     *
134
     * @param \mQueue\Model\User $user
135
     * @param int $rating @see \mQueue\Model\Status
136
     *
137
     * @return \mQueue\Model\Status
138
     */
139
    public function setStatus(User $user, $rating)
140
    {
141
        $status = StatusMapper::set($this, $user, $rating);
142
143
        return $status;
144
    }
145
146
    /**
147
     * Set the source for the movie if any. In any case record the search date and count
148
     *
149
     * @param array|false $source
150
     */
151
    public function setSource($source): void
152
    {
153
        $this->dateSearch = Zend_Date::now()->get(Zend_Date::ISO_8601);
0 ignored issues
show
Bug Best Practice introduced by
The property dateSearch does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
154
        ++$this->searchCount;
0 ignored issues
show
Bug Best Practice introduced by
The property searchCount does not exist on mQueue\Model\Movie. Since you implemented __get, consider adding a @property annotation.
Loading history...
155
        if ($source && @$source['score']) {
156
            $this->identity = $source['identity'];
0 ignored issues
show
Bug Best Practice introduced by
The property identity does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
157
            $this->quality = $source['quality'];
0 ignored issues
show
Bug Best Practice introduced by
The property quality does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
158
            $this->score = $source['score'];
0 ignored issues
show
Bug Best Practice introduced by
The property score does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
159
            $this->source = $source['link'];
0 ignored issues
show
Bug Best Practice introduced by
The property source does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
160
        }
161
    }
162
}
163