UnknownFileModel::getContent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Fousky\Component\iDoklad\Model\Other;
4
5
use Fousky\Component\iDoklad\Model\iDokladAbstractModel;
6
use Fousky\Component\iDoklad\Model\iDokladModelInterface;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * @author Lukáš Brzák <[email protected]>
11
 */
12
class UnknownFileModel extends iDokladAbstractModel
13
{
14
    /**
15
     * RAW content of file (should be saved to disc with some filename+extension).
16
     *
17
     * @var string
18
     */
19
    protected $content;
20
21
    /**
22
     * MIME-type detected of raw content. You can check extension by this MIME.
23
     *
24
     * @var string
25
     */
26
    protected $mime;
27
28
    /**
29
     * @throws \RuntimeException
30
     */
31
    public function __construct()
32
    {
33
        if (!\function_exists('mime_content_type')) {
34
            throw new \RuntimeException('Function `mime_content_type` does not exists, please install PHP extension `fileinfo` (php_fileinfo.so or php_fileinfo.dll).');
35
        }
36
    }
37
38
    /**
39
     * @param ResponseInterface $response
40
     *
41
     * @throws \Exception
42
     *
43
     * @return iDokladModelInterface
44
     */
45
    public static function createFromResponse(ResponseInterface $response): iDokladModelInterface
46
    {
47
        return (new static())->init($response->getBody()->getContents());
48
    }
49
50
    /**
51
     * @param string $raw
52
     *
53
     * @throws \Exception
54
     *
55
     * @return iDokladModelInterface
56
     */
57
    public function init(string $raw): iDokladModelInterface
58
    {
59
        $this->content = base64_decode($raw);
60
61
        $temp = sprintf('%s/%s', sys_get_temp_dir(), bin2hex(random_bytes(10)));
62
        file_put_contents($temp, $this->content);
63
64
        $this->mime = mime_content_type($temp);
65
        @unlink($temp);
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...
66
67
        return $this;
68
    }
69
70
    /**
71
     * @return string
72
     */
73
    public function getContent(): string
74
    {
75
        return $this->content;
76
    }
77
78
    /**
79
     * @return string
80
     */
81
    public function getMime(): string
82
    {
83
        return $this->mime;
84
    }
85
}
86