Completed
Push — 4-cactus ( f0b320...c9f1dc )
by Alberto
19s queued 16s
created

StreamsTable::clone()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 9
c 1
b 0
f 1
dl 0
loc 13
rs 9.9666
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2017 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
14
namespace BEdita\Core\Model\Table;
15
16
use BEdita\Core\Filesystem\Thumbnail;
17
use BEdita\Core\Model\Entity\Stream;
18
use Cake\Event\Event;
19
use Cake\ORM\RulesChecker;
20
use Cake\ORM\Table;
21
use Cake\Validation\Validator;
22
23
/**
24
 * Streams Model
25
 *
26
 * @property \BEdita\Core\Model\Table\ObjectsTable|\Cake\ORM\Association\BelongsTo $Objects
27
 * @method \BEdita\Core\Model\Entity\Stream get($primaryKey, $options = [])
28
 * @method \BEdita\Core\Model\Entity\Stream newEntity($data = null, array $options = [])
29
 * @method \BEdita\Core\Model\Entity\Stream[] newEntities(array $data, array $options = [])
30
 * @method \BEdita\Core\Model\Entity\Stream|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
31
 * @method \BEdita\Core\Model\Entity\Stream patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
32
 * @method \BEdita\Core\Model\Entity\Stream[] patchEntities($entities, array $data, array $options = [])
33
 * @method \BEdita\Core\Model\Entity\Stream findOrCreate($search, callable $callback = null, $options = [])
34
 * @mixin \Cake\ORM\Behavior\TimestampBehavior
35
 * @mixin \BEdita\Core\Model\Behavior\UploadableBehavior
36
 * @since 4.0.0
37
 */
38
class StreamsTable extends Table
39
{
40
    /**
41
     * {@inheritDoc}
42
     *
43
     * @codeCoverageIgnore
44
     */
45
    public function initialize(array $config): void
46
    {
47
        parent::initialize($config);
48
49
        $this->setTable('streams');
50
        $this->setPrimaryKey('uuid');
51
        $this->setDisplayField('uri');
52
53
        $this->addBehavior('Timestamp');
54
        $this->addBehavior('BEdita/Core.Uploadable', [
55
            'files' => [
56
                [
57
                    'path' => 'uri',
58
                    'contents' => 'contents',
59
                ],
60
            ],
61
        ]);
62
63
        $this->belongsTo('Objects');
64
    }
65
66
    /**
67
     * {@inheritDoc}
68
     *
69
     * @codeCoverageIgnore
70
     */
71
    public function validationDefault(Validator $validator): Validator
72
    {
73
        $validator
74
            ->uuid('uuid')
75
            ->add('uuid', 'unique', ['rule' => 'validateUnique', 'provider' => 'table'])
76
            ->allowEmptyString('uuid', null, 'create');
77
78
        $validator
79
            ->naturalNumber('version')
80
            ->allowEmptyString('version', null, 'create');
81
82
        $validator
83
            ->allowEmptyString('uri', null, 'create');
84
85
        $validator
86
            ->requirePresence('file_name', 'create')
87
            ->notEmptyString('file_name');
88
89
        $validator
90
            ->requirePresence('mime_type', 'create')
91
            ->notEmptyString('mime_type');
92
93
        $validator
94
            ->naturalNumber('file_size')
95
            ->allowEmptyString('file_size', null, 'create');
96
97
        $validator
98
            ->ascii('hash_md5')
99
            ->allowEmptyString('hash_md5', null, 'create');
100
101
        $validator
102
            ->ascii('hash_sha1')
103
            ->allowEmptyString('hash_sha1', null, 'create');
104
105
        $validator
106
            ->naturalNumber('width')
107
            ->allowEmptyString('width');
108
109
        $validator
110
            ->naturalNumber('height')
111
            ->allowEmptyString('height');
112
113
        $validator
114
            ->naturalNumber('duration')
115
            ->allowEmptyString('duration');
116
117
        $validator
118
            ->notEmptyString('contents')
119
            ->requirePresence('contents', 'create');
120
121
        return $validator;
122
    }
123
124
    /**
125
     * Validator for cloning streams.
126
     *
127
     * @param \Cake\Validation\Validator $validator Validator instance.
128
     * @return \Cake\Validation\Validator
129
     * @codeCoverageIgnore
130
     */
131
    public function validationClone(Validator $validator): Validator
132
    {
133
        return $this->validationDefault($validator)
134
            ->requirePresence('contents', false);
135
    }
136
137
    /**
138
     * {@inheritDoc}
139
     *
140
     * @codeCoverageIgnore
141
     */
142
    public function buildRules(RulesChecker $rules): RulesChecker
143
    {
144
        $rules->add($rules->isUnique(['uri']));
145
        $rules->add($rules->existsIn(['object_id'], 'Objects'));
146
147
        return $rules;
148
    }
149
150
    /**
151
     * Generate file path before entity is saved.
152
     *
153
     * @param \Cake\Event\Event $event Dispatched event.
154
     * @param \BEdita\Core\Model\Entity\Stream $entity Entity.
155
     * @return void
156
     */
157
    public function beforeSave(Event $event, Stream $entity)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

157
    public function beforeSave(/** @scrutinizer ignore-unused */ Event $event, Stream $entity)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
158
    {
159
        if (!$entity->isNew()) {
160
            return;
161
        }
162
163
        if (!$entity->has('uri')) {
164
            // Fill path where file contents will be stored.
165
            $entity->uri = $entity->filesystemPath();
166
        }
167
    }
168
169
    /**
170
     * Clean up all thumbnails after deleting a stream.
171
     *
172
     * @param \Cake\Event\Event $event Dispatched event.
173
     * @param \BEdita\Core\Model\Entity\Stream $stream Entity.
174
     * @return void
175
     */
176
    public function afterDelete(Event $event, Stream $stream)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

176
    public function afterDelete(/** @scrutinizer ignore-unused */ Event $event, Stream $stream)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
177
    {
178
        Thumbnail::delete($stream);
179
    }
180
181
    /**
182
     * Clone a stream.
183
     *
184
     * @param \BEdita\Core\Model\Entity\Stream $stream Stream to clone.
185
     * @return \BEdita\Core\Model\Entity\Stream
186
     */
187
    public function clone(Stream $stream): Stream
188
    {
189
        $clone = $this->newEntity($stream->extract(Stream::FILE_PROPERTIES), [
190
            'accessibleFields' => array_fill_keys(Stream::FILE_PROPERTIES, true),
191
            'validate' => 'clone',
192
        ]);
193
        $clone->uri = $clone->filesystemPath();
194
195
        return $this->getConnection()->transactional(function () use ($clone, $stream): Stream {
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getConnect...ion(...) { /* ... */ }) could return the type false which is incompatible with the type-hinted return BEdita\Core\Model\Entity\Stream. Consider adding an additional type-check to rule them out.
Loading history...
196
            $clone = $this->saveOrFail($clone, ['atomic' => false]);
197
            $this->copyFiles($stream, $clone);
0 ignored issues
show
Bug introduced by
The method copyFiles() does not exist on BEdita\Core\Model\Table\StreamsTable. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

197
            $this->/** @scrutinizer ignore-call */ 
198
                   copyFiles($stream, $clone);
Loading history...
198
199
            return $this->get($clone->get('uuid'));
200
        });
201
    }
202
}
203