webnaplo-gulbaba-api/src/App/Action/Fault/FaultAttachmentAction.php

105 lines
3.1 KiB
PHP
Raw Normal View History

2018-11-11 12:01:18 +01:00
<?php
namespace App\Action\Fault;
use App\Action\AbstractCrudAction;
use App\Response\JsonCorsResponse;
use App\Service\FaultAttachmentService;
use App\Service\FaultManagerService;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UploadedFileInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\EmptyResponse;
use Zend\Diactoros\Stream;
class FaultAttachmentAction extends AbstractCrudAction
{
const CORS_ALLOW_METHODS = [
'GET',
'POST',
];
/**
* @var FaultManagerService
*/
private $faultManagerService;
/**
* @var FaultAttachmentService
*/
private $attachmentService;
public function __construct(
FaultManagerService $faultManagerService,
FaultAttachmentService $attachmentService
) {
$this->faultManagerService = $faultManagerService;
$this->attachmentService = $attachmentService;
}
/**
* Post a new fault report
*
* @param ServerRequestInterface $request
* @param DelegateInterface $delegate
* @return \Zend\Diactoros\Response
*/
public function create(ServerRequestInterface $request, DelegateInterface $delegate): Response
{
$faultId = $request->getAttribute('id');
$type = $request->getAttribute('type', 'file');
$token = $request->getAttribute('token');
try {
/** @var UploadedFileInterface[] $files */
$files = $request->getUploadedFiles()['file'];
return new JsonCorsResponse(
$this->attachmentService->createAttachments($faultId, $files, $token->uid, $type),
201
);
} catch (\Exception $e) {
return new JsonCorsResponse($e->getMessage(), 500);
}
}
/**
* @param ServerRequestInterface $request
* @param DelegateInterface $delegate
* @return Response
*/
public function get(ServerRequestInterface $request, DelegateInterface $delegate): Response
{
$id = $request->getAttribute('id');
$attachment = $this->attachmentService->get($id);
$stream = new Stream($attachment->getIoStream());
switch ($attachment->getType()) {
case 'image':
$contentType = 'image/jpg';
break;
case 'expense':
$contentType = 'application/pdf';
break;
default:
$contentType = 'application/octet-stream';
}
$response = new Response($stream);
return $response->withStatus(200)
->withHeader('Content-type', $contentType)
// ->withHeader('Content-disposition', 'attachment;filename='.$attachment->getFileName())
;
}
/**
* Configure CORS preflight
*
* @param ServerRequestInterface $request
* @param DelegateInterface $delegate
* @return \Zend\Diactoros\Response
*/
public function options(ServerRequestInterface $request, DelegateInterface $delegate): Response
{
return $this->withCorsHeaders(new EmptyResponse(), self::CORS_ALLOW_METHODS);
}
}