Completed
Push — master ( 0a7932...aee286 )
by Maksim
13s
created

StreamLoader   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1
Metric Value
dl 0
loc 67
wmc 10
lcom 1
cbo 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 4
B find() 0 30 6
1
<?php
2
3
namespace Liip\ImagineBundle\Binary\Loader;
4
5
use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
6
7
class StreamLoader implements LoaderInterface
8
{
9
    /**
10
     * The wrapper prefix to append to the path to be loaded.
11
     *
12
     * @var string
13
     */
14
    protected $wrapperPrefix;
15
16
    /**
17
     * A stream context resource to use.
18
     *
19
     * @var resource|null
20
     */
21
    protected $context;
22
23
    /**
24
     * @param string        $wrapperPrefix
25
     * @param resource|null $context
26
     *
27
     * @throws \InvalidArgumentException
28
     */
29
    public function __construct($wrapperPrefix, $context = null)
30
    {
31
        $this->wrapperPrefix = $wrapperPrefix;
32
33
        if ($context && !is_resource($context)) {
34
            throw new \InvalidArgumentException('The given context is no valid resource.');
35
        }
36
37
        $this->context = empty($context) ? null : $context;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function find($path)
44
    {
45
        $name = $this->wrapperPrefix.$path;
46
47
        /*
48
         * This looks strange, but at least in PHP 5.3.8 it will raise an E_WARNING if the 4th parameter is null.
49
         * fopen() will be called only once with the correct arguments.
50
         *
51
         * The error suppression is solely to determine whether the file exists.
52
         * file_exists() is not used as not all wrappers support stat() to actually check for existing resources.
53
         */
54
        if (($this->context && !$resource = @fopen($name, 'r', null, $this->context)) || !$resource = @fopen($name, 'r')) {
55
            throw new NotLoadableException(sprintf('Source image %s not found.', $name));
56
        }
57
58
        // Closing the opened stream to avoid locking of the resource to find.
59
        fclose($resource);
60
61
        try {
62
            $content = file_get_contents($name, null, $this->context);
63
        } catch (\Exception $e) {
64
            throw new NotLoadableException(sprintf('Source image %s could not be loaded.', $name), $e->getCode(), $e);
65
        }
66
67
        if (false === $content) {
68
            throw new NotLoadableException(sprintf('Source image %s could not be loaded.', $name));
69
        }
70
71
        return $content;
72
    }
73
}
74