Completed
Push — master ( fd37e6...67719f )
by Lukas Kahwe
08:55 queued 13s
created

ImagineController::createRedirectResponse()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.1111
c 0
b 0
f 0
cc 6
nc 5
nop 4
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
    public function __construct(
50
        FilterService $filterService,
51
        DataManager $dataManager,
52
        SignerInterface $signer,
53
        ?ControllerConfig $controllerConfig = null
54
    ) {
55
        $this->filterService = $filterService;
56
        $this->dataManager = $dataManager;
57
        $this->signer = $signer;
58
59
        if (null === $controllerConfig) {
60
            @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...
61
                '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
62
            ), E_USER_DEPRECATED);
63
        }
64
65
        $this->controllerConfig = $controllerConfig ?? new ControllerConfig(301);
66
    }
67
68
    /**
69
     * This action applies a given filter to a given image, saves the image and redirects the browser to the stored
70
     * image.
71
     *
72
     * The resulting image is cached so subsequent requests will redirect to the cached image instead applying the
73
     * filter and storing the image again.
74
     *
75
     * @param string $path
76
     * @param string $filter
77
     *
78
     * @throws RuntimeException
79
     * @throws NotFoundHttpException
80
     *
81
     * @return RedirectResponse
82
     */
83
    public function filterAction(Request $request, $path, $filter)
84
    {
85
        $path = PathHelper::urlPathToFilePath($path);
86
        $resolver = $request->get('resolver');
87
88
        return $this->createRedirectResponse(function () use ($path, $filter, $resolver, $request) {
89
            return $this->filterService->getUrlOfFilteredImage(
90
                $path,
91
                $filter,
92
                $resolver,
93
                $this->isWebpSupported($request)
94
            );
95
        }, $path, $filter);
96
    }
97
98
    /**
99
     * This action applies a given filter -merged with additional runtime filters- to a given image, saves the image and
100
     * redirects the browser to the stored image.
101
     *
102
     * The resulting image is cached so subsequent requests will redirect to the cached image instead applying the
103
     * filter and storing the image again.
104
     *
105
     * @param string $hash
106
     * @param string $path
107
     * @param string $filter
108
     *
109
     * @throws RuntimeException
110
     * @throws BadRequestHttpException
111
     * @throws NotFoundHttpException
112
     *
113
     * @return RedirectResponse
114
     */
115
    public function filterRuntimeAction(Request $request, $hash, $path, $filter)
116
    {
117
        $resolver = $request->get('resolver');
118
        $path = PathHelper::urlPathToFilePath($path);
119
        $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...
120
121
        if (!\is_array($runtimeConfig)) {
122
            throw new NotFoundHttpException(sprintf('Filters must be an array. Value was "%s"', $runtimeConfig));
123
        }
124
125
        if (true !== $this->signer->check($hash, $path, $runtimeConfig)) {
126
            throw new BadRequestHttpException(sprintf('Signed url does not pass the sign check for path "%s" and filter "%s" and runtime config %s', $path, $filter, json_encode($runtimeConfig)));
127
        }
128
129
        return $this->createRedirectResponse(function () use ($path, $filter, $runtimeConfig, $resolver, $request) {
130
            return $this->filterService->getUrlOfFilteredImageWithRuntimeFilters(
131
                $path,
132
                $filter,
133
                $runtimeConfig,
134
                $resolver,
135
                $this->isWebpSupported($request)
136
            );
137
        }, $path, $filter, $hash);
138
    }
139
140
    private function createRedirectResponse(\Closure $url, string $path, string $filter, ?string $hash = null): RedirectResponse
141
    {
142
        try {
143
            return new RedirectResponse($url(), $this->controllerConfig->getRedirectResponseCode());
144
        } catch (NotLoadableException $exception) {
145
            if (null !== $this->dataManager->getDefaultImageUrl($filter)) {
146
                return new RedirectResponse($this->dataManager->getDefaultImageUrl($filter));
147
            }
148
149
            throw new NotFoundHttpException(sprintf('Source image for path "%s" could not be found', $path), $exception);
150
        } catch (NonExistingFilterException $exception) {
151
            throw new NotFoundHttpException(sprintf('Requested non-existing filter "%s"', $filter), $exception);
152
        } catch (RuntimeException $exception) {
153
            throw new \RuntimeException(vsprintf('Unable to create image for path "%s" and filter "%s". Message was "%s"', [$hash ? sprintf('%s/%s', $hash, $path) : $path, $filter, $exception->getMessage()]), 0, $exception);
154
        }
155
    }
156
157
    private function isWebpSupported(Request $request): bool
158
    {
159
        return false !== mb_stripos($request->headers->get('accept', ''), 'image/webp');
160
    }
161
}
162