Completed
Push — master ( dcbc0d...f67f2c )
by Adrien
05:17 queued 01:22
created

Movie::fetchData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 37
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 25
c 0
b 0
f 0
dl 0
loc 37
rs 9.52
ccs 0
cts 24
cp 0
cc 3
nc 3
nop 0
crap 12
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
        $dateReleaseEntries = $xpath->evaluate('//*[@id="overview-top"]//meta[contains(@itemprop, "datePublished")]/@content');
78
        if ($dateReleaseEntries->length == 1) {
79
            $this->dateRelease = $dateReleaseEntries->item(0)->value;
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...
80
        } else {
81
            $this->dateRelease = null;
82
        }
83
84
        $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...
85
        $this->setReadOnly(false); // If the movie is coming from a joined query, we need to set non-readonly before saving
86
        $this->save();
87
    }
88
89
    /**
90
     * Sets the ID for the movie from any string containing a valid ID
91
     *
92
     * @param string $id
93
     *
94
     * @return \mQueue\Model\Movie
95
     */
96
    public function setId($id)
97
    {
98
        $extractedId = self::extractId($id);
99
        if (!$extractedId) {
100
            throw new Exception(sprintf('Invalid Id for movie. Given "%1$s", extracted "%2$s"', $id, $extractedId));
101
        }
102
103
        $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...
104
105
        return $this;
106
    }
107
108
    /**
109
     * Returns the IMDb url for the movie
110
     *
111
     * @param string $lang suggested language for hostname
112
     *
113
     * @return string
114
     */
115
    public function getImdbUrl()
116
    {
117
        return 'https://www.imdb.com/title/tt' . str_pad($this->id, 7, '0', STR_PAD_LEFT) . '/';
118
    }
119
120
    /**
121
     * Returns the status for this movie and the specified user
122
     *
123
     * @param \mQueue\Model\User $user
124
     *
125
     * @return \mQueue\Model\Status
126
     */
127
    public function getStatus(User $user = null)
128
    {
129
        return StatusMapper::find($this->id, $user);
130
    }
131
132
    /**
133
     * Set the status for the specified user
134
     *
135
     * @param \mQueue\Model\User $user
136
     * @param int $rating @see \mQueue\Model\Status
137
     *
138
     * @return \mQueue\Model\Status
139
     */
140
    public function setStatus(User $user, $rating)
141
    {
142
        $status = StatusMapper::set($this, $user, $rating);
143
144
        return $status;
145
    }
146
147
    /**
148
     * Set the source for the movie if any. In any case record the search date and count
149
     *
150
     * @param array|false $source
151
     */
152
    public function setSource($source): void
153
    {
154
        $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...
155
        ++$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...
156
        if ($source && @$source['score']) {
157
            $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...
158
            $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...
159
            $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...
160
            $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...
161
        }
162
    }
163
}
164