Completed
Push — master ( 1b4b09...acfc22 )
by Valentyn
10:09
created

Poster::savePoster()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 0
cts 22
cp 0
rs 9.0648
c 0
b 0
f 0
cc 5
nc 9
nop 2
crap 30
1
<?php
2
3
namespace App\Movies\Utils;
4
5
class Poster
6
{
7
    const TMDB_BASE_URL = 'https://image.tmdb.org/t/p/original';
8
    const BASE_URL = '/f/movies/{movieId}/poster.jpg';
9
    const BASE_PATH = __DIR__ . '/../../../public/f/movies/{movieId}/poster.jpg';
10
11
    /**
12
     * @param int $movieId
13
     * @param string $posterUrl
14
     * @return null|string
15
     */
16
    public static function savePoster(int $movieId, string $posterUrl): ?string
17
    {
18
        $saveTo = str_replace('{movieId}', $movieId, self::BASE_PATH);
19
        $destinationDir = dirname($saveTo);
20
21
        if (is_dir($destinationDir) === false) {
22
            if (is_file($destinationDir)) {
23
                unlink($destinationDir);
24
            }
25
            mkdir($destinationDir);
26
        }
27
28
        $ch = curl_init($posterUrl);
29
        curl_setopt($ch, CURLOPT_HEADER, 0);
30
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
31
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
32
        $raw = curl_exec($ch);
33
34
        if (curl_errno($ch) !== 0) {
35
            curl_close($ch);
36
            return null;
37
        }
38
39
        curl_close($ch);
40
41
        if (file_exists($saveTo)) {
42
            unlink($saveTo);
43
        }
44
        $fp = fopen($saveTo, 'x');
45
        fwrite($fp, $raw);
46
        fclose($fp);
47
48
        return $saveTo;
49
    }
50
51
    /**
52
     * @param int $movieId
53
     * @return string
54
     */
55
    public static function getUrl(int $movieId): string
56
    {
57
        return str_replace('{movieId}', $movieId, self::BASE_URL);
58
    }
59
}