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

AbstractDoctrineLoader   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 62
wmc 4
c 1
b 0
f 0
lcom 1
cbo 2
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
mapPathToId() 0 1 ?
getStreamFromImage() 0 1 ?
A __construct() 0 5 1
A find() 0 18 3
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