Completed
Push — master ( 2ce148...a7fdb1 )
by Adam
06:40
created

MediaController::uploadLocalAction()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 4
nop 1
1
<?php
2
/*
3
 * WellCommerce Open-Source E-Commerce Platform
4
 *
5
 * This file is part of the WellCommerce package.
6
 *
7
 * (c) Adam Piotrowski <[email protected]>
8
 *
9
 * For the full copyright and license information,
10
 * please view the LICENSE file that was distributed with this source code.
11
 */
12
13
namespace WellCommerce\Bundle\AppBundle\Controller\Admin;
14
15
use Carbon\Carbon;
16
use Symfony\Component\Finder\Finder;
17
use Symfony\Component\HttpFoundation\File\UploadedFile;
18
use Symfony\Component\HttpFoundation\JsonResponse;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
use WellCommerce\Bundle\AppBundle\Exception\InvalidMediaException;
22
use WellCommerce\Bundle\AppBundle\Service\Media\Uploader\MediaUploaderInterface;
23
use WellCommerce\Bundle\CoreBundle\Controller\Admin\AbstractAdminController;
24
25
/**
26
 * Class MediaController
27
 *
28
 * @author  Adam Piotrowski <[email protected]>
29
 */
30
class MediaController extends AbstractAdminController
31
{
32
    /**
33
     * @var \WellCommerce\Bundle\AppBundle\Manager\MediaManager
34
     */
35
    protected $manager;
36
    
37
    public function addAction(Request $request): Response
38
    {
39
        if (false === $request->files->has('file')) {
40
            return $this->redirectToAction('index');
41
        }
42
        
43
        $file   = $request->files->get('file');
44
        $helper = $this->getImageHelper();
45
        
46
        try {
47
            $media     = $this->getUploader()->upload($file, 'images');
48
            $thumbnail = $helper->getImage($media->getPath(), 'medium');
49
            
50
            $response = [
51
                'sId'        => $media->getId(),
52
                'sThumb'     => $thumbnail,
53
                'sFilename'  => $media->getName(),
54
                'sExtension' => $media->getExtension(),
55
                'sFileType'  => $media->getMime(),
56
            ];
57
        } catch (InvalidMediaException $e) {
58
            $response = [
59
                'sError'   => $this->trans('uploader.error'),
60
                'sMessage' => $this->trans($e->getMessage()),
61
            ];
62
        }
63
        
64
        return $this->jsonResponse($response);
65
    }
66
    
67
    public function indexLocalAction(Request $request): JsonResponse
68
    {
69
        $rootPath   = trim($request->get('rootPath'), '/');
70
        $path       = trim($request->get('path'), '/');
71
        $extensions = $request->get('types');
72
        $finder     = $this->createFinder($path, $extensions);
73
        $files      = [];
74
        $inRoot     = $rootPath === $path;
75
        
76
        if (!$inRoot) {
77
            $currentPath = explode('/', $path);
78
            array_pop($currentPath);
79
            
80
            $files[] = [
81
                'dir'   => true,
82
                'name'  => '..',
83
                'path'  => implode('/', $currentPath),
84
                'size'  => '',
85
                'mtime' => '',
86
            ];
87
        }
88
        
89
        foreach ($finder as $file) {
90
            $files[] = [
91
                'dir'   => $file->isDir(),
92
                'name'  => $file->getFilename(),
93
                'path'  => sprintf('%s/%s', $path, $file->getFilename()),
94
                'size'  => $file->isDir() ? '' : $file->getSize(),
95
                'mtime' => Carbon::createFromTimestamp($file->getMTime())->format('Y-m-d H:i:s'),
96
            ];
97
        }
98
        
99
        return $this->jsonResponse([
100
            'files'  => $files,
101
            'inRoot' => $inRoot,
102
            'cwd'    => $path,
103
        ]);
104
    }
105
    
106
    private function createFinder(string $path, array $extensions): Finder
107
    {
108
        $directory = $this->getKernel()->getRootDir() . '/../' . $path;
109
        $finder    = new Finder();
110
        
111
        $finder->in($directory)->ignoreVCS(true)->sortByType()->depth(0)->filter(function (\SplFileInfo $file) use ($extensions) {
112
            if ($this->isValidFile($file, $extensions) || $this->isValidDirectory($file)) {
113
                return true;
114
            }
115
            
116
            return false;
117
        });
118
        
119
        return $finder;
120
    }
121
    
122
    public function uploadLocalAction(Request $request): JsonResponse
123
    {
124
        if ($request->files->has('file')) {
125
            $file = $request->files->get('file');
126
            if ($file instanceof UploadedFile) {
127
                if (!$file->isValid()) {
128
                    return $this->jsonResponse([
129
                        'sError'   => 'File was not uploaded',
130
                        'sMessage' => $file->getError(),
131
                    ]);
132
                }
133
                $directory = $request->get('cwd');
134
                $uploadDir = $this->getKernel()->getRootDir() . '/../' . $directory;
135
                $file->move($uploadDir, $file->getClientOriginalName());
136
                
137
                return $this->jsonResponse([
138
                    'sFilename' => $file->getClientOriginalName(),
139
                ]);
140
            }
141
        }
142
        
143
        return $this->jsonResponse([
144
            'sError'   => 'File was not uploaded',
145
            'sMessage' => 'No file to upload',
146
        ]);
147
    }
148
    
149
    private function isValidFile(\SplFileInfo $file, array $extensions): bool
150
    {
151
        return $file->isFile() && $file->isReadable() && in_array($file->getExtension(), $extensions);
152
    }
153
    
154
    private function isValidDirectory(\SplFileInfo $file): bool
155
    {
156
        return $file->isDir() && $file->isReadable();
157
    }
158
    
159
    private function getUploader(): MediaUploaderInterface
160
    {
161
        return $this->get('media.uploader');
162
    }
163
}
164