diff --git a/Command/CheckCommand.php b/Command/CheckCommand.php index a883bd6b0270c380738992b4976db28496f15e8a..46a0a2b94994333a456575e261ae3c9abf526a47 100644 --- a/Command/CheckCommand.php +++ b/Command/CheckCommand.php @@ -25,8 +25,7 @@ class CheckCommand extends ContainerAwareCommand { $this ->setName('irstea:file-upload:check') - ->setDescription("Vérifie l'intégrité des fichiers.") - ; + ->setDescription("Vérifie l'intégrité des fichiers."); } protected function execute(InputInterface $input, OutputInterface $output) @@ -38,7 +37,7 @@ class CheckCommand extends ContainerAwareCommand $files = $manager->findFilesToValidate(); - if(count($files) == 0) { + if (count($files) == 0) { $output->writeln('Aucun fichier à vérifier.'); return; } @@ -48,9 +47,9 @@ class CheckCommand extends ContainerAwareCommand $progress = new ProgressBar($output, count($files)); $progress->start(); - foreach($files as $file){ + foreach ($files as $file) { $file->validate(); - if(!$file->isValid()) { + if (!$file->isValid()) { $output->writeln(sprintf("\nFichier %s: %s", $file->getEtat(), $file->getPath())); $em->persist($file); } diff --git a/Command/CollectGarbageCommand.php b/Command/CollectGarbageCommand.php index dcab1c3a90d48194434f7d509cf7130f23bb1f89..976d9981a2137b5add8361776e1025cf685ed024 100644 --- a/Command/CollectGarbageCommand.php +++ b/Command/CollectGarbageCommand.php @@ -26,8 +26,7 @@ class CollectGarbageCommand extends ContainerAwareCommand $this ->setName('irstea:file-upload:collect-garbage') ->setDescription("Nettoie les fichiers orphelins et partiels.") - ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Affiche ce qui devrait être fait, sans le faire') - ; + ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Affiche ce qui devrait être fait, sans le faire'); } protected function execute(InputInterface $input, OutputInterface $output) @@ -37,12 +36,12 @@ class CollectGarbageCommand extends ContainerAwareCommand $files = $manager->findGarbage(); - if(count($files) == 0) { + if (count($files) == 0) { $output->writeln('Aucun fichier à supprimer.'); return; } - if($input->getOption('dry-run')) { + if ($input->getOption('dry-run')) { $output->writeln(sprintf('%d fichier(s) à supprimer.', count($files))); return; } @@ -52,7 +51,7 @@ class CollectGarbageCommand extends ContainerAwareCommand $progress = new ProgressBar($output, count($files)); $progress->start(); - foreach($files as $file){ + foreach ($files as $file) { $manager->delete($file); $progress->advance(); } diff --git a/Command/CreateCommand.php b/Command/CreateCommand.php index b4c250c5266296b15d9ac10f0f417f3ece7ecbc4..b5dfbb14487df584b89c5e0077170f5ea1a6857a 100644 --- a/Command/CreateCommand.php +++ b/Command/CreateCommand.php @@ -30,8 +30,7 @@ class CreateCommand extends ContainerAwareCommand ->addOption('mime-type', 't', InputOption::VALUE_REQUIRED, "Force le type MIME.") ->addOption('display-name', 'd', InputOption::VALUE_REQUIRED, "Indique un nom de fichier.") ->addOption('metadata', 'm', InputOption::VALUE_REQUIRED, "Ajoute des métadata (format JSON).") - ->addArgument('path', InputArgument::REQUIRED, "Nom du fichier à ajouter, - pour lire l'entrée standard") - ; + ->addArgument('path', InputArgument::REQUIRED, "Nom du fichier à ajouter, - pour lire l'entrée standard"); } protected function execute(InputInterface $input, OutputInterface $output) @@ -41,52 +40,54 @@ class CreateCommand extends ContainerAwareCommand $id = $written = null; - $em->transactional(function() use($input, $output, $em, &$file, &$written) { - - /* @var $manager FileManagerInterface */ - $manager = $this->getContainer()->get('irstea_file_upload.file_manager'); - - $path = $input->getArgument("path"); - if("-" === $path) { - $realPath = 'php://stdin'; - $displayName = "stdin"; - $lastModified = time(); - $size = 0; - } else { - $realPath = $path; - $displayName = pathinfo($path, PATHINFO_FILENAME); - $size = filesize($path); - $lastModified = filemtime($path); + $em->transactional( + function () use ($input, $output, $em, &$file, &$written) { + + /* @var $manager FileManagerInterface */ + $manager = $this->getContainer()->get('irstea_file_upload.file_manager'); + + $path = $input->getArgument("path"); + if ("-" === $path) { + $realPath = 'php://stdin'; + $displayName = "stdin"; + $lastModified = time(); + $size = 0; + } else { + $realPath = $path; + $displayName = pathinfo($path, PATHINFO_FILENAME); + $size = filesize($path); + $lastModified = filemtime($path); + } + + $mimeType = $input->getOption('mime-type'); + if (null !== $forcedDisplayName = $input->getOption('display-name')) { + $displayName = $forcedDisplayName; + } + $metadata = null; + if (null !== $jsonMetadata = $input->getOption('metadata')) { + $metadata = json_decode($jsonMetadata); + } + + $file = $manager->create($displayName, $size, $mimeType ?: 'application/octet-stream', $lastModified, null, 'console'); + + $fh = fopen($realPath, 'rb'); + $written = $file->copyFrom($fh); + fclose($fh); + + $manager->completed($file); + + if ($mimeType) { + $file->setMimeType($mimetype); + } + if ($metadata) { + $file->setMetadata(array_merge($file->getMetadata(), $metadata)); + } + + $em->flush(); } + ); - $mimeType = $input->getOption('mime-type'); - if(null !== $forcedDisplayName = $input->getOption('display-name')) { - $displayName = $forcedDisplayName; - } - $metadata = null; - if(null !== $jsonMetadata = $input->getOption('metadata')) { - $metadata = json_decode($jsonMetadata); - } - - $file = $manager->create($displayName, $size, $mimeType ?: 'application/octet-stream', $lastModified, null, 'console'); - - $fh = fopen($realPath, 'rb'); - $written = $file->copyFrom($fh); - fclose($fh); - - $manager->completed($file); - - if($mimeType) { - $file->setMimeType($mimetype); - } - if($metadata) { - $file->setMetadata(array_merge($file->getMetadata(), $metadata)); - } - - $em->flush(); - }); - - if($output->isVerbose()) { + if ($output->isVerbose()) { $output->writeln(sprintf("%s crée, %d octets lus.", $file->getId(), $written)); } else { $output->writeln($file->getId()); diff --git a/Command/ReadCommand.php b/Command/ReadCommand.php index ce7bec97cc86afd7a54cd22176a896b3abc781d1..312728b6c412ee11173f3750c76a6948521fc9c5 100644 --- a/Command/ReadCommand.php +++ b/Command/ReadCommand.php @@ -30,8 +30,7 @@ class ReadCommand extends ContainerAwareCommand ->addOption('append', 'a', InputOption::VALUE_NONE, "Ajoute au fichier de destination au lieu de l'écraser.") ->addOption('overwrite', 'y', InputOption::VALUE_NONE, "Ecrase le fichier de destination s'il existe.") ->addArgument('id', InputArgument::REQUIRED, "Identifiant du fichier à récupérer.") - ->addArgument('filepath', InputArgument::OPTIONAL, "Chemin du fichier dans lequel écrire.") - ; + ->addArgument('filepath', InputArgument::OPTIONAL, "Chemin du fichier dans lequel écrire."); } protected function execute(InputInterface $input, OutputInterface $output) @@ -43,12 +42,12 @@ class ReadCommand extends ContainerAwareCommand $path = $input->getArgument('filepath'); - if(null == $path) { + if (null == $path) { $fh = fopen('php://stdout', 'wb'); } else { - if($input->getOption('append')) { + if ($input->getOption('append')) { $fh = fopen($path, 'ab'); - } elseif($input->getOption('overwrite')) { + } elseif ($input->getOption('overwrite')) { $fh = fopen($path, 'wb'); } else { $fh = fopen($path, 'xb'); @@ -58,7 +57,7 @@ class ReadCommand extends ContainerAwareCommand $written = $file->copyTo($fh); fclose($fh); - if($output->isVerbose() && null !== $path) { + if ($output->isVerbose() && null !== $path) { $output->writeln(sprintf("%d octets écrits.", $written)); } } diff --git a/Controller/UploadController.php b/Controller/UploadController.php index f7ace7187b946a81b913853376555008515fa7ce..1f0f34cb59d3c55ea5d40c81153689449074a5d8 100644 --- a/Controller/UploadController.php +++ b/Controller/UploadController.php @@ -111,13 +111,13 @@ class UploadController extends Controller [ 'put_url' => $this->urlGenerator->generate('file_upload_put_content', $parameters), 'delete_type' => 'DELETE', - 'delete_url' => $deleteUrl + 'delete_url' => $deleteUrl, ] ), // On a pas de get pour l'instant, le DELETE et ce qui y ressemble le plus - [ 'Location' => $deleteUrl ] + ['Location' => $deleteUrl] ); - } catch(\Exception $ex) { + } catch (\Exception $ex) { return $this->createExceptionResponse($ex); } } @@ -140,13 +140,12 @@ class UploadController extends Controller $file->copyFrom($input, $maxlen, $offset); fclose($input); - if($complete) { + if ($complete) { return $this->completeUpload($file); } return $this->createResponse(Response::HTTP_OK, 'Chunk received'); - - } catch(\Exception $ex) { + } catch (\Exception $ex) { return $this->createExceptionResponse($ex); } } @@ -154,42 +153,44 @@ class UploadController extends Controller /** * * @param Request $request + * * @return array */ protected function handleRangeHeader(Request $request) { - if(null === $range = $request->headers->get('Content-Range', null)) { + if (null === $range = $request->headers->get('Content-Range', null)) { return [0, PHP_INT_MAX, true]; } $matches = []; - if(!preg_match('@^bytes (\d+)-(\d+)/(\d+)$@', $range, $matches)) { + if (!preg_match('@^bytes (\d+)-(\d+)/(\d+)$@', $range, $matches)) { throw new BadRequestHttpException("Invalid Content-Range"); } $start = intval($matches[1]); - $end = intval($matches[2]); + $end = intval($matches[2]); $total = intval($matches[3]); - if($start < 0 || $start >= $end || $end >= $total) { + if ($start < 0 || $start >= $end || $end >= $total) { throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE); } - return [$start, 1 + ($end - $start), $end === ($total-1)]; + return [$start, 1 + ($end - $start), $end === ($total - 1)]; } /** * * @param UploadedFileInterface $file + * * @return Response */ protected function completeUpload(UploadedFileInterface $file) { try { $this->fileManager->completed($file); - } catch(RejectedFileException $ex) { - return $this->createResponse(Response::HTTP_FORBIDDEN, 'File rejected: '.$ex->getMessage()); + } catch (RejectedFileException $ex) { + return $this->createResponse(Response::HTTP_FORBIDDEN, 'File rejected: ' . $ex->getMessage()); } $parameters = ['id' => $file->getId()]; @@ -202,7 +203,7 @@ class UploadController extends Controller 'repr' => $this->templating->render( 'IrsteaFileUploadBundle:Extension:uploaded_file.html.twig', ['file' => $file->toArray()] - ) + ), ] ); @@ -219,7 +220,7 @@ class UploadController extends Controller { $this->validateCsrfToken($request); - if(!$file->isValid()) { + if (!$file->isValid()) { throw new NotFoundHttpException(); } @@ -242,7 +243,7 @@ class UploadController extends Controller $this->fileManager->delete($file); return $this->createResponse(); - } catch(\Exception $ex) { + } catch (\Exception $ex) { return $this->createExceptionResponse($ex); } } @@ -250,11 +251,12 @@ class UploadController extends Controller /** * * @param Request $request + * * @throws HttpException */ protected function validateCsrfToken(Request $request) { - if(!$this->csrfProvider->isCsrfTokenValid(self::CSRF_INTENTION, $request->query->get('token', null))) { + if (!$this->csrfProvider->isCsrfTokenValid(self::CSRF_INTENTION, $request->query->get('token', null))) { throw new HttpException(Response::HTTP_FORBIDDEN, 'Invalid CSRF token'); } } @@ -265,6 +267,7 @@ class UploadController extends Controller * @param string $message * @param array $data * @param array $headers + * * @return JsonResponse */ protected function createResponse($status = Response::HTTP_OK, $message = 'OK', array $data = [], array $headers = []) @@ -279,6 +282,7 @@ class UploadController extends Controller /** * * @param \Exception $ex + * * @return JsonResponse */ protected function createExceptionResponse(\Exception $ex) @@ -289,11 +293,11 @@ class UploadController extends Controller [ 'exception' => [ 'class' => get_class($ex), - 'file' => $ex->getFile(), - 'line' => $ex->getLine(), - 'code' => $ex->getCode(), + 'file' => $ex->getFile(), + 'line' => $ex->getLine(), + 'code' => $ex->getCode(), 'trace' => $ex->getTrace(), - ] + ], ] ); } diff --git a/Controller/UploadedFileController.php b/Controller/UploadedFileController.php index c2f74a3106fb3ab66461a491728b8d5c449c3dba..6f3a71fee958eb286bdb056fd730c70ccc9df6d0 100644 --- a/Controller/UploadedFileController.php +++ b/Controller/UploadedFileController.php @@ -43,7 +43,7 @@ class UploadedFileController extends Controller return [ 'uploadedFiles' => $uploadedFiles, - 'pager' => $pager, + 'pager' => $pager, ]; } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 8f487b357465c01614287a9aca0cfb9c1e83935c..92e0acd7c5f289d58871e0a1b2ac108c981e00a5 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -20,27 +20,29 @@ class Configuration implements ConfigurationInterface $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('irstea_file_upload'); - $rootNode + $rootNode ->children() - ->integerNode('max_chunk_size') - ->beforeNormalization() - ->ifString() - ->then(function($v) { - $int = intval($v); - if(strpos($v, "K")) { - return 1000*$int; - } - if(strpos($v, "M")) { - return 1000000*$int; - } - return $int; - }) - ->end() - ->defaultValue(0) - ->treatNullLike(0) - ->treatFalseLike(0) - ->min(0) - ->end() + ->integerNode('max_chunk_size') + ->beforeNormalization() + ->ifString() + ->then( + function ($v) { + $int = intval($v); + if (strpos($v, "K")) { + return 1000 * $int; + } + if (strpos($v, "M")) { + return 1000000 * $int; + } + return $int; + } + ) + ->end() + ->defaultValue(0) + ->treatNullLike(0) + ->treatFalseLike(0) + ->min(0) + ->end() ->end(); return $treeBuilder; diff --git a/DependencyInjection/IrsteaFileUploadExtension.php b/DependencyInjection/IrsteaFileUploadExtension.php index 4b02ee2447f54c499c0a6209b211123f963cd3d3..48544d6371a176ddd62ae181fb6c3e460f6fd008 100644 --- a/DependencyInjection/IrsteaFileUploadExtension.php +++ b/DependencyInjection/IrsteaFileUploadExtension.php @@ -18,13 +18,13 @@ class IrsteaFileUploadExtension extends Extension implements PrependExtensionInt $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); - $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); $container->setParameter('irstea_file_upload.max_chunk_size', $config['max_chunk_size']); $bundles = $container->getParameter('kernel.bundles'); - if(!isset($bundles['CLTissueBundle'])) { + if (!isset($bundles['CLTissueBundle'])) { // On a pas le CLTissueBundle => pas d'antivirus $container->removeDefinition('irstea_file_upload.virus_scanner'); } @@ -41,8 +41,8 @@ class IrsteaFileUploadExtension extends Extension implements PrependExtensionInt 'assetic', [ 'assets' => [ - 'form_js' => [ - 'inputs' => [ + 'form_js' => [ + 'inputs' => [ "$pluginDir/js/jquery.fileupload.js", "$pluginDir/js/jquery.fileupload-process.js", "$pluginDir/js/jquery.fileupload-validate.js", @@ -50,14 +50,14 @@ class IrsteaFileUploadExtension extends Extension implements PrependExtensionInt "@BazingaJsTranslationBundle/Resources/js/translator.js", 'js/translations/file_upload/*.js', 'js/translations/validators/*.js', - '@IrsteaFileUploadBundle/Resources/js/widget/file_upload.js' + '@IrsteaFileUploadBundle/Resources/js/widget/file_upload.js', ], ], 'form_css' => [ - 'inputs' => [ + 'inputs' => [ "$pluginDir/css/jquery.fileupload.css", "$pluginDir/css/jquery.fileupload-ui.css", - '@IrsteaFileUploadBundle/Resources/less/file_upload.less' + '@IrsteaFileUploadBundle/Resources/less/file_upload.less', ], ], ], diff --git a/Entity/Repository/UploadedFileRepository.php b/Entity/Repository/UploadedFileRepository.php index b2c1888dfc30776e0cc6937ba0e77708467d963e..47f2fb975153cf937a9eccdcaa01e29ef27f55ae 100644 --- a/Entity/Repository/UploadedFileRepository.php +++ b/Entity/Repository/UploadedFileRepository.php @@ -73,8 +73,8 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte 'filename' => $filename, 'size' => $size, 'mimeType' => $mimeType, - 'lastModified' => $lastModified - ] + 'lastModified' => $lastModified, + ], ] ); @@ -89,7 +89,7 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte public function duplicate(UploadedFileInterface $original) { if (!$original->isValid()) { - throw new InvalidArgumentException("Impossible de dupliquer le fichier ".$original->getId()." car il est invalide !"); + throw new InvalidArgumentException("Impossible de dupliquer le fichier " . $original->getId() . " car il est invalide !"); } $new = new UploadedFile(); @@ -157,7 +157,6 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte $this->_em->flush(); $this->log(LogLevel::INFO, 'File completed', ['file' => $file]); - } catch (RejectedFileException $ex) { $file->setEtat(UploadedFileInterface::ETAT_REJETE); diff --git a/Entity/UploadedFile.php b/Entity/UploadedFile.php index 1a8c0ee924a951692c00ee87c53e5b58231dae57..ddbf453e8d788d215a8f970f1a9540ab1b130da0 100644 --- a/Entity/UploadedFile.php +++ b/Entity/UploadedFile.php @@ -129,7 +129,7 @@ class UploadedFile implements UploadedFileInterface public function __construct() { $this->id = Uuid::uuid4()->toString(); - $this->actualPath = $this->path = self::ORPHAN_PREFIX.$this->id; + $this->actualPath = $this->path = self::ORPHAN_PREFIX . $this->id; } /** @@ -182,7 +182,7 @@ class UploadedFile implements UploadedFileInterface */ public function setPath($path) { - if(!static::isSafePath($path)) { + if (!static::isSafePath($path)) { throw new InvalidArgumentException("Unsafe path: $path"); } $this->path = trim($path, '/'); @@ -257,7 +257,7 @@ class UploadedFile implements UploadedFileInterface */ public function setEtat($etat) { - if(!in_array( + if (!in_array( $etat, [ self::ETAT_CORROMPU, @@ -265,14 +265,14 @@ class UploadedFile implements UploadedFileInterface self::ETAT_MANQUANT, self::ETAT_NORMAL, self::ETAT_ORPHELIN, - self::ETAT_REJETE + self::ETAT_REJETE, ] )) { throw new InvalidArgumentException(sprintf("Etat invalide: '%s'", (string)$etat)); } // Déplace le fichier hors de l'orphelinat quand on passe d'orphelin à nouveau - if($this->etat === self::ETAT_ORPHELIN && $etat === self::ETAT_NORMAL && 0 === strpos($this->path, self::ORPHAN_PREFIX)) { + if ($this->etat === self::ETAT_ORPHELIN && $etat === self::ETAT_NORMAL && 0 === strpos($this->path, self::ORPHAN_PREFIX)) { $this->path = substr($this->path, strlen(self::ORPHAN_PREFIX)); } @@ -322,10 +322,10 @@ class UploadedFile implements UploadedFileInterface { $unit = ""; $size = $this->size ?: 0; - if($size >= 10240) { + if ($size >= 10240) { $size /= 1024; $unit = "k"; - if($size >= 10240) { + if ($size >= 10240) { $size /= 1024; $unit = "m"; } @@ -335,6 +335,7 @@ class UploadedFile implements UploadedFileInterface /** * @param Filesystem $filesystem + * * @return self * * @internal @@ -391,7 +392,7 @@ class UploadedFile implements UploadedFileInterface { try { return new \DateTime(sprintf('@%d', $this->filesystem->mtime($this->getActualPath()))); - } catch(FileNotFound $ex) { + } catch (FileNotFound $ex) { return null; } } @@ -417,7 +418,7 @@ class UploadedFile implements UploadedFileInterface */ public function copyFrom($source, $maxlen = -1, $writeOffset = 0) { - if($maxlen === 0) { + if ($maxlen === 0) { return 0; } @@ -425,16 +426,16 @@ class UploadedFile implements UploadedFileInterface $stream->open(new StreamMode('cb')); $stream->seek($writeOffset); - if(false !== $fileHandle = $stream->cast(STREAM_CAST_AS_STREAM)) { + if (false !== $fileHandle = $stream->cast(STREAM_CAST_AS_STREAM)) { // Utilise stream_copy_to_stream si le Gaufrette\Stream peut nous retourner un filehandle $copied = $this->stream_copy_to_stream($source, $fileHandle, $maxlen); } else { // Sinon fait une copie par blocs (moins performant) - if($maxlen === -1) { + if ($maxlen === -1) { $maxlen = PHP_INT_MAX; } $copied = 0; - while(!$this->feof($source) && $copied <= $maxlen) { + while (!$this->feof($source) && $copied <= $maxlen) { $copied += $stream->write($this->fread($source, min(static::$copyBlockSize, $maxlen - $copied))); } } @@ -448,7 +449,7 @@ class UploadedFile implements UploadedFileInterface */ public function copyTo($dest, $maxlen = -1, $readOffset = 0) { - if($maxlen === -1) { + if ($maxlen === -1) { $actualLength = $this->getSize() - $readOffset; } else { $actualLength = min($maxlen, $this->getSize() - $readOffset); @@ -462,13 +463,13 @@ class UploadedFile implements UploadedFileInterface $stream->open(new StreamMode('rb')); $stream->seek($readOffset); - if(false !== $fileHandle = $stream->cast(STREAM_CAST_AS_STREAM)) { + if (false !== $fileHandle = $stream->cast(STREAM_CAST_AS_STREAM)) { // Utilise stream_copy_to_stream si le Stream nous renvoie un filehandle $copied = $this->stream_copy_to_stream($fileHandle, $dest, $actualLength); } else { // Sinon, on fait ça à la main par blocs de 8ko $copied = 0; - while(!$stream->eof() && $copied < $actualLength) { + while (!$stream->eof() && $copied < $actualLength) { $copied += $this->fwrite($dest, $stream->read(min(static::$copyBlockSize, $actualLength - $copied))); } } @@ -544,18 +545,19 @@ class UploadedFile implements UploadedFileInterface * @internal */ public static function isSafePath($path) - { /** - * @return string - */ + { + /** + * @return string + */ $parts = explode('/', trim($path, '/')); $level = 0; - foreach($parts as $part) { - switch($part) { + foreach ($parts as $part) { + switch ($part) { case '.': break; case '..': $level--; - if($level < 0) { + if ($level < 0) { return false; } break; @@ -596,7 +598,7 @@ class UploadedFile implements UploadedFileInterface 'etat' => $this->getEtat(), 'description' => $this->getDescription(), 'checksum' => $this->getChecksum(), - 'icon' => MimeTypeIcon::getMimeTypeIcon($this->getMimeType()) + 'icon' => MimeTypeIcon::getMimeTypeIcon($this->getMimeType()), ]; } @@ -648,7 +650,7 @@ class UploadedFile implements UploadedFileInterface */ public function getLocalPath() { - if(null !== $this->localTempPath) { + if (null !== $this->localTempPath) { return $this->localTempPath; } @@ -656,8 +658,8 @@ class UploadedFile implements UploadedFileInterface $stream->open(new StreamMode('rb')); $handle = $stream->cast(STREAM_CAST_AS_STREAM); - if(false !== $handle) { - if(stream_is_local($handle)) { + if (false !== $handle) { + if (stream_is_local($handle)) { $this->localTempPath = stream_get_meta_data($handle)['uri']; fclose($handle); return $this->localTempPath; diff --git a/Form/DataTranformer/UploadedFileTransformer.php b/Form/DataTranformer/UploadedFileTransformer.php index d4eab3a19e0008b1c1087ad621b2d954ca5312d5..e236d7cfb63235b892ac0c80783bd0ff09102863 100644 --- a/Form/DataTranformer/UploadedFileTransformer.php +++ b/Form/DataTranformer/UploadedFileTransformer.php @@ -41,21 +41,21 @@ class UploadedFileTransformer implements DataTransformerInterface */ public function reverseTransform($value) { - if(!$this->multiple) { + if (!$this->multiple) { return $this->reverseTransformFile($value); } - if(empty($value)) { + if (empty($value)) { return []; } - if(!is_array($value) && !$value instanceof Traversable) { + if (!is_array($value) && !$value instanceof Traversable) { throw new TransformationFailedException('Expected an array or a \Traversable.'); } $result = []; - foreach($value as $identifier) { - if(null !== $file = $this->reverseTransformFile($identifier)) { + foreach ($value as $identifier) { + if (null !== $file = $this->reverseTransformFile($identifier)) { $result[] = $file; } } @@ -67,21 +67,21 @@ class UploadedFileTransformer implements DataTransformerInterface */ public function transform($value) { - if(!$this->multiple) { + if (!$this->multiple) { return $this->transformFile($value); } - if(empty($value)) { + if (empty($value)) { return []; } - if(!is_array($value) && !$value instanceof Traversable) { + if (!is_array($value) && !$value instanceof Traversable) { throw new TransformationFailedException('Expected an array or a \Traversable.'); } $result = []; - foreach($value as $file) { - if(null !== $item = $this->transformFile($file)) { + foreach ($value as $file) { + if (null !== $item = $this->transformFile($file)) { $result[] = $item; } } @@ -92,15 +92,16 @@ class UploadedFileTransformer implements DataTransformerInterface /** * * @param mixed $value + * * @return mixed */ public function transformFile($value) { - if(empty($value)) { + if (empty($value)) { return null; } - if(!$value instanceof UploadedFileInterface) { + if (!$value instanceof UploadedFileInterface) { throw new TransformationFailedException('Expected an UploadedFileInterface.'); } @@ -110,30 +111,33 @@ class UploadedFileTransformer implements DataTransformerInterface /** * * @param mixed $value + * * @return UploadedFileInterface */ public function reverseTransformFile($value) { - if(empty($value)) { + if (empty($value)) { return null; } - if(!is_array($value)) { - throw new TransformationFailedException(sprintf('Expected an array, not a %s.', is_object($value) ? get_class($value) : gettype($value))); + if (!is_array($value)) { + throw new TransformationFailedException( + sprintf('Expected an array, not a %s.', is_object($value) ? get_class($value) : gettype($value)) + ); } - if(empty($value['id'])) { + if (empty($value['id'])) { return null; } $identifier = $value['id']; $file = $this->fileManager->get($identifier); - if(null === $file) { + if (null === $file) { return null; } - if($file->isOrphelin()) { + if ($file->isOrphelin()) { $file->setEtat(UploadedFileInterface::ETAT_NORMAL); } $file->setDescription(!empty($value['description']) ? $value['description'] : null); diff --git a/Form/Type/FileUploadType.php b/Form/Type/FileUploadType.php index 1968f8cf4794c9b44ba120e1b22eedeca78c0af2..cdaf9eadc42ad99d94b3e319326798a625327ad6 100644 --- a/Form/Type/FileUploadType.php +++ b/Form/Type/FileUploadType.php @@ -66,9 +66,9 @@ class FileUploadType extends AbstractType /** * - * @param Router $router + * @param Router $router * @param FileManagerInterface $fileManager - * @param int $defaultMaxChunkSize + * @param int $defaultMaxChunkSize */ public function __construct(Router $router, FileManagerInterface $fileManager, $defaultMaxChunkSize) { @@ -130,7 +130,7 @@ class FileUploadType extends AbstractType [ 'constraints' => function (OptionsResolver $options, $constraints) { return $this->addConstraints($options, $constraints); - } + }, ] ); } @@ -154,17 +154,18 @@ class FileUploadType extends AbstractType if (!empty($range)) { $constraints[] = new Count($range); } - } elseif ($options['required']) { $required = new NotBlank(['message' => 'file_upload.required']); $constraints[] = $required; } if ($options['min_file_size'] || $options['max_file_size']) { - $constraints[] = new FileSize([ - 'min' => $options['min_file_size'], - 'max' => $options['max_file_size'] - ]); + $constraints[] = new FileSize( + [ + 'min' => $options['min_file_size'], + 'max' => $options['max_file_size'], + ] + ); } if ($options['accept_file_types']) { diff --git a/Http/UploadedFileResponse.php b/Http/UploadedFileResponse.php index 9f27226198a9e8033f07e67f403f7fb19792cba6..400045b9a3631810fcfe16c287f64b9ff8871b71 100644 --- a/Http/UploadedFileResponse.php +++ b/Http/UploadedFileResponse.php @@ -44,14 +44,19 @@ class UploadedFileResponse extends Response /** * Constructor. * - * @param UploadedFileInterface $file The file to stream - * @param int $status The response status code - * @param array $headers An array of response headers - * @param bool $public Files are public by default - * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename + * @param UploadedFileInterface $file The file to stream + * @param int $status The response status code + * @param array $headers An array of response headers + * @param bool $public Files are public by default + * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename */ - public function __construct(UploadedFileInterface $file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null) - { + public function __construct( + UploadedFileInterface $file = null, + $status = 200, + $headers = [], + $public = true, + $contentDisposition = null + ) { parent::__construct(null, $status, $headers); if ($file) { @@ -64,25 +69,24 @@ class UploadedFileResponse extends Response } /** - * @param UploadedFileInterface $file The file to stream - * @param int $status The response status code - * @param array $headers An array of response headers - * @param bool $public Files are public by default - * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename + * @param UploadedFileInterface $file The file to stream + * @param int $status The response status code + * @param array $headers An array of response headers + * @param bool $public Files are public by default + * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename * * @return UploadedFileResponse The created response */ - public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null) + public static function create($file = null, $status = 200, $headers = [], $public = true, $contentDisposition = null) { return new static($file, $status, $headers, $public, $contentDisposition); } - /** * Sets the file to stream. * - * @param UploadedFileInterface $file The file to stream - * @param string $contentDisposition + * @param UploadedFileInterface $file The file to stream + * @param string $contentDisposition * * @return UploadedFileResponse * @@ -116,8 +120,8 @@ class UploadedFileResponse extends Response /** * Sets the Content-Disposition header with the given filename. * - * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT - * @param string $filename Optionally use this filename instead of the real name of the file + * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT + * @param string $filename Optionally use this filename instead of the real name of the file * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename * * @return UploadedFileResponse @@ -168,15 +172,15 @@ class UploadedFileResponse extends Response $range = $request->headers->get('Range'); $fileSize = $this->file->getSize(); - list($start, $end) = explode('-', substr($range, 6), 2) + array(0); + list($start, $end) = explode('-', substr($range, 6), 2) + [0]; - $end = ('' === $end) ? $fileSize - 1 : (int) $end; + $end = ('' === $end) ? $fileSize - 1 : (int)$end; if ('' === $start) { $start = $fileSize - $end; $end = $fileSize - 1; } else { - $start = (int) $start; + $start = (int)$start; } if ($start <= $end) { diff --git a/Listener/UploadedFileListener.php b/Listener/UploadedFileListener.php index cb37ea6d8f4fcf0402a12472a4006120bdd1c42b..0ee585038d7a10dd4c9c44fe9f1db55aa9fa80d5 100644 --- a/Listener/UploadedFileListener.php +++ b/Listener/UploadedFileListener.php @@ -56,7 +56,7 @@ class UploadedFileListener { $changes = $event->getEntityManager()->getUnitOfWork()->getEntityChangeSet($file); - if(!isset($changes['path'])) { + if (!isset($changes['path'])) { return; } @@ -82,7 +82,7 @@ class UploadedFileListener { try { $this->filesystem->delete($this->scheduledDeletion[$file->getId()]); - } catch(FileNotFound $ex) { + } catch (FileNotFound $ex) { // NOOP } } diff --git a/Model/FileManagerInterface.php b/Model/FileManagerInterface.php index 85923d35dc48fc15e890de84bcfe801ad4e365e9..ff5e4490c06f57a230793b6bfebab7704631b589 100644 --- a/Model/FileManagerInterface.php +++ b/Model/FileManagerInterface.php @@ -49,6 +49,7 @@ interface FileManagerInterface * Le nouveau fichier est automatiquement orphelin, avec un chemin par défaut. * * @param UploadedFileInterface $original + * * @return UploadedFileInterface * @throws InvalidArgumentException Le fichier original est invalide. * diff --git a/Model/UploadedFileInterface.php b/Model/UploadedFileInterface.php index ce2f423a8cf47fc47fb06dd79c9a9e752a8b88b7..e7a45f25816a13c951de082fb084c28e3d9b5202 100644 --- a/Model/UploadedFileInterface.php +++ b/Model/UploadedFileInterface.php @@ -37,7 +37,7 @@ interface UploadedFileInterface * * @var string */ - const ETAT_NORMAL = 'normal'; + const ETAT_NORMAL = 'normal'; /** Fichier corrompu. * @@ -61,7 +61,7 @@ interface UploadedFileInterface * * @var string */ - const ETAT_REJETE = 'rejete'; + const ETAT_REJETE = 'rejete'; /** Retourne l'identifiant du fichier. * @@ -75,6 +75,7 @@ interface UploadedFileInterface * Set originalFilename * * @param string $displayName + * * @return UploadedFileInterface * * @api @@ -91,6 +92,7 @@ interface UploadedFileInterface /** * @param string $description + * * @return UploadedFileInterface * * @api @@ -141,6 +143,7 @@ interface UploadedFileInterface * Set mimeType * * @param string $mimeType + * * @return UploadedFileInterface * * @api @@ -159,6 +162,7 @@ interface UploadedFileInterface * Set size * * @param integer $size + * * @return UploadedFileInterface * * @api @@ -177,6 +181,7 @@ interface UploadedFileInterface * Set checksum * * @param string $checksum + * * @return UploadedFileInterface * * @api @@ -194,6 +199,7 @@ interface UploadedFileInterface /** Modifie l'état courant du fichier. * * @param string $etat + * * @return UploadedFileInterface * * @api @@ -211,6 +217,7 @@ interface UploadedFileInterface /** Définit la date de création du fichier. * * @param DateTime $time + * * @return self * * @api @@ -220,6 +227,7 @@ interface UploadedFileInterface /** Définit le nom de l'utilisateur ayant uploadé le fichier. * * @param string $username + * * @return self * * @api @@ -229,6 +237,7 @@ interface UploadedFileInterface /** Retourne l'adresse IP du client ayant uploadé le fichier. * * @param string $ipAddress + * * @return self * * @api @@ -386,6 +395,7 @@ interface UploadedFileInterface * Détermine si ce fichier a le même contenu qu'un autre fichier. * * @param UploadedFileInterface $other + * * @return bool True si les deux fichiers ont le même contenu. * * @api diff --git a/Service/FileUrlGeneratorInterface.php b/Service/FileUrlGeneratorInterface.php index 123941fca4af6a039efe244201992699838c5893..f1f402cf16631c1c09913c96e3611e1e3104b466 100644 --- a/Service/FileUrlGeneratorInterface.php +++ b/Service/FileUrlGeneratorInterface.php @@ -21,6 +21,7 @@ interface FileUrlGeneratorInterface * * @param string $idFile Identifiant du fichier pour lequel générer l'URL. * @param string|bool $referenceType Type d'URL à générer. + * * @return string L'url générée. */ public function generate($idFile, $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH); diff --git a/Tests/Entity/UploadedFileTest.php b/Tests/Entity/UploadedFileTest.php index 5327921bac18b01f39389b947674e7c85598b325..799e4adb842785f2f0683790a8cff181e3c2cce2 100644 --- a/Tests/Entity/UploadedFileTest.php +++ b/Tests/Entity/UploadedFileTest.php @@ -22,11 +22,11 @@ class UploadedFileTest extends PHPUnit_Framework_TestCase */ protected function setUp() { - $this->file = new UploadedFile; + $this->file = new UploadedFile(); } /** - * @covers Irstea\FileUploadBundle\Entity\UploadedFile::isSafePath + * @covers Irstea\FileUploadBundle\Entity\UploadedFile::isSafePath * @dataProvider getIsSafePathvalues */ public function testIsSafePath($isSafe, $path) @@ -37,13 +37,13 @@ class UploadedFileTest extends PHPUnit_Framework_TestCase public function getIsSafePathvalues() { return [ - [true, 'toto.php'], + [true, 'toto.php'], [false, '../toto.php'], - [true, 'bla/../toto.php'], + [true, 'bla/../toto.php'], [false, 'bla/.././../toto.php'], [false, '/../toto.php'], - [true, '/bla/../toto.php'], - [false, '../toto.php'] + [true, '/bla/../toto.php'], + [false, '../toto.php'], ]; } diff --git a/Tests/Form/DataTranformer/UploadedFileTransformerTest.php b/Tests/Form/DataTranformer/UploadedFileTransformerTest.php index 80286d54d1ca848d767a683515097fe22bb8a285..ed453b09969902452950c56899dd572f0fe3f88c 100644 --- a/Tests/Form/DataTranformer/UploadedFileTransformerTest.php +++ b/Tests/Form/DataTranformer/UploadedFileTransformerTest.php @@ -45,10 +45,10 @@ class UploadedFileTransformerTest extends PHPUnit_Framework_TestCase public function getEmptyValues() { $values = []; - foreach([null, '', []] as $value) { - foreach(['transform', 'reverseTransform'] as $method) { + foreach ([null, '', []] as $value) { + foreach (['transform', 'reverseTransform'] as $method) { $values[] = [[], $method, $value]; - $values[] = [null, $method."File", $value]; + $values[] = [null, $method . "File", $value]; } } return $values; diff --git a/Tests/Listener/UploadedFileListenerTest.php b/Tests/Listener/UploadedFileListenerTest.php index cbf43098889f4960b55646f35689bb0a88de252f..9af079ba912ce2b998b37e012c091eab9db6d8f9 100644 --- a/Tests/Listener/UploadedFileListenerTest.php +++ b/Tests/Listener/UploadedFileListenerTest.php @@ -73,7 +73,6 @@ class UploadedFileListenerTest extends PHPUnit_Framework_TestCase $this->event = new LifecycleEventArgs($this->file, $this->om); } - /** * @covers Irstea\FileUploadBundle\Listener\UploadedFileListener::postLoad * @todo Implement testPostLoad(). @@ -102,7 +101,9 @@ class UploadedFileListenerTest extends PHPUnit_Framework_TestCase */ public function testPostUpdatePathChanged() { - $this->unitOfWork->expects($this->once())->method('getEntityChangeSet')->with($this->file)->willReturn(['path' => ['before', 'after']]); + $this->unitOfWork->expects($this->once())->method('getEntityChangeSet')->with($this->file)->willReturn( + ['path' => ['before', 'after']] + ); $this->filesystem->expects($this->once())->method('rename')->with('before', 'after'); diff --git a/Tests/Listener/VirusScannerListenerTest.php b/Tests/Listener/VirusScannerListenerTest.php index 9551c61637a6d1eb20f8f29cca30b3ebfe2a7fda..8cd8e3235b2d7f264b01bf9a301f2b113fec7f41 100644 --- a/Tests/Listener/VirusScannerListenerTest.php +++ b/Tests/Listener/VirusScannerListenerTest.php @@ -81,7 +81,7 @@ class VirusScannerListenerTest extends PHPUnit_Framework_TestCase $this->listener->onFileUploadCompleted($this->event); } -/** + /** * @expectedException Irstea\FileUploadBundle\Exception\RejectedFileException */ public function testOnFileUploadCompletedVirusFoundNoDescription() diff --git a/Tests/Utils/MimeTypeIconTest.php b/Tests/Utils/MimeTypeIconTest.php index 6b3f9bdd4783c67a5aed90fc4124989897907c2a..ac1396fb8ee20dab473277d867be88871f135054 100644 --- a/Tests/Utils/MimeTypeIconTest.php +++ b/Tests/Utils/MimeTypeIconTest.php @@ -11,7 +11,7 @@ use PHPUnit_Framework_TestCase; class MimeTypeIconTest extends PHPUnit_Framework_TestCase { /** - * @covers Irstea\FileUploadBundle\Utils\MimeTypeIcon::getMimeTypeIcon + * @covers Irstea\FileUploadBundle\Utils\MimeTypeIcon::getMimeTypeIcon * @dataProvider getTestValues */ public function testGetMimeTypeIcon($expected, $input) @@ -28,7 +28,7 @@ class MimeTypeIconTest extends PHPUnit_Framework_TestCase ['text', 'text/plain'], ['video', 'video/mpeg'], ['image', 'image/png'], - ['pdf', 'application/pdf'], + ['pdf', 'application/pdf'], ['archive', 'application/zip'], ['text', 'text/plain; charset=UTF-8'], ['archive', 'application/zip; format=lzh'], diff --git a/Twig/FileUploadExtension.php b/Twig/FileUploadExtension.php index 3b804bcdaca414b8dd3e9e0ac107b33494ac5ae0..aeb829bb355f1511ec86c8270d9fdb4ced84bade 100644 --- a/Twig/FileUploadExtension.php +++ b/Twig/FileUploadExtension.php @@ -59,14 +59,14 @@ class FileUploadExtension extends Twig_Extension [$this, 'formatUploadedFile'], [ 'needs_environment' => true, - 'is_safe' => ['html'] + 'is_safe' => ['html'], ] ), new Twig_SimpleFunction( 'irstea_file_url', [$this, 'generateFileUrl'], [ - 'is_safe' => ['html', 'html_attr'] + 'is_safe' => ['html', 'html_attr'], ] ), new Twig_SimpleFunction( @@ -105,25 +105,24 @@ class FileUploadExtension extends Twig_Extension * * Usage : `{{ irstea_uploaded_file(file) }}` * - * @param Twig_Environment $env + * @param Twig_Environment $env * @param UploadedFileInterface $file * * @return string */ public function formatUploadedFile(Twig_Environment $env, $file = null) { - if(null === $file) { + if (null === $file) { return ''; - } elseif($file instanceof UploadedFile) { + } elseif ($file instanceof UploadedFile) { $file = $file->toArray(); - } elseif(!is_array($file)) { + } elseif (!is_array($file)) { throw new InvalidArgumentException("irstea_uploaded_file expects an UploadedFile instance, array or null"); } return $env->render('IrsteaFileUploadBundle:Extension:uploaded_file.html.twig', ['file' => $file]); } - /** Genère un URL sécurisée pour télécharger un fichier. * * Usage : `{{ irstea_file_path(file.id) }}` @@ -151,7 +150,7 @@ class FileUploadExtension extends Twig_Extension public function formatFileIcon($mimeType) { $icon = MimeTypeIcon::getMimeTypeIcon($mimeType); - return sprintf('<i class="icon fa fa-file%s-o"></i>', ($icon && $icon !== 'file') ? ('-'.$icon) : ''); + return sprintf('<i class="icon fa fa-file%s-o"></i>', ($icon && $icon !== 'file') ? ('-' . $icon) : ''); } /** Formate une taille de fichier. @@ -169,28 +168,28 @@ class FileUploadExtension extends Twig_Extension */ public function formatFileSize($context, $size, $precision = null, $locale = null) { - if(!is_numeric($size)) { + if (!is_numeric($size)) { return ''; } - if($size > 1000000000) { + if ($size > 1000000000) { $size /= 1000000000.0; $defaultPrecision = 2; $unit = 'Gi'; - } elseif($size > 1000000) { + } elseif ($size > 1000000) { $size /= 1000000.0; $defaultPrecision = 1; $unit = 'Mi'; - } elseif($size > 1000) { + } elseif ($size > 1000) { $size /= 1000.0; $defaultPrecision = 1; $unit = 'Ki'; } else { $unit = ''; $defaultPrecision = 0; - } + } - if(null === $locale) { + if (null === $locale) { $locale = $context['app']->getRequest()->getLocale(); } diff --git a/Utils/MimeTypeIcon.php b/Utils/MimeTypeIcon.php index 716889a6de9e7e94633ad9ad9f08516efbdb125e..db051f75c456c72687cf88775032d8f29b4ca8ec 100644 --- a/Utils/MimeTypeIcon.php +++ b/Utils/MimeTypeIcon.php @@ -15,45 +15,46 @@ namespace Irstea\FileUploadBundle\Utils; final class MimeTypeIcon { private static $icons = [ - 'application/vnd.oasis.opendocument.text' => 'word', - 'application/vnd.oasis.opendocument.spreadsheet' => 'excel', - 'application/vnd.oasis.opendocument.presentation' => 'powerpoint', - 'application/vnd.oasis.opendocument.graphics' => 'image', - 'application/vnd.ms-excel' => 'excel', - 'application/vnd.ms-powerpoint' => 'powerpoint', - 'application/msword' => 'word', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'excel', + 'application/vnd.oasis.opendocument.text' => 'word', + 'application/vnd.oasis.opendocument.spreadsheet' => 'excel', + 'application/vnd.oasis.opendocument.presentation' => 'powerpoint', + 'application/vnd.oasis.opendocument.graphics' => 'image', + 'application/vnd.ms-excel' => 'excel', + 'application/vnd.ms-powerpoint' => 'powerpoint', + 'application/msword' => 'word', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'excel', 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'powerpoint', - 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'word', - 'application/pdf' => 'pdf', - 'application/zip' => 'archive', - 'application/x-rar-compressed' => 'archive', - 'application/x-gtar' => 'archive', - 'application/x-gzip' => 'archive', - 'application/x-tar' => 'archive' + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'word', + 'application/pdf' => 'pdf', + 'application/zip' => 'archive', + 'application/x-rar-compressed' => 'archive', + 'application/x-gtar' => 'archive', + 'application/x-gzip' => 'archive', + 'application/x-tar' => 'archive', ]; /** * * @param string $mimeType + * * @return string|null */ public static function getMimeTypeIcon($mimeType) { - if(!is_string($mimeType)) { + if (!is_string($mimeType)) { return null; } - if(false !== $sep = strpos($mimeType, ';')) { + if (false !== $sep = strpos($mimeType, ';')) { $mimeType = trim(substr($mimeType, 0, $sep)); } - if(isset(self::$icons[$mimeType])) { + if (isset(self::$icons[$mimeType])) { return self::$icons[$mimeType]; } $matches = []; - if(preg_match('@^(text|audio|video|image)/@', $mimeType, $matches)) { + if (preg_match('@^(text|audio|video|image)/@', $mimeType, $matches)) { return $matches[1]; } diff --git a/Validation/FileMimeTypeValidator.php b/Validation/FileMimeTypeValidator.php index 8e7f9a2ce06deaa7ee2b61f7832d4c8f3f821a39..1c27b4db5d3975262b7a567d0764fed7275f76a1 100644 --- a/Validation/FileMimeTypeValidator.php +++ b/Validation/FileMimeTypeValidator.php @@ -26,7 +26,7 @@ class FileMimeTypeValidator extends ConstraintValidator if (!$value instanceof UploadedFileInterface) { return; } - if (preg_match('@^'.$constraint->acceptedMimeTypes.'$@i', $value->getMimeType())) { + if (preg_match('@^' . $constraint->acceptedMimeTypes . '$@i', $value->getMimeType())) { return; } $this->context->buildViolation($constraint->message)