1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* BEdita, API-first content management framework |
6
|
|
|
* Copyright 2021 Atlas Srl, ChannelWeb Srl, Chialab Srl |
7
|
|
|
* |
8
|
|
|
* This file is part of BEdita: you can redistribute it and/or modify |
9
|
|
|
* it under the terms of the GNU Lesser General Public License as published |
10
|
|
|
* by the Free Software Foundation, either version 3 of the License, or |
11
|
|
|
* (at your option) any later version. |
12
|
|
|
* |
13
|
|
|
* See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details. |
14
|
|
|
*/ |
15
|
|
|
namespace BEdita\WebTools\Media; |
16
|
|
|
|
17
|
|
|
use BEdita\WebTools\ApiClientProvider; |
18
|
|
|
use Cake\Http\Exception\BadRequestException; |
19
|
|
|
use Psr\Http\Message\UploadedFileInterface; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Use this trait in a controller or component to upload media files. |
23
|
|
|
* An `UploadedFileInterface` item is required representing a file sent via. |
24
|
|
|
* It is normally found in requesta data where `<input type="file">` is used. |
25
|
|
|
* A media object is then created via API client having the file as internal stream. |
26
|
|
|
*/ |
27
|
|
|
trait UploadTrait |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* Upload a file and create a media object having the file as internal stream. |
31
|
|
|
* |
32
|
|
|
* @param \Psr\Http\Message\UploadedFileInterface $file The array of file data. |
33
|
|
|
* @param string $type The media object type to create. |
34
|
|
|
* @param bool $private Impose a private URL for stream file (default `false`). |
35
|
|
|
* @return array|null |
36
|
|
|
* @throws \Cake\Http\Exception\BadRequestException When missing file or type |
37
|
|
|
*/ |
38
|
|
|
protected function uploadMedia(UploadedFileInterface $file, string $type, bool $private = false): ?array |
39
|
|
|
{ |
40
|
|
|
if (empty($file->getClientFilename()) || empty($type)) { |
41
|
|
|
throw new BadRequestException(__('Missing file to upload or object type.')); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** @var \BEdita\SDK\BEditaClient $apiClient */ |
45
|
|
|
$apiClient = ApiClientProvider::getApiClient(); |
46
|
|
|
|
47
|
|
|
$headers = ['Content-Type' => $file->getClientMediaType()]; |
48
|
|
|
$fileTmp = file_get_contents($file->getStream()->getMetadata('uri')); |
49
|
|
|
$query = $private ? '?private_url=true' : ''; |
50
|
|
|
|
51
|
|
|
return $apiClient->post( |
52
|
|
|
sprintf('/%s/upload/%s%s', $type, $file->getClientFilename(), $query), |
53
|
|
|
$fileTmp, |
54
|
|
|
$headers |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|