Test Failed
Push — develop ( 8ff4ed...2e815f )
by Daniel
04:44
created

FixtureFileUploader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Silverback\ApiComponentBundle\File\Uploader;
4
5
use Silverback\ApiComponentBundle\Entity\Component\FileInterface;
6
use Symfony\Component\Filesystem\Filesystem;
7
use Symfony\Component\HttpFoundation\File\File;
8
use Symfony\Component\HttpFoundation\File\UploadedFile;
9
10
class FixtureFileUploader
11
{
12
    private $fileUploader;
13
14
    public function __construct(
15
        FileUploader $fileUploader
16
    ) {
17
        $this->fileUploader = $fileUploader;
18
    }
19
20
    /**
21
     * @param FileInterface $entity
22
     * @param File $file
23
     * @param string $field
24
     * @return \Silverback\ApiComponentBundle\Entity\Component\FileInterface
25
     * @throws \Exception
26
     */
27
    public function upload(FileInterface $entity, File $file, string $field = 'filePath'): FileInterface
28
    {
29
        if (!($entity instanceof FileInterface)) {
0 ignored issues
show
introduced by
$entity is always a sub-type of Silverback\ApiComponentB...Component\FileInterface.
Loading history...
30
            throw new \Exception('Invalid entity returned from FixtureFileUploader::upload factory');
31
        }
32
        $tempFile = tmpfile();
33
        if (false === $tempFile) {
34
            throw new \Exception('Could not create temporary file');
35
        }
36
        $tempPath = stream_get_meta_data($tempFile)['uri'];
37
        fclose($tempFile);
38
39
        $fs = new Filesystem();
40
        $fs->copy($file->getRealPath(), $tempPath, true);
41
        $uploadedFile = new UploadedFile(
42
            $tempPath,
43
            $file->getFilename(),
44
            $file->getMimeType(),
45
            null,
46
            true
47
        );
48
        $this->fileUploader->upload($entity, $field, $uploadedFile);
49
        return $entity;
50
    }
51
}
52