Completed
Pull Request — master (#1307)
by Peter
01:44
created

ImagineController::isSupportWebp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
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\Controller;
13
14
use Imagine\Exception\RuntimeException;
15
use Liip\ImagineBundle\Config\Controller\ControllerConfig;
16
use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
17
use Liip\ImagineBundle\Exception\Imagine\Filter\NonExistingFilterException;
18
use Liip\ImagineBundle\Imagine\Cache\Helper\PathHelper;
19
use Liip\ImagineBundle\Imagine\Cache\SignerInterface;
20
use Liip\ImagineBundle\Imagine\Data\DataManager;
21
use Liip\ImagineBundle\Service\FilterService;
22
use Symfony\Component\HttpFoundation\RedirectResponse;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
25
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
26
27
class ImagineController
28
{
29
    /**
30
     * @var FilterService
31
     */
32
    private $filterService;
33
34
    /**
35
     * @var DataManager
36
     */
37
    private $dataManager;
38
39
    /**
40
     * @var SignerInterface
41
     */
42
    private $signer;
43
44
    /**
45
     * @var ControllerConfig
46
     */
47
    private $controllerConfig;
48
49
    /**
50
     * @param FilterService         $filterService
51
     * @param DataManager           $dataManager
52
     * @param SignerInterface       $signer
53
     * @param ControllerConfig|null $controllerConfig
54
     */
55
    public function __construct(FilterService $filterService, DataManager $dataManager, SignerInterface $signer, ?ControllerConfig $controllerConfig = null)
56
    {
57
        $this->filterService = $filterService;
58
        $this->dataManager = $dataManager;
59
        $this->signer = $signer;
60
61
        if (null === $controllerConfig) {
62
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
63
                'Instantiating "%s" without a forth argument of type "%s" is deprecated since 2.2.0 and will be required in 3.0.', self::class, ControllerConfig::class
64
            ), E_USER_DEPRECATED);
65
        }
66
67
        $this->controllerConfig = $controllerConfig ?? new ControllerConfig(301);
68
    }
69
70
    /**
71
     * This action applies a given filter to a given image, saves the image and redirects the browser to the stored
72
     * image.
73
     *
74
     * The resulting image is cached so subsequent requests will redirect to the cached image instead applying the
75
     * filter and storing the image again.
76
     *
77
     * @param Request $request
78
     * @param string  $path
79
     * @param string  $filter
80
     *
81
     * @throws RuntimeException
82
     * @throws NotFoundHttpException
83
     *
84
     * @return RedirectResponse
85
     */
86
    public function filterAction(Request $request, $path, $filter)
87
    {
88
        $path = PathHelper::urlPathToFilePath($path);
89
        $resolver = $request->get('resolver');
90
91
        return $this->createRedirectResponse(function () use ($path, $filter, $resolver, $request) {
92
            return $this->filterService->getUrlOfFilteredImage(
93
                $path,
94
                $filter,
95
                $resolver,
96
                $this->isSupportWebp($request)
97
            );
98
        }, $path, $filter);
99
    }
100
101
    /**
102
     * This action applies a given filter -merged with additional runtime filters- to a given image, saves the image and
103
     * redirects the browser to the stored image.
104
     *
105
     * The resulting image is cached so subsequent requests will redirect to the cached image instead applying the
106
     * filter and storing the image again.
107
     *
108
     * @param Request $request
109
     * @param string  $hash
110
     * @param string  $path
111
     * @param string  $filter
112
     *
113
     * @throws RuntimeException
114
     * @throws BadRequestHttpException
115
     * @throws NotFoundHttpException
116
     *
117
     * @return RedirectResponse
118
     */
119
    public function filterRuntimeAction(Request $request, $hash, $path, $filter)
120
    {
121
        $resolver = $request->get('resolver');
122
        $path = PathHelper::urlPathToFilePath($path);
123
        $runtimeConfig = $request->query->get('filters', []);
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
124
125
        if (!\is_array($runtimeConfig)) {
126
            throw new NotFoundHttpException(sprintf('Filters must be an array. Value was "%s"', $runtimeConfig));
127
        }
128
129
        if (true !== $this->signer->check($hash, $path, $runtimeConfig)) {
130
            throw new BadRequestHttpException(sprintf(
131
                'Signed url does not pass the sign check for path "%s" and filter "%s" and runtime config %s',
132
                $path,
133
                $filter,
134
                json_encode($runtimeConfig)
135
            ));
136
        }
137
138
        return $this->createRedirectResponse(function () use ($path, $filter, $runtimeConfig, $resolver, $request) {
139
            return $this->filterService->getUrlOfFilteredImageWithRuntimeFilters(
140
                $path,
141
                $filter,
142
                $runtimeConfig,
143
                $resolver,
144
                $this->isSupportWebp($request)
145
            );
146
        }, $path, $filter, $hash);
147
    }
148
149
    /**
150
     * @param \Closure    $url
151
     * @param string      $path
152
     * @param string      $filter
153
     * @param string|null $hash
154
     *
155
     * @return RedirectResponse
156
     */
157
    private function createRedirectResponse(\Closure $url, string $path, string $filter, ?string $hash = null): RedirectResponse
158
    {
159
        try {
160
            return new RedirectResponse($url(), $this->controllerConfig->getRedirectResponseCode());
161
        } catch (NotLoadableException $exception) {
162
            if (null !== $this->dataManager->getDefaultImageUrl($filter)) {
163
                return new RedirectResponse($this->dataManager->getDefaultImageUrl($filter));
164
            }
165
166
            throw new NotFoundHttpException(sprintf('Source image for path "%s" could not be found', $path), $exception);
167
        } catch (NonExistingFilterException $exception) {
168
            throw new NotFoundHttpException(sprintf('Requested non-existing filter "%s"', $filter), $exception);
169
        } catch (RuntimeException $exception) {
170
            throw new \RuntimeException(vsprintf('Unable to create image for path "%s" and filter "%s". Message was "%s"', [
171
                $hash ? sprintf('%s/%s', $hash, $path) : $path,
172
                $filter,
173
                $exception->getMessage(),
174
            ]), 0, $exception);
175
        }
176
    }
177
178
    /**
179
     * @param Request $request
180
     *
181
     * @return bool
182
     */
183
    private function isSupportWebp(Request $request)
184
    {
185
        return false !== stripos($request->headers->get('accept', ''), 'image/webp');
186
    }
187
}
188