Passed
Push — master ( 1a3e0d...5a2f2e )
by Julito
11:01
created

BaseResourceFileAction::setLinks()   D

Complexity

Conditions 19
Paths 37

Size

Total Lines 98
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 50
c 0
b 0
f 0
nc 37
nop 2
dl 0
loc 98
rs 4.5166

How to fix   Long Method    Complexity   

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
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller\Api;
8
9
use Chamilo\CoreBundle\Entity\AbstractResource;
10
use Chamilo\CoreBundle\Entity\Course;
11
use Chamilo\CoreBundle\Entity\ResourceLink;
12
use Chamilo\CoreBundle\Entity\ResourceRight;
13
use Chamilo\CoreBundle\Entity\Session;
14
use Chamilo\CoreBundle\Entity\User;
15
use Chamilo\CoreBundle\Repository\ResourceRepository;
16
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
17
use Chamilo\CourseBundle\Entity\CGroup;
18
use DateTime;
19
use Doctrine\ORM\EntityManager;
20
use Exception;
21
use InvalidArgumentException;
22
use Symfony\Component\HttpFoundation\File\UploadedFile;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
25
26
class BaseResourceFileAction
27
{
28
    public static function setLinks(AbstractResource $resource, $em): void
29
    {
30
        $resourceNode = $resource->getResourceNode();
31
        $links = $resource->getResourceLinkArray();
32
        if ($links) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $links of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
33
            $groupRepo = $em->getRepository(CGroup::class);
34
            $courseRepo = $em->getRepository(Course::class);
35
            $sessionRepo = $em->getRepository(Session::class);
36
            $userRepo = $em->getRepository(User::class);
37
38
            foreach ($links as $link) {
39
                $resourceLink = new ResourceLink();
40
                $linkSet = false;
41
                if (isset($link['cid']) && !empty($link['cid'])) {
42
                    $course = $courseRepo->find($link['cid']);
43
                    if (null !== $course) {
44
                        $linkSet = true;
45
                        $resourceLink->setCourse($course);
46
                    } else {
47
                        throw new InvalidArgumentException(sprintf('Course #%s does not exists', $link['cid']));
48
                    }
49
                }
50
51
                if (isset($link['sid']) && !empty($link['sid'])) {
52
                    $session = $sessionRepo->find($link['sid']);
53
                    if (null !== $session) {
54
                        $linkSet = true;
55
                        $resourceLink->setSession($session);
56
                    } else {
57
                        throw new InvalidArgumentException(sprintf('Session #%s does not exists', $link['sid']));
58
                    }
59
                }
60
61
                if (isset($link['gid']) && !empty($link['gid'])) {
62
                    $group = $groupRepo->find($link['gid']);
63
                    if (null !== $group) {
64
                        $linkSet = true;
65
                        $resourceLink->setGroup($group);
66
                    } else {
67
                        throw new InvalidArgumentException(sprintf('Group #%s does not exists', $link['gid']));
68
                    }
69
                }
70
71
                if (isset($link['uid']) && !empty($link['uid'])) {
72
                    $user = $userRepo->find($link['uid']);
73
                    if (null !== $user) {
74
                        $linkSet = true;
75
                        $resourceLink->setUser($user);
76
                    } else {
77
                        throw new InvalidArgumentException(sprintf('User #%s does not exists', $link['uid']));
78
                    }
79
                }
80
81
                if (isset($link['visibility'])) {
82
                    $resourceLink->setVisibility((int) $link['visibility']);
83
                } else {
84
                    throw new InvalidArgumentException('Link needs a visibility key');
85
                }
86
87
                if ($linkSet) {
88
                    $em->persist($resourceLink);
89
                    $resourceNode->addResourceLink($resourceLink);
90
                    //$em->persist($resourceNode);
91
                    //$em->persist($resource->getResourceNode());
92
                }
93
            }
94
        }
95
96
        // Use by Chamilo not api platform.
97
        $links = $resource->getResourceLinkEntityList();
98
        if ($links) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $links of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
99
            //error_log('$resource->getResourceLinkEntityList()');
100
            foreach ($links as $link) {
101
                /*$rights = [];
102
                switch ($link->getVisibility()) {
103
                    case ResourceLink::VISIBILITY_PENDING:
104
                    case ResourceLink::VISIBILITY_DRAFT:
105
                        $editorMask = ResourceNodeVoter::getEditorMask();
106
                        $resourceRight = new ResourceRight();
107
                        $resourceRight
108
                            ->setMask($editorMask)
109
                            ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
110
                        ;
111
                        $rights[] = $resourceRight;
112
113
                        break;
114
                }
115
116
                if (!empty($rights)) {
117
                    foreach ($rights as $right) {
118
                        $link->addResourceRight($right);
119
                    }
120
                }*/
121
                //error_log('link adding to node: '.$resource->getResourceNode()->getId());
122
                //error_log('link with user : '.$link->getUser()->getUsername());
123
                $resource->getResourceNode()->addResourceLink($link);
124
125
                $em->persist($link);
126
            }
127
        }
128
    }
129
    /**
130
     * Function loaded when creating a resource using the api, then the ResourceListener is executed.
131
     */
132
    protected function handleCreateRequest(AbstractResource $resource, ResourceRepository $resourceRepository, Request $request): array
133
    {
134
        //error_log('handleCreateRequest');
135
        $contentData = $request->getContent();
136
        if (!empty($contentData)) {
137
            $contentData = json_decode($contentData, true);
138
            $title = $contentData['title'] ?? '';
139
            $comment = $contentData['comment'] ?? '';
140
            $parentResourceNodeId = $contentData['parentResourceNodeId'] ?? 0;
141
            $fileType = $contentData['filetype'] ?? '';
142
            $resourceLinkList = $contentData['resourceLinkList'] ?? [];
143
        } else {
144
            $title = $request->get('title');
145
            $comment = $request->get('comment');
146
            $parentResourceNodeId = (int) $request->get('parentResourceNodeId');
147
            $fileType = $request->get('filetype');
148
            $resourceLinkList = $request->get('resourceLinkList', []);
149
            if (!empty($resourceLinkList)) {
150
                $resourceLinkList = false === strpos($resourceLinkList, '[') ? json_decode('['.$resourceLinkList.']', true) : json_decode($resourceLinkList, true);
151
                if (empty($resourceLinkList)) {
152
                    $message = 'resourceLinkList is not a valid json. Use for example: [{"cid":1, "visibility":1}]';
153
154
                    throw new InvalidArgumentException($message);
155
                }
156
            }
157
        }
158
159
        if (empty($fileType)) {
160
            throw new Exception('filetype needed: folder or file');
161
        }
162
163
        if (0 === $parentResourceNodeId) {
164
            throw new Exception('parentResourceNodeId int value needed');
165
        }
166
167
        $resource->setParentResourceNode($parentResourceNodeId);
168
169
        switch ($fileType) {
170
            case 'file':
171
                $content = '';
172
                if ($request->request->has('contentFile')) {
173
                    $content = $request->request->get('contentFile');
174
                }
175
                $fileParsed = false;
176
                // File upload.
177
                if ($request->files->count() > 0) {
178
                    if (!$request->files->has('uploadFile')) {
179
                        throw new BadRequestHttpException('"uploadFile" is required');
180
                    }
181
182
                    /** @var UploadedFile $uploadedFile */
183
                    $uploadedFile = $request->files->get('uploadFile');
184
                    $title = $uploadedFile->getClientOriginalName();
185
                    $resource->setUploadFile($uploadedFile);
186
                    $fileParsed = true;
187
                }
188
189
                // Get data in content and create a HTML file.
190
                if (!$fileParsed && $content) {
191
                    $uploadedFile = $resourceRepository->createTempUploadedFile($title.'.html', 'text/html', $content);
192
                    $resource->setUploadFile($uploadedFile);
193
                    $fileParsed = true;
194
                }
195
196
                if (!$fileParsed) {
197
                    throw new InvalidArgumentException('filetype was set to "file" but not upload file found');
198
                }
199
200
                break;
201
            case 'folder':
202
                break;
203
        }
204
205
        if (empty($title)) {
206
            throw new InvalidArgumentException('title is required');
207
        }
208
209
        $resource->setResourceName($title);
210
211
        // Set resource link list if exists.
212
        if (!empty($resourceLinkList)) {
213
            $resource->setResourceLinkArray($resourceLinkList);
214
        }
215
216
        return [
217
            'filetype' => $fileType,
218
            'comment' => $comment,
219
        ];
220
    }
221
222
    protected function handleUpdateRequest(AbstractResource $resource, ResourceRepository $repo, Request $request, EntityManager $em)
223
    {
224
        $contentData = $request->getContent();
225
        $resourceLinkList = [];
226
        if (!empty($contentData)) {
227
            $contentData = json_decode($contentData, true);
228
            $title = $contentData['title'] ?? '';
229
            $content = $contentData['contentFile'] ?? '';
230
            $resourceLinkList = $contentData['resourceLinkListFromEntity'] ?? [];
231
        } else {
232
            $title = $request->get('title');
233
            $content = $request->request->get('contentFile');
234
            //$comment = $request->request->get('comment');
235
        }
236
237
        $repo->setResourceName($resource, $title);
238
239
        $hasFile = $resource->getResourceNode()->hasResourceFile();
240
241
        $resourceNode = $resource->getResourceNode();
242
243
        if ($hasFile && !empty($content)) {
244
            if ($resourceNode->hasResourceFile()) {
245
                // The content is updated by the ResourceNodeListener.php
246
                $resourceNode->setContent($content);
247
                $resourceNode->getResourceFile()->setSize(\strlen($content));
248
            }
249
            $resourceNode->getResourceFile()->setUpdatedAt(new DateTime());
250
            $resource->setResourceNode($resourceNode);
251
        }
252
253
        $link = null;
254
        if (!empty($resourceLinkList)) {
255
            foreach ($resourceLinkList as $key => &$linkArray) {
256
                // Find the exact link.
257
                $linkId = $linkArray['id'] ?? 0;
258
                if (!empty($linkId)) {
259
                    /** @var ResourceLink $link */
260
                    $link = $resourceNode->getResourceLinks()->filter(fn ($link) => $link->getId() === $linkId)->first();
261
262
                    if (null !== $link) {
263
                        $link->setVisibility((int) $linkArray['visibility']);
264
                        unset($resourceLinkList[$key]);
265
266
                        $em->persist($link);
267
                    }
268
                }
269
            }
270
271
            $resource->setResourceLinkArray($resourceLinkList);
272
            self::setLinks($resource, $em);
273
        }
274
275
        $isRecursive = !$hasFile;
276
        // If it's a folder then change the visibility to the children (That have the same link).
277
        if ($isRecursive && null !== $link) {
278
            $repo->copyVisibilityToChildren($resource->getResourceNode(), $link);
279
        }
280
281
        $resourceNode->setUpdatedAt(new DateTime());
282
283
        return $resource;
284
    }
285
}
286