Completed
Push — master ( 2ae089...5f42d6 )
by Luis Ramón
13:38
created

FolderController::processFileUpload()   C

Complexity

Conditions 7
Paths 151

Size

Total Lines 63
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 63
rs 6.1545
c 0
b 0
f 0
cc 7
eloc 42
nc 151
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
  ÁTICA - Aplicación web para la gestión documental de centros educativos
4
5
  Copyright (C) 2015-2017: Luis Ramón López López
6
7
  This program is free software: you can redistribute it and/or modify
8
  it under the terms of the GNU Affero General Public License as published by
9
  the Free Software Foundation, either version 3 of the License, or
10
  (at your option) any later version.
11
12
  This program is distributed in the hope that it will be useful,
13
  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
  GNU Affero General Public License for more details.
16
17
  You should have received a copy of the GNU Affero General Public License
18
  along with this program.  If not, see [http://www.gnu.org/licenses/].
19
*/
20
21
namespace AppBundle\Controller\Documentation;
22
23
use AppBundle\Entity\Documentation\Entry;
24
use AppBundle\Entity\Documentation\Folder;
25
use AppBundle\Entity\Documentation\FolderPermission;
26
use AppBundle\Entity\Documentation\FolderRepository;
27
use AppBundle\Entity\Documentation\History;
28
use AppBundle\Entity\Documentation\Version;
29
use AppBundle\Entity\ElementRepository;
30
use AppBundle\Entity\Organization;
31
use AppBundle\Form\Model\DocumentUpload;
32
use AppBundle\Form\Type\Documentation\FolderType;
33
use AppBundle\Form\Type\Documentation\UploadType;
34
use AppBundle\Security\OrganizationVoter;
35
use Doctrine\Common\Collections\ArrayCollection;
36
use Doctrine\ORM\EntityManager;
37
use Doctrine\ORM\QueryBuilder;
38
use Pagerfanta\Adapter\DoctrineORMAdapter;
39
use Pagerfanta\Pagerfanta;
40
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
41
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
42
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
43
use Symfony\Component\Form\Form;
44
use Symfony\Component\HttpFoundation\File\UploadedFile;
45
use Symfony\Component\HttpFoundation\Request;
46
47
/**
48
 * @Route("/documentos")
49
 */
50
class FolderController extends Controller
51
{
52
    /**
53
     * @Route("/carpeta/{id}/nueva", name="documentation_folder_new", methods={"GET", "POST"})
54
     * @Route("/carpeta/{id}", name="documentation_folder_form", requirements={"id" = "\d+"}, methods={"GET", "POST"})
55
     * @Security("is_granted('FOLDER_MANAGE', folder)")
56
     */
57
    public function folderFormAction(Folder $folder = null, Request $request)
58
    {
59
        $organization = $this->get('AppBundle\Service\UserExtensionService')->getCurrentOrganization();
60
        $this->denyAccessUnlessGranted(OrganizationVoter::MANAGE, $organization);
61
62
        $em = $this->getDoctrine()->getManager();
63
        $new = $request->get('_route') === 'documentation_folder_new';
64
65
        $sourceFolder = $folder;
66
67
        if ($new) {
68
            $newFolder = new Folder();
69
            $newFolder
70
                ->setOrganization($organization)
71
                ->setParent($folder);
72
            $folder = $newFolder;
73
            $em->persist($folder);
74
        } else {
75
            if (null === $sourceFolder->getParent()) {
76
                throw $this->createAccessDeniedException();
77
            }
78
        }
79
        $breadcrumb = $sourceFolder->getParent() ? $this->generateBreadcrumb($sourceFolder, false) : [];
80
81
        if ($request->request->get('folder')) {
82
            $folder->setType($request->request->get('folder')['type']);
1 ignored issue
show
Bug introduced by
It seems like $folder is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
83
        }
84
        $form = $this->createForm(FolderType::class, $folder, [
85
            'new' => $new,
86
            'allow_extra_fields' => !$request->request->has('submit')
87
        ]);
88
89
        $this->setFolderRolesInForm($folder, $form);
90
        $form->handleRequest($request);
91
        $breadcrumb[] = ['fixed' => $this->get('translator')->trans($new ? 'title.folder.new' : 'title.folder.edit', [], 'documentation')];
92
93
        if ($form->isSubmitted() && $form->isValid() && $request->request->has('submit')) {
94
            try {
95
                $this->updateFolderRolesFromForm($folder, $em, $form);
1 ignored issue
show
Bug introduced by
It seems like $folder defined by parameter $folder on line 57 can be null; however, AppBundle\Controller\Doc...teFolderRolesFromForm() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
96
                $em->flush();
97
                $this->addFlash('success', $this->get('translator')->trans('message.folder.saved', [], 'documentation'));
98
                return $this->redirectToRoute('documentation', ['id' => $sourceFolder->getId()]);
99
            } catch (\Exception $e) {
100
                $this->addFlash('error', $this->get('translator')->trans('message.folder.save_error', [], 'documentation'));
101
            }
102
        }
103
104
        return $this->render('documentation/folder_form.html.twig', [
105
            'menu_path' => 'documentation',
106
            'breadcrumb' => $breadcrumb,
107
            'title' => $this->get('translator')->trans($new ? 'title.folder.new' : 'title.folder.edit', [], 'documentation'),
108
            'form' => $form->createView(),
109
            'folder' => $folder
110
        ]);
111
    }
112
113
    /**
114
     * @param Folder $folder
115
     * @param Form $form
116
     */
117
    private function setFolderRolesInForm(Folder $folder = null, Form $form)
118
    {
119
        if (null === $folder) {
120
            return;
121
        }
122
123
        $permissions = $folder->getPermissions();
124
125
        $permissionTypes = [
126
            'access' => FolderPermission::PERMISSION_VISIBLE,
127
            'manager' => FolderPermission::PERMISSION_MANAGE,
128
            'upload' => FolderPermission::PERMISSION_UPLOAD,
129
            'review' => FolderPermission::PERMISSION_REVIEW,
130
            'approve' => FolderPermission::PERMISSION_APPROVE
131
        ];
132
133
        foreach ($permissionTypes as $name => $type) {
134
            if ($form->has('profiles_'.$name)) {
135
                $data = [];
136
137
                /** @var FolderPermission $permission */
138
                foreach ($permissions as $permission) {
139
                    if ($permission->getPermission() === $type) {
140
                        $data[] = $permission->getElement();
141
                    }
142
                }
143
144
                if (!empty($data)) {
145
                    $form->get('profiles_' . $name)->setData($data);
146
                }
147
            }
148
        }
149
    }
150
151
    /**
152
     * @param Folder $folder
153
     * @param EntityManager $em
154
     * @param Form $form
155
     */
156
    private function updateFolderRolesFromForm($folder, EntityManager $em, $form)
157
    {
158
        $oldPermissions = $folder->getPermissions();
159
160
        $permissionTypes = [
161
            'access' => FolderPermission::PERMISSION_VISIBLE,
162
            'manager' => FolderPermission::PERMISSION_MANAGE,
163
            'upload' => FolderPermission::PERMISSION_UPLOAD,
164
            'review' => FolderPermission::PERMISSION_REVIEW,
165
            'approve' => FolderPermission::PERMISSION_APPROVE
166
        ];
167
168
        foreach ($permissionTypes as $name => $type) {
169
170
            $data = $form->has('profiles_' . $name) ? $form->get('profiles_' . $name)->getData() : [];
171
            if (!$data instanceof ArrayCollection) {
172
                $data = new ArrayCollection($data);
173
            }
174
175
            /** @var FolderPermission $permission */
176
            foreach ($oldPermissions as $permission) {
177
                if ($permission->getPermission() === $type) {
178
                    if (!$data->contains($permission->getElement())) {
179
                        $em->remove($permission);
180
                    } else {
181
                        $data->removeElement($permission->getElement());
182
                    }
183
                }
184
            }
185
186
            foreach ($data as $datum) {
187
                $permission = new FolderPermission();
188
                $permission
189
                    ->setFolder($folder)
190
                    ->setPermission($type)
191
                    ->setElement($datum);
192
                $em->persist($permission);
193
            }
194
        }
195
        $em->flush();
196
    }
197
198
    /**
199
     * @Route("/operacion/{id}", name="documentation_operation", requirements={"id" = "\d+"}, methods={"POST"})
200
     * @Security("is_granted('FOLDER_MANAGE', folder)")
201
     */
202
    public function operationAction($id, Request $request)
203
    {
204
        $organization = $this->get('AppBundle\Service\UserExtensionService')->getCurrentOrganization();
205
206
        $folder = $this->getFolder($organization, $id);
207
208
        if (null === $folder || $folder->getOrganization() !== $organization) {
209
            throw $this->createNotFoundException();
210
        }
211
        $ok = false;
212
        $em = $this->getDoctrine()->getManager();
213
        foreach (['up', 'down'] as $op) {
214
            if ($request->get($op)) {
215
                $method = 'move'.ucfirst($op);
216
                $em->getRepository('AppBundle:Documentation\Folder')->$method($folder);
217
                $ok = true;
218
            }
219
        }
220
        if ($ok) {
221
            $em->flush();
222
        }
223
        return $this->redirectToRoute('documentation', ['id' => $folder->getId()]);
224
    }
225
226
    /**
227
     * @Route("/{id}/{page}", name="documentation", requirements={"page" = "\d+", "id" = "\d+"}, defaults={"page" = "1", "folder" = null}, methods={"GET"})
228
     */
229
    public function browseAction($page, $id = null, Request $request)
230
    {
231
        $organization = $this->get('AppBundle\Service\UserExtensionService')->getCurrentOrganization();
232
233
        $q = $request->get('q', null);
234
235
        $folder = (null === $id) ? $this->getRootFolder($organization) : $this->getFolder($organization, $id);
236
237
        if (null === $folder) {
238
            throw $this->createNotFoundException();
239
        }
240
        $this->denyAccessUnlessGranted('FOLDER_ACCESS', $folder);
241
242
        $pager = $this->getFolderEntriesPager($page, $folder, $q);
243
244
        $breadcrumb = $this->generateBreadcrumb($folder);
245
246
        return $this->render('documentation/list.html.twig', [
247
            'breadcrumb' => $breadcrumb,
248
            'pager' => $pager,
249
            'current' => $folder,
250
            'permissions' => ['is_folder_manager' => $this->isGranted('FOLDER_MANAGE', $folder), 'is_organization_manager' => $this->isGranted('ORGANIZATION_MANAGE', $organization)],
251
            'tree' => $this->getOrganizationTree($this->getRootFolder($organization), $folder),
252
            'q' => $q,
253
            'domain' => 'element'
254
        ]);
255
    }
256
257
    /**
258
     * @param Organization $organization
259
     * @return Folder
260
     */
261 View Code Duplication
    private function getRootFolder($organization)
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...
262
    {
263
        /** @var FolderRepository $folderRepository */
264
        $folderRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Documentation\Folder');
265
266
        /** @var Folder|null $folder */
267
        $folder = $folderRepository->findOneBy(['organization' => $organization, 'parent' => null]);
268
269
        return $folder;
270
    }
271
272
    /**
273
     * @param Organization $organization
274
     * @param int $id
275
     * @return Folder
276
     */
277 View Code Duplication
    private function getFolder($organization, $id)
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...
278
    {
279
        /** @var FolderRepository $folderRepository */
280
        $folderRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Documentation\Folder');
281
282
        /** @var Folder|null $folder */
283
        $folder = $folderRepository->findOneBy(['organization' => $organization, 'id' => $id]);
284
285
        return $folder;
286
    }
287
288
    /**
289
     * @param $page
290
     * @param Folder|null $folder
291
     * @param $q
292
     * @return Pagerfanta
293
     */
294
    private function getFolderEntriesPager($page, Folder $folder = null, $q)
295
    {
296
        /** @var ElementRepository $entriesRepository */
297
        $entriesRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Documentation\Entry');
298
299
        // obtener las carpetas
300
        $folders = $this->getDoctrine()->getManager()->getRepository('AppBundle:Documentation\Folder')->getChildren($folder, false, false, 'ASC', true);
301
302
        /** @var QueryBuilder $queryBuilder */
303
        $queryBuilder = $entriesRepository->createQueryBuilder('e')
304
            ->andWhere('e.folder IN (:folders)')
305
            ->setParameter('folders', $folders)
306
            ->join('e.folder', 'f')
307
            ->addOrderBy('f.left')
308
            ->addOrderBy('e.position')
309
            ->addSelect('v')
310
            ->leftJoin('e.currentVersion', 'v');
311
312
        if ($q) {
313
            $queryBuilder
314
                ->andWhere('e.name LIKE :tq')
315
                ->setParameter('tq', '%'.$q.'%');
316
        }
317
318
        $adapter = new DoctrineORMAdapter($queryBuilder, false);
319
        $pager = new Pagerfanta($adapter);
320
        $pager
321
            ->setMaxPerPage($this->getParameter('page.size'))
322
            ->setCurrentPage($q ? 1 : $page);
323
324
        return $pager;
325
    }
326
327
    /**
328
     * Returns breadcrumb that matches the folder (ignores root element)
329
     * @param Folder $folder
330
     * @param bool $ignoreLast
331
     * @return array
332
     */
333 View Code Duplication
    private function generateBreadcrumb(Folder $folder = null, $ignoreLast = true)
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...
334
    {
335
        $breadcrumb = [];
336
337
        if (null === $folder) {
338
            return null;
339
        }
340
341
        $item = $folder;
342
        while ($item->getParent()) {
343
            $entry = ['fixed' => $item->getName()];
344
            if ($item !== $folder || !$ignoreLast) {
345
                $entry['routeName'] = 'documentation';
346
                $entry['routeParams'] = ['id' => $item->getId()];
347
            }
348
            array_unshift($breadcrumb, $entry);
349
            $item = $item->getParent();
350
        }
351
        return $breadcrumb;
352
    }
353
354
    /**
355
     * Returns folder tree
356
     *
357
     * @param Folder $folder
358
     * @param Folder $current
359
     *
360
     * @return array
361
     */
362
    private function getOrganizationTree(Folder $folder, Folder $current = null)
363
    {
364
        /** @var FolderRepository $folderRepository */
365
        $folderRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Documentation\Folder');
366
367
        $children = $folderRepository->childrenHierarchy($folder);
368
369
        $organization = $folder->getOrganization();
370
        $disabled = $this->isGranted('ORGANIZATION_MANAGE', $organization) ? [] : array_map(function (Folder $f) {
371
            return $f->getId();
372
        }, $folderRepository->getAccessDeniedFoldersForUserAndOrganizationArray($this->getUser(), $organization));
1 ignored issue
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<AppBundle\Entity\User>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
373
374
        list($tree) = $this->processChildren($children, $current ? $current->getId() : null, $disabled);
1 ignored issue
show
Bug introduced by
It seems like $children can also be of type string; however, AppBundle\Controller\Doc...ller::processChildren() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
375
376
        return $tree;
377
    }
378
379
    /**
380
     * Convert children array into a treeview array
381
     *
382
     * @param array $children
383
     * @param integer $currentId
384
     * @param array $disabledId
385
     * @return mixed
386
     */
387
    private function processChildren(array $children, $currentId = null, $disabledId = [])
388
    {
389
        $result = [];
390
        $selected = false;
391
        foreach ($children as $child) {
392
            $item = [];
393
            $item['text'] = $child['name'];
394
395
            $disabled = in_array($child['id'], $disabledId,false);
396
            if ($disabled) {
397
                $item['state'] = ['disabled' => true];
398
            }
399
            if ($currentId === $child['id']) {
400
                $item['state'] = ['selected' => true, 'expanded' => true];
401
                $selected = true;
402
            }
403
            if (!$disabled && count($child['__children']) > 0) {
404
                list($item['nodes'], $selected) = $this->processChildren($child['__children'], $currentId, $disabledId);
405
            } else {
406
                $item['icon'] = 'fa fa-folder';
407
            }
408
            if ($selected) {
409
                if (!isset($item['state'])) {
410
                    $item['state'] = [];
411
                }
412
                $item['state']['expanded'] = true;
413
            }
414
            $item['href'] = $this->generateUrl('documentation', ['id' => $child['id']]);
415
            $result[] = $item;
416
        }
417
418
        return [$result, $selected];
419
    }
420
421
    /**
422
     * @Route("/carpeta/{id}/subir", name="documentation_folder_upload", methods={"GET", "POST"})
423
     * @Security("is_granted('FOLDER_UPLOAD', folder) and folder.getType() != constant('AppBundle\\Entity\\Documentation\\Folder::TYPE_TASKS')")
424
     */
425
    public function uploadFormAction(Request $request, Folder $folder)
426
    {
427
        $breadcrumb = $this->generateBreadcrumb($folder, false);
428
429
        $title = $this->get('translator')->trans('title.entry.new', [], 'documentation');
430
        $breadcrumb[] = ['fixed' => $title];
431
432
        $upload = new DocumentUpload();
433
434
        if ($this->isGranted('FOLDER_MANAGE', $folder)) {
435
            $profiles = $this->getDoctrine()->getManager()->getRepository('AppBundle:Element')->findAllProfilesByFolderPermission($folder, FolderPermission::PERMISSION_UPLOAD, true);
1 ignored issue
show
Bug introduced by
The method findAllProfilesByFolderPermission() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findAll()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
436
        } else {
437
            $profiles = $this->getDoctrine()->getManager()->getRepository('AppBundle:Element')->findAllProfilesByFolderPermissionAndUser($folder, FolderPermission::PERMISSION_UPLOAD, $this->getUser(), true);
1 ignored issue
show
Bug introduced by
The method findAllProfilesByFolderPermissionAndUser() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findAll()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
438
        }
439
        $form = $this->createForm(UploadType::class, $upload, ['upload_profiles' => $profiles]);
440
441
        $form->handleRequest($request);
442
443
        if ($form->isSubmitted() && $form->isValid()) {
444
            if ($this->processFileUpload($folder, $upload)) {
445
                $this->addFlash('success', $this->get('translator')->trans('message.upload.save_ok', [], 'upload'));
446
                return $this->redirectToRoute('documentation', ['id' => $folder->getId()]);
447
            }
448
            $this->addFlash('error', $this->get('translator')->trans('message.upload.save_error', [], 'upload'));
449
        }
450
451
        return $this->render('documentation/folder_upload.html.twig', [
452
            'menu_path' => 'documentation',
453
            'title' => $title,
454
            'breadcrumb' => $breadcrumb,
455
            'folder' => $folder,
456
            'form' => $form->createView()
457
        ]);
458
    }
459
460
    private function processFileUpload(Folder $folder, DocumentUpload $upload)
461
    {
462
        $em = $this->getDoctrine()->getManager();
463
        $processedFileName = null;
464
        $filesystem = $this->get('entries_filesystem');
465
        try {
466
            /** @var UploadedFile $file */
467
            $file = $upload->getFile();
468
            $fileName = hash_file('sha256', $file->getRealPath());
469
            $fileName = substr($fileName, 0, 2).'/'.substr($fileName, 2, 2).'/'.$fileName;
470
            if (!$filesystem->has($fileName)) {
471
                $filesystem->write($fileName, file_get_contents($file->getRealPath()));
472
            }
473
            $processedFileName = $fileName;
474
475
            $entry = new Entry();
476
            $entry
477
                ->setName($upload->getTitle() ?: $file->getClientOriginalName())
478
                ->setFolder($folder)
479
                ->setElement($upload->getUploadProfile())
480
                ->setDescription($upload->getDescription());
481
482
            if ($upload->getCreateDate()) {
483
                $entry->setCreatedAt($upload->getCreateDate());
484
            }
485
486
            $em->persist($entry);
487
488
            $version = new Version();
489
            $version
490
                ->setEntry($entry)
491
                ->setFile($fileName)
492
                ->setState(Version::STATUS_APPROVED)
493
                ->setVersionNr($upload->getVersion());
494
495
            $entry->setCurrentVersion($version);
496
497
            $em->persist($version);
498
499
            $history = new History();
500
            $history
501
                ->setEntry($entry)
502
                ->setVersion($upload->getVersion())
503
                ->setCreatedBy($this->getUser())
1 ignored issue
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<AppBundle\Entity\User>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
504
                ->setEvent(History::LOG_CREATE);
505
506
            $em->persist($history);
507
508
            $em->flush();
509
510
            return true;
511
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
512
        }
513
514
        if ($processedFileName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $processedFileName of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
515
            // ha ocurrido un error pero el fichero se había almacenado, borrarlo si no se estaba usando
516
            if (0 == (int) $em->getRepository('AppBundle:Documentation\Version')->countByFile($processedFileName)) {
517
                $filesystem->delete($processedFileName);
518
            }
519
        }
520
521
        return false;
522
    }
523
}
524