Completed
Push — master ( 73901c...0cd867 )
by Lukas Kahwe
13s
created

FileSystemLoader::find()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 18
rs 9.4285
cc 3
eloc 10
nc 3
nop 1
1
<?php
2
3
namespace Liip\ImagineBundle\Binary\Loader;
4
5
use Liip\ImagineBundle\Exception\InvalidArgumentException;
6
use Liip\ImagineBundle\Model\FileBinary;
7
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface;
8
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
9
use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
10
11
class FileSystemLoader implements LoaderInterface
12
{
13
    /**
14
     * @var MimeTypeGuesserInterface
15
     */
16
    protected $mimeTypeGuesser;
17
18
    /**
19
     * @var ExtensionGuesserInterface
20
     */
21
    protected $extensionGuesser;
22
23
    /**
24
     * @var string
25
     */
26
    protected $rootPath;
27
28
    /**
29
     * @param MimeTypeGuesserInterface  $mimeTypeGuesser
30
     * @param ExtensionGuesserInterface $extensionGuesser
31
     * @param string                    $rootPath
32
     */
33
    public function __construct(
34
        MimeTypeGuesserInterface $mimeTypeGuesser,
35
        ExtensionGuesserInterface $extensionGuesser,
36
        $rootPath
37
    ) {
38
        $this->mimeTypeGuesser = $mimeTypeGuesser;
39
        $this->extensionGuesser = $extensionGuesser;
40
41
        if (empty($rootPath) || !($realRootPath = realpath($rootPath))) {
42
            throw new InvalidArgumentException(sprintf('Root image path not resolvable "%s"', $rootPath));
43
        }
44
45
        $this->rootPath = $realRootPath;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function find($path)
52
    {
53
        if (!($absolutePath = realpath($this->rootPath.DIRECTORY_SEPARATOR.$path))) {
54
            throw new NotLoadableException(sprintf('Source image not resolvable "%s"', $path));
55
        }
56
57
        if (0 !== strpos($absolutePath, $this->rootPath)) {
58
            throw new NotLoadableException(sprintf('Source image invalid "%s" as it is outside of the defined root path', $absolutePath));
59
        }
60
61
        $mimeType = $this->mimeTypeGuesser->guess($absolutePath);
62
63
        return new FileBinary(
64
            $absolutePath,
65
            $mimeType,
66
            $this->extensionGuesser->guess($mimeType)
67
        );
68
    }
69
}
70