Completed
Pull Request — 2.0 (#1096)
by Rob
02:10
created

ChainLoader::find()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
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 ChainLoader implements LoaderInterface
17
{
18
    /**
19
     * @var LoaderInterface[]
20
     */
21
    private $loaders;
22
23
    /**
24
     * @param LoaderInterface[] $loaders
25
     */
26
    public function __construct(array $loaders)
27
    {
28
        $this->loaders = array_filter($loaders, function ($loader) {
29
            return $loader instanceof LoaderInterface;
30
        });
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function find($path)
37
    {
38
        $exceptions = [];
39
40
        foreach ($this->loaders as $loader) {
41
            try {
42
                return $loader->find($path);
43
            } catch (\Exception $e) {
44
                $exceptions[$e->getMessage()] = $loader;
45
            }
46
        }
47
48
        throw new NotLoadableException(self::getLoaderExceptionMessage($path, $exceptions, $this->loaders));
49
    }
50
51
    /**
52
     * @param string       $path
53
     * @param \Exception[] $exceptions
54
     * @param array        $loaders
55
     *
56
     * @return string
57
     */
58
    private static function getLoaderExceptionMessage(string $path, array $exceptions, array $loaders): string
59
    {
60
        array_walk($loaders, function (LoaderInterface &$loader, string $name): void {
61
            $loader = sprintf('%s=[%s]', (new \ReflectionObject($loader))->getShortName(), $name);
62
        });
63
64
        array_walk($exceptions, function (LoaderInterface &$loader, string $message): void {
65
            $loader = sprintf('%s=[%s]', (new \ReflectionObject($loader))->getShortName(), $message);
66
        });
67
68
        return vsprintf('Source image not resolvable "%s" using "%s" %d loaders (internal exceptions: %s).', [
69
            $path,
70
            implode(', ', $loaders),
71
            count($loaders),
72
            implode(', ', $exceptions),
73
        ]);
74
    }
75
}
76