Commit 98609835 authored by Guillaume Perréal's avatar Guillaume Perréal
Browse files

CS.

parent 69f6727a
<?php
/*
* Copyright (C) 2015 IRSTEA
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
......@@ -11,13 +10,10 @@ use Irstea\FileUploadBundle\Model\FileManagerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Description of GarbageCollectorCommand
*
* @author Guillaume Perréal <guillaume.perreal@irstea.fr>
* Description of GarbageCollectorCommand.
*/
class CheckCommand extends ContainerAwareCommand
{
......@@ -39,6 +35,7 @@ class CheckCommand extends ContainerAwareCommand
if (count($files) == 0) {
$output->writeln('Aucun fichier à vérifier.');
return;
}
......
<?php
/*
* Copyright (C) 2015 IRSTEA
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
......@@ -15,9 +14,7 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Description of GarbageCollectorCommand
*
* @author Guillaume Perréal <guillaume.perreal@irstea.fr>
* Description of GarbageCollectorCommand.
*/
class CollectGarbageCommand extends ContainerAwareCommand
{
......@@ -25,7 +22,7 @@ class CollectGarbageCommand extends ContainerAwareCommand
{
$this
->setName('irstea:file-upload:collect-garbage')
->setDescription("Nettoie les fichiers orphelins et partiels.")
->setDescription('Nettoie les fichiers orphelins et partiels.')
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Affiche ce qui devrait être fait, sans le faire');
}
......@@ -38,15 +35,17 @@ class CollectGarbageCommand extends ContainerAwareCommand
if (count($files) == 0) {
$output->writeln('Aucun fichier à supprimer.');
return;
}
if ($input->getOption('dry-run')) {
$output->writeln(sprintf('%d fichier(s) à supprimer.', count($files)));
return;
}
$output->writeln("Suppression des fichiers");
$output->writeln('Suppression des fichiers');
$progress = new ProgressBar($output, count($files));
$progress->start();
......
<?php
/*
* Copyright (C) 2015 IRSTEA
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
......@@ -16,9 +15,7 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Description of GarbageCollectorCommand
*
* @author Guillaume Perréal <guillaume.perreal@irstea.fr>
* Description of GarbageCollectorCommand.
*/
class CreateCommand extends ContainerAwareCommand
{
......@@ -26,10 +23,10 @@ class CreateCommand extends ContainerAwareCommand
{
$this
->setName('irstea:file-upload:create')
->setDescription("Créer un fichier.")
->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).")
->setDescription('Créer un fichier.')
->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");
}
......@@ -42,14 +39,13 @@ class CreateCommand extends ContainerAwareCommand
$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) {
$path = $input->getArgument('path');
if ('-' === $path) {
$realPath = 'php://stdin';
$displayName = "stdin";
$displayName = 'stdin';
$lastModified = time();
$size = 0;
} else {
......@@ -88,7 +84,7 @@ class CreateCommand extends ContainerAwareCommand
);
if ($output->isVerbose()) {
$output->writeln(sprintf("%s crée, %d octets lus.", $file->getId(), $written));
$output->writeln(sprintf('%s crée, %d octets lus.', $file->getId(), $written));
} else {
$output->writeln($file->getId());
}
......
<?php
/*
* Copyright (C) 2015 IRSTEA
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
namespace Irstea\FileUploadBundle\Command;
use Doctrine\ORM\EntityManager;
use Irstea\FileUploadBundle\Model\FileManagerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
......@@ -16,9 +14,7 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Description of GarbageCollectorCommand
*
* @author Guillaume Perréal <guillaume.perreal@irstea.fr>
* Description of GarbageCollectorCommand.
*/
class ReadCommand extends ContainerAwareCommand
{
......@@ -29,8 +25,8 @@ class ReadCommand extends ContainerAwareCommand
->setDescription("Récupère le contenu d'un fichier.")
->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('id', InputArgument::REQUIRED, 'Identifiant du fichier à récupérer.')
->addArgument('filepath', InputArgument::OPTIONAL, 'Chemin du fichier dans lequel écrire.');
}
protected function execute(InputInterface $input, OutputInterface $output)
......@@ -58,7 +54,7 @@ class ReadCommand extends ContainerAwareCommand
fclose($fh);
if ($output->isVerbose() && null !== $path) {
$output->writeln(sprintf("%d octets écrits.", $written));
$output->writeln(sprintf('%d octets écrits.', $written));
}
}
}
<?php
/*
* Copyright (C) 2015 IRSTEA
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
......@@ -32,16 +31,14 @@ use Symfony\Component\Templating\EngineInterface;
*/
class UploadController extends Controller
{
const CSRF_INTENTION = "uploaded_file";
const CSRF_INTENTION = 'uploaded_file';
/**
*
* @var FileManagerInterface
*/
protected $fileManager;
/**
*
* @var UrlGeneratorInterface
*/
protected $urlGenerator;
......@@ -61,9 +58,6 @@ class UploadController extends Controller
*/
protected $templating;
/**
*
*/
public function __construct(
FileManagerInterface $fileManager,
UrlGeneratorInterface $urlGenerator,
......@@ -81,6 +75,7 @@ class UploadController extends Controller
/**
* @Route("", name="file_upload_create")
* @Method("POST")
*
* @param Request $request
*/
public function createAction(Request $request)
......@@ -125,7 +120,8 @@ class UploadController extends Controller
/**
* @Route("/{id}/content", name="file_upload_put_content")
* @Method("PUT")
* @param Request $request
*
* @param Request $request
* @param UploadedFile $file
*/
public function putContentAction(Request $request, UploadedFile $file)
......@@ -151,21 +147,19 @@ class UploadController extends Controller
}
/**
*
* @param Request $request
*
* @return array
*/
protected function handleRangeHeader(Request $request)
{
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)) {
throw new BadRequestHttpException("Invalid Content-Range");
throw new BadRequestHttpException('Invalid Content-Range');
}
$start = intval($matches[1]);
......@@ -180,7 +174,6 @@ class UploadController extends Controller
}
/**
*
* @param UploadedFileInterface $file
*
* @return Response
......@@ -213,7 +206,8 @@ class UploadController extends Controller
/**
* @Route("/{id}/content", name="file_upload_get_content")
* @Method("GET")
* @param Request $request
*
* @param Request $request
* @param UploadedFile $file
*/
public function getContentAction(Request $request, UploadedFile $file)
......@@ -226,13 +220,15 @@ class UploadController extends Controller
$response = UploadedFileResponse::create($file, 200, [], false, ResponseHeaderBag::DISPOSITION_ATTACHMENT);
$response->isNotModified($request);
return $response;
}
/**
* @Route("/{id}", name="file_upload_delete")
* @Method("DELETE")
* @param Request $request
*
* @param Request $request
* @param UploadedFile $file
*/
public function deleteAction(Request $request, UploadedFile $file)
......@@ -249,7 +245,6 @@ class UploadController extends Controller
}
/**
*
* @param Request $request
*
* @throws HttpException
......@@ -262,11 +257,10 @@ class UploadController extends Controller
}
/**
*
* @param int $status
* @param int $status
* @param string $message
* @param array $data
* @param array $headers
* @param array $data
* @param array $headers
*
* @return JsonResponse
*/
......@@ -276,11 +270,11 @@ class UploadController extends Controller
$data['message'] = $message;
$response = new JsonResponse($data, $status, $headers);
$response->setStatusCode($status, $message);
return $response;
}
/**
*
* @param \Exception $ex
*
* @return JsonResponse
......@@ -289,7 +283,7 @@ class UploadController extends Controller
{
return $this->createResponse(
$ex instanceof HttpException ? $ex->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR,
preg_replace("/[\n\r]+/", " ", $ex->getMessage()),
preg_replace("/[\n\r]+/", ' ', $ex->getMessage()),
[
'exception' => [
'class' => get_class($ex),
......
<?php
/*
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
namespace Irstea\FileUploadBundle\Controller;
......@@ -9,7 +13,6 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
......@@ -33,11 +36,11 @@ class UploadedFileController extends Controller
$em = $this->getDoctrine()->getManager();
$queryBuilder = $em->getRepository('IrsteaFileUploadBundle:UploadedFile')
->createQueryBuilder("u")
->orderBy("u.createdAt", "DESC");
->createQueryBuilder('u')
->orderBy('u.createdAt', 'DESC');
$pager = new Pagerfanta(new DoctrineORMAdapter($queryBuilder));
$pager->setCurrentPage($request->query->get("page", 1));
$pager->setCurrentPage($request->query->get('page', 1));
$uploadedFiles = $pager->getCurrentPageResults();
......@@ -56,7 +59,6 @@ class UploadedFileController extends Controller
*/
public function showAction(UploadedFile $uploadedFile)
{
return [
'uploadedFile' => $uploadedFile,
];
......@@ -64,7 +66,7 @@ class UploadedFileController extends Controller
/**
* @param string $message
* @param array $parameters
* @param array $parameters
*/
public function notice($message, array $parameters = [])
{
......
<?php
/*
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
namespace Irstea\FileUploadBundle\DependencyInjection;
......@@ -6,7 +10,7 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
......@@ -28,12 +32,13 @@ class Configuration implements ConfigurationInterface
->then(
function ($v) {
$int = intval($v);
if (strpos($v, "K")) {
if (strpos($v, 'K')) {
return 1000 * $int;
}
if (strpos($v, "M")) {
if (strpos($v, 'M')) {
return 1000000 * $int;
}
return $int;
}
)
......
<?php
/*
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
namespace Irstea\FileUploadBundle\DependencyInjection;
......@@ -47,7 +51,7 @@ class IrsteaFileUploadExtension extends Extension implements PrependExtensionInt
"$pluginDir/js/jquery.fileupload-process.js",
"$pluginDir/js/jquery.fileupload-validate.js",
"$pluginDir/js/jquery.fileupload-ui.js",
"@BazingaJsTranslationBundle/Resources/js/translator.js",
'@BazingaJsTranslationBundle/Resources/js/translator.js',
'js/translations/file_upload/*.js',
'js/translations/validators/*.js',
'@IrsteaFileUploadBundle/Resources/js/widget/file_upload.js',
......
<?php
/*
* Copyright (C) 2015 IRSTEA
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
......@@ -24,9 +23,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Description of UploadedFileRepository
*
* @author Guillaume Perréal <guillaume.perreal@irstea.fr>
* Description of UploadedFileRepository.
*/
class UploadedFileRepository extends EntityRepository implements FileManagerInterface
{
......@@ -43,7 +40,6 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte
protected $eventDispatcher;
/**
*
* @param Filesystem $filesystem
*/
public function setFilesystem(Filesystem $filesystem)
......@@ -52,7 +48,6 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte
}
/**
*
* @param EventDispatcherInterface $eventDispatcher
*/
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
......@@ -89,16 +84,16 @@ 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();
$metadata = $original->getMetadata();
if (!isset($metadata["duplicateOf"])) {
$metadata["duplicateOf"] = [$original->getId()];
if (!isset($metadata['duplicateOf'])) {
$metadata['duplicateOf'] = [$original->getId()];
} else {
array_unshift($metadata["duplicateOf"], $original->getId());
array_unshift($metadata['duplicateOf'], $original->getId());
}
$new
......@@ -111,7 +106,7 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte
->setSize($original->getSize());
$stream = $this->filesystem->createStream($new->getPath());
$stream->open(new StreamMode("cb"));
$stream->open(new StreamMode('cb'));
$original->copyTo($stream->cast(STREAM_CAST_AS_STREAM));
$stream->close();
......@@ -134,8 +129,9 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte
return null;
}
if (!is_string($uuid) || !Uuid::isValid($uuid)) {
throw new InvalidArgumentException(sprintf("Identifiant invalide: %s", (string)$uuid));
throw new InvalidArgumentException(sprintf('Identifiant invalide: %s', (string) $uuid));
}
return $this->findOneById($uuid);
}
......@@ -168,10 +164,9 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte
}
/**
*
* @param string $level
* @param string $message
* @param array $context
* @param array $context
*/
protected function log($level, $message, array $context = [])
{
......@@ -191,6 +186,7 @@ class UploadedFileRepository extends EntityRepository implements FileManagerInte
$files,
function (UploadedFileInterface $file) use ($limit) {
$mtime = $file->getLastModified();
return $mtime === null || $mtime < $limit;
}
);
......
<?php
/*
* Copyright (C) 2015 IRSTEA
* Copyright (C) 2015-2017 IRSTEA
* All rights reserved.
*/
......@@ -28,25 +27,28 @@ use Rhumsaa\Uuid\Uuid;
class UploadedFile implements UploadedFileInterface
{
// Taille de bloc utilisé pour les copies
static public $copyBlockSize = 8192;
public static $copyBlockSize = 8192;
const ORPHAN_PREFIX = "orphan/";
const ORPHAN_PREFIX = 'orphan/';
/**
* @ORM\Id
* @ORM\Column(type="guid")
*
* @var string
*/
private $id;
/**
* @ORM\Column(type="string", length=1024)
*
* @var string
*/
private $displayName;
/**
* @ORM\Column(type="string", length=1024)
*
* @var string
*/
private $path;
......@@ -57,56 +59,64 @@ class UploadedFile implements UploadedFileInterface
private $actualPath;
/**
*
* @ORM\Column(type="string", length=255, nullable=true)
*
* @var string
*/
private $mimeType = null;
/**
* @ORM\Column(type="integer", nullable=true)
*
* @var int
*/
private $size = null;
/**
* @ORM\Column(type="string", length=64, nullable=true)
*
* @var string
*/
private $checksum = null;
/**
* @ORM\Column(type="string", length=10)
*
* @var string
*/
private $etat = self::ETAT_EN_COURS;
/**
* @ORM\Column(type="datetime")
*
* @var DateTime
*/
private $createdAt;
/**
* @ORM\Column(type="string", nullable=true)
*
* @var string
*/
private $createdBy;
/**
* @ORM\Column(type="string", nullable=true)
*
* @var string
*/
private $createdFrom;
/**
* @ORM\Column(type="json_array", nullable=true)
*
* @var array
*/
private $metadata = null;
/**
* @ORM\Column(type="string", length=256, nullable=true)
*
* @var string
*/
private $description = null;
......@@ -117,13 +127,11 @@ class UploadedFile implements UploadedFileInterface
private $filesystem;
/** Contient le nom de chemin local.
*
* @var string
*/