StreamLoader::find()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 30
rs 8.8177
cc 6
nc 4
nop 1
1
<?php
2
3
/*
4
 * This file is part of the `liip/LiipImagineBundle` project.
5
 *
6
 * (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
7
 *
8
 * For the full copyright and license information, please view the LICENSE.md
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Liip\ImagineBundle\Binary\Loader;
13
14
use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
15
16
class StreamLoader implements LoaderInterface
17
{
18
    /**
19
     * The wrapper prefix to append to the path to be loaded.
20
     *
21
     * @var string
22
     */
23
    protected $wrapperPrefix;
24
25
    /**
26
     * A stream context resource to use.
27
     *
28
     * @var resource|null
29
     */
30
    protected $context;
31
32
    /**
33
     * @param string        $wrapperPrefix
34
     * @param resource|null $context
35
     *
36
     * @throws \InvalidArgumentException
37
     */
38
    public function __construct($wrapperPrefix, $context = null)
39
    {
40
        $this->wrapperPrefix = $wrapperPrefix;
41
42
        if ($context && !\is_resource($context)) {
43
            throw new \InvalidArgumentException('The given context is no valid resource.');
44
        }
45
46
        $this->context = empty($context) ? null : $context;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function find($path)
53
    {
54
        $name = $this->wrapperPrefix.$path;
55
56
        /*
57
         * This looks strange, but at least in PHP 5.3.8 it will raise an E_WARNING if the 4th parameter is null.
58
         * fopen() will be called only once with the correct arguments.
59
         *
60
         * The error suppression is solely to determine whether the file exists.
61
         * file_exists() is not used as not all wrappers support stat() to actually check for existing resources.
62
         */
63
        if (($this->context && !$resource = @fopen($name, 'rb', null, $this->context)) || !$resource = @fopen($name, 'rb')) {
64
            throw new NotLoadableException(sprintf('Source image %s not found.', $name));
65
        }
66
67
        // Closing the opened stream to avoid locking of the resource to find.
68
        fclose($resource);
69
70
        try {
71
            $content = file_get_contents($name, null, $this->context);
72
        } catch (\Exception $e) {
73
            throw new NotLoadableException(sprintf('Source image %s could not be loaded.', $name), $e->getCode(), $e);
74
        }
75
76
        if (false === $content) {
77
            throw new NotLoadableException(sprintf('Source image %s could not be loaded.', $name));
78
        }
79
80
        return $content;
81
    }
82
}
83