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

StreamsController::clone()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 18
rs 9.8333
c 0
b 0
f 0
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\API\Controller;
15
16
use Cake\Event\Event;
17
use Cake\Http\Exception\ForbiddenException;
18
use Cake\Http\Response;
19
use Cake\ORM\TableRegistry;
20
use Cake\Routing\Router;
21
use Cake\Utility\Hash;
22
23
/**
24
 * Controller for `/streams` endpoint.
25
 *
26
 * @since 4.0.0
27
 * @property \BEdita\Core\Model\Table\StreamsTable $Table
28
 * @property \BEdita\API\Controller\Component\UploadComponent $Upload
29
 */
30
class StreamsController extends ResourcesController
31
{
32
    /**
33
     * @inheritDoc
34
     */
35
    protected $_defaultConfig = [
36
        'allowedAssociations' => [
37
            'object' => [], // Descendant types of `media` are automatically added in controller initialization.
38
        ],
39
    ];
40
41
    /**
42
     * @inheritDoc
43
     */
44
    public $modelClass = 'Streams';
45
46
    /**
47
     * @inheritDoc
48
     */
49
    public function initialize(): void
50
    {
51
        /** @var \BEdita\Core\Model\Table\ObjectTypesTable $ObjectTypes */
52
        $ObjectTypes = TableRegistry::getTableLocator()->get('ObjectTypes');
53
        $allowed = $ObjectTypes->find('list')
54
            ->where(['parent_id' => $ObjectTypes->get('media')->id])
55
            ->all()
56
            ->toList();
57
        $this->setConfig('allowedAssociations.object', $allowed);
58
59
        parent::initialize();
60
61
        if ($this->request->getParam('action') === 'upload') {
62
            $this->loadComponent('BEdita/API.Upload');
63
        }
64
    }
65
66
    /**
67
     * Allow custom `Accept` header if we are downloading a stream
68
     *
69
     * {@inheritDoc}
70
     */
71
    public function beforeFilter(Event $event)
72
    {
73
        if ($this->request->getParam('action') === 'download') {
74
            return;
75
        }
76
77
        return parent::beforeFilter($event);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::beforeFilter($event) targeting BEdita\API\Controller\Ap...troller::beforeFilter() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
78
    }
79
80
    /**
81
     * Upload a new stream.
82
     *
83
     * @param string $fileName Original file name.
84
     * @return void
85
     */
86
    public function upload($fileName): void
87
    {
88
        $data = $this->Upload->upload($fileName);
89
90
        $this->set(compact('data'));
91
        $this->setSerialize(['data']);
92
93
        $this->response = $this->response
94
            ->withStatus(201)
95
            ->withHeader(
96
                'Location',
97
                Router::url(
98
                    [
99
                        '_name' => 'api:resources:resource',
100
                        'controller' => $this->name,
101
                        'id' => $data->get('uuid'),
102
                    ],
103
                    true
104
                )
105
            );
106
    }
107
108
    /**
109
     * Clone a Stream by its UUID.
110
     *
111
     * @param string $uuid ID of the Stream to clone.
112
     * @return void
113
     */
114
    public function clone(string $uuid): void
115
    {
116
        $data = $this->Table->clone($this->Table->get($uuid));
117
118
        $this->set(compact('data'));
119
        $this->setSerialize(['data']);
120
121
        $this->response = $this->response
122
            ->withStatus(201)
123
            ->withHeader(
124
                'Location',
125
                Router::url(
126
                    [
127
                        '_name' => 'api:resources:resource',
128
                        'controller' => $this->name,
129
                        'id' => $data->get('uuid'),
130
                    ],
131
                    true
132
                )
133
            );
134
    }
135
136
    /**
137
     * Download a stream.
138
     *
139
     * @param string $uuid Stream UUID.
140
     * @return \Cake\Http\Response
141
     * @throws \Cake\Http\Exception\NotFoundException
142
     */
143
    public function download(string $uuid): Response
144
    {
145
        /** @var \BEdita\Core\Model\Entity\Stream $stream */
146
        $stream = $this->Table->get($uuid);
147
        $filename = Hash::get($stream, 'file_name', sprintf('stream-%s', $uuid));
148
149
        $response = $this->response->withType($stream->get('mime_type'));
150
151
        /** @var \Psr\Http\Message\StreamInterface $content */
152
        $content = $stream->get('contents');
153
        if ($content !== null) {
154
            $response = $response->withStringBody($content->getContents());
155
        }
156
157
        return $response->withDownload($filename);
158
    }
159
160
    /**
161
     * {@inheritDoc}
162
     *
163
     * @throws \Cake\Http\Exception\ForbiddenException An exception is thrown on attempts to update existing streams.
164
     */
165
    public function resource($id)
166
    {
167
        if ($this->request->is('patch')) {
168
            throw new ForbiddenException(__d(
169
                'bedita',
170
                'You are not allowed to update existing streams, please delete and re-upload'
171
            ));
172
        }
173
174
        return parent::resource($id);
175
    }
176
}
177