Completed
Push — master ( 1fd677...d734d1 )
by Alejandro
27s queued 11s
created

PreviewGenerator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 16
dl 0
loc 41
c 0
b 0
f 0
ccs 15
cts 15
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generatePreview() 0 20 3
A __construct() 0 5 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\PreviewGenerator\Service;
5
6
use mikehaertl\wkhtmlto\Image;
7
use Shlinkio\Shlink\PreviewGenerator\Exception\PreviewGenerationException;
8
use Shlinkio\Shlink\PreviewGenerator\Image\ImageBuilderInterface;
9
use Symfony\Component\Filesystem\Filesystem;
10
11
use function sprintf;
12
use function urlencode;
13
14
/** @deprecated */
15
class PreviewGenerator implements PreviewGeneratorInterface
0 ignored issues
show
Deprecated Code introduced by
The interface Shlinkio\Shlink\PreviewG...eviewGeneratorInterface has been deprecated. ( Ignorable by Annotation )

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

15
class PreviewGenerator implements /** @scrutinizer ignore-deprecated */ PreviewGeneratorInterface

This interface has been deprecated. The supplier of the interface has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the interface will be removed and what other interface to use instead.

Loading history...
16
{
17
    /** @var string */
18
    private $location;
19
    /** @var ImageBuilderInterface */
20
    private $imageBuilder;
21
    /** @var Filesystem */
22
    private $filesystem;
23
24 3
    public function __construct(ImageBuilderInterface $imageBuilder, Filesystem $filesystem, string $location)
25
    {
26 3
        $this->location = $location;
27 3
        $this->imageBuilder = $imageBuilder;
28 3
        $this->filesystem = $filesystem;
29
    }
30
31
    /**
32
     * Generates and stores preview for provided website and returns the path to the image file
33
     *
34
     * @throws PreviewGenerationException
35
     */
36 3
    public function generatePreview(string $url): string
37
    {
38 3
        $image = $this->imageBuilder->build(Image::class, ['url' => $url]);
39
40
        // If the file already exists, return its path
41 3
        $cacheId = sprintf('preview_%s.%s', urlencode($url), $image->type);
42 3
        $path = $this->location . '/' . $cacheId;
43 3
        if ($this->filesystem->exists($path)) {
44 1
            return $path;
45
        }
46
47
        // Save and check if an error occurred
48 2
        $image->saveAs($path);
49 2
        $error = $image->getError();
50 2
        if (! empty($error)) {
51 1
            throw PreviewGenerationException::fromImageError($error);
52
        }
53
54
        // Cache the path and return it
55 1
        return $path;
56
    }
57
}
58