Completed
Push — master ( 265a2d...f9e310 )
by jerome
05:38 queued 02:58
created

FTPController   B

Complexity

Total Complexity 30

Size/Duplication

Total Lines 292
Duplicated Lines 25.68 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 30
c 3
b 0
f 0
lcom 1
cbo 16
dl 75
loc 292
rs 8.4614

10 Methods

Rating   Name   Duplication   Size   Complexity  
A setContainer() 0 13 2
A indexAction() 0 4 1
B showAction() 0 25 2
B createAction() 39 39 4
B updateAction() 36 36 4
B deleteAction() 0 45 5
A createResource() 0 19 4
A getResource() 0 20 2
A getForm() 0 14 3
A redirectTo() 0 18 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * This file is part of Dedipanel project
5
 *
6
 * (c) 2010-2015 Dedipanel <http://www.dedicated-panel.net>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace DP\GameServer\GameServerBundle\Controller;
13
14
use DP\Core\CoreBundle\Controller\ResourceController;
15
use Symfony\Component\HttpFoundation\JsonResponse;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
18
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20
use DP\GameServer\GameServerBundle\Entity\GameServer;
21
use Dedipanel\PHPSeclibWrapperBundle\SFTP\AbstractItem;
22
use Dedipanel\PHPSeclibWrapperBundle\SFTP\Directory;
23
use Dedipanel\PHPSeclibWrapperBundle\SFTP\File;
24
use Dedipanel\PHPSeclibWrapperBundle\SFTP\Exception\InvalidPathException;
25
26
/**
27
 * @todo: Apply criteria & sorting
28
 * @todo: refacto phpseclib
29
 */
30
class FTPController extends ResourceController
31
{
32
    const TYPE_FILE = 'file';
33
    const TYPE_DIRECTORY  = 'directory';
34
35
    /**
36
     * @var FTPDomainManager
37
     */
38
    protected $domainManager;
39
40
41
    public function setContainer(ContainerInterface $container = null)
42
    {
43
        parent::setContainer($container);
44
45
        if ($container !== null) {
46
            $this->domainManager = new FTPDomainManager(
47
                $container->get($this->config->getServiceName('manager')),
48
                $container->get('event_dispatcher'),
49
                $this->flashHelper,
50
                $this->config
51
            );
52
        }
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     * 
58
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
59
     */
60
    public function indexAction(Request $request)
61
    {
62
        throw new NotFoundHttpException();
63
    }
64
    
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function showAction(Request $request)
69
    {
70
        $this->isGrantedOr403('FTP', $this->find($request));
71
        
72
        $config = $this->getConfiguration();
73
        /** @var GameServer $server */
74
        $server = $this->findOr404($request);
75
76
        $resource = $this->getResource($server, $request->get('path'));
77
78
        if ($resource instanceof File) {
79
            throw new MethodNotAllowedHttpException(array('POST', 'PUT'));
80
        }
81
        
82
        $view = $this
83
            ->view()
84
            ->setTemplate($config->getTemplate('show.html'))
85
            ->setData(array(
86
                'server' => $server,
87
                'resource' => $resource,
88
            ))
89
        ;
90
91
        return $this->handleView($view);
92
    }
93
    
94
    /**
95
     * {@inheritdoc}
96
     */
97 View Code Duplication
    public function createAction(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
98
    {
99
        $this->isGrantedOr403('CREATE');
100
        
101
        $config = $this->getConfiguration();
102
        $server = $this->findOr404($request);
103
104
        $resource = $this->createResource($server,
105
            $request->get('path'),
106
            $request->get('type')
107
        );
108
        $form     = $this->getForm($resource);
109
        
110
        $form->handleRequest($request);
111
112
        if ($form->isSubmitted()) {
113
            if ($form->isValid()) {
114
                $resource = $this->domainManager->createResource($server, $resource);
115
116
                return $this->redirectTo($server, $resource);
117
            }
118
        }
119
        
120
        if ($config->isApiRequest()) {
121
            return $this->handleView($this->view($form));
122
        }
123
        
124
        $view = $this
125
            ->view()
126
            ->setTemplate($config->getTemplate('create.html'))
127
            ->setData(array(
128
                'server'   => $server,
129
                'form'     => $form->createView(),
130
                'resource' => $resource,
131
            ))
132
        ;
133
        
134
        return $this->handleView($view);
135
    }
136
137
    /**
138
     * Display the form for editing or update the resource.
139
     */
140 View Code Duplication
    public function updateAction(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141
    {
142
        $this->isGrantedOr403('UPDATE', $this->find($request));
143
144
        $config = $this->getConfiguration();
145
        $server = $this->findOr404($request);
146
        
147
        $resource = $this->getResource($server, $request->get('path'));
148
        $form     = $this->getForm($resource);
149
        
150
        $form->handleRequest($request);
151
152
        if ($form->isSubmitted()) {
153
            if ($form->isValid()) {
154
                $resource = $this->domainManager->updateResource($server, $resource);
155
156
                return $this->redirectTo($server, $resource);
157
            }
158
        }
159
160
        if ($config->isApiRequest()) {
161
            return $this->handleView($this->view($form));
162
        }
163
164
        $view = $this
165
            ->view()
166
            ->setTemplate($config->getTemplate('update.html'))
167
            ->setData(array(
168
                'server'   => $server,
169
                'form'     => $form->createView(),
170
                'resource' => $resource,
171
            ))
172
        ;
173
174
        return $this->handleView($view);
175
    }
176
177
    /**
178
     * Delete resource.
179
     */
180
    public function deleteAction(Request $request)
181
    {
182
        $this->isGrantedOr403('DELETE', $this->find($request));
183
        
184
        $server   = $this->findOr404($request);
185
        $resource = $this->getResource($server, $request->get('path'));
186
        
187
        if ($request->request->get('confirmed', false)) {
188
            $resource = $this->domainManager->deleteResource($server, $resource);
189
190
            if ($request->isXmlHttpRequest()) {
191
                return JsonResponse::create(array('id' => $request->get('id')));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Symfony\Componen... $request->get('id'))); (Symfony\Component\HttpFoundation\JsonResponse) is incompatible with the return type of the parent method Sylius\Bundle\ResourceBu...ontroller::deleteAction of type Symfony\Component\HttpFoundation\RedirectResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
192
            }
193
194
            $this->flashHelper->setFlash('success', 'delete');
195
196
            $config = $this->getConfiguration();
197
            $parameters = $config->getRedirectParameters();
198
199
            if (empty($parameters)) {
200
                $parameters['id'] = $server->getId();
201
                $parameters['path'] = $resource->getPath();
202
            }
203
204
            return $this->redirectHandler->redirectToRoute(
205
                $config->getRedirectRoute('show'),
206
                $parameters
207
            );
208
        }
209
210
        if ($request->isXmlHttpRequest()) {
211
            throw new AccessDeniedHttpException;
212
        }
213
214
        $view = $this
215
            ->view()
216
            ->setTemplate($request->attributes->get('template', 'SyliusWebBundle:Backend/Misc:delete.html.twig'))
217
            ->setData(array(
218
                'server'   => $server,
219
                'resource' => $resource,
220
            ))
221
        ;
222
223
        return $this->handleView($view);
224
    }
225
226
    /**
227
     * Get a new resource
228
     *
229
     * @param GameServer $server
230
     * @param string $path
231
     * @param string $type
232
     * @return Directory|File
233
     * @throws \RuntimeException
234
     */
235
    public function createResource(GameServer $server, $path, $type)
236
    {
237
        if ($type != self::TYPE_FILE && $type != self::TYPE_DIRECTORY) {
238
            throw new \RuntimeException('Not supported ftp resource type.');
239
        }
240
241
        $conn    = $server->getMachine()->getConnection();
242
        $gameDir = $server->getAbsoluteGameContentDir();
243
        $path    = '~/' . $path;
244
245
        if ($type == self::TYPE_FILE) {
246
            $item = new File($conn, $path, $gameDir, true);
247
        }
248
        else {
249
            $item = new Directory($conn, $path, $gameDir, true);
250
        }
251
252
        return $item;
253
    }
254
255
    /**
256
     * @param GameServer $server
257
     * @param string     $path
258
     *
259
     * @return \Dedipanel\PHPSeclibWrapperBundle\SFTP\AbstractItem
260
     */
261
    public function getResource(GameServer $server, $path)
262
    {
263
        $path = '~/' . $path;
264
265
        /** @var \Dedipanel\PHPSeclibWrapperBundle\SFTP\SFTPItemFactory $factory */
266
        $factory  = $this->get('dedipanel.sftp_factory');
267
268
        try {
269
            $resource = $factory->getItem(
270
                $server->getMachine()->getConnection(),
271
                $path,
272
                $server->getAbsoluteGameContentDir()
273
            );
274
        }
275
        catch (InvalidPathException $e) {
276
            throw new NotFoundHttpException($e->getMessage(), $e);
277
        }
278
279
        return $resource;
280
    }
281
    
282
    /**
283
     * {@inheritdoc}
284
     */
285
    public function getForm($resource = null)
286
    {
287
        if ($resource instanceof File) {
288
            $formType = 'dedipanel_game_ftp_file';
289
        }
290
        elseif ($resource instanceof Directory) {
291
            $formType = 'dedipanel_game_ftp_directory';
292
        }
293
        else {
294
            throw new \RuntimeException('Not supported ftp resource type.');
295
        }
296
        
297
        return $this->createForm($formType, $resource);
298
    }
299
    
300
    /**
301
     * {@inheritdoc}
302
     */
303
    public function redirectTo(GameServer $server, AbstractItem $resource)
304
    {
305
        $config = $this->getConfiguration();
306
307
        $parameters = $config->getRedirectParameters();
308
        $route = $config->getRedirectRoute('show');
309
        
310
        if (empty($parameters)) {
311
            $parameters['id'] = $server->getId();
312
            $parameters['path'] = $resource->getRelativePath();
313
314
            if ($resource instanceof File) {
315
                $parameters['path'] = $resource->getPath();
316
            }
317
        }
318
319
        return $this->redirectHandler->redirectToRoute($route, $parameters);
320
    }
321
}
322