Completed
Push — 6.8 ( dec908...85856c )
by
unknown
15:07
created

BinaryLoader::find()   B

Complexity

Conditions 5
Paths 13

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 13
nop 1
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * File containing the BinaryLoader class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Bundle\EzPublishCoreBundle\Imagine;
10
11
use Exception;
12
use eZ\Publish\Core\IO\Exception\InvalidBinaryFileIdException;
13
use eZ\Publish\Core\IO\IOServiceInterface;
14
use eZ\Publish\Core\IO\Values\MissingBinaryFile;
15
use Liip\ImagineBundle\Binary\Loader\LoaderInterface;
16
use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
17
use Liip\ImagineBundle\Model\Binary;
18
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface;
19
20
/**
21
 * Binary loader using eZ IOService.
22
 * To be used by LiipImagineBundle.
23
 */
24
class BinaryLoader implements LoaderInterface
25
{
26
    /**
27
     * @var \eZ\Publish\Core\IO\IOServiceInterface
28
     */
29
    private $ioService;
30
31
    /**
32
     * @var \Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface
33
     */
34
    private $extensionGuesser;
35
36
    public function __construct(IOServiceInterface $ioService, ExtensionGuesserInterface $extensionGuesser)
37
    {
38
        $this->ioService = $ioService;
39
        $this->extensionGuesser = $extensionGuesser;
40
    }
41
42
    public function find($path)
43
    {
44
        try {
45
            $binaryFile = $this->ioService->loadBinaryFile($path);
46
            // Treat a MissingBinaryFile as a not loadable file.
47
            if ($binaryFile instanceof MissingBinaryFile) {
48
                throw new NotLoadableException("Source image not found in $path");
49
            }
50
51
            $mimeType = $this->ioService->getMimeType($path);
52
53
            return new Binary(
54
                $this->ioService->getFileContents($binaryFile),
55
                $mimeType,
56
                $this->extensionGuesser->guess($mimeType)
57
            );
58
        } catch (InvalidBinaryFileIdException $e) {
59
            $message =
60
                "Source image not found in $path. Repository images path are expected to be " .
61
                'relative to the var/<site>/storage/images directory';
62
63
            $suggestedPath = preg_replace('#var/[^/]+/storage/images/#', '', $path);
64
            if ($suggestedPath !== $path) {
65
                $message .= "\nSuggested value: '$suggestedPath'";
66
            }
67
68
            throw new NotLoadableException($message);
69
        } catch (Exception $e) {
70
            throw new NotLoadableException("Source image not found in $path", 0, $e);
71
        }
72
    }
73
}
74