Completed
Push — upgrade-2.0-from-1.0 ( 918602 )
by David
13:04
created

ResampleFilterLoader   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 132
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 15
c 0
b 0
f 0
lcom 1
cbo 4
dl 0
loc 132
rs 10

6 Methods

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