Completed
Push — master ( 4a96cd...f470dd )
by Zlatin
05:43
created

MediaProvider::save()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 38
rs 8.439
cc 5
eloc 24
nc 5
nop 3
1
<?php
2
3
namespace Media\Provider;
4
5
use Doctrine\ORM\EntityManager;
6
use Media\Entity\MediaInterface;
7
use Media\Provider\MediaProviderInterface;
8
use Symfony\Component\HttpFoundation\File\UploadedFile;
9
10
class MediaProvider implements MediaProviderInterface
11
{
12
13
    /**
14
     *
15
     * @var EntityManager
16
     */
17
    private $em;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $em. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
18
19
    /**
20
     *
21
     * @var string
22
     */
23
    private $path;
24
25
    /**
26
     * 
27
     * @param EntityManager $em
28
     * @param string $path
29
     */
30
    public function __construct(EntityManager $em, $path)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
Comprehensibility introduced by
Avoid variables with short names like $em. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
31
    {
32
        $this->em = $em;
33
        $this->path = $path;
34
    }
35
36
    /**
37
     * 
38
     * @param UploadedFile $file
39
     * @param string $directory
40
     * 
41
     * @return string
42
     */
43
    public function generateName(UploadedFile $file, $directory)
44
    {
45
        $extension = $file->guessClientExtension();
46
        do {
47
            $filename = md5(uniqid()) . '.' . $extension;
48
            if (file_exists($directory . DIRECTORY_SEPARATOR . $filename)) {
49
                $filename = null;
50
            }
51
        } while (is_null($filename));
52
53
        return $filename;
54
    }
55
56
    public function save(MediaInterface $media, $class, $options)
57
    {
58
59
        if (!$media->getFileContent() instanceof UploadedFile) {
60
            return $media;
61
        }
62
63
        $directory = $this->path . DIRECTORY_SEPARATOR . $options['context'];
64
        if (!is_dir($directory) || !is_writeable($directory)) {
65
            mkdir($directory, '0755', true);
66
        }
67
68
        if ($options['new_on_update']) {
69
            $entity = new $class;
70
        } else {
71
            $entity = clone $media;
72
        }
73
74
        $filename = $this->generateName($media->getFileContent(), $directory);
75
76
        $media->getFileContent()->move($directory, $filename);
77
78
        $entity->setFileName($filename);
79
        $entity->setContext($options['context']);
80
        $entity->setFileType($media->getFileContent()->getClientMimeType());
81
        $entity->setFileSize($media->getFileContent()->getClientSize());
82
        $entity->setMetadata([
83
            'filename' => $media->getFileContent()->getClientOriginalName(),
84
            'filesize' => $media->getFileContent()->getClientSize(),
85
            'filetype' => $media->getFileContent()->getClientMimeType(),
86
            'extension' => $media->getFileContent()->getClientOriginalExtension()
87
        ]);
88
89
        $this->em->persist($entity);
90
        $this->em->flush();
91
92
        return $entity;
93
    }
94
95
}
96