Completed
Push — master ( 37faaa...541bbf )
by Raffael
10:18 queued 06:30
created

Preview::storePreview()   B

Complexity

Conditions 5
Paths 52

Size

Total Lines 47

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 0
cts 0
cp 0
rs 8.8452
c 0
b 0
f 0
cc 5
crap 30
nc 52
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * balloon
7
 *
8
 * @copyright   Copryright (c) 2012-2019 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Balloon\App\Preview;
13
14
use Balloon\Converter;
15
use Balloon\Filesystem\Node\File;
16
use MongoDB\BSON\ObjectId;
17
use MongoDB\Database;
18
use Psr\Log\LoggerInterface;
19
20
class Preview
21
{
22
    /**
23
     * Stream limit.
24
     */
25
    protected const SIZE_LIMIT = 2097152;
26
27
    /**
28
     * Logger.
29
     *
30
     * @var LoggerInterface
31
     */
32
    protected $logger;
33
34
    /**
35
     * Database.
36
     *
37
     * @var Database
38
     */
39
    protected $db;
40
41
    /**
42
     * Converter.
43
     *
44
     * @var Converter
45
     */
46
    protected $converter;
47
48
    /**
49
     * Constructor.
50
     */
51
    public function __construct(Database $db, Converter $converter, LoggerInterface $logger)
52
    {
53
        $this->db = $db;
54
        $this->converter = $converter;
55
        $this->logger = $logger;
56
    }
57
58
    /**
59
     * Create preview.
60
     */
61
    public function createPreview(File $file): ObjectId
62
    {
63
        return $this->storePreview($file, $this->converter->createPreview($file));
64
    }
65
66
    /**
67
     * Set preview.
68
     */
69
    public function setPreview(File $file, $stream): ObjectId
70
    {
71
        return $this->storePreview($file, $stream);
72
    }
73
74
    /**
75
     * Get preview.
76
     */
77
    public function getPreview(File $file): string
78
    {
79
        $preview = $file->getAppAttribute(__NAMESPACE__, 'preview');
80
        if ($preview instanceof ObjectId) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\ObjectId does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
81
            try {
82
                $stream = $this->db->selectGridFSBucket(['bucketName' => 'thumbnail'])
83
                    ->openDownloadStream($preview);
84
                $contents = stream_get_contents($stream);
85
                fclose($stream);
86
87
                return $contents;
88
            } catch (\Exception $e) {
89
                $this->logger->warning('failed download preview from gridfs for file ['.$file->getId().']', [
90
                    'category' => get_class($this),
91
                    'exception' => $e,
92
                ]);
93
            }
94
        }
95
96
        throw new Exception\PreviewNotFound('preview does not exists');
97
    }
98
99
    /**
100
     * Delete preview.
101
     */
102
    public function deletePreview(File $file): bool
103
    {
104
        $bucket = $this->db->selectGridFSBucket(['bucketName' => 'thumbnail']);
105
        $preview = $file->getAppAttribute(__NAMESPACE__, 'preview');
106
107
        if ($preview instanceof ObjectId) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\ObjectId does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
108
            $references = $this->db->{'thumbnail.files'}->count([
109
                'apps' => [__NAMESPACE__ => ['preview' => $preview]],
110
            ]);
111
112
            if (1 === $references) {
113
                $this->logger->debug('delete preview ['.$preview.'] from file ['.$file->getId().']', [
114
                    'category' => get_class($this),
115
                ]);
116
117
                $bucket->delete($preview);
118
            } else {
119
                $this->logger->debug('do not remove preview blob ['.$preview.'] from file ['.$file->getId().'], there are still other references left', [
120
                    'category' => get_class($this),
121
                ]);
122
            }
123
124
            $file->unsetAppAttribute(__NAMESPACE__, 'preview');
125
126
            return true;
127
        }
128
129
        return false;
130
    }
131
132
    /**
133
     * Store new preview.
134
     */
135
    protected function storePreview(File $file, $content): ObjectId
136
    {
137
        $this->logger->info('store new preview for file ['.$file->getId().']', [
138
            'category' => get_class($this),
139
        ]);
140
141
        try {
142
            $preview = $file->getAppAttribute(__NAMESPACE__, 'preview');
143
144
            if ($preview instanceof ObjectId) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\ObjectId does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
145
                $this->deletePreview($file);
146
            }
147
        } catch (\Exception $e) {
148
            //ignore exception
149
        }
150
151
        try {
152
            $result = stream_get_contents($content, self::SIZE_LIMIT);
153
            $hash = md5($result);
154
            rewind($content);
155
156
            $found = $this->db->{'thumbnail.files'}->findOne([
157
                'md5' => $hash,
158
            ], ['_id', 'thumbnail']);
159
160
            if ($found) {
161
                $this->logger->debug('found existing preview ['.$found['_id'].'] with same hash, use stored preview', [
162
                    'category' => get_class($this),
163
                ]);
164
165
                $file->setAppAttribute(__NAMESPACE__, 'preview', $found['_id']);
166
167
                return $found['_id'];
168
            }
169
170
            $id = new ObjectId();
171
            $bucket = $this->db->selectGridFSBucket(['bucketName' => 'thumbnail']);
172
            $stream = $bucket->openUploadStream(null, ['_id' => $id]);
173
            stream_copy_to_stream($content, $stream);
174
175
            return $id;
176
        } catch (\Exception $e) {
177
            $file->unsetAppAttribute(__NAMESPACE__, 'preview');
178
179
            throw $e;
180
        }
181
    }
182
}
183