Completed
Push — master ( cc131d...ea3b27 )
by Valentyn
03:32
created

ActorPhoto::savePhoto()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 0
cts 22
cp 0
rs 9.0488
c 0
b 0
f 0
cc 5
nc 9
nop 2
crap 30
1
<?php
2
3
namespace App\Actors\Utils;
4
5
// TODO need to refactor.. But I need to find more information about best practises, some recommendations and so on
6
// I want to make easy way to change urls to images (for example if we would have some new server for files etc)
7
class ActorPhoto
8
{
9
    const TMDB_BASE_URL = 'https://image.tmdb.org/t/p/original';
10
    const BASE_URL = '/f/actors/{actorId}/photo.jpg';
11
    const BASE_PATH = __DIR__.'/../../../public' . self::BASE_URL;
12
13
    public static function savePhoto(int $actorId, string $photoUrl): ?string
14
    {
15
        $saveTo = str_replace('{actorId}', $actorId, self::BASE_PATH);
16
        $destinationDir = dirname($saveTo);
17
18
        if (is_dir($destinationDir) === false) {
19
            if (is_file($destinationDir)) {
20
                unlink($destinationDir);
21
            }
22
            mkdir($destinationDir);
23
        }
24
25
        $ch = curl_init($photoUrl);
26
        curl_setopt($ch, CURLOPT_HEADER, 0);
27
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
28
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
29
        $raw = curl_exec($ch);
30
31
        if (curl_errno($ch) !== 0) {
32
            curl_close($ch);
33
34
            return null;
35
        }
36
37
        curl_close($ch);
38
39
        if (file_exists($saveTo)) {
40
            unlink($saveTo);
41
        }
42
        $fp = fopen($saveTo, 'x');
43
        fwrite($fp, $raw);
44
        fclose($fp);
45
46
        return $saveTo;
47
    }
48
49
    public static function getUrl(int $actorId): string
50
    {
51
        return str_replace('{actorId}', $actorId, self::BASE_URL);
52
    }
53
}
54