Completed
Push — master ( ae9ef6...808367 )
by Benjamin
02:31
created

MediaController::uploadFilesWysiwygAction()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 1 Features 0
Metric Value
c 7
b 1
f 0
dl 0
loc 22
rs 6.9811
cc 7
eloc 14
nc 7
nop 1
1
<?php
2
3
namespace Alpixel\Bundle\MediaBundle\Controller;
4
5
use Alpixel\Bundle\MediaBundle\Entity\Media;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\Filesystem\Filesystem;
10
use Symfony\Component\HttpFoundation\File\Exception\UploadException;
11
use Symfony\Component\HttpFoundation\File\UploadedFile;
12
use Symfony\Component\HttpFoundation\JsonResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
16
class MediaController extends Controller
17
{
18
    /**
19
     * @Route("/media/upload/wysiwyg", name="upload_wysiwyg")
20
     *
21
     * @Method({"POST"})
22
     *
23
     * @param Request $request
24
     *
25
     * @return Response
26
     */
27
    public function uploadFilesWysiwygAction(Request $request)
0 ignored issues
show
Coding Style introduced by
uploadFilesWysiwygAction uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
uploadFilesWysiwygAction uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
uploadFilesWysiwygAction uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
28
    {
29
        $template = 'AlpixelMediaBundle:admin:blocks/upload_wysiwyg.html.twig';
30
31
        try {
32
            $file = $request->files->get("upload");
33
            if ($file !== null) {
34
                $media = $this->get('alpixel_media.manager')->upload($file, $request->get('folder'), null);
35
                return $this->render($template, [
36
                    'file_uploaded' => $media,
37
                ]);
38
            } else {
39
                if (empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
40
                    throw new UploadException(sprintf("Votre fichier dépasse la limite maximale de %s", ini_get('post_max_size')));
41
                }
42
            }
43
        } catch (\Exception $e) {
44
            return $this->render($template, [
45
                'error' => $e->getMessage()
46
            ]);
47
        }
48
    }
49
50
    /**
51
     * @Route("/media/upload", name="upload")
52
     *
53
     * @Method({"POST"})
54
     *
55
     * @param Request $request
56
     *
57
     * @return JsonResponse
58
     */
59
    public function uploadAction(Request $request)
60
    {
61
        $returnData = [];
62
63
        if ($request->get('lifetime') !== null) {
64
            $lifetime = new \DateTime($request->get('lifetime'));
65
        }
66
67
        if (empty($lifetime) || $lifetime == new \DateTime('now')) {
68
            $lifetime = new \DateTime('+6 hours');
69
        }
70
71
        $mediaPreview = $this->get('twig.extension.media_preview_extension');
72
        foreach ($request->files as $files) {
73
            if (!is_array($files)) {
74
                $files = [$files];
75
            }
76
            foreach ($files as $file) {
77
                $media = $this->get('alpixel_media.manager')->upload($file, $request->get('folder'), $lifetime);
78
                $path = $mediaPreview->generatePathFromSecretKey($media->getSecretKey());
79
                $returnData[] = [
80
                    'id' => $media->getSecretKey(),
81
                    'path' => $path,
82
                    'name' => $media->getName(),
83
                ];
84
            }
85
        }
86
87
        return new JsonResponse($returnData);
88
    }
89
90
    /**
91
     * @Route("/media/download/{id}-{name}", name="media_download_public")
92
     * @Route("/media/download/{filter}/{id}-{name}", name="media_download_public_filters")
93
     * @Route("/media/download/{secretKey}/{filter}", name="media_download_private")
94
     *
95
     * @Method({"GET"})
96
     */
97
    public function downloadMediaAction(Media $media)
98
    {
99
        $response = new Response();
100
        $response->setContent(file_get_contents($this->get('alpixel_media.manager')->getAbsolutePath($media)));
101
        $response->headers->set('Content-Type', 'application/force-download');
102
        $response->headers->set('Content-disposition', 'filename=' . $media->getName());
103
104
        return $response;
105
    }
106
107
    /**
108
     * @Route("/media/{id}-{name}", name="media_show_public")
109
     * @Route("/media/{filter}/{id}-{name}", name="media_show_public_filters")
110
     * @Route("/media/{secretKey}/{filter}", name="media_show_private")
111
     *
112
     * @Method({"GET"})
113
     */
114
    public function showMediaAction(Request $request, Media $media, $filter = null)
115
    {
116
        $response = new Response();
117
        $lastModified = new \DateTime('now');
118
119
        //Checking if it is an image or not
120
        $src = $this->get('alpixel_media.manager')->getAbsolutePath($media);
121
        $isImage = @getimagesize($src);
122
123
        if ($isImage) {
124
            $response->headers->set('Content-disposition', 'inline;filename=' . $media->getName());
125
            if (!empty($filter) && $isImage) {
126
                $src = $this->get('alpixel_media.manager')->getAbsolutePath($media, $filter);
127
                $dataManager = $this->get('liip_imagine.data.manager'); // the data manager service
128
                $filterManager = $this->get('liip_imagine.filter.manager'); // the filter manager service
129
                $uploadDir = $this->get('alpixel_media.manager')->getUploadDir($filter);
130
131
                if (!is_file($src)) {
132
                    $fs = new Filesystem();
133
                    if (!$fs->exists($uploadDir . $media->getFolder())) {
134
                        $fs->mkdir($uploadDir . $media->getFolder());
135
                    }
136
137
                    $path = 'upload/' . $media->getUri();
138
139
                    // find the image and determine its type
140
                    $image = $dataManager->find($filter, $path);
141
142
                    // run the filter
143
                    $responseData = $filterManager->applyFilter($image, $filter);
144
                    $data = $responseData->getContent();
145
                    file_put_contents($uploadDir . $media->getUri(), $data);
146
                } else {
147
                    $data = file_get_contents($src);
148
                    $lastModified->setTimestamp(filemtime($src));
149
                }
150
            } else {
151
                $src = $this->get('alpixel_media.manager')->getAbsolutePath($media);
152
                $lastModified->setTimestamp(filemtime($src));
153
                $data = file_get_contents($src);
154
            }
155
        } else {
156
            $lastModified->setTimestamp(filemtime($src));
157
            $data = file_get_contents($src);
158
            $response->headers->set('Content-disposition', 'attachment;filename=' . basename($media->getUri()));
159
        }
160
161
        $response->setLastModified($lastModified);
162
        $response->setPublic();
163
        $response->headers->set('Content-Type', $media->getMime());
164
165
        if ($response->isNotModified($request)) {
166
            return $response;
167
        }
168
169
        $response->setContent($data);
170
171
        return $response;
172
    }
173
}
174