Completed
Push — master ( 8fe45b...3e4cf7 )
by Jeroen
08:37
created

MediaBuilder::guessMimeType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Kunstmaan\FixturesBundle\Builder;
4
5
use Doctrine\ORM\EntityManager;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Kunstmaan\FixturesBundle\Loader\Fixture;
8
use Kunstmaan\MediaBundle\Entity\Folder;
9
use Kunstmaan\MediaBundle\Entity\Media;
10
use Kunstmaan\MediaBundle\Helper\File\FileHandler;
11
use Kunstmaan\MediaBundle\Helper\MimeTypeGuesserFactoryInterface;
12
use Symfony\Component\HttpFoundation\File\File;
13
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface;
14
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
15
use Symfony\Component\Mime\MimeTypes;
16
17
class MediaBuilder implements BuilderInterface
18
{
19
    /** @var EntityManagerInterface */
20
    private $em;
21
    /** @var FileHandler */
22
    private $fileHandler;
23
    /** @var MimeTypes|ExtensionGuesserInterface */
24
    private $mimeTypeGuesser;
25
26
    private $folder;
27
28
    public function __construct(EntityManager $em, FileHandler $fileHandler, /* MimeTypes */$mimeTypeGuesser)
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...
29
    {
30
        $this->em = $em;
31
        $this->fileHandler = $fileHandler;
32
        $this->mimeTypeGuesser = $mimeTypeGuesser;
33
        if ($mimeTypeGuesser instanceof MimeTypeGuesserFactoryInterface) {
34
            @trigger_error(sprintf('Passing an instance of "%s" for the "$mimeTypeGuesser" parameter is deprecated since KunstmaanMediaBundle 5.7 and will be replaced by the "@mime_types" service in KunstmaanMediaBundle 6.0. Inject the correct service instead.', MimeTypeGuesserFactoryInterface::class), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
35
36
            $this->mimeTypeGuesser = $mimeTypeGuesser->get();
0 ignored issues
show
Documentation Bug introduced by
It seems like $mimeTypeGuesser->get() of type object<Symfony\Component...meTypeGuesserInterface> is incompatible with the declared type object<Symfony\Component...ensionGuesserInterface> of property $mimeTypeGuesser.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
37
        }
38
    }
39
40
    public function canBuild(Fixture $fixture)
41
    {
42
        if ($fixture->getEntity() instanceof Media) {
43
            return true;
44
        }
45
46
        return false;
47
    }
48
49
    public function preBuild(Fixture $fixture)
50
    {
51
        $properties = $fixture->getProperties();
52
        if (!isset($properties['folder'])) {
53
            throw new \Exception('There is no folder specified for media fixture '.$fixture->getName());
54
        }
55
56
        $this->folder = $this->em->getRepository(Folder::class)->findOneBy(['rel' => $properties['folder']]);
57
58
        if (!$this->folder instanceof Folder) {
59
            $this->folder = $this->em->getRepository(Folder::class)->findOneBy(['internalName' => $properties['folder']]);
60
        }
61
62
        if (!$this->folder instanceof Folder) {
63
            throw new \Exception('Could not find the specified folder for media fixture '.$fixture->getName());
64
        }
65
    }
66
67
    public function postBuild(Fixture $fixture)
68
    {
69
        /** @var Media $media */
70
        $media = $fixture->getEntity();
71
72
        $filePath = $media->getOriginalFilename();
73
        $data = new File($filePath, true);
74
        $contentType = $this->guessMimeType($data->getPathname());
75
76
        if (method_exists($data, 'getClientOriginalName')) {
77
            $media->setOriginalFilename($data->getClientOriginalName());
78
        } else {
79
            $media->setOriginalFilename($data->getFilename());
80
        }
81
82
        if ($media->getName() === null) {
83
            $media->setName($media->getOriginalFilename());
84
        }
85
86
        $media->setContent($data);
87
88
        $media->setContentType($contentType);
89
        $media->setFolder($this->folder);
0 ignored issues
show
Documentation introduced by
$this->folder is of type object|null, but the function expects a object<Kunstmaan\MediaBundle\Entity\Folder>.

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...
90
91
        $this->fileHandler->prepareMedia($media);
92
        $this->fileHandler->updateMedia($media);
93
        $this->fileHandler->saveMedia($media);
94
    }
95
96
    private function guessMimeType($pathName): ?string
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
97
    {
98
        if ($this->mimeTypeGuesser instanceof MimeTypeGuesserInterface) {
99
            return $this->mimeTypeGuesser->guess($pathName);
100
        }
101
102
        return $this->mimeTypeGuesser->guessMimeType($pathName);
0 ignored issues
show
Bug introduced by
The method guessMimeType does only exist in Symfony\Component\Mime\MimeTypes, but not in Symfony\Component\HttpFo...tensionGuesserInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
103
    }
104
105
    public function postFlushBuild(Fixture $fixture)
106
    {
107
        return;
108
    }
109
}
110