Passed
Push — master ( 240c83...03f39b )
by Mathias
06:41
created

UploadHandler::handleUpload()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 29
rs 9.6
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Auth\Service;
6
7
8
use Auth\AuthenticationService;
9
use Auth\Entity\UserImage;
10
use Auth\Entity\UserInterface;
11
use Core\Entity\ImageMetadata;
12
use Core\Service\FileManager;
13
use Doctrine\ODM\MongoDB\DocumentManager;
14
use Psr\Container\ContainerInterface;
15
16
class UploadHandler
17
{
18
    /**
19
     * @var FileManager
20
     */
21
    private FileManager $fileManager;
22
23
    /**
24
     * @var AuthenticationService
25
     */
26
    private AuthenticationService $auth;
0 ignored issues
show
introduced by
The private property $auth is not used, and could be removed.
Loading history...
27
28
    /**
29
     * @var DocumentManager
30
     */
31
    private DocumentManager $dm;
32
33
    public function __construct(
34
        DocumentManager $dm,
35
        FileManager $fileManager
36
    )
37
    {
38
        $this->fileManager = $fileManager;
39
        $this->dm = $dm;
40
    }
41
42
    public static function factory(ContainerInterface $container): self
43
    {
44
        $dm = $container->get(DocumentManager::class);
45
        $fileManager = $container->get(FileManager::class);
46
        return new self($dm, $fileManager);
47
    }
48
49
    public function handleUpload(UserInterface $user, array $uploaded): UserInterface
50
    {
51
        /* @var UserInterface $user */
52
        $dm = $this->dm;
53
        $fileManager = $this->fileManager;
54
        $metadata = new ImageMetadata();
55
56
        if(!is_null($image = $user->getInfo()->getImage())){
57
            $user->getInfo()->setImage(null);
58
            $this->dm->persist($user);
59
            $this->dm->flush();
60
        }
61
62
        $metadata
63
            ->setUser($user)
64
            ->setContentType($uploaded['type'])
65
            ->setKey('original')
66
        ;
67
        $this->dm->persist($user);
68
        $file = $fileManager->uploadFromFile(
69
            UserImage::class,
70
            $metadata,
71
            $uploaded['tmp_name'],
72
            $uploaded['name']
73
        );
74
        $user->getInfo()->setImage($file);
75
        $dm->flush();
76
77
        return $user;
78
    }
79
}