Completed
Pull Request — master (#732)
by 12345
03:41
created

AbstractDoctrineLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace Liip\ImagineBundle\Binary\Loader;
4
5
use Doctrine\Common\Persistence\ObjectManager;
6
use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
7
8
abstract class AbstractDoctrineLoader implements LoaderInterface
9
{
10
    /**
11
     * @var ObjectManager
12
     */
13
    protected $manager;
14
15
    /**
16
     * @var string
17
     */
18
    protected $class;
19
20
    /**
21
     * @param ObjectManager $manager
22
     * @param string        $class
23
     */
24
    public function __construct(ObjectManager $manager, $class = null)
25
    {
26
        $this->manager = $manager;
27
        $this->class = $class;
28
    }
29
30
    /**
31
     * Map the requested path (ie. subpath in the URL) to an id that can be used to lookup the image in the Doctrine store.
32
     *
33
     * @param string $path
34
     *
35
     * @return string
36
     */
37
    abstract protected function mapPathToId($path);
38
39
    /**
40
     * Return a stream resource from the Doctrine entity/document with the image content.
41
     *
42
     * @param object $image
43
     *
44
     * @return resource
45
     */
46
    abstract protected function getStreamFromImage($image);
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function find($path)
52
    {
53
        $image = $this->manager->find($this->class, $this->mapPathToId($path));
54
55
        if (!$image) {
56
            // try to find the image without extension
57
            $info = pathinfo($path);
58
            $name = $info['dirname'].'/'.$info['filename'];
59
60
            $image = $this->manager->find($this->class, $this->mapPathToId($name));
61
        }
62
63
        if (!$image) {
64
            throw new NotLoadableException(sprintf('Source image was not found with id "%s"', $path));
65
        }
66
67
        return stream_get_contents($this->getStreamFromImage($image));
68
    }
69
}
70