ResampleFilterLoader::resolveOptions()   A
last analyzed

Complexity

Conditions 5
Paths 2

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 9.0488
c 0
b 0
f 0
cc 5
nc 2
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\Imagine\Filter\Loader;
13
14
use Imagine\Image\ImageInterface;
15
use Imagine\Image\ImagineInterface;
16
use Liip\ImagineBundle\Exception\Imagine\Filter\LoadFilterException;
17
use Liip\ImagineBundle\Exception\InvalidArgumentException;
18
use Symfony\Component\OptionsResolver\Exception\ExceptionInterface;
19
use Symfony\Component\OptionsResolver\Options;
20
use Symfony\Component\OptionsResolver\OptionsResolver;
21
22
class ResampleFilterLoader implements LoaderInterface
23
{
24
    /**
25
     * @var ImagineInterface
26
     */
27
    private $imagine;
28
29
    public function __construct(ImagineInterface $imagine)
30
    {
31
        $this->imagine = $imagine;
32
    }
33
34
    /**
35
     * @throws LoadFilterException
36
     *
37
     * @return ImageInterface
38
     */
39
    public function load(ImageInterface $image, array $options = [])
40
    {
41
        $options = $this->resolveOptions($options);
42
        $tmpFile = $this->getTemporaryFile($options['temp_dir']);
43
44
        try {
45
            $image->save($tmpFile, $this->getImagineSaveOptions($options));
46
            $image = $this->imagine->open($tmpFile);
47
            $this->delTemporaryFile($tmpFile);
48
        } catch (\Exception $exception) {
49
            $this->delTemporaryFile($tmpFile);
50
            throw new LoadFilterException('Unable to save/open file in resample filter loader.', null, $exception);
51
        }
52
53
        return $image;
54
    }
55
56
    /**
57
     * @param string $path
58
     *
59
     * @throws \RuntimeException
60
     *
61
     * @return string
62
     */
63
    private function getTemporaryFile($path)
64
    {
65
        if (!is_dir($path) || false === $file = tempnam($path, 'liip-imagine-bundle')) {
66
            throw new \RuntimeException(sprintf('Unable to create temporary file in "%s" base path.', $path));
67
        }
68
69
        return $file;
70
    }
71
72
    /**
73
     * @param $file
74
     *
75
     * @throws \RuntimeException
76
     */
77
    private function delTemporaryFile($file)
78
    {
79
        if (file_exists($file)) {
80
            unlink($file);
81
        }
82
    }
83
84
    /**
85
     * @return array
86
     */
87
    private function getImagineSaveOptions(array $options)
88
    {
89
        $saveOptions = [
90
            'resolution-units' => $options['unit'],
91
            'resolution-x' => $options['x'],
92
            'resolution-y' => $options['y'],
93
        ];
94
95
        if (isset($options['filter'])) {
96
            $saveOptions['resampling-filter'] = $options['filter'];
97
        }
98
99
        return $saveOptions;
100
    }
101
102
    /**
103
     * @return array
104
     */
105
    private function resolveOptions(array $options)
106
    {
107
        $resolver = new OptionsResolver();
108
109
        $resolver->setRequired(['x', 'y', 'unit', 'temp_dir']);
110
        $resolver->setDefined(['filter']);
111
        $resolver->setDefault('temp_dir', sys_get_temp_dir());
112
        $resolver->setDefault('filter', 'UNDEFINED');
113
114
        $resolver->setAllowedTypes('x', ['int', 'float']);
115
        $resolver->setAllowedTypes('y', ['int', 'float']);
116
        $resolver->setAllowedTypes('temp_dir', ['string']);
117
        $resolver->setAllowedTypes('filter', ['string']);
118
119
        $resolver->setAllowedValues('unit', [
120
            ImageInterface::RESOLUTION_PIXELSPERINCH,
121
            ImageInterface::RESOLUTION_PIXELSPERCENTIMETER,
122
        ]);
123
124
        $resolver->setNormalizer('filter', function (Options $options, $value) {
125
            foreach (['\Imagine\Image\ImageInterface::FILTER_%s', '\Imagine\Image\ImageInterface::%s', '%s'] as $format) {
126
                if (\defined($constant = sprintf($format, mb_strtoupper($value))) || \defined($constant = sprintf($format, $value))) {
127
                    return \constant($constant);
128
                }
129
            }
130
131
            throw new InvalidArgumentException('Invalid value for "filter" option: must be a valid constant resolvable using one of formats '.'"\Imagine\Image\ImageInterface::FILTER_%s", "\Imagine\Image\ImageInterface::%s", or "%s".');
132
        });
133
134
        try {
135
            return $resolver->resolve($options);
136
        } catch (ExceptionInterface $exception) {
137
            throw new InvalidArgumentException(sprintf('Invalid option(s) passed to %s::load().', __CLASS__), null, $exception);
138
        }
139
    }
140
}
141