Completed
Push — master ( 1b4b09...acfc22 )
by Valentyn
10:09
created

ImageController::resizeImage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 17
cp 0
rs 9.504
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
1
<?php
2
3
namespace App\Images\Controller;
4
5
use App\Controller\BaseController;
6
use Gumlet\ImageResize;
7
use Symfony\Component\HttpFoundation\BinaryFileResponse;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\Routing\Annotation\Route;
10
11
class ImageController extends BaseController
12
{
13
    /**
14
     * @Route("/f/{image}", methods={"GET"}, name="resizeImage", requirements={"image"=".+"})
15
     * @param string $image
16
     * @return BinaryFileResponse|Response
17
     * @throws \Gumlet\ImageResizeException
18
     */
19
    public function resizeImage(string $image)
20
    {
21
        $pathToFile = PUBLIC_PATH . '/f/' . $image;
22
        $imagePathParts = explode('/', $image);
23
        $filename = end($imagePathParts);
24
        $filenameParts = explode('.', $filename);
25
        $ext = end($filenameParts);
26
27
        if (in_array($ext, ['jpg']) === false) {
28
            return new Response('Image not found (404)', 404);
29
        }
30
        $size = $filenameParts[1]; // string '64x64'
31
        $originalFile = str_replace(".$size", '', $pathToFile);
32
33
        if (file_exists($originalFile) === false) {
34
            return new Response('Image not found (404)', 404);
35
        }
36
37
        // resize image and then return
38
        list($width, $height) = explode('x', $size);
39
        $resizer = new ImageResize($originalFile);
40
        $resizer->crop($width, $height);
41
        $resizer->save($pathToFile);
42
43
        return new BinaryFileResponse($pathToFile);
44
    }
45
}