Lines 100.00% 26 / 26
Methods 100.00% 5 / 5
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 2 / 2 100.00% 1 / 1 1
 writeUploadToScope 100.00% 5 / 5 100.00% 1 / 1 1
 writeUploadToCluster 100.00% 5 / 5 100.00% 1 / 1 1
 getUploadedFile 100.00% 2 / 2 100.00% 1 / 1 2
 createImage 100.00% 12 / 12 100.00% 1 / 1 4
14class FileUploader
15{
16    public $imageData;
17
18    protected $allowedTypes = array('image/gif','image/jpeg','image/png','image/svg+xml');
19
20    protected $files = null;
21
22    protected $uploadFile = null;
23
24    protected $mediaType = '';
25
26    protected $request = null;
27
28    public function __construct(\Psr\Http\Message\RequestInterface $request, $imageName)
29    {
30        $this->request = $request;
31        $this->imageData = $this->createImage($imageName);
32    }
33
34    public function writeUploadToScope($entityId): static
35    {
36        $this->imageData = \App::$http->readPostResult(
37            '/scope/' . $entityId . '/imagedata/calldisplay/',
38            $this->imageData
39        )->getEntity();
40        return $this;
41    }
42
43    public function writeUploadToCluster($entityId): static
44    {
45        $this->imageData = \App::$http->readPostResult(
46            '/cluster/' . $entityId . '/imagedata/calldisplay/',
47            $this->imageData
48        )->getEntity();
49        return $this;
50    }
51
52    protected function getUploadedFile($imageName)
53    {
54        $files = $this->request->getUploadedFiles();
55        return (isset($files[$imageName])) ? $files[$imageName] : false;
56    }
57
58    protected function createImage($imageName): Mimepart|null
59    {
60        $image = null;
61        $this->uploadFile = $this->getUploadedFile($imageName);
62        if ($this->uploadFile && $this->uploadFile->getError() === UPLOAD_ERR_OK) {
63            $this->mediaType = $this->uploadFile->getClientMediaType();
64            if (in_array($this->mediaType, $this->allowedTypes)) {
65                $image = new Mimepart();
66                $image->mime = $this->mediaType;
67                $image->base64 = true;
68                $data = file_get_contents($this->uploadFile->getFilePath());
69                $image->content = base64_encode($data);
70            } else {
71                throw new \Exception('Wrong Mediatype given, use gif, jpg, svg or png');
72            }
73        }
74        return $image;
75    }
76}