1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
<?php
namespace JsonApi\Routes\StockImages;
use JsonApi\Errors\AuthorizationFailedException;
use JsonApi\Errors\BadRequestException;
use JsonApi\Errors\RecordNotFoundException;
use JsonApi\NonJsonApiController;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\UploadedFileInterface;
use Studip\StockImages\Scaler;
use Studip\StockImages\PaletteCreator;
class StockImagesUpload extends NonJsonApiController
{
use UploadHelpers;
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function __invoke(Request $request, Response $response, $args): Response
{
$resource = \StockImage::find($args['id']);
if (!$resource) {
throw new RecordNotFoundException();
}
if (!Authority::canUploadStockImage($this->getUser($request))) {
throw new AuthorizationFailedException();
}
$this->handleUpload($request, $resource);
$this->processStockImage($resource);
return $this->redirectToStockImage($response, $resource);
}
private function handleUpload(Request $request, \StockImage $resource): void
{
$uploadedFile = self::getUploadedFile($request);
if (UPLOAD_ERR_OK !== $uploadedFile->getError()) {
$error = self::getErrorString($uploadedFile->getError());
throw new BadRequestException($error);
}
$error = self::validate($uploadedFile);
if (!empty($error)) {
throw new BadRequestException($error);
}
$resource->mime_type = $uploadedFile->getClientMediaType();
$resource->size = $uploadedFile->getSize();
$uploadedFile->moveTo($resource->getPath());
$imageSize = getimagesize($resource->getPath());
$resource->width = $imageSize[0];
$resource->height = $imageSize[1];
$resource->store();
}
/**
* @return string|null null, if the file is valid, otherwise a string containing the error
*/
private function validate(UploadedFileInterface $file)
{
$mimeType = $file->getClientMediaType();
if (!in_array($mimeType, ['image/gif', 'image/jpeg', 'image/png', 'image/webp'])) {
return 'Unsupported media type.';
}
}
/**
* @SuppressWarnings(PHPMD.Superglobals)
*/
private function redirectToStockImage(Response $response, \StockImage $stockImage): Response
{
$pathinfo = $this->getSchema($stockImage)
->getSelfLink($stockImage)
->getStringRepresentation($this->container->get('json-api-integration-urlPrefix'));
$old = \URLHelper::setBaseURL($GLOBALS['ABSOLUTE_URI_STUDIP']);
$url = \URLHelper::getURL($pathinfo, [], true);
\URLHelper::setBaseURL($old);
return $response->withHeader('Location', $url)->withStatus(201);
}
private function processStockImage(\StockImage $resource): void
{
$scaler = new Scaler();
$scaler($resource);
$paletteCreator = new PaletteCreator();
$paletteCreator($resource);
}
}
|