GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

CRUDController::importAction()   B
last analyzed

Complexity

Conditions 8
Paths 33

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 57
rs 7.6937
c 0
b 0
f 0
cc 8
nc 33
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Sigmapix\Sonata\ImportBundle\Controller;
4
5
use Doctrine\DBAL\Exception\ConstraintViolationException;
6
use Sigmapix\Sonata\ImportBundle\Admin\ImportableAdminTrait;
7
use Sigmapix\Sonata\ImportBundle\Service\ImportService;
8
use Sonata\AdminBundle\Controller\CRUDController as Controller;
9
use Symfony\Component\Form\Extension\Core\Type\FileType;
10
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
11
use Symfony\Component\HttpFoundation\File\Exception\FileException;
12
use Symfony\Component\HttpFoundation\File\UploadedFile;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
16
17
class CRUDController extends Controller
18
{
19
    /**
20
     * Export data to specified format.
21
     *
22
     * @param Request $request
23
     *
24
     * @throws AccessDeniedException If access is not granted
25
     * @throws \RuntimeException     If the export format is invalid
26
     *
27
     * @return Response
28
     */
29
    public function exportAction(Request $request)
30
    {
31
        $this->admin->checkAccess('export');
32
33
        $format = $request->get('format');
34
35
        // NEXT_MAJOR: remove the check
36
        if (!$this->has('sonata.admin.admin_exporter')) {
37
            @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
38
                'Not registering the exporter bundle is deprecated since version 3.14.'
39
                .' You must register it to be able to use the export action in 4.0.',
40
                E_USER_DEPRECATED
41
            );
42
            $allowedExportFormats = (array) $this->admin->getExportFormats();
43
44
            $class = $this->admin->getClass();
45
            $filename = sprintf(
46
                'export_%s_%s.%s',
47
                strtolower(substr($class, strripos($class, '\\') + 1)),
48
                date('Y_m_d_H_i_s', strtotime('now')),
49
                $format
50
            );
51
            $exporter = $this->get('sonata.admin.exporter');
52
        } else {
53
            $adminExporter = $this->get('sonata.admin.admin_exporter');
54
            $allowedExportFormats = $adminExporter->getAvailableFormats($this->admin);
55
            $filename = $adminExporter->getExportFilename($this->admin, $format);
56
            $exporter = $this->get('sonata.exporter.exporter');
57
        }
58
59
        if (!\in_array($format, $allowedExportFormats)) {
60
            throw new \RuntimeException(
61
                sprintf(
62
                    'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`',
63
                    $format,
64
                    $this->admin->getClass(),
65
                    implode(', ', $allowedExportFormats)
66
                )
67
            );
68
        }
69
70
        $defaultHeaders = array_map(function () {return ''; }, $this->admin->getExportFields());
71
72
        return $exporter->getResponse(
73
            $format,
74
            $filename,
75
            $this->admin->getDataSourceIterator(),
76
            $defaultHeaders
77
        );
78
    }
79
80
    public function uploadAction(Request $request)
81
    {
82
        /** @var $admin ImportableAdminTrait */
83
        $admin = $this->admin;
84
85
        // todo: $admin->checkAccess('import');
86
        $admin->setFormTabs(['default' => ['groups' => []]]);
0 ignored issues
show
Bug introduced by
It seems like setFormTabs() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
87
        $formBuilder = $this->createFormBuilder();
88
        $formBuilder
89
            ->add('importFile', FileType::class)
90
            ->add('upload', SubmitType::class)
91
        ;
92
        $form = $formBuilder->getForm();
93
        $form->handleRequest($request);
94
95
        if ($form->isSubmitted()) {
96
            if ($form->isValid()) {
97
                $files = $request->files->get('form');
98
                if (!empty($files) && array_key_exists('importFile', $files)) {
99
                    /** @var $file UploadedFile */
100
                    $file = $files['importFile'];
101
                    $fileName = md5(uniqid());
102
103
                    $file->move($this->getParameter('import_directory'), $fileName);
104
105
                    return $this->redirect($admin->generateUrl('import', ['fileName' => $fileName]));
0 ignored issues
show
Bug introduced by
It seems like generateUrl() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
106
                }
107
            }
108
            // todo: show an error message if the form failed validation
109
        }
110
111
        return $this->render('SigmapixSonataImportBundle:CRUD:base_import_form.html.twig', [
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Contr...RUDController::render() has been deprecated with message: since sonata-project/admin-bundle 3.27, to be removed in 4.0. Use Sonata\AdminBundle\Controller\CRUDController::renderWithExtraParams() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
112
            'action' => 'upload',
113
            'form' => $form->createView(),
114
            'object' => null,
115
        ], null);
116
    }
117
118
    public function importAction(Request $request)
119
    {
120
        /** @var $admin ImportableAdminTrait */
121
        $admin = $this->admin;
122
123
        /** @var $is ImportService */
124
        $is = $this->get('sigmapix.sonata.import.service');
125
126
        // todo: $admin->checkAccess('import');
127
128
        $fileName = $request->get('fileName');
129
        if (!empty($fileName)) {
130
            try {
131
                $file = new UploadedFile($this->getParameter('import_directory').$fileName, $fileName);
132
133
                $headers = $is->getHeaders($file);
134
135
                /** @var $form \Symfony\Component\Form\Form */
136
                $form = $admin->getImportForm($headers);
137
                $form->handleRequest($request);
138
139
                if ($form->isSubmitted()) {
140
                    $preResponse = $admin->preImport($request, $form);
141
                    if (null !== $preResponse) {
142
                        return $preResponse;
143
                    }
144
145
                    try {
146
                        $results = $is->import($file, $form, $admin, $request);
147
148
                        $postResponse = $admin->postImport($request, $file, $form, $results);
149
150
                        if (null !== $postResponse) {
151
                            return $postResponse;
152
                        }
153
154
                        $this->addFlash('success', 'message_success');
155
                    } catch (ConstraintViolationException $constraintViolationException) {
156
                        $this->addFlash('error', $constraintViolationException->getMessage());
157
                    } catch (\Exception $exception) {
158
                        $this->addFlash('error', $exception->getMessage());
159
                    }
160
161
                    return $this->redirect($admin->generateUrl('list'));
0 ignored issues
show
Bug introduced by
It seems like generateUrl() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
162
                }
163
            } catch (FileException $e) {
164
                // TODO: show an error message if the file is missing
165
            }
166
        }
167
        // todo: show an error message if the fileName is missing
168
169
        return $this->render('SigmapixSonataImportBundle:CRUD:base_import_form.html.twig', [
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Contr...RUDController::render() has been deprecated with message: since sonata-project/admin-bundle 3.27, to be removed in 4.0. Use Sonata\AdminBundle\Controller\CRUDController::renderWithExtraParams() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
170
            'action' => 'import',
171
            'form' => $form->createView(),
0 ignored issues
show
Bug introduced by
The variable $form does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
172
            'object' => null,
173
        ], null);
174
    }
175
}
176