Image   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 186
Duplicated Lines 12.9 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 24
loc 186
c 0
b 0
f 0
wmc 16
lcom 1
cbo 0
ccs 0
cts 114
cp 0
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A loadImages() 0 17 1
B saveImages() 0 25 7
A saveImageRelation() 0 12 1
A removeImageRelation() 11 11 1
A updateImagePosition() 13 13 1
A uploadImage() 0 10 1
A getAllowedExtensions() 0 8 1
A getBaseDir() 0 6 1
A getSubDir() 0 4 1

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
 * File: Image.php
4
 *
5
 * @author      Maciej Sławik <[email protected]>
6
 * Github:      https://github.com/maciejslawik
7
 */
8
9
namespace MSlwk\ICatalogue\Model\ResourceModel\Catalogue\Relation;
10
11
use Magento\Framework\Model\AbstractModel;
12
use MSlwk\ICatalogue\Api\Catalogue\ImageInterface;
13
use Magento\Framework\App\ResourceConnection;
14
use MSlwk\ICatalogue\Model\ResourceModel\Catalogue;
15
use Magento\MediaStorage\Model\File\UploaderFactory;
16
use Magento\Framework\File\Uploader;
17
use Magento\Framework\Filesystem;
18
use Magento\Framework\App\Filesystem\DirectoryList;
19
use MSlwk\ICatalogue\Api\CatalogueInterface;
20
21
/**
22
 * Class Image
23
 *
24
 * @package MSlwk\ICatalogue\Model\ResourceModel\Catalogue\Relation
25
 */
26
class Image implements ImageInterface
27
{
28
    /**
29
     * @var Filesystem
30
     */
31
    protected $fileSystem;
32
33
    /**
34
     * @var UploaderFactory
35
     */
36
    protected $uploaderFactory;
37
38
    /**
39
     * @var ResourceConnection
40
     */
41
    protected $resourceConnection;
42
43
    /**
44
     * Image constructor.
45
     *
46
     * @param Filesystem $fileSystem
47
     * @param UploaderFactory $uploaderFactory
48
     * @param ResourceConnection $resourceConnection
49
     */
50
    public function __construct(
51
        Filesystem $fileSystem,
52
        UploaderFactory $uploaderFactory,
53
        ResourceConnection $resourceConnection
54
    ) {
55
        $this->fileSystem = $fileSystem;
56
        $this->uploaderFactory = $uploaderFactory;
57
        $this->resourceConnection = $resourceConnection;
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63
    public function loadImages(AbstractModel $object)
64
    {
65
        $connection = $this->resourceConnection->getConnection(ResourceConnection::DEFAULT_CONNECTION);
66
        $images = $connection->fetchAll(
67
            'SELECT ' . ImageInterface::IMAGE_ID . ', ' .
68
            ImageInterface::IMAGE_URI . ', ' .
69
            ImageInterface::SORT_ORDER . '
70
            FROM ' . Catalogue::CATALOGUE_IMAGE_TABLE . ' 
71
            WHERE ' . CatalogueInterface::CATALOGUE_ID . ' = :catalog_id
72
            ORDER BY ' . ImageInterface::SORT_ORDER . ' ASC;',
73
            [
74
                ':catalog_id' => $object->getId()
75
            ]
76
        );
77
78
        $object->setImages($images);
79
    }
80
81
    /**
82
     * @param AbstractModel $object
83
     * @return void
84
     * @throws \Exception
85
     */
86
    public function saveImages(AbstractModel $object)
87
    {
88
        $imagesData = $object->getImages();
89
        if ($imagesData) {
90
            foreach ($imagesData['position'] as $imageId => $position) {
91
                if (isset($imagesData['delete']) && isset($imagesData['delete'][$imageId])) {
92
                    $this->removeImageRelation($object, $imageId);
93
                } else {
94
                    $input = "images[{$imageId}]";
95
                    try {
96
                        $filename = $this->uploadImage($input);
97
                    } catch (\Exception $e) {
98
                        if ($e->getCode() === Uploader::TMP_NAME_EMPTY) {
99
                            $this->updateImagePosition($imageId, $position);
100
                            continue;
101
                        } else {
102
                            throw $e;
103
                        }
104
                    }
105
                    $this->removeImageRelation($object, $imageId);
106
                    $this->saveImageRelation($object, $filename, $position);
107
                }
108
            }
109
        }
110
    }
111
112
    /**
113
     * @param AbstractModel $object
114
     * @param string $file
115
     * @param int $position
116
     * @return void
117
     */
118
    protected function saveImageRelation(AbstractModel $object, string $file, $position = 0)
119
    {
120
        $connection = $this->resourceConnection->getConnection(ResourceConnection::DEFAULT_CONNECTION);
121
        $connection->insert(
122
            Catalogue::CATALOGUE_IMAGE_TABLE,
123
            [
124
                CatalogueInterface::CATALOGUE_ID => $object->getId(),
125
                ImageInterface::IMAGE_URI => $file,
126
                ImageInterface::SORT_ORDER => $position
127
            ]
128
        );
129
    }
130
131
    /**
132
     * @param AbstractModel $object
133
     * @param string $imageId
134
     * @return void
135
     */
136 View Code Duplication
    protected function removeImageRelation(AbstractModel $object, string $imageId)
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...
137
    {
138
        $connection = $this->resourceConnection->getConnection(ResourceConnection::DEFAULT_CONNECTION);
139
        $connection->delete(
140
            Catalogue::CATALOGUE_IMAGE_TABLE,
141
            [
142
                CatalogueInterface::CATALOGUE_ID . ' = ' . $object->getId(),
143
                ImageInterface::IMAGE_ID . ' = ' . $imageId,
144
            ]
145
        );
146
    }
147
148
    /**
149
     * @param string $imageId
150
     * @param string $position
151
     * @return void
152
     */
153 View Code Duplication
    protected function updateImagePosition(string $imageId, string $position)
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...
154
    {
155
        $connection = $this->resourceConnection->getConnection(ResourceConnection::DEFAULT_CONNECTION);
156
        $connection->update(
157
            Catalogue::CATALOGUE_IMAGE_TABLE,
158
            [
159
                ImageInterface::SORT_ORDER => $position,
160
            ],
161
            [
162
                ImageInterface::IMAGE_ID . ' = ' . $imageId
163
            ]
164
        );
165
    }
166
167
    /**
168
     * @param string $input
169
     * @return string
170
     */
171
    protected function uploadImage(string $input): string
172
    {
173
        $uploader = $this->uploaderFactory->create(['fileId' => $input]);
174
        $uploader->setAllowRenameFiles(true);
175
        $uploader->setFilesDispersion(true);
176
        $uploader->setAllowCreateFolders(true);
177
        $uploader->setAllowedExtensions($this->getAllowedExtensions());
178
        $result = $uploader->save($this->getBaseDir());
179
        return $this->getSubDir() . $result['file'];
180
    }
181
182
    /**
183
     * @return array
184
     */
185
    protected function getAllowedExtensions(): array
186
    {
187
        return [
188
            'jpg',
189
            'jpeg',
190
            'png'
191
        ];
192
    }
193
194
    /**
195
     * @return string
196
     */
197
    protected function getBaseDir(): string
198
    {
199
        return $this->fileSystem
200
            ->getDirectoryWrite(DirectoryList::MEDIA)
201
            ->getAbsolutePath($this->getSubDir());
202
    }
203
204
    /**
205
     * @return string
206
     */
207
    protected function getSubDir(): string
208
    {
209
        return 'icatalogue/images';
210
    }
211
}
212