Completed
Push — master ( 603670...576387 )
by Adam
06:48
created

MediaController::indexLocalAction()   B

Complexity

Conditions 4
Paths 6

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 38
Code Lines 27

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 27
nc 6
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
                $directory = $request->get('cwd');
128
                $uploadDir = $this->getKernel()->getRootDir() . '/../' . $directory;
129
                $file->move($uploadDir, $file->getClientOriginalName());
130
                
131
                return $this->jsonResponse([
132
                    'sFilename' => $file->getClientOriginalName(),
133
                ]);
134
            }
135
        }
136
        
137
        return $this->jsonResponse([
138
            'error' => 'No file to upload',
139
        ]);
140
    }
141
    
142
    private function isValidFile(\SplFileInfo $file, array $extensions): bool
143
    {
144
        return $file->isFile() && $file->isReadable() && in_array($file->getExtension(), $extensions);
145
    }
146
    
147
    private function isValidDirectory(\SplFileInfo $file): bool
148
    {
149
        return $file->isDir() && $file->isReadable();
150
    }
151
    
152
    private function getUploader(): MediaUploaderInterface
153
    {
154
        return $this->get('media.uploader');
155
    }
156
}
157