Completed
Push — master ( 395774...b3be9a )
by
unknown
16s queued 12s
created

CustomImagesAdminController::uploadFile()   B

Complexity

Conditions 6
Paths 68

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 8.4032
c 0
b 0
f 0
cc 6
nc 68
nop 2

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 Dealer\Controller\Image;
4
5
use Dealer\Dealer;
6
use Dealer\Form\DealerImageBoxForm;
7
use Dealer\Form\DealerImageHeaderForm;
8
use Dealer\Model\DealerImage;
9
use Dealer\Model\DealerImageQuery;
10
use Thelia\Controller\Admin\FileController;
11
use Thelia\Core\Event\File\FileCreateOrUpdateEvent;
12
use Thelia\Core\Event\File\FileDeleteEvent;
13
use Thelia\Core\Event\TheliaEvents;
14
use Thelia\Core\Security\AccessManager;
15
use Thelia\Core\Security\Resource\AdminResources;
16
use Thelia\Log\Tlog;
17
use Thelia\Model\Lang;
18
use Thelia\Model\LangQuery;
19
use Thelia\Tools\URL;
20
21
class CustomImagesAdminController extends FileController
22
{
23
    const MODULE_RIGHT = Dealer::DOMAIN_NAME;
24
    const PRODUCT_IMAGE_PARENT_TYPE = 'dealer';
25
26
    public function updateProductImageHeader()
27
    {
28
        return $this->uploadProductFile(DealerImageHeaderForm::DEALER_IMAGE_HEADER_FORM_ID);
29
    }
30
31
    public function updateProductImageBox()
32
    {
33
        return $this->uploadProductFile(DealerImageBoxForm::DEALER_IMAGE_BOX_FORM_ID);
34
    }
35
36
    public function updateCustomImageAction($id, $parentId, $type)
37
    {
38
        try {
39
            $this->registerDealerCustomProductImageType($type);
40
            if (null !== $response = $this->checkAccessForParentType(AccessManager::UPDATE)) {
41
                return $response;
42
            }
43
            return $this->updateFileAction($id, self::PRODUCT_IMAGE_PARENT_TYPE, $type, TheliaEvents::IMAGE_UPDATE);
44
        } catch (\Exception $exception) {
45
            Tlog::getInstance()->error($exception->getMessage());
46
        }
47
        return $this
48
            ->generateRedirect(URL::getInstance()
49
                ->absoluteUrl(sprintf('/admin/module/dealer/image/%1$s/edit/%2$s/%3$s', $type, $parentId, $id))
50
            );
51
    }
52
53
    /**
54
     * @param $type
55
     * @param $parentId
56
     * @param $id
57
     * @return mixed|\Thelia\Core\HttpFoundation\Response
58
     * @throws \Exception
59
     */
60
    public function editCustomImageAction($type, $parentId, $id)
61
    {
62
        $this->registerDealerCustomProductImageType($type);
63
        if (null !== $response = $this->checkAccessForParentType(AccessManager::UPDATE)) {
64
            return $response;
65
        }
66
        $fileManager = $this->getFileManager();
67
        $imageModel = $fileManager->getModelInstance($type, self::PRODUCT_IMAGE_PARENT_TYPE);
68
69
        /** @var DealerImage $image */
70
        $image = DealerImageQuery::create()
71
            ->filterByType(DealerImage::getTypeIdFromLabel($type))
72
            ->findPk($id);
73
        if ($image === null) {
74
            return $this->pageNotFound();
75
        }
76
77
        $redirectionUrl = '/admin/module/Dealer/dealer/edit?dealer_id=' . $parentId;
78
        $redirectUrl = URL::getInstance()->absoluteUrl($redirectionUrl, ['current_tab' => 'images']);
79
80
        return $this->render('custom-dealer-image-edit', array(
81
            'imageId' => $id,
82
            'imageType' => $type,
83
            'redirectUrl' => $redirectUrl,
84
            'parentId' => $parentId,
85
            'formId' => $imageModel->getUpdateFormId(),
86
        ));
87
    }
88
89
    public function deleteCustomImageAction($type, $parentId, $id)
90
    {
91
        $message = null;
92
        $this->registerDealerCustomProductImageType($type);
93
        $this->checkAccessForParentType(AccessManager::UPDATE);
94
95
        $fileManager = $this->getFileManager();
96
        $modelInstance = $fileManager->getModelInstance($type, self::PRODUCT_IMAGE_PARENT_TYPE);
97
        $model = $modelInstance->getQueryInstance()->findPk($id);
98
        if ($model == null) {
99
            return $this->pageNotFound();
100
        }
101
        // Feed event
102
        $fileDeleteEvent = new FileDeleteEvent($model);
103
        // Dispatch Event to the Action
104
        try {
105
            $this->dispatch(TheliaEvents::IMAGE_DELETE, $fileDeleteEvent);
106
            $this->adminLogAppend(
107
                $this->getAdminResources()->getResource(self::PRODUCT_IMAGE_PARENT_TYPE, ucfirst(Dealer::DOMAIN_NAME)),
108
                $this->getTranslator()->trans(
109
                    'Deleting %obj% for %id% with parent id %parentId%',
110
                    array(
111
                        '%obj%' => $type,
112
                        '%id%' => $fileDeleteEvent->getFileToDelete()->getId(),
113
                        '%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(),
114
                    )
115
                ),
116
                AccessManager::UPDATE,
117
                $fileDeleteEvent->getFileToDelete()->getId()
118
            );
119
        } catch (\Exception $e) {
120
            $message = $this->getTranslator()->trans(
121
                'Fail to delete  %obj% for %id% with parent id %parentId% (Exception : %e%)',
122
                array(
123
                    '%obj%' => $type,
124
                    '%id%' => $fileDeleteEvent->getFileToDelete()->getId(),
125
                    '%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(),
126
                    '%e%' => $e->getMessage()
127
                )
128
            );
129
        }
130
        if (null === $message) {
131
            $message = $this->getTranslator()->trans(
132
                '%obj%s deleted successfully',
133
                ['%obj%' => ucfirst($type)],
134
                Dealer::DOMAIN_NAME
135
            );
136
        }
137
        $this->adminLogAppend(
138
            self::PRODUCT_IMAGE_PARENT_TYPE,
139
            AccessManager::UPDATE,
140
            $message,
141
            $fileDeleteEvent->getFileToDelete()->getId()
142
        );
143
        $redirectionUrl = '/admin/module/Dealer/dealer/edit?dealer_id=' . $parentId;
144
        return $this->generateRedirect(URL::getInstance()->absoluteUrl($redirectionUrl, ['current_tab' => 'images']));
145
    }
146
147
    private function uploadProductFile($formName)
148
    {
149
        if (null !== $response = $this->checkAuth(AdminResources::PRODUCT, [], AccessManager::UPDATE)) {
150
            return $response;
151
        }
152
        return self::uploadFile($formName, true);
153
    }
154
155
    /**
156
     * @param $formName
157
     * @param $forProduct
158
     * @return null|\Symfony\Component\HttpFoundation\Response
159
     */
160
    private function uploadFile($formName, $forProduct)
161
    {
162
        $imageForm = $this->createForm($formName);
163
        try {
164
            $form = $this->validateForm($imageForm);
165
            $imageFile = $form->get('file')->getData();
166
            if (is_null($imageFile)) {
167
                /** @noinspection PhpTranslationKeyInspection */
168
                throw new \Exception($this->getTranslator()->trans('No files uploaded', [], Dealer::DOMAIN_NAME));
169
            }
170
            $parentId = $form->get('parent_id')->getData();
171
172
            if ($forProduct) {
173
                $fileModel = DealerImage::fromProductIdAndFormName($parentId, $formName);
174
            }
175
176
            $uploadDir = $fileModel->getUploadDir();
0 ignored issues
show
Bug introduced by
The variable $fileModel 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...
177
            if (!file_exists($uploadDir)) {
178
                mkdir($uploadDir, 0777, true);
179
            }
180
181
            $fileCreateOrUpdateEvent = new FileCreateOrUpdateEvent($parentId);
182
            $fileCreateOrUpdateEvent->setModel($fileModel);
183
            $fileCreateOrUpdateEvent->setUploadedFile($imageFile);
184
185
            $this->dispatch(
186
                TheliaEvents::IMAGE_SAVE,
187
                $fileCreateOrUpdateEvent
188
            );
189
190
            // Compensate issue #1005
191
            $langs = LangQuery::create()->find();
192
193
            /** @var Lang $lang */
194
            foreach ($langs as $lang) {
195
                $pageProductImage = $fileCreateOrUpdateEvent->getModel();
196
                $pageProductImage->setLocale($lang->getLocale());
197
                $pageProductImage->setTitle('');
198
                $pageProductImage->save();
199
            }
200
201
            return $this->generateSuccessRedirect($imageForm);
202
203
        } catch (\Exception $e) {
204
            Tlog::getInstance()->addError(sprintf("Failed to upload file with form %s error :%s", $formName, $e->getMessage()));
205
            $error_message = $e->getMessage();
206
            $imageForm->setErrorMessage($error_message);
207
            $this->getParserContext()
208
                ->addForm($imageForm)
209
                ->setGeneralError($error_message);
210
            return $this->generateErrorRedirect($imageForm);
211
        }
212
    }
213
214
215
    /**
216
     * @param string $access
217
     * @return mixed null if authorization is granted, or a Response object which contains the error page otherwise
218
     */
219
    protected function checkAccessForParentType($access)
220
    {
221
        return $this->checkAuth(AdminResources::MODULE, [Dealer::DOMAIN_NAME], $access);
222
    }
223
224
    private function registerDealerCustomProductImageType($type)
225
    {
226
        /** @noinspection PhpParamsInspection */
227
        /** @noinspection PhpUnhandledExceptionInspection */
228
        $this->getAdminResources()->addModuleResources([strtoupper(self::PRODUCT_IMAGE_PARENT_TYPE) => "admin.Dealer"], ucfirst(static::MODULE_RIGHT));
229
        $this->getFileManager()->addFileModel(
230
            $type,
231
            self::PRODUCT_IMAGE_PARENT_TYPE,
232
            DealerImage::class
233
        );
234
    }
235
}