Commit 88a12d91 authored by Guillaume Perréal's avatar Guillaume Perréal Committed by Guillaume Perréal
Browse files

Correction de défauts de typage, comparaison et CS.

Showing with 87 additions and 43 deletions
+87 -43
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
namespace Irstea\FileUploadBundle\Command; namespace Irstea\FileUploadBundle\Command;
use Doctrine\ORM\EntityManagerInterface;
use Irstea\FileUploadBundle\Model\FileManagerInterface; use Irstea\FileUploadBundle\Model\FileManagerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Helper\ProgressBar;
...@@ -32,9 +33,10 @@ class CheckCommand extends ContainerAwareCommand ...@@ -32,9 +33,10 @@ class CheckCommand extends ContainerAwareCommand
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
/* @var $manager FileManagerInterface */ /** @var FileManagerInterface $manager */
$manager = $this->getContainer()->get('irstea_file_upload.file_manager'); $manager = $this->getContainer()->get('irstea_file_upload.file_manager');
/** @var EntityManagerInterface $em */
$em = $this->getContainer()->get('doctrine.orm.entity_manager'); $em = $this->getContainer()->get('doctrine.orm.entity_manager');
$files = $manager->findFilesToValidate(); $files = $manager->findFilesToValidate();
......
...@@ -34,12 +34,12 @@ class CollectGarbageCommand extends ContainerAwareCommand ...@@ -34,12 +34,12 @@ class CollectGarbageCommand extends ContainerAwareCommand
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
/* @var $manager FileManagerInterface */ /** @var FileManagerInterface $manager */
$manager = $this->getContainer()->get('irstea_file_upload.file_manager'); $manager = $this->getContainer()->get('irstea_file_upload.file_manager');
$files = $manager->findGarbage(); $files = $manager->findGarbage();
if (count($files) == 0) { if (count($files) === 0) {
$output->writeln('Aucun fichier à supprimer.'); $output->writeln('Aucun fichier à supprimer.');
return; return;
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
namespace Irstea\FileUploadBundle\Command; namespace Irstea\FileUploadBundle\Command;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManagerInterface;
use Irstea\FileUploadBundle\Model\FileManagerInterface; use Irstea\FileUploadBundle\Model\FileManagerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
...@@ -38,18 +38,18 @@ class CreateCommand extends ContainerAwareCommand ...@@ -38,18 +38,18 @@ class CreateCommand extends ContainerAwareCommand
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
/* @var $em EntityManager */ /** @var EntityManagerInterface $em */
$em = $this->getContainer()->get('doctrine.orm.entity_manager'); $em = $this->getContainer()->get('doctrine.orm.entity_manager');
$written = null; $written = null;
$em->transactional( $em->transactional(
function () use ($input, $output, $em, &$file, &$written) { function () use ($input, $em, &$file, &$written) {
/* @var $manager FileManagerInterface */ /** @var FileManagerInterface $manager */
$manager = $this->getContainer()->get('irstea_file_upload.file_manager'); $manager = $this->getContainer()->get('irstea_file_upload.file_manager');
$path = $input->getArgument('path'); $path = $input->getArgument('path');
if ('-' === $path) { if ($path === '-') {
$realPath = 'php://stdin'; $realPath = 'php://stdin';
$displayName = 'stdin'; $displayName = 'stdin';
$lastModified = time(); $lastModified = time();
...@@ -62,15 +62,17 @@ class CreateCommand extends ContainerAwareCommand ...@@ -62,15 +62,17 @@ class CreateCommand extends ContainerAwareCommand
} }
$mimeType = $input->getOption('mime-type'); $mimeType = $input->getOption('mime-type');
if (null !== $forcedDisplayName = $input->getOption('display-name')) { $forcedDisplayName = $input->getOption('display-name');
if (null !== $forcedDisplayName) {
$displayName = $forcedDisplayName; $displayName = $forcedDisplayName;
} }
$metadata = null; $metadata = null;
if (null !== $jsonMetadata = $input->getOption('metadata')) { $jsonMetadata = $input->getOption('metadata');
if ($jsonMetadata !== null) {
$metadata = json_decode($jsonMetadata); $metadata = json_decode($jsonMetadata);
} }
$file = $manager->create($displayName, $size, $mimeType ?: 'application/octet-stream', $lastModified, null, 'console'); $file = $manager->create($displayName, $size, $mimeType ?: 'application/octet-stream', $lastModified);
$fh = fopen($realPath, 'rb'); $fh = fopen($realPath, 'rb');
$written = $file->copyFrom($fh); $written = $file->copyFrom($fh);
......
...@@ -37,10 +37,14 @@ class ReadCommand extends ContainerAwareCommand ...@@ -37,10 +37,14 @@ class ReadCommand extends ContainerAwareCommand
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
/* @var $manager FileManagerInterface */ /** @var FileManagerInterface $manager */
$manager = $this->getContainer()->get('irstea_file_upload.file_manager'); $manager = $this->getContainer()->get('irstea_file_upload.file_manager');
$file = $manager->get($input->getArgument('id')); $id = $input->getArgument('id');
$file = $manager->get($id);
if ($file === null) {
throw new \RuntimeException("File not found: $id");
}
$path = $input->getArgument('filepath'); $path = $input->getArgument('filepath');
......
...@@ -6,9 +6,12 @@ ...@@ -6,9 +6,12 @@
namespace Irstea\FileUploadBundle\Controller; namespace Irstea\FileUploadBundle\Controller;
use Doctrine\ORM\EntityRepository;
use Irstea\FileUploadBundle\Entity\UploadedFile; use Irstea\FileUploadBundle\Entity\UploadedFile;
use Pagerfanta\Adapter\DoctrineORMAdapter; use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta; use Pagerfanta\Pagerfanta;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
...@@ -39,7 +42,10 @@ class UploadedFileController extends Controller ...@@ -39,7 +42,10 @@ class UploadedFileController extends Controller
{ {
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
$queryBuilder = $em->getRepository('IrsteaFileUploadBundle:UploadedFile') /** @var EntityRepository $repo */
$repo = $em->getRepository('IrsteaFileUploadBundle:UploadedFile');
$queryBuilder = $repo
->createQueryBuilder('u') ->createQueryBuilder('u')
->orderBy('u.createdAt', 'DESC'); ->orderBy('u.createdAt', 'DESC');
...@@ -78,6 +84,8 @@ class UploadedFileController extends Controller ...@@ -78,6 +84,8 @@ class UploadedFileController extends Controller
*/ */
public function notice($message, array $parameters = []) public function notice($message, array $parameters = [])
{ {
$this->get('monolog.logger.irstea_logger')->notice($message, $parameters); /** @var LoggerInterface $logger */
$logger = $this->get('monolog.logger.irstea_logger') ?? new NullLogger();
$logger->notice($message, $parameters);
} }
} }
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
namespace Irstea\FileUploadBundle\DependencyInjection; namespace Irstea\FileUploadBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\ConfigurationInterface;
...@@ -21,11 +22,14 @@ class Configuration implements ConfigurationInterface ...@@ -21,11 +22,14 @@ class Configuration implements ConfigurationInterface
public function getConfigTreeBuilder() public function getConfigTreeBuilder()
{ {
$treeBuilder = new TreeBuilder(); $treeBuilder = new TreeBuilder();
/** @var ArrayNodeDefinition $rootNode */
$rootNode = $treeBuilder->root('irstea_file_upload'); $rootNode = $treeBuilder->root('irstea_file_upload');
$rootNode $rootNode
->children() ->children()
->integerNode('max_chunk_size') ->integerNode('max_chunk_size')
->min(0)
->beforeNormalization() ->beforeNormalization()
->ifString() ->ifString()
->then( ->then(
...@@ -45,7 +49,6 @@ class Configuration implements ConfigurationInterface ...@@ -45,7 +49,6 @@ class Configuration implements ConfigurationInterface
->defaultValue(0) ->defaultValue(0)
->treatNullLike(0) ->treatNullLike(0)
->treatFalseLike(0) ->treatFalseLike(0)
->min(0)
->end() ->end()
->end(); ->end();
......
...@@ -282,7 +282,7 @@ class UploadedFile implements UploadedFileInterface ...@@ -282,7 +282,7 @@ class UploadedFile implements UploadedFileInterface
], ],
true true
)) { )) {
throw new InvalidArgumentException(sprintf("Etat invalide: '%s'", (string) $etat)); throw new InvalidArgumentException(sprintf("Etat invalide: '%s'", $etat));
} }
// Déplace le fichier hors de l'orphelinat quand on passe d'orphelin à nouveau // Déplace le fichier hors de l'orphelinat quand on passe d'orphelin à nouveau
......
...@@ -27,6 +27,12 @@ class UploadedFileTransformer implements DataTransformerInterface ...@@ -27,6 +27,12 @@ class UploadedFileTransformer implements DataTransformerInterface
*/ */
private $fileManager; private $fileManager;
/**
* UploadedFileTransformer constructor.
*
* @param FileManagerInterface $fileManager
* @param bool $multiple
*/
public function __construct(FileManagerInterface $fileManager, $multiple = false) public function __construct(FileManagerInterface $fileManager, $multiple = false)
{ {
$this->fileManager = $fileManager; $this->fileManager = $fileManager;
...@@ -52,7 +58,8 @@ class UploadedFileTransformer implements DataTransformerInterface ...@@ -52,7 +58,8 @@ class UploadedFileTransformer implements DataTransformerInterface
$result = []; $result = [];
foreach ($value as $identifier) { foreach ($value as $identifier) {
if (null !== $file = $this->reverseTransformFile($identifier)) { $file = $this->reverseTransformFile($identifier);
if ($file !== null) {
$result[] = $file; $result[] = $file;
} }
} }
...@@ -79,7 +86,8 @@ class UploadedFileTransformer implements DataTransformerInterface ...@@ -79,7 +86,8 @@ class UploadedFileTransformer implements DataTransformerInterface
$result = []; $result = [];
foreach ($value as $file) { foreach ($value as $file) {
if (null !== $item = $this->transformFile($file)) { $item = $this->transformFile($file);
if ($item !== null) {
$result[] = $item; $result[] = $item;
} }
} }
...@@ -108,9 +116,9 @@ class UploadedFileTransformer implements DataTransformerInterface ...@@ -108,9 +116,9 @@ class UploadedFileTransformer implements DataTransformerInterface
/** /**
* @param mixed $value * @param mixed $value
* *
* @return UploadedFileInterface * @return UploadedFileInterface|null
*/ */
public function reverseTransformFile($value) public function reverseTransformFile($value): ?UploadedFileInterface
{ {
if (empty($value)) { if (empty($value)) {
return null; return null;
......
...@@ -138,7 +138,7 @@ class UploadedFileResponse extends Response ...@@ -138,7 +138,7 @@ class UploadedFileResponse extends Response
*/ */
public function prepare(Request $request) public function prepare(Request $request)
{ {
$this->headers->set('Content-Length', $this->file->getSize()); $this->headers->set('Content-Length', (string) $this->file->getSize());
if (!$this->headers->has('Accept-Ranges')) { if (!$this->headers->has('Accept-Ranges')) {
// Only accept ranges on safe HTTP methods // Only accept ranges on safe HTTP methods
...@@ -149,7 +149,7 @@ class UploadedFileResponse extends Response ...@@ -149,7 +149,7 @@ class UploadedFileResponse extends Response
$this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream'); $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
} }
if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) { if ($request->server->get('SERVER_PROTOCOL') !== 'HTTP/1.0') {
$this->setProtocolVersion('1.1'); $this->setProtocolVersion('1.1');
} }
...@@ -160,15 +160,15 @@ class UploadedFileResponse extends Response ...@@ -160,15 +160,15 @@ class UploadedFileResponse extends Response
if ($request->headers->has('Range')) { if ($request->headers->has('Range')) {
// Process the range headers. // Process the range headers.
if (!$request->headers->has('If-Range') || $this->getEtag() == $request->headers->get('If-Range')) { if (!$request->headers->has('If-Range') || $this->getEtag() === $request->headers->get('If-Range')) {
$range = $request->headers->get('Range'); $range = $request->headers->get('Range');
$fileSize = $this->file->getSize(); $fileSize = $this->file->getSize();
[$start, $end] = explode('-', substr($range, 6), 2) + [0]; [$start, $end] = explode('-', substr($range, 6), 2) + [0];
$end = ('' === $end) ? $fileSize - 1 : (int) $end; $end = ($end === '') ? $fileSize - 1 : (int) $end;
if ('' === $start) { if ($start === '') {
$start = $fileSize - $end; $start = $fileSize - $end;
$end = $fileSize - 1; $end = $fileSize - 1;
} else { } else {
...@@ -184,7 +184,7 @@ class UploadedFileResponse extends Response ...@@ -184,7 +184,7 @@ class UploadedFileResponse extends Response
$this->setStatusCode(206); $this->setStatusCode(206);
$this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize)); $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
$this->headers->set('Content-Length', $end - $start + 1); $this->headers->set('Content-Length', (string) ($end - $start + 1));
} }
} }
} }
...@@ -232,6 +232,6 @@ class UploadedFileResponse extends Response ...@@ -232,6 +232,6 @@ class UploadedFileResponse extends Response
*/ */
public function getContent() public function getContent()
{ {
return false; return '';
} }
} }
...@@ -41,15 +41,20 @@ class VirusScannerListener ...@@ -41,15 +41,20 @@ class VirusScannerListener
$file = $event->getUploadedFile(); $file = $event->getUploadedFile();
$path = $file->getLocalPath(); $path = $file->getLocalPath();
/** @var array $result */
$result = $client->scanFile($path); $result = $client->scanFile($path);
$hasVirus = $result['status'] === Client::RESULT_FOUND;
$status = $result['status'] ?? Client::RESULT_ERROR;
$hasVirus = $status === Client::RESULT_FOUND;
$meta = $file->getMetadata(); $meta = $file->getMetadata();
$meta['virus_scanner'] = ['has_virus' => $hasVirus]; $meta['virus_scanner'] = ['has_virus' => $hasVirus];
if ($hasVirus) { if ($hasVirus) {
$desc = $result['reason']; $desc = $result['reason'] ?? '???';
$meta['virus_scanner']['detected'] = $result['reason']; $meta['virus_scanner']['detected'] = $result['reason'];
} else {
$desc = false;
} }
$file->setMetadata($meta); $file->setMetadata($meta);
......
...@@ -289,7 +289,7 @@ interface UploadedFileInterface ...@@ -289,7 +289,7 @@ interface UploadedFileInterface
public function isOrphelin(); public function isOrphelin();
/** Retourne la date de dernière modification dans le filesystem. /** Retourne la date de dernière modification dans le filesystem.
* @return DateTime * @return DateTime|null
* *
* @api * @api
*/ */
......
...@@ -74,8 +74,16 @@ final class FileManager implements FileManagerInterface ...@@ -74,8 +74,16 @@ final class FileManager implements FileManagerInterface
$this->filesystem = $filesystem; $this->filesystem = $filesystem;
$this->eventDispatcher = $eventDispatcher; $this->eventDispatcher = $eventDispatcher;
$this->logger = $logger ?: new NullLogger(); $this->logger = $logger ?: new NullLogger();
$this->entityManager = $doctrine->getEntityManagerForClass($entityClass);
$this->repository = $this->entityManager->getRepository($entityClass); $em = $doctrine->getEntityManagerForClass($entityClass);
if ($em === null) {
throw new InvalidArgumentException("Cannot find entity manager of $entityClass");
}
$this->entityManager = $em;
/** @var EntityRepository $repo */
$repo = $this->entityManager->getRepository($entityClass);
$this->repository = $repo;
} }
/** /**
......
...@@ -38,7 +38,7 @@ class FileUrlGenerator implements FileUrlGeneratorInterface ...@@ -38,7 +38,7 @@ class FileUrlGenerator implements FileUrlGeneratorInterface
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function generate($idFile, $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH) public function generate(string $idFile, $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{ {
$token = $this->tokenManager->getToken(UploadController::CSRF_INTENTION); $token = $this->tokenManager->getToken(UploadController::CSRF_INTENTION);
......
...@@ -16,10 +16,10 @@ interface FileUrlGeneratorInterface ...@@ -16,10 +16,10 @@ interface FileUrlGeneratorInterface
/** /**
* Génère une URL sécurisée pour un fichier. * Génère une URL sécurisée pour un fichier.
* *
* @param string $idFile identifiant du fichier pour lequel générer l'URL * @param string $idFile identifiant du fichier pour lequel générer l'URL
* @param bool|int|string $referenceType type d'URL à générer * @param int $referenceType type d'URL à générer
* *
* @return string L'url générée * @return string L'url générée
*/ */
public function generate($idFile, $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH); public function generate(string $idFile, $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH);
} }
...@@ -11,6 +11,9 @@ namespace Irstea\FileUploadBundle\Utils; ...@@ -11,6 +11,9 @@ namespace Irstea\FileUploadBundle\Utils;
*/ */
final class MimeTypeIcon final class MimeTypeIcon
{ {
/**
* @var array
*/
private static $icons = [ private static $icons = [
'application/vnd.oasis.opendocument.text' => 'word', 'application/vnd.oasis.opendocument.text' => 'word',
'application/vnd.oasis.opendocument.spreadsheet' => 'excel', 'application/vnd.oasis.opendocument.spreadsheet' => 'excel',
...@@ -35,13 +38,14 @@ final class MimeTypeIcon ...@@ -35,13 +38,14 @@ final class MimeTypeIcon
* *
* @return string|null * @return string|null
*/ */
public static function getMimeTypeIcon($mimeType) public static function getMimeTypeIcon($mimeType): ?string
{ {
if (!is_string($mimeType)) { if (!is_string($mimeType)) {
return null; return null;
} }
if (false !== $sep = strpos($mimeType, ';')) { $sep = strpos($mimeType, ';');
if ($sep !== false) {
$mimeType = trim(substr($mimeType, 0, $sep)); $mimeType = trim(substr($mimeType, 0, $sep));
} }
......
...@@ -20,7 +20,7 @@ class FileMimeTypeValidator extends ConstraintValidator ...@@ -20,7 +20,7 @@ class FileMimeTypeValidator extends ConstraintValidator
*/ */
public function validate($value, Constraint $constraint) public function validate($value, Constraint $constraint)
{ {
if (!$value instanceof UploadedFileInterface) { if (!($value instanceof UploadedFileInterface) || !($constraint instanceof FileMimeType)) {
return; return;
} }
if (preg_match('@^' . $constraint->acceptedMimeTypes . '$@i', $value->getMimeType())) { if (preg_match('@^' . $constraint->acceptedMimeTypes . '$@i', $value->getMimeType())) {
......
...@@ -20,19 +20,19 @@ class FileSizeValidator extends ConstraintValidator ...@@ -20,19 +20,19 @@ class FileSizeValidator extends ConstraintValidator
*/ */
public function validate($value, Constraint $constraint) public function validate($value, Constraint $constraint)
{ {
if (!$value instanceof UploadedFileInterface) { if (!($value instanceof UploadedFileInterface) || !($constraint instanceof FileSize)) {
return; return;
} }
if ($constraint->min && $value->getSize() < $constraint->min) { if ($constraint->min && $value->getSize() < $constraint->min) {
$this->context->buildViolation($constraint->minMessage) $this->context->buildViolation($constraint->minMessage)
->setParameter('%displayName%', $value->getDisplayName()) ->setParameter('%displayName%', $value->getDisplayName())
->setParameter('%min%', $constraint->min) ->setParameter('%min%', (string) $constraint->min)
->addViolation(); ->addViolation();
} }
if ($constraint->max && $value->getSize() > $constraint->max) { if ($constraint->max && $value->getSize() > $constraint->max) {
$this->context->buildViolation($constraint->maxMessage) $this->context->buildViolation($constraint->maxMessage)
->setParameter('%displayName%', $value->getDisplayName()) ->setParameter('%displayName%', $value->getDisplayName())
->setParameter('%max%', $constraint->max) ->setParameter('%max%', (string) $constraint->max)
->addViolation(); ->addViolation();
} }
} }
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment