Completed
Pull Request — 2.x (#1300)
by Gocha
01:52
created

FormatExtensionResolver::replaceExtension()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 2
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\Imagine\Cache\Resolver;
13
14
use Liip\ImagineBundle\Binary\BinaryInterface;
15
use Liip\ImagineBundle\Imagine\Filter\FilterConfiguration;
16
17
class FormatExtensionResolver implements ResolverInterface
18
{
19
    /**
20
     * @var ResolverInterface
21
     */
22
    private $resolver;
23
24
    /**
25
     * @var FilterConfiguration
26
     */
27
    private $filterConfig;
28
29
    public function __construct(ResolverInterface $resolver, FilterConfiguration $filterConfig)
30
    {
31
        $this->resolver = $resolver;
32
        $this->filterConfig = $filterConfig;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function resolve($path, $filter)
39
    {
40
        $path = $this->replaceExtension($path, $filter);
41
42
        return $this->resolver->resolve($path, $filter);
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function store(BinaryInterface $binary, $targetPath, $filter)
49
    {
50
        $targetPath = $this->replaceExtension($targetPath, $filter);
51
52
        return $this->resolver->store($binary, $targetPath, $filter);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function isStored($path, $filter)
59
    {
60
        $path = $this->replaceExtension($path, $filter);
61
62
        return $this->resolver->isStored($path, $filter);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function remove(array $paths, array $filters)
69
    {
70
        $newPaths = [];
71
        foreach ($paths as $path) {
72
            foreach ($filters as $filter) {
73
                $newPath = $this->replaceExtension($path, $filter);
74
                if (!\in_array($newPath, $newPaths, true)) {
75
                    $newPaths[] = $newPath;
76
                }
77
            }
78
        }
79
80
        return $this->resolver->remove($newPaths, $filters);
81
    }
82
83
    private function replaceExtension(string $path, string $filter): string
84
    {
85
        $config = $this->filterConfig->get($filter);
86
        if (!$config['format']) {
87
            return $path;
88
        }
89
90
        $extension = pathinfo($path, PATHINFO_EXTENSION);
91
        $path = ($extension ? mb_substr($path, 0, -mb_strlen($extension)) : $path.'.').$config['format'];
92
93
        return $path;
94
    }
95
}
96