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