<?php
namespace App\EventSubscriber;
use App\Annotation\PartialUpload;
use App\Model\Upload;
use App\Traits\Autowired\Manager\UploadManagerTrait;
use App\Traits\Autowired\Vendor\RequestStackTrait;
use App\Traits\Autowired\Vendor\SerializerSubscriberTrait;
use GollumSF\RestBundle\Annotation\Serialize;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class PartialUploadSubscriber implements EventSubscriberInterface
{
use UploadManagerTrait;
use SerializerSubscriberTrait;
use RequestStackTrait;
public static function getSubscribedEvents() {
return [
KernelEvents::CONTROLLER_ARGUMENTS => [
['onKernelControllerArguments', -20],
]
];
}
public function onKernelControllerArguments(ControllerArgumentsEvent $event)
{
$request = $event->getRequest();
/** @var PartialUpload $annotation */
$annotation = $request->attributes->get('_' . PartialUpload::ALIAS_NAME);
if ($annotation) {
/** @var Upload $upload */
$upload = $request->attributes->get($annotation->getName());
if (!$upload) {
throw new BadRequestHttpException(sprintf('%s parameter not found', $annotation->getName()));
}
$maxSize = null;
if ($annotation->getMaxSize()) {
$maxSize = is_string($annotation->getMaxSize()) ? $this->human2byte($annotation->getMaxSize()) : $annotation->getMaxSize();
}
if (!$upload->isEndOfFile()) {
$upload = $this->uploadManager->partialUpload($upload, $maxSize);
$request->attributes->set($annotation->getName(), $upload);
$event->setController([ $this, 'partialControllerAction' ]);
} else {
$upload = $this->uploadManager->finalUpload($upload, $maxSize, $annotation->getMimeTypes());
$request->attributes->set($annotation->getName(), $upload);
}
}
}
public function partialControllerAction(): Upload {
$request = $this->requestStack->getCurrentRequest();
/** @var PartialUpload $annotation */
/** @var Serialize $serialize */
$annotation = $request->attributes->get('_' . PartialUpload::ALIAS_NAME);
$serialize = $request->attributes->get('_' . Serialize::ALIAS_NAME);
$serialize->setCode(Response::HTTP_OK);
return $request->attributes->get($annotation->getName());
}
protected function human2byte($value) {
return preg_replace_callback('/^\s*(\d+)\s*(?:([kmgt]?)b?)?\s*$/i', function ($m) {
switch (strtolower($m[2])) {
case 't': $m[1] *= 1024;
case 'g': $m[1] *= 1024;
case 'm': $m[1] *= 1024;
case 'k': $m[1] *= 1024;
}
return $m[1];
}, $value);
}
}