forked from liip/LiipImagineBundle
/
ChainLoader.php
75 lines (64 loc) · 2.1 KB
/
ChainLoader.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
<?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 ChainLoader implements LoaderInterface
{
/**
* @var LoaderInterface[]
*/
private $loaders;
/**
* @param LoaderInterface[] $loaders
*/
public function __construct(array $loaders)
{
$this->loaders = array_filter($loaders, function ($loader) {
return $loader instanceof LoaderInterface;
});
}
/**
* {@inheritdoc}
*/
public function find($path)
{
$exceptions = [];
foreach ($this->loaders as $loader) {
try {
return $loader->find($path);
} catch (\Exception $e) {
$exceptions[$e->getMessage()] = $loader;
}
}
throw new NotLoadableException(self::getLoaderExceptionMessage($path, $exceptions, $this->loaders));
}
/**
* @param string $path
* @param \Exception[] $exceptions
* @param array $loaders
*
* @return string
*/
private static function getLoaderExceptionMessage(string $path, array $exceptions, array $loaders): string
{
array_walk($loaders, function (LoaderInterface &$loader, string $name): void {
$loader = sprintf('%s=[%s]', (new \ReflectionObject($loader))->getShortName(), $name);
});
array_walk($exceptions, function (LoaderInterface &$loader, string $message): void {
$loader = sprintf('%s=[%s]', (new \ReflectionObject($loader))->getShortName(), $message);
});
return vsprintf('Source image not resolvable "%s" using "%s" %d loaders (internal exceptions: %s).', [
$path,
implode(', ', $loaders),
count($loaders),
implode(', ', $exceptions),
]);
}
}