Files
emails/api/common/Controller/Attachments.php

59 lines
2.3 KiB
PHP
Raw Normal View History

2022-11-25 20:52:52 -03:00
<?php
namespace ProVM\Common\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
2023-06-12 21:14:07 -04:00
use Psr\Log\LoggerInterface;
2022-11-25 20:52:52 -03:00
use ProVM\Common\Implement\Controller\Json;
2023-06-12 21:14:07 -04:00
use ProVM\Common\Service;
2022-11-28 22:56:21 -03:00
use ProVM\Emails\Model\Attachment;
2023-06-12 21:14:07 -04:00
use ProVM\Common\Exception\Request\MissingArgument;
use function Safe\json_decode;
2022-11-25 20:52:52 -03:00
class Attachments
{
use Json;
2023-06-12 21:14:07 -04:00
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service\Attachments $service): ResponseInterface
2022-11-25 20:52:52 -03:00
{
2022-11-28 22:56:21 -03:00
$attachments = array_map(function(Attachment $attachment) {
return $attachment->toArray();
},$service->getAll());
$output = [
'total' => count($attachments),
'attachments' => $attachments
2022-11-25 20:52:52 -03:00
];
return $this->withJson($response, $output);
}
2023-06-12 21:14:07 -04:00
public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Attachments $service, LoggerInterface $logger, int $attachment_id): ResponseInterface
{
$attachment = $service->getRepository()->fetchById($attachment_id);
$response->withHeader('Content-Type', 'application/pdf');
$response->withHeader('Content-Disposition', "'attachment;filename='{$attachment->getFullFilename()}'");
$response->getBody()->write($service->getFile($attachment_id));
return $response;
}
public function grab(ServerRequestInterface $request, ResponseInterface $response, Service\Attachments $service, Service\Messages $messagesService): ResponseInterface
2022-11-25 20:52:52 -03:00
{
2022-11-28 22:56:21 -03:00
$body = $request->getBody();
2023-06-12 21:14:07 -04:00
$json = json_decode($body->getContents());
2022-11-28 22:56:21 -03:00
if (!isset($json->messages)) {
2023-06-12 21:14:07 -04:00
throw new MissingArgument('messages', 'array', 'Messages UIDs');
2022-11-25 20:52:52 -03:00
}
2022-11-28 22:56:21 -03:00
$output = [
'messages' => $json->messages,
2023-06-12 21:14:07 -04:00
'attachments' => [],
'total' => 0
2022-11-28 22:56:21 -03:00
];
2023-06-12 21:14:07 -04:00
foreach ($json->messages as $message_uid) {
$message = $messagesService->getLocalMessage($message_uid);
$attachments = $service->grab($message->getId());
$output['attachments'] = array_merge($output['attachments'], $attachments);
$output['total'] += count($attachments);
2022-11-25 20:52:52 -03:00
}
2022-11-29 11:12:06 -03:00
2023-06-12 21:14:07 -04:00
return $this->withJson($response, $output);
2022-11-29 11:12:06 -03:00
}
2023-06-12 21:14:07 -04:00
}