Completed
Push — master ( a7fdb1...d902cc )
by Adam
10:16 queued 11s
created

MediaController::deleteLocalAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
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\Filesystem\Filesystem;
17
use Symfony\Component\Finder\Finder;
18
use Symfony\Component\HttpFoundation\File\UploadedFile;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use WellCommerce\Bundle\AppBundle\Exception\InvalidMediaException;
23
use WellCommerce\Bundle\AppBundle\Service\Media\Uploader\MediaUploaderInterface;
24
use WellCommerce\Bundle\CoreBundle\Controller\Admin\AbstractAdminController;
25
26
/**
27
 * Class MediaController
28
 *
29
 * @author  Adam Piotrowski <[email protected]>
30
 */
31
class MediaController extends AbstractAdminController
32
{
33
    /**
34
     * @var \WellCommerce\Bundle\AppBundle\Manager\MediaManager
35
     */
36
    protected $manager;
37
    
38
    public function addAction(Request $request): Response
39
    {
40
        if (false === $request->files->has('file')) {
41
            return $this->redirectToAction('index');
42
        }
43
        
44
        $file   = $request->files->get('file');
45
        $helper = $this->getImageHelper();
46
        
47
        try {
48
            $media     = $this->getUploader()->upload($file, 'images');
49
            $thumbnail = $helper->getImage($media->getPath(), 'medium');
50
            
51
            $response = [
52
                'sId'        => $media->getId(),
53
                'sThumb'     => $thumbnail,
54
                'sFilename'  => $media->getName(),
55
                'sExtension' => $media->getExtension(),
56
                'sFileType'  => $media->getMime(),
57
            ];
58
        } catch (InvalidMediaException $e) {
59
            $response = [
60
                'sError'   => $this->trans('uploader.error'),
61
                'sMessage' => $this->trans($e->getMessage()),
62
            ];
63
        }
64
        
65
        return $this->jsonResponse($response);
66
    }
67
    
68
    public function indexLocalAction(Request $request): JsonResponse
69
    {
70
        $rootPath   = trim($request->get('rootPath'), '/');
71
        $path       = trim($request->get('path'), '/');
72
        $extensions = $request->get('types');
73
        $finder     = $this->createFinder($path, $extensions);
74
        $files      = [];
75
        $inRoot     = $rootPath === $path;
76
        $hierarchy  = 0;
77
        
78
        if (!$inRoot) {
79
            $currentPath = explode('/', $path);
80
            array_pop($currentPath);
81
            
82
            $files[] = [
83
                'dir'       => true,
84
                'name'      => '..',
85
                'path'      => implode('/', $currentPath),
86
                'size'      => '',
87
                'mtime'     => '',
88
                'hierarchy' => $hierarchy++,
89
            ];
90
        }
91
        
92
        foreach ($finder as $file) {
93
            $files[] = [
94
                'dir'       => $file->isDir(),
95
                'name'      => $file->getFilename(),
96
                'path'      => sprintf('%s/%s', $path, $file->getFilename()),
97
                'size'      => $file->isDir() ? '' : $file->getSize(),
98
                'mtime'     => Carbon::createFromTimestamp($file->getMTime())->format('Y-m-d H:i:s'),
99
                'hierarchy' => $hierarchy++,
100
            ];
101
        }
102
        
103
        return $this->jsonResponse([
104
            'files'  => $files,
105
            'inRoot' => $inRoot,
106
            'cwd'    => $path,
107
        ]);
108
    }
109
    
110
    private function createFinder(string $path, array $extensions): Finder
111
    {
112
        $directory = $this->getKernel()->getRootDir() . '/../' . $path;
113
        $finder    = new Finder();
114
        
115
        $finder->in($directory)->ignoreVCS(true)->sortByType()->depth(0)->filter(function (\SplFileInfo $file) use ($extensions) {
116
            if ($this->isValidFile($file, $extensions) || $this->isValidDirectory($file)) {
117
                return true;
118
            }
119
            
120
            return false;
121
        });
122
        
123
        return $finder;
124
    }
125
    
126
    public function deleteLocalAction(Request $request): JsonResponse
127
    {
128
        $file       = $this->getKernel()->getRootDir() . '/../' . trim($request->get('file'), '/');
129
        $filesystem = new Filesystem();
130
        
131
        if ($filesystem->exists($file)) {
132
            $filesystem->remove($file);
133
        }
134
        
135
        return $this->jsonResponse([
136
            'success' => true,
137
        ]);
138
    }
139
    
140
    public function createLocalFolderAction(Request $request): JsonResponse
141
    {
142
        $cwd        = trim($request->get('cwd'), '/');
143
        $name       = trim($request->get('name'), '/');
144
        $rootDir    = $this->getKernel()->getRootDir();
145
        $directory  = sprintf('%s/../%s/%s', $rootDir, $cwd, $name);
146
        $filesystem = new Filesystem();
147
        if (false === $filesystem->exists($directory)) {
148
            $filesystem->mkdir($directory);
149
        }
150
        
151
        return $this->jsonResponse([
152
            'sDirectory' => $directory,
153
            'sCwd'       => $request->get('cwd'),
154
            'sName'      => $request->get('name'),
155
        ]);
156
    }
157
    
158
    public function uploadLocalAction(Request $request): JsonResponse
159
    {
160
        if ($request->files->has('file')) {
161
            $file = $request->files->get('file');
162
            if ($file instanceof UploadedFile) {
163
                if (!$file->isValid()) {
164
                    return $this->jsonResponse([
165
                        'sError'   => 'File was not uploaded',
166
                        'sMessage' => $file->getError(),
167
                    ]);
168
                }
169
                $directory = $request->get('cwd');
170
                $uploadDir = $this->getKernel()->getRootDir() . '/../' . $directory;
171
                $file->move($uploadDir, $file->getClientOriginalName());
172
                
173
                return $this->jsonResponse([
174
                    'sFilename' => $file->getClientOriginalName(),
175
                ]);
176
            }
177
        }
178
        
179
        return $this->jsonResponse([
180
            'sError'   => 'File was not uploaded',
181
            'sMessage' => 'No file to upload',
182
        ]);
183
    }
184
    
185
    private function isValidFile(\SplFileInfo $file, array $extensions): bool
186
    {
187
        return $file->isFile() && $file->isReadable() && in_array($file->getExtension(), $extensions);
188
    }
189
    
190
    private function isValidDirectory(\SplFileInfo $file): bool
191
    {
192
        return $file->isDir() && $file->isReadable();
193
    }
194
    
195
    private function getUploader(): MediaUploaderInterface
196
    {
197
        return $this->get('media.uploader');
198
    }
199
}
200